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
//! **THE GENERATIONS SEAT**: the run every generational row was written under, the pointer that says
//! which run is CURRENT, and the seam its engines are written against.
//!
//! A replace-set family re-analysed is not a family EDITED. The second run does not reach into the
//! first one's rows and correct them — it writes its own, whole, beside them — and what makes the two
//! tellable apart is a framework column naming the RUN, plus one row somewhere durable saying which
//! run a reader should be looking at.
//!
//! ```text
//! __ig_current_media
//! ┌───────────────┬───────┬──────────────────┬──────────────────────┐
//! │ root          │ scope │ run              │ flipped_second       │ …
//! ├───────────────┼───────┼──────────────────┼──────────────────────┤
//! │ <the key>     │ whole │ 1756…            │ 1756…                │
//! └───────────────┴───────┴──────────────────┴──────────────────────┘
//! ```
//!
//! # THE CLOSURE GRAIN, and it is why a flip is ONE act rather than one per table
//!
//! A re-run does not re-derive one table. It re-derives a CASCADE CLOSURE — every family downstream
//! of the root it started from — and a reader that saw the new generation in one of those tables and
//! the old generation in another would be reading a join that never existed at any moment in time.
//! So the pointer is keyed by `(root, scope)` and the flip covers the whole closure at once, which is
//! what [`Scope`] names: a closure, spelled, so a deployment that re-derives two independent closures
//! off one root flips them independently and neither ever borrows the other's generation.
//!
//! # THE ORDERING: the pointer lands FIRST, and nothing is erased until it has
//!
//! [`Curator`] is where that lives and its own note argues it. The shape is the retirement ledger's
//! discipline one seat over — durable write first, the rest after — with the second half being
//! DESTRUCTIVE rather than publishing, which is what makes the direction non-negotiable:
//!
//! ```text
//!   registry says CLOSED ──► Curator::flipped ──► store.point(row).await ──► store.sweep(…).await
//!                            (queue, return)      THE DURABLE FLIP           THE RETENTION DUTY
//! ```
//!
//! An interruption between them leaves a family holding MORE generations than its retention allows,
//! which the next flip's sweep collects for free. The opposite order would delete rows the pointer
//! still names, and no restart repairs that: there is no second copy to re-read.
//!
//! # VISIBILITY IS THE WRITE, which is stronger than a cache being told
//!
//! There is no mirror here and the absence is a ruling. The retirement ledger publishes into
//! [`RetiredMirror`](crate::RetiredMirror) because *is this key retired* is asked once per hit on every page a deployment renders, and no
//! read path can afford a database round trip for it. *Which run is current* is not that question: it
//! is asked once per PLAN, and it is answered INSIDE the plan — an anchored subquery against this
//! very table (see [`sql::current_filter`]). So the moment the pointer row commits is the moment
//! every reader sees the new generation, with nothing in between to publish and nothing to fall out
//! of step.
//!
//! # WHAT IS EXEMPT, and the exemptions are not omissions
//!
//! Generations are a REPLACE-SET discipline. An upsert family is one whose rows are corrected in
//! place by key — there is no second generation to point at — and an observation register accumulates
//! rather than replaces, so a run column on either would be a column that never selects anything.
//! [`Retired`](crate::RootState::Retired) is orthogonal and MASKS every generation: a retired root's
//! rows are hidden whichever run wrote them, so the two filters compose rather than competing.
//!
//! # ENGINES ARE A SEAM, and the three here are its first occupants
//!
//! [`GenerationsStore`] is a trait, not an enum. The three the framework ships — SQLite, PostgreSQL
//! and MySQL — are the three the graph word admits today, because the retention sweep is an ANCHORED
//! DELETE and that is a SQL shape. A document store keeps the same pointer and sweeps by MEMBERSHIP
//! instead — read the run set, delete what is not in it — which is this seam implemented elsewhere
//! rather than a change to it; see [`GenerationsEngine`], where the word's own vocabulary is argued.
//!
//! # WHAT THIS SEAT DOES NOT BUILD, stated because a reader will look for it
//!
//! The `__ig_run__` column's WORD, its TYPE ([`RunId`]), its MINT ([`Stamp`](crate::Stamp)), the
//! transition it is spent at and both of its readers — the sweep and the read filter — are here. What
//! is NOT here is the record-emission pass that puts the column into a generational family's own
//! `CREATE TABLE` and its insert: that is a new citizen on the storage ladder — a stored form, a
//! comparison row, a DDL word, an encode and a decode per dialect — and it is its own task rather
//! than a paragraph of this one. Until it lands, a deployment states its closure's tables through
//! [`Generational`], which is the same door a hand-wired store uses afterwards.

use core::{future::Future, num::NonZeroUsize, pin::Pin};

use std::sync::{
  Arc,
  atomic::{AtomicU64, Ordering},
};

use smol_bytes::Utf8Bytes;

use crate::Timestamp;

mod curator;
mod options;
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
mod sql;

#[cfg(test)]
mod tests;

pub use curator::{Curator, CuratorBody, CuratorReport, prepare};
pub use options::{
  DEFAULT_KEEP, GenerationsEngine, GenerationsOptions, GenerationsOverride,
  UnknownGenerationsEngine,
};
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
pub use sql::{GenerationsSql, SqlGenerations, current_filter};

/// The prefix every current-pointer table's name carries — the framework's own reserved stem.
///
/// `__ig_` is what every identifier this framework mints rather than reads off a declaration wears:
/// a companion column, a derived index, an unnested alias. A pointer table is the same kind of thing
/// — nobody declared it, and the prefix is what says so to a person reading a schema.
///
/// # It is PINNED to the reserved namespace, at compile time
///
/// [`RETIRED_TABLE_PREFIX`](crate::RETIRED_TABLE_PREFIX)'s pin, spent again at the second runtime
/// mint. A pointer table's name is not emitted — families are opened rather than declared, so it is
/// minted here, at run time, from a family this crate learns at run time — and `EmissionPrefix` is
/// `ingraph-codegen`'s type, which this crate cannot name. What the emission-prefix seat asks of a
/// mint is that the mark be ONE value rather than a copy per site, and this answers it the only way
/// a runtime literal can: the bytes stay a literal a reader can see whole, and the agreement is
/// ASSERTED, so a namespace that moves without this moving is a compile error rather than a schema
/// that disagrees with itself.
///
/// The SAME checker as the ledger's and the catalog's, never a third copy of the loop — see
/// [`leads_with`](crate::query::sql). It rides `sqlx` because that is where the reserved-namespace
/// const lives, which is every build that can put this name into a statement at all.
///
/// In the seat's own vocabulary the shape is `prefixed`, not `framed`: a pointer table is a minted
/// OBJECT rather than a synthesized column, so it wears the mark in front and no `__` behind. The
/// column one const down is the other case.
pub const CURRENT_TABLE_PREFIX: &str = "__ig_current_";

/// The stem this prefix adds to the reserved namespace — named so the pin below can measure it
/// rather than restate a number.
const CURRENT_STEM: &str = "_current_";

#[cfg(feature = "sqlx")]
const _: () = assert!(
  crate::query::sql::leads_with(CURRENT_TABLE_PREFIX, crate::comparison::sql::ALIAS_PREFIX)
    && CURRENT_TABLE_PREFIX.len()
      == crate::comparison::sql::ALIAS_PREFIX.len() + CURRENT_STEM.len(),
  "the generations seat's pointer-table prefix is the reserved namespace plus `_current_`"
);

/// **THE RUN COLUMN** every generational record wears — the framework's own, on every replace-set
/// family.
///
/// `__ig_run__` rather than `run`, and the shape is the synthesized-column law
/// ([`crate::interface`]'s own note): a column the framework invents wears `__ig_` at the front and
/// `__` at the end, so it can never collide with a field somebody declared and a reader of a schema
/// can tell at a glance which columns are the framework's.
///
/// # It is PINNED to the reserved namespace too, and it is the FRAMED case
///
/// [`CURRENT_TABLE_PREFIX`]'s pin one const up, over the same checker, with the arithmetic that
/// makes this the other of the emission-prefix seat's two shapes: a table is `prefixed` and wears
/// the mark in front, while a synthesized COLUMN is `framed` and wears `__` behind it as well. The
/// stem below carries that tail, so the length the assertion measures is the whole frame rather than
/// the lead alone — and a namespace that moves without this moving is a compile error.
pub const RUN_COLUMN: &str = "__ig_run__";

/// The stem this column adds to the reserved namespace — the joining `_`, the word, and the frame's
/// own trailing `__`, so the pin below measures the whole shape rather than restating a number.
const RUN_STEM: &str = "_run__";

#[cfg(feature = "sqlx")]
const _: () = assert!(
  crate::query::sql::leads_with(RUN_COLUMN, crate::comparison::sql::ALIAS_PREFIX)
    && RUN_COLUMN.len() == crate::comparison::sql::ALIAS_PREFIX.len() + RUN_STEM.len(),
  "the generations seat's run column is the reserved namespace framed around `run`"
);

/// THE FUTURE A STORE'S VERB HANDS BACK — one act, turning.
///
/// Boxed, and that is what a seam reached through `Arc<dyn GenerationsStore<Root>>` costs: an
/// `impl Future` return is not dyn-safe, and the party that holds a store holds it erased. A flip is
/// a once-per-run act rather than a hot path, so one allocation per act buys the erasure and costs
/// nothing anybody can measure.
///
/// # A SECOND alias beside [`Landing`](crate::Landing), and the second one is FORCED
///
/// The retirement ledger's alias one module over is the same boxed shape with its ERROR TYPE baked
/// in — `Result<T, RetiredStoreError>` — so it cannot carry a verb of this seam's, whose refusals
/// are [`GenerationsStoreError`]. Two aliases is what that leaves, and given two, two NAMES is
/// strictly better than one word meaning different things in two modules a reader moves between.
///
/// Widening the ledger's to `Landing<'a, T, E>` would fold them, and it is not this seat's change to
/// make: it would re-spell every signature in a module that has just landed, to save a type alias.
pub type Turning<'a, T> =
  Pin<Box<dyn Future<Output = Result<T, GenerationsStoreError>> + Send + 'a>>;

/// **WHICH RUN A ROW WAS WRITTEN UNDER** — the framework's own stamp on a generational record, and
/// the value the pointer points AT.
///
/// # It is ORDERED, and the order is what retention is spent against
///
/// `keep = N` means *the newest N runs*, so a generation has to be comparable with its predecessors
/// — which is the whole reason this is a number rather than a random identifier. [`mint`](Self::mint)
/// seeds from the wall clock in MICROSECONDS and then only ever counts up, so a restarted deployment
/// resumes above every run it wrote before without reading a row to find out where it got to.
///
/// # It is not globally unique, and it does not need to be
///
/// A run is unique WITHIN a root: the pointer is keyed by `(root, scope)` and retention is counted
/// per root, so two roots that opened in the same driver pass share a run number and nothing
/// anywhere compares them. That sharing is the honest reading of what a pass IS — one sweep of the
/// feed, one generation of work — and it is what lets the number be a [`Stamp`](crate::Stamp)'s
/// third reading rather than a fourth clock somebody has to remember to read.
///
/// # THE SIGNED BOUNDARY
///
/// SQL integers are signed, so a run crosses as an `i64` ([`as_i64`](Self::as_i64)) and comes back
/// through [`from_i64`](Self::from_i64). Every MINTED value is a microsecond reading and therefore
/// far below `2^63`; a value a caller built by hand above it round-trips exactly — the crossing is
/// two's complement both ways — but sorts as a negative number in the database, which is the
/// caller's own statement rather than something this type can correct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RunId(u64);

/// Where [`RunId::mint`] has got to. Seeded on first use — see that door for why the seed is a clock
/// reading rather than zero.
static RUNS: AtomicU64 = AtomicU64::new(0);

impl RunId {
  /// The run a caller already holding the number states — a row read back, a test, a deployment
  /// numbering its own runs.
  #[inline]
  #[must_use]
  pub const fn new(raw: u64) -> Self {
    Self(raw)
  }

  /// The number, as it is written.
  #[inline]
  #[must_use]
  pub const fn get(self) -> u64 {
    self.0
  }

  /// **THE NEXT RUN**, strictly above every run this process has minted.
  ///
  /// Seeded from the wall clock in microseconds and then counted up with a relaxed add, which is the
  /// pairing the two halves need: the SEED is what makes a restart resume above its predecessor
  /// without reading a row, and the COUNT is what makes two runs minted in the same microsecond
  /// distinct. `Relaxed` is the honest ordering — the number orders runs against one another and
  /// publishes nothing, the publishing being the pointer row's own job.
  ///
  /// A deployment minting more than a million runs a second would outrun its own seed and start
  /// numbering into the next second's range. That is a graph re-deriving a root every microsecond,
  /// and the consequence — a later restart's seed landing below a number this process reached — is
  /// repaired by the first mint after it, which reads the counter rather than the clock.
  #[must_use]
  pub fn mint() -> Self {
    // TWO STEPS, and neither can be dropped. `fetch_max` raises the counter to the clock where the
    // clock has moved past it — which is what the first mint of a process needs, the counter having
    // started at zero — and never lowers it, so a later mint under a clock that went backwards keeps
    // counting from where this process got to. `fetch_add` is then what makes two mints in one
    // microsecond distinct, and what makes two THREADS minting at once distinct: each takes a
    // different value out of the add.
    //
    // `Relaxed` throughout is the honest ordering. The number orders runs against one another and
    // publishes nothing; the publishing is the pointer row's own job, one seat over.
    let _raised = RUNS.fetch_max(Self::seed(), Ordering::Relaxed);
    Self(RUNS.fetch_add(1, Ordering::Relaxed) + 1)
  }

  /// The wall clock in microseconds — the mint's floor. Saturating at zero, because a clock set
  /// before the epoch is a machine whose runs still have to be ordered against one another.
  fn seed() -> u64 {
    let now = Timestamp::from(jiff::Timestamp::now());
    let micros =
      i128::from(now.as_second()) * 1_000_000 + i128::from(now.subsec_nanosecond()) / 1_000;
    u64::try_from(micros).unwrap_or(0)
  }

  /// The run as a SQL integer — see the type note for the boundary this crosses.
  #[inline]
  #[must_use]
  pub const fn as_i64(self) -> i64 {
    self.0 as i64
  }

  /// The inverse of [`as_i64`](Self::as_i64) — total, which is what a column read back has to be.
  #[inline]
  #[must_use]
  pub const fn from_i64(raw: i64) -> Self {
    Self(raw as u64)
  }
}

impl core::fmt::Display for RunId {
  #[inline]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "{run}", run = self.0)
  }
}

/// **WHICH CASCADE CLOSURE A POINTER IS FOR** — the word that makes a flip cover one set of families
/// rather than everything a root ever touched.
///
/// A re-run re-derives a closure, and a deployment may have more than one off a single root: a text
/// pipeline and a frame pipeline that share a `MediaId` and share nothing else. Flipping them
/// together would mean a text re-run invalidating frames it never looked at, and flipping them under
/// one name would mean the pointer could not say which of them a run belonged to. So a pointer row is
/// keyed by `(root, scope)`, and this is the scope.
///
/// # [`WHOLE`](Self::WHOLE) is the framework's own closure, and it is what a graph gets unasked
///
/// A root family has exactly one closure until somebody says otherwise — every family downstream of
/// the root — so the default is a name for that and not an absence. Spelling it rather than leaving
/// the column empty is what makes a table a person opens legible: a row says `whole`, which is a
/// closure, rather than `''`, which is a question.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Scope(Utf8Bytes);

impl Scope {
  /// The whole of what a root cascades into — see the type note.
  pub const WHOLE: &'static str = "whole";

  /// The closure `word` names.
  ///
  /// # It REFUSES a word it cannot splice, and the refusal is the SQL audit
  ///
  /// A scope is BOUND rather than spliced in every statement this seat runs — it is a value, not an
  /// identifier — so this refusal is narrower than [`CurrentTable::new`]'s and is here for a
  /// different reason: a scope names a closure in a schema a person reads and in a refusal a person
  /// gets back, and a word carrying a quote or a newline makes both unreadable. The rule is
  /// [`slot`](crate::slot)'s own: ASCII `[A-Za-z0-9_]`, not digit-leading.
  ///
  /// # Errors
  ///
  /// [`UnnameableScope`], carrying what was written.
  pub fn new(word: impl Into<Utf8Bytes>) -> Result<Self, UnnameableScope> {
    let word = word.into();
    if !crate::slot::is_identifier(word.as_bytes()) {
      return Err(UnnameableScope { word });
    }
    Ok(Self(word))
  }

  /// The word, as it is written into the column.
  #[inline]
  #[must_use]
  pub fn as_str(&self) -> &str {
    self.0.as_str()
  }

  /// The word, as the shared byte string a bind takes.
  #[inline]
  #[must_use]
  pub fn named(&self) -> Utf8Bytes {
    self.0.clone()
  }
}

impl Default for Scope {
  /// [`WHOLE`](Self::WHOLE) — the closure a graph has until somebody declares a second one.
  #[inline]
  fn default() -> Self {
    Self(Utf8Bytes::from_static(Self::WHOLE))
  }
}

impl core::fmt::Display for Scope {
  #[inline]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(self.as_str())
  }
}

/// A word that cannot name a closure — see [`Scope::new`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnnameableScope {
  /// What was written.
  word: Utf8Bytes,
}

impl UnnameableScope {
  /// What was written.
  #[inline]
  #[must_use]
  pub fn word(&self) -> &str {
    self.word.as_str()
  }
}

impl core::fmt::Display for UnnameableScope {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "`{word}` cannot name a cascade closure — a scope is a bare identifier (ASCII letters, digits \
       and `_`, not digit-leading), because it is the word a schema and a refusal both show a person",
      word = self.word,
    )
  }
}

impl core::error::Error for UnnameableScope {}

/// ONE ROW OF THE POINTER TABLE: which closure of which root is looking at which run, and when it
/// started to.
///
/// The stamp is not bookkeeping. A generation that a flip landed and a sweep has not yet collected
/// is indistinguishable from one still being written unless something says when the flip happened —
/// so `at` is what an operator reads to tell *this deployment is mid-run* from *this deployment
/// stopped mid-run*, and it is WALL time for exactly that reason.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CurrentRow<Root> {
  /// The root whose closure this points for.
  key: Root,
  /// Which closure — see [`Scope`].
  scope: Scope,
  /// The run every reader of this closure should be looking at.
  run: RunId,
  /// When the flip landed — WALL time, because this is the reading a person opening the table wants.
  at: Timestamp,
}

impl<Root> CurrentRow<Root> {
  /// The row a flip earns.
  #[inline]
  #[must_use]
  pub const fn new(key: Root, scope: Scope, run: RunId, at: Timestamp) -> Self {
    Self {
      key,
      scope,
      run,
      at,
    }
  }

  /// The root whose closure this points for.
  #[inline]
  #[must_use]
  pub const fn key(&self) -> &Root {
    &self.key
  }

  /// Which closure.
  #[inline]
  #[must_use]
  pub const fn scope(&self) -> &Scope {
    &self.scope
  }

  /// The run this closure is pointed at.
  #[inline]
  #[must_use]
  pub const fn run(&self) -> RunId {
    self.run
  }

  /// When the flip landed.
  #[inline]
  #[must_use]
  pub const fn at(&self) -> Timestamp {
    self.at
  }

  /// The key, taken out of the row.
  #[inline]
  #[must_use]
  pub fn into_key(self) -> Root {
    self.key
  }
}

/// **WHAT ONE SWEEP COLLECTED** — how many tables it reached and how many rows went.
///
/// A count rather than a list, and the grain is the duty's: a sweep is a retention duty run on every
/// flip, so what a deployment wants from it is *is anything accumulating* rather than *which rows*.
/// A zero is the ordinary answer at `keep = 1` on a root analysed once.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Culled {
  /// How many of the closure's tables were reached.
  pub tables: usize,
  /// How many rows the retention bound removed, across all of them.
  pub rows: u64,
}

/// **ONE TABLE OF A CLOSURE, AND THE TWO WORDS A SWEEP NEEDS OF IT** — where the rows are, and how
/// to find one root's.
///
/// The RUN column is not here because it is not a variable: every generational record wears
/// [`RUN_COLUMN`], which is the framework's own word and the same in every table. What differs per
/// table is its NAME and the column its root key is held in, that one being whatever the declaration
/// called the field.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Generational {
  /// The record table, as the schema names it.
  table: Utf8Bytes,
  /// The column its root key is held in.
  root: Utf8Bytes,
}

impl Generational {
  /// `table`, whose root key is in `root`.
  ///
  /// # It REFUSES a name it cannot splice, and this is the audit
  ///
  /// Both words are SPLICED into the sweep's `DELETE` — an identifier cannot be bound — so this is
  /// the one door a caller-supplied string reaches a statement through, and this is where it is
  /// stopped. Both must be bare identifiers ([`slot`](crate::slot)'s own rule: ASCII `[A-Za-z0-9_]`,
  /// not digit-leading), which admits no quote, no comment, no semicolon and no whitespace.
  ///
  /// # Errors
  ///
  /// [`UnnameableTable`], carrying whichever word was refused.
  pub fn new(
    table: impl Into<Utf8Bytes>,
    root: impl Into<Utf8Bytes>,
  ) -> Result<Self, UnnameableTable> {
    let table = table.into();
    let root = root.into();
    for word in [&table, &root] {
      if !crate::slot::is_identifier(word.as_bytes()) {
        return Err(UnnameableTable { word: word.clone() });
      }
    }
    Ok(Self { table, root })
  }

  /// The record table.
  #[inline]
  #[must_use]
  pub fn table(&self) -> &str {
    self.table.as_str()
  }

  /// The column its root key is held in.
  #[inline]
  #[must_use]
  pub fn root(&self) -> &str {
    self.root.as_str()
  }
}

/// A word whose spelling cannot reach a statement — see [`Generational::new`] and
/// [`CurrentTable::new`].
///
/// # It is NOT [`UnnameableFamily`](crate::UnnameableFamily), and the two are not duplicates
///
/// The retirement ledger's refusal is about a FAMILY, and its sentence says so. This one is wider by
/// necessity: [`Generational::new`] audits a record TABLE and the COLUMN its root key sits in,
/// neither of which is a family, so a family-worded refusal would be the wrong sentence for two of
/// the three doors that raise this. What the two share is the RULE — `slot::is_identifier`, because
/// the word is spliced and an identifier cannot be bound — and the rule is shared as CODE rather
/// than by making one error stand for both.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnnameableTable {
  /// What was written.
  word: Utf8Bytes,
}

impl UnnameableTable {
  /// What was written.
  #[inline]
  #[must_use]
  pub fn word(&self) -> &str {
    self.word.as_str()
  }
}

impl core::fmt::Display for UnnameableTable {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "`{word}` cannot name a table or a column here — it is a bare identifier (ASCII letters, \
       digits and `_`, not digit-leading), because the name is spliced into every statement and an \
       identifier cannot be bound",
      word = self.word,
    )
  }
}

impl core::error::Error for UnnameableTable {}

/// **THE TABLE ONE FAMILY'S POINTERS LIVE IN** — its name, and the five column words every engine
/// spells the same.
///
/// A value rather than an emitted type, for the reason families have: they are OPENED rather than
/// declared (see [`Registries`](crate::Registries)), so the set of pointer tables a deployment has is
/// the set of families something attributed work to — a runtime fact. What the graph word decides is
/// the ENGINE; what the family decides is the NAME.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CurrentTable {
  /// The family — `media`, `track` — as [`Attributes::FAMILY`](crate::Attributes::FAMILY) spells it.
  family: Utf8Bytes,
  /// `__ig_current_<family>`, minted once so every statement reads the same string.
  name: Utf8Bytes,
}

impl CurrentTable {
  /// The column the root key itself is held in.
  pub const ROOT: &'static str = "root";

  /// The column the closure's own word is held in — see [`Scope`].
  pub const SCOPE: &'static str = "scope";

  /// The column the current run is held in.
  pub const RUN: &'static str = "run";

  /// The column holding the flip's whole SECONDS — [`Timestamp`]'s own storage shape, which this
  /// framework already spells as two integers everywhere else a timestamp is a column.
  pub const FLIPPED_SECOND: &'static str = "flipped_second";

  /// The column holding the flip's SUB-SECOND NANOSECONDS — the other half of the pair.
  pub const FLIPPED_NANOSECOND: &'static str = "flipped_nanosecond";

  /// The table `family`'s pointers live in.
  ///
  /// # It REFUSES a family it cannot name — [`Generational::new`]'s audit, for the same reason
  ///
  /// The name is spliced into every statement this seat runs, so `family` must be a bare identifier.
  /// The families a graph actually opens come from [`Attributes::FAMILY`](crate::Attributes::FAMILY),
  /// which is a snake-cased Rust type name and therefore always accepted; this refusal is for the
  /// caller that built one by hand.
  ///
  /// # Errors
  ///
  /// [`UnnameableTable`], carrying what was written.
  pub fn new(family: impl Into<Utf8Bytes>) -> Result<Self, UnnameableTable> {
    let family = family.into();
    if !crate::slot::is_identifier(family.as_bytes()) {
      return Err(UnnameableTable { word: family });
    }
    let name = Utf8Bytes::from(format!("{CURRENT_TABLE_PREFIX}{family}"));
    Ok(Self { family, name })
  }

  /// The family this table points for.
  #[inline]
  #[must_use]
  pub fn family(&self) -> &str {
    self.family.as_str()
  }

  /// `__ig_current_<family>` — the identifier every statement names.
  #[inline]
  #[must_use]
  pub fn name(&self) -> &str {
    self.name.as_str()
  }

  /// The name, as the shared byte string the statements were built over.
  #[inline]
  #[must_use]
  pub fn named(&self) -> Utf8Bytes {
    self.name.clone()
  }
}

/// **WHAT A STORE COULD NOT DO** — one refusal, carrying whatever the engine said underneath.
///
/// One type rather than an associated `Error`, and the seam is what decides it: an
/// `Arc<dyn GenerationsStore<Root>>` cannot project an associated type, and the party holding one —
/// the [`Curator`] — has exactly one thing to do with a failure whatever engine produced it, which is
/// to report it and sweep nothing. So the engine's own error is a SOURCE rather than a variant,
/// reachable by a caller that knows which engine it built.
#[derive(Debug)]
pub struct GenerationsStoreError {
  /// Which verb was refused — `ready`, `point`, `current`, `roll`, `sweep`.
  verb: &'static str,
  /// The table it was refused on.
  table: Utf8Bytes,
  /// What the engine said.
  source: Box<dyn core::error::Error + Send + Sync + 'static>,
}

impl GenerationsStoreError {
  /// The refusal an engine's own error becomes.
  #[must_use]
  pub fn new(
    verb: &'static str,
    table: impl Into<Utf8Bytes>,
    source: impl core::error::Error + Send + Sync + 'static,
  ) -> Self {
    Self {
      verb,
      table: table.into(),
      source: Box::new(source),
    }
  }

  /// Which verb was refused.
  #[inline]
  #[must_use]
  pub const fn verb(&self) -> &'static str {
    self.verb
  }

  /// The table it was refused on.
  #[inline]
  #[must_use]
  pub fn table(&self) -> &str {
    self.table.as_str()
  }
}

impl core::fmt::Display for GenerationsStoreError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "the generations store refused `{verb}` on `{table}`",
      verb = self.verb,
      table = self.table,
    )
  }
}

impl core::error::Error for GenerationsStoreError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    Some(self.source.as_ref())
  }
}

/// **THE ENGINE SEAM**: where one closure's current pointers live, and what collects what they
/// supersede.
///
/// Five verbs, and each is one act. An implementation is written per ENGINE and per closure — a
/// `GenerationsStore<MediaId>` knows its own table and its own roster — so nothing here takes a
/// family argument and nothing here is generic over more than the key.
///
/// # It is a SEAM, and the three shipped engines are its first occupants rather than its definition
///
/// A deployment that keeps its pointers somewhere this framework has never heard of writes this trait
/// and hands the result to [`Curator::new`]. What such a store owes is exactly the five verbs and the
/// one ordering the [`Curator`]'s note names; nothing about SQL, about a pool or about a dialect
/// reaches this declaration.
///
/// # Every verb is FALLIBLE, and a refused `point` sweeps NOTHING
///
/// A store that would not take the pointer leaves the closure looking at its previous generation,
/// which is a deployment one run behind rather than a deployment that lost a run — and a sweep run
/// anyway would delete rows against a bound the pointer never moved to. So the refusal stops the act
/// and is reported; see [`CuratorReport`].
pub trait GenerationsStore<Root>: Send + Sync {
  /// **THE TABLE EXISTS** — create it if it does not, and answer once it does.
  ///
  /// Idempotent, and called on the boot road before anything else. A store whose home needs no
  /// creation — a document collection, a service — answers `Ok` having done nothing, which is the
  /// honest implementation rather than a stub.
  ///
  /// # Errors
  ///
  /// [`GenerationsStoreError`], carrying whatever the engine said.
  fn ready(&self) -> Turning<'_, ()>;

  /// **THE FLIP** — `row`'s closure is looking at `row`'s run, as of `row`'s stamp.
  ///
  /// An UPSERT on `(root, scope)`, whose update sets the run and the stamp: a closure has ONE current
  /// generation, so a second flip replaces the first rather than accumulating beside it.
  ///
  /// # Errors
  ///
  /// [`GenerationsStoreError`], carrying whatever the engine said.
  fn point<'a>(&'a self, row: &'a CurrentRow<Root>) -> Turning<'a, ()>;

  /// **WHICH RUN `key`'s `scope` IS LOOKING AT**, or [`None`] where nothing has flipped it yet.
  ///
  /// `None` is an honest answer rather than a defect: a root nothing has finished analysing has no
  /// current generation, and a read of it is a read of a family that has nothing to say.
  ///
  /// # Errors
  ///
  /// [`GenerationsStoreError`], carrying whatever the engine said.
  fn current<'a>(&'a self, key: &'a Root, scope: &'a Scope) -> Turning<'a, Option<RunId>>;

  /// **EVERY POINTER** — the whole table, for an audit or a boot read.
  ///
  /// Read-all rather than paged, and the shape is the grain's: a row per `(root, scope)` is a
  /// deployment's analysed roots rather than its content.
  ///
  /// # Errors
  ///
  /// [`GenerationsStoreError`], carrying whatever the engine said.
  fn roll(&self) -> Turning<'_, Vec<CurrentRow<Root>>>;

  /// **THE RETENTION DUTY** — drop everything of `key`'s below the newest `keep` generations, where
  /// `current` is the newest one the sweep is allowed to count from.
  ///
  /// Run after every flip and never before one; see the [module note](self) for the ordering and why
  /// its direction is not negotiable.
  ///
  /// # `current` IS THE CEILING, and that is what makes a concurrent run safe
  ///
  /// Retention counted off *the newest runs present in the table* would count a run still being
  /// WRITTEN — a re-analysis whose rows have started landing and whose flip has not — and at
  /// `keep = 1` it would then delete the generation every reader is currently on, in favour of one
  /// that is half there. So the count starts at the run the pointer was just moved to and looks
  /// only DOWNWARDS: nothing at or above `current` is ever a candidate, whatever else the table
  /// holds.
  ///
  /// Total on a root with fewer than `keep` generations below the ceiling: there is nothing beyond
  /// the bound, so the answer is a [`Culled`] of zero rows rather than a refusal.
  ///
  /// # Errors
  ///
  /// [`GenerationsStoreError`], carrying whatever the engine said.
  fn sweep<'a>(&'a self, key: &'a Root, current: RunId, keep: NonZeroUsize) -> Turning<'a, Culled>;
}

/// A store held behind a pointer is a store — so a [`Curator`] may be handed either.
impl<Root, S> GenerationsStore<Root> for Arc<S>
where
  S: GenerationsStore<Root> + ?Sized,
{
  #[inline]
  fn ready(&self) -> Turning<'_, ()> {
    S::ready(self)
  }

  #[inline]
  fn point<'a>(&'a self, row: &'a CurrentRow<Root>) -> Turning<'a, ()> {
    S::point(self, row)
  }

  #[inline]
  fn current<'a>(&'a self, key: &'a Root, scope: &'a Scope) -> Turning<'a, Option<RunId>> {
    S::current(self, key, scope)
  }

  #[inline]
  fn roll(&self) -> Turning<'_, Vec<CurrentRow<Root>>> {
    S::roll(self)
  }

  #[inline]
  fn sweep<'a>(&'a self, key: &'a Root, current: RunId, keep: NonZeroUsize) -> Turning<'a, Culled> {
    S::sweep(self, key, current, keep)
  }
}