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
//! THE SEAT'S OWN SUITE: the run's arithmetic, the words a name has to be, and the ORDERING the
//! whole design rests on.
//!
//! The ordering tests are the ones that matter. Everything else here is a value comparison; those
//! are a store that WRITES DOWN what it was asked to do, in order, so that *the pointer lands before
//! anything is erased* is asserted against a transcript rather than against a comment.

use core::num::NonZeroUsize;

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

use crate::{Timestamp, drive::registry::Flip};

use super::{
  Culled, Curator, CurrentRow, CurrentTable, Generational, GenerationsOptions, GenerationsOverride,
  GenerationsStore, GenerationsStoreError, RunId, Scope, Turning, prepare,
};

// ── The run ─────────────────────────────────────────────────────────────────────────────────────

/// A minted run is above every run minted before it, in this process and in the last one.
#[test]
fn a_minted_run_only_ever_rises() {
  let first = RunId::mint();
  let second = RunId::mint();
  let third = RunId::mint();
  assert!(first < second, "{first} is not below {second}");
  assert!(second < third, "{second} is not below {third}");
  // The SEED is a microsecond reading, so a fresh process starts far above zero rather than at it —
  // which is what makes a restart resume above its predecessor without reading a row.
  assert!(
    first.get() > 1_600_000_000_000_000,
    "a minted run is seeded from the wall clock, and {first} is not"
  );
}

/// The signed crossing a SQL column is, both ways, including a value no mint would produce.
#[test]
fn a_run_crosses_the_signed_boundary_and_comes_back() {
  for raw in [0, 1, 1_756_000_000_000_000, u64::MAX] {
    let run = RunId::new(raw);
    assert_eq!(
      RunId::from_i64(run.as_i64()),
      run,
      "{raw} did not round-trip"
    );
  }
}

// ── The words ───────────────────────────────────────────────────────────────────────────────────

/// The default closure is a WORD rather than an absence — see [`Scope`]'s own note.
#[test]
fn the_default_scope_is_spelled() {
  assert_eq!(Scope::default().as_str(), Scope::WHOLE);
  assert_eq!(Scope::default().to_string(), "whole");
}

/// A scope that could not be read in a schema is refused, and the refusal carries what was written.
#[test]
fn a_scope_is_a_bare_identifier() {
  for word in ["\"; DROP TABLE media; --", "with space", "0leading", ""] {
    let refusal = Scope::new(word).expect_err("this should not name a closure");
    assert_eq!(refusal.word(), word);
  }
  assert!(Scope::new("frames_v2").is_ok());
}

/// The pointer table's name is minted off the family and wears the framework's own stem.
#[test]
fn a_pointer_table_is_named_for_its_family() {
  let table = CurrentTable::new("media").expect("`media` is an identifier");
  assert_eq!(table.family(), "media");
  assert_eq!(table.name(), "__ig_current_media");
  assert_eq!(table.named().as_str(), "__ig_current_media");
}

/// A family that could be spliced into a statement is refused at the one door that mints a name.
#[test]
fn a_family_that_cannot_be_spliced_is_refused() {
  let refusal =
    CurrentTable::new("media\"; DROP TABLE media; --").expect_err("a quote is not an identifier");
  assert_eq!(refusal.word(), "media\"; DROP TABLE media; --");
}

/// Both words of a roster entry are audited, not just the table's.
#[test]
fn a_roster_entry_audits_both_of_its_words() {
  assert!(Generational::new("clip", "media").is_ok());
  assert_eq!(
    Generational::new("clip", "media\" = 1 OR \"1")
      .expect_err("a quote is not an identifier")
      .word(),
    "media\" = 1 OR \"1"
  );
  assert_eq!(
    Generational::new("clip; DROP TABLE media", "media")
      .expect_err("a semicolon is not an identifier")
      .word(),
    "clip; DROP TABLE media"
  );
}

// ── The ordering ────────────────────────────────────────────────────────────────────────────────

/// What a [`Recorder`] was asked to do, in the order it was asked.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Act {
  Ready,
  Point(RunId),
  Roll,
  /// The sweep, with the CEILING it was given and the depth it was given.
  Sweep(RunId, usize),
}

/// A store that writes down what it was asked to do — the instrument every ordering claim below is
/// asserted against.
struct Recorder {
  transcript: Mutex<Vec<Act>>,
  /// Whether `point` refuses, which is what *a refused flip sweeps nothing* is tested with.
  refuse_point: bool,
}

impl Recorder {
  fn new(refuse_point: bool) -> Arc<Self> {
    Arc::new(Self {
      transcript: Mutex::new(Vec::new()),
      refuse_point,
    })
  }

  fn transcript(&self) -> Vec<Act> {
    self.transcript.lock().expect("not poisoned").clone()
  }

  fn wrote(&self, act: Act) {
    self.transcript.lock().expect("not poisoned").push(act);
  }
}

/// A refusal with a source of its own, so the error's whole chain is exercised too.
fn refusal(verb: &'static str) -> GenerationsStoreError {
  GenerationsStoreError::new(
    verb,
    "__ig_current_media",
    std::io::Error::other("the engine said no"),
  )
}

impl GenerationsStore<u64> for Recorder {
  fn ready(&self) -> Turning<'_, ()> {
    Box::pin(async move {
      self.wrote(Act::Ready);
      Ok(())
    })
  }

  fn point<'a>(&'a self, row: &'a CurrentRow<u64>) -> Turning<'a, ()> {
    Box::pin(async move {
      self.wrote(Act::Point(row.run()));
      if self.refuse_point {
        return Err(refusal("point"));
      }
      Ok(())
    })
  }

  fn current<'a>(&'a self, _key: &'a u64, _scope: &'a Scope) -> Turning<'a, Option<RunId>> {
    Box::pin(async move { Ok(None) })
  }

  fn roll(&self) -> Turning<'_, Vec<CurrentRow<u64>>> {
    Box::pin(async move {
      self.wrote(Act::Roll);
      Ok(Vec::new())
    })
  }

  fn sweep<'a>(&'a self, _key: &'a u64, current: RunId, keep: NonZeroUsize) -> Turning<'a, Culled> {
    Box::pin(async move {
      self.wrote(Act::Sweep(current, keep.get()));
      Ok(Culled { tables: 2, rows: 5 })
    })
  }
}

/// A curator over `store`, holding on to the seat so a hand-driven body's line stays open.
fn seated(
  store: Arc<Recorder>,
  options: GenerationsOptions,
) -> (Curator<u64>, super::CuratorBody<u64>) {
  Curator::new(
    store as Arc<dyn GenerationsStore<u64>>,
    Scope::default(),
    options,
  )
}

/// **THE ORDERING**: the pointer lands, and only then is anything collected behind it.
#[tokio::test]
async fn the_pointer_lands_before_anything_is_erased() {
  let store = Recorder::new(false);
  let (_seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
  let run = RunId::new(42);
  body
    .perform(&1, Flip::new(run, Timestamp::UNIX_EPOCH))
    .await;
  assert_eq!(
    store.transcript(),
    vec![Act::Point(run), Act::Sweep(run, 1)],
    "the sweep must follow the flip and never precede it"
  );
  let report = body.report();
  assert_eq!(report.flipped, 1);
  assert_eq!(report.swept, 5);
  assert_eq!(report.refused, 0);
}

/// **THE CEILING**: the sweep is given the run the flip just made durable, not the newest run in the
/// table — which is what keeps a concurrent re-analysis safe.
#[tokio::test]
async fn the_sweep_is_anchored_on_the_run_that_landed() {
  let store = Recorder::new(false);
  let (_seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
  for run in [10, 20, 30] {
    body
      .perform(&1, Flip::new(RunId::new(run), Timestamp::UNIX_EPOCH))
      .await;
  }
  assert_eq!(
    store.transcript(),
    vec![
      Act::Point(RunId::new(10)),
      Act::Sweep(RunId::new(10), 1),
      Act::Point(RunId::new(20)),
      Act::Sweep(RunId::new(20), 1),
      Act::Point(RunId::new(30)),
      Act::Sweep(RunId::new(30), 1),
    ]
  );
}

/// **A REFUSED FLIP ERASES NOTHING** — the sweep is not reached at all, and the refusal is counted.
#[tokio::test]
async fn a_refused_flip_sweeps_nothing() {
  let store = Recorder::new(true);
  let (_seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
  body
    .perform(&1, Flip::new(RunId::new(9), Timestamp::UNIX_EPOCH))
    .await;
  assert_eq!(
    store.transcript(),
    vec![Act::Point(RunId::new(9))],
    "a `DELETE` must not follow a pointer that did not land"
  );
  let report = body.report();
  assert_eq!(report.flipped, 0);
  assert_eq!(report.swept, 0);
  assert_eq!(report.refused, 1);
}

/// The depth is read PER ACT, which is what makes the third tier a live dial rather than a value
/// frozen when the curator was built.
#[tokio::test]
async fn the_retention_depth_is_read_at_every_flip() {
  let store = Recorder::new(false);
  let (seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
  body
    .perform(&1, Flip::new(RunId::new(1), Timestamp::UNIX_EPOCH))
    .await;
  seat.apply_knobs(&GenerationsOverride::new().with_keep(NonZeroUsize::new(4).expect("not zero")));
  body
    .perform(&1, Flip::new(RunId::new(2), Timestamp::UNIX_EPOCH))
    .await;
  assert_eq!(
    store.transcript(),
    vec![
      Act::Point(RunId::new(1)),
      Act::Sweep(RunId::new(1), 1),
      Act::Point(RunId::new(2)),
      Act::Sweep(RunId::new(2), 4),
    ]
  );
  assert_eq!(seat.options().keep().get(), 4);
}

/// An override that names nothing changes nothing — the fold's own law, one seat over.
#[test]
fn an_override_that_names_nothing_moves_no_knob() {
  let store = Recorder::new(false);
  let (seat, _body) = seated(
    store,
    GenerationsOptions::new().with_keep(NonZeroUsize::new(3).expect("not zero")),
  );
  seat.apply_knobs(&GenerationsOverride::new());
  assert_eq!(seat.options().keep().get(), 3);
}

/// The boot road makes the table and then counts what is in it, in that order.
#[tokio::test]
async fn the_boot_road_readies_before_it_rolls() {
  let store = Recorder::new(false);
  let held = prepare::<u64>(store.as_ref())
    .await
    .expect("nothing refused");
  assert_eq!(held, 0);
  assert_eq!(store.transcript(), vec![Act::Ready, Act::Roll]);
}

/// A refusal names the verb and the table, and carries the engine's own words underneath.
#[test]
fn a_refusal_names_the_verb_and_keeps_the_engine_underneath() {
  let refusal = refusal("point");
  assert_eq!(refusal.verb(), "point");
  assert_eq!(refusal.table(), "__ig_current_media");
  assert_eq!(
    refusal.to_string(),
    "the generations store refused `point` on `__ig_current_media`"
  );
  assert!(core::error::Error::source(&refusal).is_some());
}

// ── The statements ──────────────────────────────────────────────────────────────────────────────
//
// Each of the three is `#[tokio::test]` and awaits nothing. A LAZY pool still spawns sqlx's own
// maintenance task at construction, so a runtime has to be in scope to build the store whose
// statements are being read — no connection is opened and no statement is run.

/// The pointer table's DDL, its flip and its sweep, at SQLite — the shape a schema review reads.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_sqlite_statements_are_what_the_module_note_says() {
  use super::{SqlGenerations, current_filter};

  let table = CurrentTable::new("media").expect("`media` is an identifier");
  let clip = Generational::new("clip", "media").expect("both are identifiers");
  let store = SqlGenerations::<sqlx::Sqlite, u64>::new(
    sqlx::Pool::connect_lazy("sqlite::memory:").expect("a lazy pool opens nothing"),
    "media",
    vec![clip.clone()],
  )
  .expect("`media` is an identifier");

  assert_eq!(store.table().name(), "__ig_current_media");
  assert!(
    store
      .create_statement()
      .starts_with("CREATE TABLE IF NOT EXISTS \"__ig_current_media\" ("),
    "{create}",
    create = store.create_statement()
  );
  assert!(
    store
      .create_statement()
      .ends_with("PRIMARY KEY (\"root\", \"scope\"))"),
    "the pointer's grain is the pair: {create}",
    create = store.create_statement()
  );
  assert_eq!(
    store.point_statement(),
    "INSERT INTO \"__ig_current_media\" (\"root\", \"scope\", \"run\", \"flipped_second\", \
     \"flipped_nanosecond\") VALUES (?, ?, ?, ?, ?) ON CONFLICT (\"root\", \"scope\") DO UPDATE \
     SET \"run\" = excluded.\"run\", \"flipped_second\" = excluded.\"flipped_second\", \
     \"flipped_nanosecond\" = excluded.\"flipped_nanosecond\""
  );
  assert_eq!(
    store.current_statement(),
    "SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = ? AND \"scope\" = ?"
  );

  // THE SWEEP: the ceiling is bound, the depth is spliced, and the inner `FROM` is a derived table.
  let swept = store.sweep_statement(&clip, NonZeroUsize::new(2).expect("not zero"));
  assert_eq!(
    swept,
    "DELETE FROM \"clip\" WHERE \"media\" = ? AND \"__ig_run__\" < (SELECT MIN(r) FROM (SELECT \
     DISTINCT \"__ig_run__\" AS r FROM \"clip\" WHERE \"media\" = ? AND \"__ig_run__\" <= ? ORDER \
     BY r DESC LIMIT 2) AS kept)"
  );

  // THE READ FILTER: an anchored subquery correlated on the record's own root column.
  assert_eq!(
    current_filter::<sqlx::Sqlite>("clip", "media", &table, 1),
    "\"clip\".\"__ig_run__\" = (SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = \
     \"clip\".\"media\" AND \"scope\" = ?)"
  );
}

/// PostgreSQL is the one dialect that COUNTS its parameters, and every statement has to agree.
#[cfg(feature = "postgres")]
#[tokio::test]
async fn postgres_numbers_every_marker() {
  use super::{SqlGenerations, current_filter};

  let table = CurrentTable::new("media").expect("`media` is an identifier");
  let clip = Generational::new("clip", "media").expect("both are identifiers");
  let store = SqlGenerations::<sqlx::Postgres, u64>::new(
    sqlx::Pool::connect_lazy("postgres://user@localhost/db").expect("a lazy pool opens nothing"),
    "media",
    vec![clip.clone()],
  )
  .expect("`media` is an identifier");

  assert!(
    store
      .point_statement()
      .contains("VALUES ($1, $2, $3, $4, $5)"),
    "{point}",
    point = store.point_statement()
  );
  assert!(
    store
      .point_statement()
      .contains("DO UPDATE SET \"run\" = EXCLUDED.\"run\""),
    "{point}",
    point = store.point_statement()
  );
  assert_eq!(
    store.current_statement(),
    "SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = $1 AND \"scope\" = $2"
  );
  // THREE binds in one order for every dialect, so one body can do the binding for all of them —
  // PostgreSQL could reuse `$1` and deliberately does not.
  let swept = store.sweep_statement(&clip, NonZeroUsize::new(1).expect("not zero"));
  assert!(swept.contains("\"media\" = $1"), "{swept}");
  assert!(swept.contains("\"media\" = $2"), "{swept}");
  assert!(swept.contains("\"__ig_run__\" <= $3"), "{swept}");
  assert!(swept.ends_with("LIMIT 1) AS kept)"), "{swept}");
  assert_eq!(
    current_filter::<sqlx::Postgres>("clip", "media", &table, 7),
    "\"clip\".\"__ig_run__\" = (SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = \
     \"clip\".\"media\" AND \"scope\" = $7)"
  );
}

/// MySQL brackets with backticks and names no conflict target — one table, one unique key.
#[cfg(feature = "mysql")]
#[tokio::test]
async fn mysql_brackets_with_backticks_and_names_no_target() {
  use super::SqlGenerations;

  let clip = Generational::new("clip", "media").expect("both are identifiers");
  let store = SqlGenerations::<sqlx::MySql, u64>::new(
    sqlx::Pool::connect_lazy("mysql://user@localhost/db").expect("a lazy pool opens nothing"),
    "media",
    vec![clip.clone()],
  )
  .expect("`media` is an identifier");

  assert!(
    store.point_statement().contains(
      "ON DUPLICATE KEY UPDATE `run` = VALUES(`run`), `flipped_second` = \
       VALUES(`flipped_second`), `flipped_nanosecond` = VALUES(`flipped_nanosecond`)"
    ),
    "{point}",
    point = store.point_statement()
  );
  let swept = store.sweep_statement(&clip, NonZeroUsize::new(1).expect("not zero"));
  assert!(
    swept.contains("FROM (SELECT DISTINCT `__ig_run__` AS r FROM `clip`"),
    "the inner FROM is a DERIVED TABLE, which is what makes it legal on MySQL: {swept}"
  );
  assert!(swept.ends_with("AS kept)"), "{swept}");
}