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
//! The full-text walk, live: Tantivy indexes the segments, SQLite stores them, and the retrieve
//! face answers with whole entities.

use core::num::NonZeroUsize;

use sqlx::Sqlite;

use super::corpus::{
  SEEDED, Segment, SegmentFilter, SegmentKey, SegmentRow, forget, shorter_than, store,
};
use crate::{
  Connected, Field, FulltextRecord, FulltextStore, FulltextSubset, FulltextTable, Identifiable,
  Ranked, SlotHandle, SlotName, TantivyDoc, TantivyFulltext, TantivyStore, Transformer,
  retrieve::{
    EqSeen, FulltextQuery, HashSeen, RetrieveError, Seen, SqlGather, filled, keyed, ranked_keys,
  },
};

/// The DERIVED INDEX, written as its expansion writes it: the upstream's key carried whole, and one
/// declared field read out of the upstream.
///
/// ```ignore
/// #[ingraph::fulltext(upstream(node = "Segment", body = "transcript"), dedup(hash))]
/// pub struct Transcript {
///   #[ingraph(searchable)]
///   body: String,
/// }
/// ```
pub(super) struct Transcript {
  /// The injected key field — `γ′`, the one field the expansion adds.
  key: SegmentKey,
  body: String,
}

impl Transcript {
  fn of(media: &str, id: i64, body: &str) -> Self {
    Self {
      key: SegmentKey {
        media: media.to_owned(),
        id,
      },
      body: body.to_owned(),
    }
  }
}

impl Identifiable for Transcript {
  type Id = <SegmentKey as Identifiable>::Id;

  fn id_ref(&self) -> &i64 {
    Identifiable::id_ref(&self.key)
  }
}

impl Transformer for Transcript {
  type Key = SegmentKey;
  type Lineage = <Segment as Transformer>::Lineage;
  type Record = ();
  type Graphql = ();

  fn key(&self) -> SegmentKey {
    self.key.clone()
  }
}

impl FulltextRecord for Transcript {
  type Document = String;

  fn document(&self) -> &String {
    &self.body
  }
}

impl FulltextTable for Transcript {
  const SLOT: &'static SlotName = SlotName::new("transcript");
}

// The key's STRUCTURE row lives in `super::corpus`, beside the key — ONE impl, engine-blind, shared
// by this file's tantivy walk and the vector walk beside it. The retired per-engine row family is
// what made a second one necessary here.

/// THE EMISSION, by hand: a record flattened into the engine's own entry — the source word off its
/// own const, the id into the identity, the key into the stored address, the document into the body.
fn entry<R>(record: &R) -> TantivyDoc
where
  R: FulltextTable + FulltextRecord<Document: AsRef<str>>,
  R::Id: Field,
  R::Key: Field,
{
  TantivyDoc::new(R::SLOT.as_ref())
    .with_identity(record.id_ref())
    .with_address(&record.key())
    .with_body(record.document().as_ref())
}

/// An index holding the seeded corpus, plus whatever `extra` documents a test wants beside it —
/// which is how a DUPLICATE key reaches the hit stream without a backend that mis-replaces.
pub(super) async fn index(
  extra: &[Transcript],
) -> (
  tempfile::TempDir,
  TantivyStore,
  SlotHandle<TantivyFulltext, Transcript>,
) {
  let dir = tempfile::tempdir().expect("a temporary directory");
  let store = TantivyStore::open(dir.path()).expect("the store opens");
  // MINTED here, which is the fixture standing in for the launch walk: this handle was opened on
  // `Transcript::SLOT`, and the brand is that fact said once.
  let mut face = SlotHandle::<_, Transcript>::mint(store.fulltext("transcript"));
  {
    let mut writer = store
      .writer("transcript", TantivyStore::MIN_WRITER_HEAP_BYTES)
      .expect("the slot's writer opens");
    for (media, id, transcript, _) in SEEDED {
      face
        .upsert_document(
          Connected::new(&store, &mut writer),
          entry(&Transcript::of(media, *id, transcript)),
        )
        .await
        .expect("the document queues");
    }
    for document in extra {
      face
        .upsert_document(Connected::new(&store, &mut writer), entry(document))
        .await
        .expect("the document queues");
    }
    writer.commit().expect("the batch commits");
  }
  store.reload("transcript").expect("the reader reloads");
  (dir, store, face)
}

/// TIER A, exactly as the emitted inherent method spells it: the engine call, then the one shared
/// core with this node's dedup mechanism named.
pub(super) async fn retrieve_keys<D>(
  slot: &mut SlotHandle<TantivyFulltext, Transcript>,
  store: &TantivyStore,
  query: &FulltextQuery<f32>,
  limit: usize,
) -> Vec<Ranked<SegmentKey, f32>>
where
  D: Seen<SegmentKey>,
{
  // THE ZERO FORK, spelled exactly as the emission spells it: the door's `usize` becomes the seam's
  // `k` above the engine, or the empty answer is returned without crossing it.
  let Some(k) = NonZeroUsize::new(limit) else {
    return Vec::new();
  };
  let hits = slot
    .search(
      Connected::new(store, ()),
      FulltextSubset::All,
      query.text(),
      k,
      None,
    )
    .await
    .expect("the search runs");
  // bytes → Key, the emission's own line: the engine answered with its addresses, and the key type
  // is named HERE because here is where it is known.
  let hits = keyed::<TantivyFulltext, SegmentKey>(hits).expect("the addresses read back");
  ranked_keys::<_, _, D>(hits, query.floor(), limit)
}

/// TIER B, exactly as the emitted inherent method spells it: tier A unbounded, then the fill loop
/// over the SQL gather.
async fn retrieve(
  slot: &mut SlotHandle<TantivyFulltext, Transcript>,
  index: &TantivyStore,
  db: &mut sqlx::sqlite::SqliteConnection,
  query: &FulltextQuery<f32>,
  filter: Option<&SegmentFilter<Sqlite>>,
  limit: usize,
) -> Result<
  Vec<Ranked<Segment, f32>>,
  RetrieveError<crate::TantivyFulltextError, crate::query::sql::SqlQueryError>,
> {
  let ranked = retrieve_keys::<HashSeen<_>>(slot, index, query, usize::MAX).await;
  let mut gather = SqlGather::<SegmentRow, Sqlite>::new(db);
  filled(ranked, &mut gather, filter, limit)
    .await
    .map_err(RetrieveError::Gather)
}

fn ids(page: &[Ranked<Segment, f32>]) -> Vec<i64> {
  page.iter().map(|hit| hit.node_ref().id).collect()
}

fn ranks(page: &[Ranked<Segment, f32>]) -> Vec<u64> {
  page.iter().map(Ranked::rank).collect()
}

/// **The multilingual claim, live.** The query is the English word `sunset`; the German and the
/// French segments contain it verbatim and are first-class hits. Nothing in the pipeline asked what
/// language anything was in.
#[tokio::test]
async fn a_german_row_holding_the_english_term_is_a_hit() {
  let (_dir, index, mut engine) = index(&[]).await;

  let ranked = retrieve_keys::<HashSeen<_>>(
    &mut engine,
    &index,
    &FulltextQuery::new("sunset", 0.0_f32),
    usize::MAX,
  )
  .await;

  let mut hit: Vec<i64> = ranked.iter().map(|hit| hit.node_ref().id).collect();
  hit.sort_unstable();
  // Every segment whose text carries the word — 5 is the heron and is the only one that does not.
  assert_eq!(hit, vec![1, 2, 3, 4, 6]);
  // Descending, which is the precondition every stage below reads.
  assert!(
    ranked
      .windows(2)
      .all(|pair| pair[0].score() >= pair[1].score()),
    "{ranked:?}"
  );
}

/// **Tier A: the floor cuts the tail, and the ranks that survive are the engine's own.**
///
/// The floor is set between the corpus's own scores, so the answer is strictly shorter than the
/// unfiltered one and the surviving ranks are a PREFIX of the raw stream's — which is what an
/// early-terminating floor produces and a `retain` afterwards also would. What separates them is
/// measured in `keys/tests.rs`; what is measured here is that a real engine's real scores calibrate
/// against a real floor at all.
#[tokio::test]
async fn the_floor_shortens_a_live_answer() {
  let (_dir, index, mut engine) = index(&[]).await;

  let all = retrieve_keys::<HashSeen<_>>(
    &mut engine,
    &index,
    &FulltextQuery::new("sunset", 0.0_f32),
    usize::MAX,
  )
  .await;
  assert_eq!(all.len(), 5);

  // Between the second and third scores of the live answer — a floor calibrated the way a caller
  // calibrates one, off the score column the wrapper hands back.
  let floor = (all[1].score() + all[2].score()) / 2.0;
  let floored = retrieve_keys::<HashSeen<_>>(
    &mut engine,
    &index,
    &FulltextQuery::new("sunset", floor),
    usize::MAX,
  )
  .await;

  assert_eq!(floored.len(), 2);
  assert_eq!(
    floored.iter().map(Ranked::rank).collect::<Vec<_>>(),
    vec![1, 2]
  );
  assert_eq!(
    floored
      .iter()
      .map(|hit| hit.node_ref().id)
      .collect::<Vec<_>>(),
    all[..2]
      .iter()
      .map(|hit| hit.node_ref().id)
      .collect::<Vec<_>>()
  );
}

/// **Tier A: a duplicate key in the live stream collapses, and the hole in the ranks stays.**
///
/// Two entries under ONE address, reached by indexing the same key from a SECOND source — which is
/// the honest way to produce the case, because this backend's keyed replace is exactly what stops
/// one source from doing it. That is the whole reason the framework dedups: engines are open
/// traits, and no backend owes uniqueness across the sources sharing a slot.
#[tokio::test]
async fn a_duplicate_key_collapses_and_leaves_its_rank_behind() {
  /// A second source over the same key space — its identity term differs by SOURCE, so its document
  /// lands beside the first rather than replacing it.
  struct Echo(Transcript);

  impl Identifiable for Echo {
    type Id = i64;

    fn id_ref(&self) -> &i64 {
      self.0.id_ref()
    }
  }

  impl Transformer for Echo {
    type Key = SegmentKey;
    type Lineage = <Segment as Transformer>::Lineage;
    type Record = ();
    type Graphql = ();

    fn key(&self) -> SegmentKey {
      self.0.key()
    }
  }

  impl FulltextRecord for Echo {
    type Document = String;

    fn document(&self) -> &String {
      self.0.document()
    }
  }

  impl FulltextTable for Echo {
    const SLOT: &'static SlotName = SlotName::new("echo");
  }

  let dir = tempfile::tempdir().expect("a temporary directory");
  let index = TantivyStore::open(dir.path()).expect("the store opens");
  let mut engine = SlotHandle::<_, Transcript>::mint(index.fulltext("transcript"));
  {
    let mut writer = index
      .writer("transcript", TantivyStore::MIN_WRITER_HEAP_BYTES)
      .expect("the slot's writer opens");
    for (media, id, transcript, _) in SEEDED {
      engine
        .upsert_document(
          Connected::new(&index, &mut writer),
          entry(&Transcript::of(media, *id, transcript)),
        )
        .await
        .expect("the document queues");
    }
    // The SAME key, from another source, with a text that scores well — so the duplicate lands high
    // in the stream rather than at the end where its collapse would be invisible.
    engine
      .upsert_document(
        Connected::new(&index, &mut writer),
        entry(&Echo(Transcript::of(
          "m3",
          6,
          "sunset sunset sunset sunset",
        ))),
      )
      .await
      .expect("the document queues");
    writer.commit().expect("the batch commits");
  }
  index.reload("transcript").expect("the reader reloads");

  let raw = keyed::<TantivyFulltext, SegmentKey>(
    engine
      .search(
        Connected::new(&index, ()),
        FulltextSubset::All,
        "sunset",
        NonZeroUsize::new(10).expect("10 is not zero"),
        None,
      )
      .await
      .expect("the search runs"),
  )
  .expect("the addresses read back");
  assert_eq!(raw.len(), 6, "the slot holds two entries at one key");
  let duplicated = raw.iter().filter(|hit| hit.data_ref().id == 6).count();
  assert_eq!(duplicated, 2);

  let ranked = retrieve_keys::<HashSeen<_>>(
    &mut engine,
    &index,
    &FulltextQuery::new("sunset", 0.0_f32),
    usize::MAX,
  )
  .await;

  assert_eq!(ranked.len(), 5, "the duplicate collapsed");
  assert_eq!(
    ranked.iter().filter(|hit| hit.node_ref().id == 6).count(),
    1
  );
  // The raw stream had six positions and five survivors wear five of them: one ordinal is missing,
  // and which one is wherever the second sighting stood.
  let worn: Vec<u64> = ranked.iter().map(Ranked::rank).collect();
  assert_eq!(worn.len(), 5);
  assert!(worn.iter().max().is_some_and(|last| *last == 6), "{worn:?}");
  // The survivor kept the FIRST sighting's score, which is the better of the two.
  let kept = ranked
    .iter()
    .find(|hit| hit.node_ref().id == 6)
    .expect("the survivor");
  let best = raw
    .iter()
    .filter(|hit| hit.data_ref().id == 6)
    .map(|hit| hit.score())
    .fold(f32::MIN, f32::max);
  assert_eq!(kept.score(), best);
}

/// **Tier B, the whole composite: whole entities, in engine order, ranked by the engine's own
/// ordinal.**
#[tokio::test]
async fn tier_b_answers_whole_entities_in_engine_order() {
  let (_dir, index, mut engine) = index(&[]).await;
  let mut db = store().await;

  let keys = retrieve_keys::<HashSeen<_>>(
    &mut engine,
    &index,
    &FulltextQuery::new("sunset", 0.0_f32),
    usize::MAX,
  )
  .await;
  let page = retrieve(
    &mut engine,
    &index,
    &mut db,
    &FulltextQuery::new("sunset", 0.0_f32),
    None,
    10,
  )
  .await
  .expect("the retrieve runs");

  assert_eq!(page.len(), 5);
  // The ENTITY, not the key and not the row: every column of the upstream is here.
  assert!(page[0].node_ref().transcript.contains("sunset"));
  assert!(page[0].node_ref().duration > 0);
  // Order and ranks are tier A's, carried across the hydration untouched.
  assert_eq!(
    ids(&page),
    keys.iter().map(|hit| hit.node_ref().id).collect::<Vec<_>>()
  );
  assert_eq!(
    ranks(&page),
    keys.iter().map(Ranked::rank).collect::<Vec<_>>()
  );
}

/// **Tier B: a filter that prunes mid-page forces a SECOND key batch, and the page still fills.**
///
/// The budget is two and the filter keeps only the short segments, so the first batch cannot
/// possibly fill the page — the loop has to go back for more keys. The ranks that come back are the
/// engine's, with the pruned rows' ordinals missing.
#[tokio::test]
async fn a_filter_forces_a_second_key_batch() {
  let (_dir, index, mut engine) = index(&[]).await;
  let mut db = store().await;
  let short = shorter_than(15);

  let unfiltered = retrieve(
    &mut engine,
    &index,
    &mut db,
    &FulltextQuery::new("sunset", 0.0_f32),
    None,
    10,
  )
  .await
  .expect("the retrieve runs");
  let page = retrieve(
    &mut engine,
    &index,
    &mut db,
    &FulltextQuery::new("sunset", 0.0_f32),
    Some(&short),
    2,
  )
  .await
  .expect("the retrieve runs");

  // Segments 2 (12s) and 4 (8s) are the only ones under the bound that also match.
  assert_eq!(page.len(), 2);
  let mut kept = ids(&page);
  kept.sort_unstable();
  assert_eq!(kept, vec![2, 4]);
  assert!(page.iter().all(|hit| hit.node_ref().duration <= 15));
  // The ranks are the RAW stream's: each kept entity wears the ordinal it had in the unfiltered
  // answer, so the page's numbers have the pruned rows' holes in them.
  for hit in &page {
    let raw = unfiltered
      .iter()
      .find(|all| all.node_ref().id == hit.node_ref().id)
      .expect("the same hit, unfiltered");
    assert_eq!(hit.rank(), raw.rank());
  }
}

/// **Tier B: a key the index knows and the store has lost is SKIPPED, and the page keeps filling.**
#[tokio::test]
async fn a_store_missing_row_is_skipped_and_the_page_fills() {
  let (_dir, index, mut engine) = index(&[]).await;
  let mut db = store().await;

  let whole = retrieve(
    &mut engine,
    &index,
    &mut db,
    &FulltextQuery::new("sunset", 0.0_f32),
    None,
    10,
  )
  .await
  .expect("the retrieve runs");
  let lost = whole[0].node_ref().id;
  forget(&mut db, lost).await;

  let page = retrieve(
    &mut engine,
    &index,
    &mut db,
    &FulltextQuery::new("sunset", 0.0_f32),
    None,
    10,
  )
  .await
  .expect("the retrieve runs");

  assert_eq!(page.len(), whole.len() - 1);
  assert!(!ids(&page).contains(&lost));
  // The survivors kept their own ranks — a missing row is a hole, not a renumbering.
  for hit in &page {
    let before = whole
      .iter()
      .find(|all| all.node_ref().id == hit.node_ref().id)
      .expect("the same hit, before the loss");
    assert_eq!(hit.rank(), before.rank());
  }
}

/// **The SHORT final page: the floor dries the stream and the answer comes back under-full, which
/// is the ruling rather than a case to pad around.**
#[tokio::test]
async fn a_floored_retrieve_answers_short() {
  let (_dir, index, mut engine) = index(&[]).await;
  let mut db = store().await;

  let all = retrieve_keys::<HashSeen<_>>(
    &mut engine,
    &index,
    &FulltextQuery::new("sunset", 0.0_f32),
    usize::MAX,
  )
  .await;
  let floor = (all[0].score() + all[1].score()) / 2.0;

  let page = retrieve(
    &mut engine,
    &index,
    &mut db,
    &FulltextQuery::new("sunset", floor),
    None,
    10,
  )
  .await
  .expect("the retrieve runs");

  assert_eq!(page.len(), 1, "asked for ten, and one cleared the floor");
  assert_eq!(page[0].rank(), 1);
}

/// The mechanism is a bounds choice and not a behaviour: the same live stream through the equality
/// membership is the same answer.
#[tokio::test]
async fn the_equality_mechanism_answers_the_same_live_stream() {
  let (_dir, index, mut engine) = index(&[]).await;
  let query = FulltextQuery::new("sunset", 0.0_f32);

  let hashed = retrieve_keys::<HashSeen<_>>(&mut engine, &index, &query, usize::MAX).await;
  let listed = retrieve_keys::<EqSeen<_>>(&mut engine, &index, &query, usize::MAX).await;

  assert_eq!(hashed, listed);
}