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
//! What the TABLES say: a family opened once, two families kept apart by their types, the options a
//! family resolves to, and the seat a durable act goes to.
//!
//! The transitions themselves are the [state suite](super::super::state)'s subject and are not
//! re-litigated here — what is here is everything the tables add around them.

use core::time::Duration;

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

use super::{
  Registries, Registry, RetireOrigin, RetiredLedger, Retirement, RootAdvance, RootState, Stamp,
};
use crate::{RegistryOptions, RegistryOverride};

/// One root family's key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MediaId(u64);

/// A SECOND family, so that *typed all the way down* is something a test can fail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct TrackId(u64);

/// A ledger that keeps what it was handed, so the acts a transition earns can be read back.
#[derive(Debug, Default)]
struct Kept(Mutex<Vec<(MediaId, Retirement)>>);

impl Kept {
  fn acts(&self) -> Vec<(MediaId, Retirement)> {
    self
      .0
      .lock()
      .unwrap_or_else(|held| held.into_inner())
      .clone()
  }
}

impl RetiredLedger<MediaId> for Kept {
  fn owed(&self, key: &MediaId, act: Retirement) {
    self
      .0
      .lock()
      .unwrap_or_else(|held| held.into_inner())
      .push((*key, act));
  }
}

/// A ledger that READS THE REGISTRY BACK from inside `owed`, which is what proves the acts are
/// spent with no stripe held.
struct Reentrant(Mutex<Vec<RootState>>, Mutex<Option<Arc<Registry<MediaId>>>>);

impl RetiredLedger<MediaId> for Reentrant {
  fn owed(&self, key: &MediaId, _act: Retirement) {
    let table = self.1.lock().unwrap_or_else(|held| held.into_inner());
    let Some(registry) = table.as_ref() else {
      return;
    };
    // If the act were handed over under `key`'s own stripe, this would deadlock rather than answer.
    let state = registry.state(key);
    self
      .0
      .lock()
      .unwrap_or_else(|held| held.into_inner())
      .push(state);
  }
}

// ── One family's table ──────────────────────────────────────────────────────────────────────────

/// An untouched family holds nothing, and every key in it is idle.
#[test]
fn an_untouched_family_is_empty_and_idle() {
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  assert!(registry.is_empty());
  assert_eq!(registry.held(), 0);
  assert_eq!(registry.state(&MediaId(1)), RootState::Idle);
  assert!(!registry.is_recorded());
}

/// A key the table is holding something for is COUNTED, and one that comes back to idle is dropped
/// — the absence and the idle state being one fact.
#[test]
fn the_table_holds_only_what_is_true_of_a_key() {
  let at = Stamp::now();
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  let key = MediaId(7);

  assert_eq!(registry.dispatched(&key, at), RootAdvance::Moved);
  assert_eq!(registry.held(), 1);
  assert!(matches!(
    registry.state(&key),
    RootState::Analyzing { inflight: 1, .. }
  ));

  assert_eq!(registry.observed(&key, at), RootAdvance::Moved);
  assert_eq!(registry.state(&key), RootState::Idle);
  assert_eq!(
    registry.held(),
    0,
    "a key back at idle leaves the table rather than sitting in it saying nothing"
  );
}

/// A retirement lands, is held, and comes back.
#[test]
fn a_retirement_lands_and_is_restored() {
  let at = Stamp::now();
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  let key = MediaId(3);

  assert_eq!(
    registry.retire(&key, RetireOrigin::Vanished, at),
    RootAdvance::Moved
  );
  assert!(matches!(
    registry.state(&key),
    RootState::Retired {
      origin: RetireOrigin::Vanished,
      ..
    }
  ));
  assert_eq!(registry.held(), 1);

  assert_eq!(registry.reappear(&key, at), RootAdvance::Moved);
  assert_eq!(registry.state(&key), RootState::Restoring);

  assert_eq!(registry.restored(&key, at), RootAdvance::Moved);
  assert_eq!(registry.state(&key), RootState::Idle);
  assert_eq!(registry.held(), 0);
}

/// Two keys in one family do not see each other.
#[test]
fn keys_in_one_family_are_independent() {
  let at = Stamp::now();
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  assert_eq!(
    registry.retire(&MediaId(1), RetireOrigin::User, at),
    RootAdvance::Moved
  );
  assert_eq!(registry.dispatched(&MediaId(2), at), RootAdvance::Moved);

  assert!(matches!(
    registry.state(&MediaId(1)),
    RootState::Retired { .. }
  ));
  assert!(matches!(
    registry.state(&MediaId(2)),
    RootState::Analyzing { .. }
  ));
  assert_eq!(registry.state(&MediaId(3)), RootState::Idle);
  assert_eq!(registry.held(), 2);
}

// ── The ledger seat ─────────────────────────────────────────────────────────────────────────────

/// The acts a transition earns reach the seated ledger, keyed by the key they are about.
#[test]
fn the_seated_ledger_takes_the_acts() {
  let at = Stamp::now();
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  let kept = Arc::new(Kept::default());
  assert!(registry.installing(Arc::clone(&kept) as Arc<dyn RetiredLedger<MediaId>>));
  assert!(registry.is_recorded());

  let key = MediaId(5);
  assert_eq!(
    registry.retire(&key, RetireOrigin::Vanished, at),
    RootAdvance::Moved
  );
  assert_eq!(registry.reappear(&key, at), RootAdvance::Moved);

  assert_eq!(
    kept.acts(),
    vec![
      (
        key,
        Retirement::Recorded {
          at: at.wall(),
          origin: RetireOrigin::Vanished,
          late_tails: false,
        }
      ),
      (key, Retirement::Erased),
    ]
  );
}

/// A family with no ledger seated still transitions — the acts simply go nowhere, which is exactly
/// the posture of a knife that exposes the seat and wires nothing to it.
#[test]
fn an_unseated_family_still_transitions() {
  let at = Stamp::now();
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  assert_eq!(
    registry.retire(&MediaId(9), RetireOrigin::User, at),
    RootAdvance::Moved
  );
  assert!(matches!(
    registry.state(&MediaId(9)),
    RootState::Retired { .. }
  ));
}

/// ONE writer per family: a second offer is refused and the first keeps the seat.
#[test]
fn the_ledger_seat_takes_one_occupant() {
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  let first = Arc::new(Kept::default());
  let second = Arc::new(Kept::default());

  assert!(registry.installing(Arc::clone(&first) as Arc<dyn RetiredLedger<MediaId>>));
  assert!(
    !registry.installing(Arc::clone(&second) as Arc<dyn RetiredLedger<MediaId>>),
    "a second writer for one family's rows is refused rather than replacing the first"
  );

  assert_eq!(
    registry.retire(&MediaId(1), RetireOrigin::User, Stamp::now()),
    RootAdvance::Moved
  );
  assert_eq!(first.acts().len(), 1);
  assert_eq!(second.acts().len(), 0);
}

/// The acts are spent with NO STRIPE HELD, so a ledger may read the registry back. A regression
/// here does not fail — it hangs — which is why the assertion is on the answer rather than on the
/// return.
#[test]
fn the_ledger_is_spent_outside_the_lock() {
  let registry = Arc::new(Registry::<MediaId>::new(RegistryOptions::new()));
  let ledger = Arc::new(Reentrant(Mutex::new(Vec::new()), Mutex::new(None)));
  *ledger.1.lock().expect("fresh") = Some(Arc::clone(&registry));
  assert!(registry.installing(Arc::clone(&ledger) as Arc<dyn RetiredLedger<MediaId>>));

  assert_eq!(
    registry.retire(&MediaId(2), RetireOrigin::User, Stamp::now()),
    RootAdvance::Moved
  );
  let seen = ledger.0.lock().expect("fresh").clone();
  assert!(
    matches!(seen.as_slice(), [RootState::Retired { .. }]),
    "the ledger read the state the act had already produced: {seen:?}"
  );
}

// ── Registries: the families ────────────────────────────────────────────────────────────────────

/// Nothing is open until something opens it, and the read door mints nothing.
#[test]
fn a_fresh_registries_has_no_families() {
  let registries = Registries::default();
  assert!(registries.is_empty());
  assert_eq!(registries.families(), 0);
  assert!(registries.of::<MediaId>().is_none());
  assert_eq!(
    registries.families(),
    0,
    "the read door does not mint a family"
  );
}

/// A family is opened once and handed back ever after — the same table, not a second one.
#[test]
fn a_family_is_opened_once() {
  let registries = Registries::default();
  let first = registries.open::<MediaId>("media");
  let second = registries.open::<MediaId>("media");
  assert!(Arc::ptr_eq(&first, &second));
  assert_eq!(registries.families(), 1);

  let read = registries.of::<MediaId>().expect("it is open");
  assert!(Arc::ptr_eq(&first, &read));

  // And what one holder writes, every holder sees.
  assert_eq!(
    first.retire(&MediaId(4), RetireOrigin::User, Stamp::now()),
    RootAdvance::Moved
  );
  assert!(matches!(
    second.state(&MediaId(4)),
    RootState::Retired { .. }
  ));
}

/// TWO families are two tables, told apart by their key TYPES and nothing else.
#[test]
fn families_are_kept_apart_by_their_types() {
  let registries = Registries::default();
  let media = registries.open::<MediaId>("media");
  let track = registries.open::<TrackId>("track");
  assert_eq!(registries.families(), 2);

  assert_eq!(
    media.retire(&MediaId(1), RetireOrigin::User, Stamp::now()),
    RootAdvance::Moved
  );
  assert_eq!(media.held(), 1);
  assert_eq!(
    track.held(),
    0,
    "a key in one family is nothing at all in another"
  );
  assert_eq!(track.state(&TrackId(1)), RootState::Idle);
}

/// A family resolves against the document the whole registries value was built with — the
/// `[registry.media]` override reaching the family that names it and no other.
#[test]
fn a_family_resolves_its_own_override() {
  let one_second = Duration::from_secs(1);
  let options = RegistryOptions::new()
    .with_debounce(Duration::from_millis(50))
    .with_family("media", RegistryOverride::new().with_debounce(one_second));
  let registries = Registries::new(options);

  assert_eq!(
    registries.open::<MediaId>("media").options().debounce(),
    one_second
  );
  assert_eq!(
    registries.open::<TrackId>("track").options().debounce(),
    Duration::from_millis(50),
    "a family nobody wrote an override for reads the defaults"
  );
}

/// A family opened with no name reads the shipped defaults, which is what an unwritten section
/// already means — see [`Attributes::FAMILY`](crate::Attributes::FAMILY), whose own default is the
/// empty string.
#[test]
fn an_unnamed_family_reads_the_defaults() {
  let registries = Registries::new(RegistryOptions::new().with_debounce(Duration::from_millis(70)));
  assert_eq!(
    registries.open::<MediaId>("").options().debounce(),
    Duration::from_millis(70)
  );
}

/// The name is read on the FIRST ask: a family already in use is not re-tuned by whoever asks next.
#[test]
fn a_second_open_does_not_retune_a_family() {
  let options = RegistryOptions::new()
    .with_debounce(Duration::from_millis(10))
    .with_family(
      "media",
      RegistryOverride::new().with_debounce(Duration::from_secs(2)),
    );
  let registries = Registries::new(options);

  assert_eq!(
    registries.open::<MediaId>("media").options().debounce(),
    Duration::from_secs(2)
  );
  assert_eq!(
    registries.open::<MediaId>("nowhere").options().debounce(),
    Duration::from_secs(2)
  );
}

/// The document is kept whole, so a family opened later resolves against the same one the first
/// did.
#[test]
fn the_document_is_kept_whole() {
  let options = RegistryOptions::new().with_family("media", RegistryOverride::new());
  let registries = Registries::new(options.clone());
  assert_eq!(registries.options(), &options);
}

/// Every door on both types takes `&self`: a table shared by reference is fully usable, which is
/// what *the registry owns its interior mutability* means in practice.
#[test]
fn a_shared_table_is_a_usable_table() {
  let registries = Arc::new(Registries::default());
  let mine = Arc::clone(&registries);
  let table = mine.open::<MediaId>("media");
  assert_eq!(
    table.dispatched(&MediaId(11), Stamp::now()),
    RootAdvance::Moved
  );
  assert!(matches!(
    registries
      .of::<MediaId>()
      .expect("open")
      .state(&MediaId(11)),
    RootState::Analyzing { .. }
  ));
}

// ── The bounded drain ───────────────────────────────────────────────────────────────────────────

/// **THE SWEEP SPENDS THE CEILING.** A key that has been draining for longer than `retire_drain`
/// retires anyway, flagged, and one that has not is left alone.
#[test]
fn a_lapse_takes_only_the_drains_that_ran_out_of_window() {
  let registry =
    Registry::<MediaId>::new(RegistryOptions::new().with_retire_drain(Duration::from_secs(30)));
  let opened = Stamp::now();
  let stale = MediaId(1);
  let fresh = MediaId(2);
  for key in [stale, fresh] {
    assert_eq!(registry.dispatched(&key, opened), RootAdvance::Moved);
    assert_eq!(
      registry.retire(&key, RetireOrigin::Vanished, opened),
      RootAdvance::Moved
    );
  }
  // The FRESH one starts its drain half a minute later, so one window from now covers the first
  // and not the second.
  let restarted = Stamp::new(
    opened.monotonic() + Duration::from_secs(40),
    crate::Timestamp::UNIX_EPOCH,
    opened.run(),
  );

  assert_eq!(
    registry.lapse(Stamp::new(
      opened.monotonic() + Duration::from_secs(20),
      crate::Timestamp::UNIX_EPOCH,
      opened.run()
    )),
    Vec::new(),
    "twenty seconds is inside a thirty-second window"
  );

  let spent = restarted;
  let lapsed = registry.lapse(spent);
  assert_eq!(
    lapsed.len(),
    2,
    "both are past the window by now: {lapsed:?}"
  );
  for key in [stale, fresh] {
    assert!(
      registry.state(&key).has_late_tails(),
      "{key:?} went out with work still owed"
    );
    assert_eq!(registry.inflight(&key), 0, "a retired key has nothing out");
  }
}

/// A lapse hands its durable acts to the ledger, and it hands them over with NO stripe held — the
/// same guarantee an ordinary transition gives, widened to a walk.
#[test]
fn a_lapse_pays_the_ledger_after_the_walk() {
  let registry = Registry::<MediaId>::new(RegistryOptions::new().with_retire_drain(Duration::ZERO));
  let kept = Arc::new(Kept::default());
  assert!(registry.installing(Arc::clone(&kept) as Arc<dyn RetiredLedger<MediaId>>));

  let at = Stamp::now();
  let key = MediaId(9);
  assert_eq!(registry.dispatched(&key, at), RootAdvance::Moved);
  assert_eq!(
    registry.retire(&key, RetireOrigin::User, at),
    RootAdvance::Moved
  );
  assert_eq!(registry.lapse(at), vec![key]);

  assert_eq!(
    kept.acts(),
    vec![(
      key,
      Retirement::Recorded {
        at: at.wall(),
        origin: RetireOrigin::User,
        late_tails: true,
      }
    )]
  );
}

/// A lapse over a family with nothing draining is a walk that finds nothing — no act, no change,
/// and no cost beyond the stripes it looked at.
#[test]
fn a_lapse_over_a_quiet_family_does_nothing() {
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  let at = Stamp::now();
  assert_eq!(registry.dispatched(&MediaId(3), at), RootAdvance::Moved);
  assert_eq!(registry.lapse(at), Vec::new());
  assert!(matches!(
    registry.state(&MediaId(3)),
    RootState::Analyzing { .. }
  ));
  assert_eq!(registry.held(), 1);
}

/// The count a family holds is what the two counting doors say it is, and `inflight` is the reading
/// of it — the door the query face and every walk in the driver suite ask through.
#[test]
fn inflight_is_the_difference_between_the_two_counting_doors() {
  let registry = Registry::<MediaId>::new(RegistryOptions::new());
  let at = Stamp::now();
  let key = MediaId(4);
  assert_eq!(registry.inflight(&key), 0, "an idle key has nothing out");

  for _ in 0..3 {
    assert_eq!(registry.dispatched(&key, at), RootAdvance::Moved);
  }
  assert_eq!(registry.inflight(&key), 3);
  assert_eq!(registry.observed(&key, at), RootAdvance::Moved);
  assert_eq!(registry.inflight(&key), 2);

  for _ in 0..2 {
    assert_eq!(registry.observed(&key, at), RootAdvance::Moved);
  }
  assert_eq!(registry.inflight(&key), 0);
  assert_eq!(
    registry.state(&key),
    RootState::Idle,
    "zero is what ends the analysis"
  );
  assert!(registry.is_empty(), "and an idle key leaves the table");
}

// ── The counting seat's own refusal ─────────────────────────────────────────────────────────────

/// **THE UNIT ROOT IS NOT A FAMILY.** `counting` opens a real one and refuses the absence, which is
/// what keeps every unattributed node in a deployment from piling into one erased key.
#[test]
fn counting_opens_a_real_family_and_refuses_the_unit() {
  let registries = Registries::default();
  assert!(
    registries.counting::<MediaId>("media").is_some(),
    "a real root is a real family"
  );
  assert!(
    registries.counting::<()>("").is_none(),
    "the unit root is the absence of a projection, not a family of one"
  );
  assert_eq!(registries.families(), 1, "and the refusal opened nothing");
}

/// `counting` OPENS where `of` only reads: a dispatch is what mints a family, so a counting site
/// that could only read would find nothing to count into for as long as it ran.
#[test]
fn counting_mints_the_family_that_of_would_have_missed() {
  let registries = Registries::default();
  assert!(registries.of::<MediaId>().is_none());
  let family = registries
    .counting::<MediaId>("media")
    .expect("a real root");
  assert_eq!(
    family.dispatched(&MediaId(1), Stamp::now()),
    RootAdvance::Moved
  );
  assert_eq!(
    registries
      .of::<MediaId>()
      .expect("now open")
      .inflight(&MediaId(1)),
    1,
    "the same table, reachable by the read that mints nothing"
  );
}