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
//! The two citizens' own claims: what a range refuses, what the closed reading buys, and the
//! columns, bytes and documents the pair occupies.

use crate::{
  ColumnKind, ColumnShape, CursorValue, FieldName, ParseTimeRangeError, TimeRange, TimeRanged,
  Timestamp, leaf_names, width,
};

fn at(second: i64) -> Timestamp {
  Timestamp::from_parts(second, 0).expect("an instant")
}

fn range(start: i64, end: i64) -> TimeRange {
  TimeRange::new(at(start), at(end)).expect("a stretch")
}

/// **THE INVARIANT REFUSES AT THE DOOR**, and it carries the PAIR — either instant alone is
/// unremarkable and the ORDER is what is wrong.
#[test]
fn an_inverted_pair_is_not_a_range() {
  let refused = TimeRange::new(at(20), at(10)).expect_err("20 is later than 10");

  assert_eq!(refused.start(), at(20));
  assert_eq!(refused.end(), at(10));
  assert!(
    refused
      .to_string()
      .contains("ends no earlier than it starts"),
    "the sentence names the rule rather than only the values"
  );
}

/// **THE DEGENERATE STRETCH IS ADMITTED**, which is `mediatime`'s POSTURE rather than a reading of
/// half-openness: that type calls `start == end` *a degenerate (instant) range* and ships `instant`
/// and `is_instant` for it.
///
/// Under half-openness the value covers NOTHING — `[t, t).holds(t)` is false, because `t > t` is —
/// so it is a MARKER rather than a one-instant stretch. Both halves are pinned here, because the two
/// together are what the posture actually says.
#[test]
fn the_two_ends_may_coincide() {
  let marker = TimeRange::new(at(10), at(10)).expect("`start <= end` admits equality");

  assert!(marker.is_instant());
  assert_eq!(marker, TimeRange::instant(at(10)));
  assert!(
    !marker.holds(at(10)),
    "a half-open stretch of zero width covers no instant at all"
  );
  assert!(!marker.contains(&range(10, 11)));
}

/// **MEMBERSHIP IS HALF-OPEN**: the start is IN and the end is OUT, so a stored instant belongs to
/// exactly ONE of two abutting stretches.
#[test]
fn the_start_is_in_and_the_end_is_out() {
  let span = range(0, 10);

  assert!(span.holds(at(0)), "the start is in the stretch");
  assert!(span.holds(at(9)));
  assert!(!span.holds(at(10)), "the end is not");
  assert!(!span.holds(at(11)));

  // Two abutting stretches partition the boundary instant between them.
  assert!(!range(0, 10).holds(at(10)));
  assert!(range(10, 20).holds(at(10)));
}

/// **`overlaps` IS THE CROSSED PAIR, AND IT IS SYMMETRIC.**
#[test]
fn overlapping_is_sharing_an_instant() {
  assert!(range(0, 10).overlaps(&range(5, 15)));
  assert!(range(5, 15).overlaps(&range(0, 10)));
  assert!(range(0, 10).overlaps(&range(2, 3)), "wholly inside counts");
  assert!(!range(0, 10).overlaps(&range(11, 20)));
}

/// **ABUTTING STRETCHES DO NOT OVERLAP**, which is what half-openness BUYS and the one thing a
/// closed reading gets silently wrong.
///
/// `[0, 10)` and `[10, 20)` share no instant: an intersection of width zero is empty. A segmentation
/// that tiles a track therefore reports no spurious meets — which is the whole practical point of
/// the convention `mediatime` sets and this crate inherits.
#[test]
fn abutting_stretches_do_not_meet() {
  assert!(!range(0, 10).overlaps(&range(10, 20)));
  assert!(!range(10, 20).overlaps(&range(0, 10)), "and symmetrically");

  // One instant either side of the boundary is enough to make them meet.
  assert!(range(0, 11).overlaps(&range(10, 20)));
}

/// **`contains` AND `within` ARE ONE RELATION READ FROM ITS TWO ENDS**, which is why a filter needs
/// both words and a value type needs one.
#[test]
fn containment_reads_both_ways() {
  let wide = range(0, 100);
  let narrow = range(10, 20);

  assert!(wide.contains(&narrow));
  assert!(narrow.within(&wide));
  assert!(!narrow.contains(&wide));
  assert!(wide.contains(&wide), "containment is reflexive");
}

/// **A DEGENERATE OPERAND IS NOT THE POINT QUESTION**, and this is the test that says so — it is the
/// argument a CLOSED reading had and half-openness takes away.
///
/// Under closed intervals `contains(instant(t))` was exactly *does this span cover `t`*. Under these
/// it is not: the two-inequality form treats the degenerate operand as its POSITION rather than as
/// the empty set, and at the boundary it disagrees with membership in both directions.
#[test]
fn a_degenerate_operand_is_not_the_membership_test() {
  let span = range(10, 20);

  // The end: MEMBERSHIP refuses it, `contains` admits it (like boundaries), `overlaps` refuses it.
  assert!(!span.holds(at(20)));
  assert!(span.contains(&TimeRange::instant(at(20))));
  assert!(!span.overlaps(&TimeRange::instant(at(20))));

  // The start: MEMBERSHIP admits it, `contains` admits it, `overlaps` REFUSES it.
  assert!(span.holds(at(10)));
  assert!(span.contains(&TimeRange::instant(at(10))));
  assert!(!span.overlaps(&TimeRange::instant(at(10))));

  // So neither word is the membership test, which is why `contains` carries an INSTANT shape.
  assert!(span.contains(&range(12, 18)), "the span shape still works");
}

/// **THE FOUR BOUNDARY TRUTHS**, derived in the module note and pinned here — where the
/// two-inequality FORM and strict set semantics part company, and which one this crate answers.
#[test]
fn the_forms_read_a_degenerate_operand_as_its_position() {
  let span = range(0, 10);

  // `overlaps`: the form refuses a degenerate operand at the boundary and admits one strictly
  // inside; set semantics would refuse both, the empty set meeting nothing.
  assert!(!span.overlaps(&TimeRange::instant(at(10))));
  assert!(span.overlaps(&TimeRange::instant(at(5))));

  // `contains`: the form admits a degenerate operand inside the CLOSED hull and refuses one outside
  // it; set semantics would admit both, the empty set being a subset of everything.
  assert!(span.contains(&TimeRange::instant(at(10))));
  assert!(!span.contains(&TimeRange::instant(at(20))));
}

/// **THE CURSOR'S ORDER IS A STORAGE ORDER, and it is start-then-end** — asserted through the BYTES
/// rather than through an [`Ord`] this type deliberately has not got.
///
/// `mediatime` declines the order because a stretch has three candidate ones; a keyset still needs
/// a total order, so the cursor picks one and says which. What makes it the right one is that the
/// SQL row value and the BSON sub-document already read the same field order — so a page's
/// `ORDER BY` and its resume token cannot disagree.
#[test]
fn the_cursor_orders_by_start_then_end() {
  fn token(span: TimeRange) -> Vec<u8> {
    let mut out = Vec::new();
    span.write_cursor(&mut out);
    out
  }

  let mut tokens = [range(10, 12), range(0, 100), range(10, 11), range(0, 5)].map(token);
  tokens.sort();

  let read: Vec<TimeRange> = tokens
    .iter()
    .map(|bytes| TimeRange::read_cursor(bytes).expect("its own encoding"))
    .collect();

  assert_eq!(
    read,
    [range(0, 5), range(0, 100), range(10, 11), range(10, 12)],
    "earlier starts first, and a tie breaks on the earlier end"
  );
}

/// **THE HALF-OPEN NOTATION, AND IT ROUND-TRIPS** — the mismatched brackets are the point rather
/// than decoration, which is `mediatime`'s own sentence for its own rendering.
#[test]
fn the_text_form_is_the_half_open_notation() {
  assert_eq!(
    range(0, 60).to_string(),
    "[1970-01-01T00:00:00Z, 1970-01-01T00:01:00Z)"
  );

  assert_eq!(
    range(0, 60).to_string().parse::<TimeRange>().unwrap(),
    range(0, 60),
    "`Display` and `FromStr` are inverse"
  );
}

/// The parse's three refusals, each naming a different fix.
#[test]
fn a_text_that_is_not_a_stretch_says_which_half_broke() {
  assert!(matches!(
    "1970-01-01T00:00:00Z".parse::<TimeRange>(),
    Err(ParseTimeRangeError::Notation)
  ));
  assert!(matches!(
    "[1970-01-01T00:00:00Z]".parse::<TimeRange>(),
    Err(ParseTimeRangeError::Notation)
  ));
  assert!(matches!(
    "[not-an-instant, 1970-01-01T00:01:00Z)".parse::<TimeRange>(),
    Err(ParseTimeRangeError::Endpoint(_))
  ));
  assert!(matches!(
    "[1970-01-01T00:01:00Z, 1970-01-01T00:00:00Z)".parse::<TimeRange>(),
    Err(ParseTimeRangeError::Inverted(_))
  ));
}

/// **FOUR LEAVES UNDER TWO PARTS**, and the leaf names are the instant's own beneath this type's two
/// seats — audited in a `const`, so a restatement that drifts does not compile.
const RANGE_LEAVES: &[&FieldName] = &[
  FieldName::new("start_secs"),
  FieldName::new("start_nanos"),
  FieldName::new("end_secs"),
  FieldName::new("end_nanos"),
];

const _: () = assert!(leaf_names(
  <TimeRange as ColumnKind>::SEGMENTS,
  RANGE_LEAVES
));
const _: () = assert!(width(<TimeRange as ColumnKind>::SEGMENTS) == 4);
const _: () = assert!(<TimeRange as ColumnKind>::SEGMENTS.len() == 2);

/// **THE RANGE FLATTENS AND THE PAYLOAD IS NAMED**, so a timed scalar is FIVE columns: the stretch's
/// four leaves under their own two seats, and one `data` leaf beside them.
const TIMED_LEAVES: &[&FieldName] = &[
  FieldName::new("start_secs"),
  FieldName::new("start_nanos"),
  FieldName::new("end_secs"),
  FieldName::new("end_nanos"),
  FieldName::new("data"),
];

const _: () = assert!(leaf_names(
  <TimeRanged<i64> as ColumnKind>::SEGMENTS,
  TIMED_LEAVES
));
const _: () = assert!(width(<TimeRanged<i64> as ColumnKind>::SEGMENTS) == 5);

/// The shapes themselves, read at run time so the failure names which part disagreed.
#[test]
fn the_segments_are_the_instants_own_under_two_seats() {
  let segments = <TimeRange as ColumnKind>::SEGMENTS;

  let ColumnShape::Composite {
    field: Some(start),
    segments: inner,
  } = segments[0]
  else {
    panic!("a seat of a range is a composite lending its own name");
  };

  assert_eq!(start.stored().as_str(), "start");
  assert_eq!(
    inner,
    <Timestamp as ColumnKind>::SEGMENTS,
    "not a second spelling of an instant's storage"
  );

  // The timed pair: the range LENDS NO NAME and the payload does.
  let timed = <TimeRanged<i64> as ColumnKind>::SEGMENTS;
  assert!(
    matches!(timed[0], ColumnShape::Composite { field: None, .. }),
    "the stretch splices into its holder's namespace"
  );
  assert!(
    matches!(timed[1], ColumnShape::Plain(data) if data.stored().as_str() == "data"),
    "a scalar payload is one column under `data`"
  );
}

/// **A COMPOSITE PAYLOAD KEEPS ITS OWN NAME BENEATH `data`**, which is what a parameter's segment
/// names being unknown to this crate costs and buys: a payload with a `start` of its own cannot
/// occupy the stretch's column.
#[test]
fn a_composite_payload_nests_under_its_seat() {
  let timed = <TimeRanged<TimeRange> as ColumnKind>::SEGMENTS;

  assert_eq!(width(timed), 8, "four leaves apiece");
  assert!(
    matches!(timed[1], ColumnShape::Composite { field: Some(data), segments } if data.stored().as_str() == "data"
        && segments == <TimeRange as ColumnKind>::SEGMENTS),
    "the payload's own parts hang beneath `data` rather than beside the stretch's"
  );
}

/// **THE CURSOR IS TWENTY-FOUR BYTES**, both instants in the order the segments state, and the pair
/// is CHECKED on the way back — a forged token naming an inverted stretch is refused rather than
/// turned into a value whose type says it cannot exist.
#[test]
fn the_cursor_round_trips_and_re_validates() {
  let span = TimeRange::new(
    Timestamp::from_parts(1_756_371_600, 123_456_789).expect("an instant"),
    Timestamp::from_parts(1_756_371_660, 0).expect("an instant"),
  )
  .expect("a stretch");

  let mut bytes = Vec::new();
  span.write_cursor(&mut bytes);

  assert_eq!(bytes.len(), 24, "two instants of twelve bytes each");
  assert_eq!(TimeRange::read_cursor(&bytes), Some(span));

  // A FORGED token: the two instants swapped, each of them perfectly decodable on its own.
  let mut inverted = Vec::new();
  span.end().write_cursor(&mut inverted);
  span.start().write_cursor(&mut inverted);
  assert_eq!(
    TimeRange::read_cursor(&inverted),
    None,
    "the pair goes back through `TimeRange::new`"
  );

  // FIXED WIDTH: a short token is refused rather than zero-extended into a plausible stretch.
  assert_eq!(TimeRange::read_cursor(&bytes[..23]), None);
  assert_eq!(TimeRange::read_cursor(&[]), None);
}

/// **A TIMED PAYLOAD'S CURSOR IS THE STRETCH'S TWENTY-FOUR BYTES AND THEN THE PAYLOAD'S**, with no
/// delimiter between them — the payload is LAST, so everything after the fixed split is its own.
///
/// The variable-width case is the one worth pinning: a `String` payload writes its bytes bare and
/// reads the whole remainder, which is what makes the *no framing* claim more than a statement about
/// integers.
#[test]
fn a_timed_cursor_splits_at_the_stretchs_fixed_width() {
  let timed = TimeRanged::new(range(10, 20), String::from("zh-Hans"));

  let mut bytes = Vec::new();
  timed.write_cursor(&mut bytes);

  assert_eq!(bytes.len(), 24 + "zh-Hans".len());
  assert_eq!(TimeRanged::<String>::read_cursor(&bytes), Some(timed));

  // The stretch's own re-validation still fires through the wrapper.
  let mut inverted = Vec::new();
  range(10, 20).end().write_cursor(&mut inverted);
  range(10, 20).start().write_cursor(&mut inverted);
  inverted.extend_from_slice(b"zh");
  assert_eq!(TimeRanged::<String>::read_cursor(&inverted), None);

  // A token too short to hold the stretch at all is refused before the payload is looked at.
  assert_eq!(TimeRanged::<String>::read_cursor(&bytes[..20]), None);
}

/// The payload moves and the timing does not, which is what `map` is for.
#[test]
fn the_payload_maps_without_the_timing_being_rebuilt() {
  let timed = TimeRanged::new(range(0, 10), 7i64);
  let mapped = timed.map(|held| held * 2);

  assert_eq!(mapped.range(), &range(0, 10));
  assert_eq!(*mapped.data(), 14);

  let (stretch, held) = mapped.into_parts();
  assert_eq!(stretch, range(0, 10));
  assert_eq!(held, 14);
}

/// **EQUALITY IS THE PAIR'S AND THERE IS NO ORDER** — the wrapper cannot manufacture the order its
/// stretch half declines, so the keyset order is the CURSOR's and is asserted through its bytes.
#[test]
fn a_timed_payload_has_equality_and_a_cursor_order() {
  assert_eq!(
    TimeRanged::new(range(10, 20), 1i64),
    TimeRanged::new(range(10, 20), 1i64)
  );
  assert_ne!(
    TimeRanged::new(range(10, 20), 1i64),
    TimeRanged::new(range(10, 20), 0i64)
  );

  fn token(timed: TimeRanged<i64>) -> Vec<u8> {
    let mut out = Vec::new();
    timed.write_cursor(&mut out);
    out
  }

  let mut tokens = [
    TimeRanged::new(range(10, 20), 1i64),
    TimeRanged::new(range(0, 5), 9i64),
    TimeRanged::new(range(10, 20), 0i64),
  ]
  .map(token);
  tokens.sort();

  let read: Vec<TimeRanged<i64>> = tokens
    .iter()
    .map(|bytes| TimeRanged::read_cursor(bytes).expect("its own encoding"))
    .collect();

  assert_eq!(
    read,
    [
      TimeRanged::new(range(0, 5), 9),
      TimeRanged::new(range(10, 20), 0),
      TimeRanged::new(range(10, 20), 1),
    ],
    "the stretch orders first and the payload breaks the tie"
  );
}

/// The BSON round trip, and the pair checked on the way back exactly as the cursor's is.
#[cfg(feature = "mongo")]
mod document {
  use super::{at, range};
  use crate::{
    MongoCarrier, TimeRange, TimeRanged, Timestamp,
    query::mongo::{MongoExtract, MongoTypeError},
  };

  /// **TWO KEYS, EACH A SUB-DOCUMENT** — the instant's own shape under this type's two seat names,
  /// and nothing here spells `secs` or `nanos`.
  #[test]
  fn a_stretch_is_two_nested_instants() {
    let span = range(10, 20);
    let bson::Bson::Document(document) = span.to_bson() else {
      panic!("a stretch writes a document");
    };

    assert_eq!(document.len(), 2);
    assert_eq!(
      document.get("start"),
      Some(&Timestamp::to_bson(&at(10))),
      "the seat holds the INSTANT's own form"
    );
    assert_eq!(TimeRange::extract(Some(&span.to_bson())), Ok(span));
  }

  /// A stored pair whose end is earlier than its start is refused with a FIXED sentence, which is
  /// what [`MongoTypeError::Range`] can carry.
  #[test]
  fn an_inverted_document_is_refused() {
    let mut document = bson::Document::new();
    document.insert("start", Timestamp::to_bson(&at(20)));
    document.insert("end", Timestamp::to_bson(&at(10)));

    let refused = TimeRange::extract(Some(&bson::Bson::Document(document)));
    assert!(matches!(refused, Err(MongoTypeError::Range(_))));

    // And a value that is not a document at all keeps the TYPE half of the refusal precise.
    assert!(matches!(
      TimeRange::extract(Some(&bson::Bson::Int32(3))),
      Err(MongoTypeError::Type { .. })
    ));
    assert!(matches!(
      TimeRange::extract(None),
      Err(MongoTypeError::Absent)
    ));
  }

  /// **THREE KEYS: the stretch's two SPLICED, and the payload under `data`** — the same shape the
  /// segments state, in the spelling this family has for it.
  #[test]
  fn a_timed_payload_splices_its_stretch_and_names_its_payload() {
    let timed = TimeRanged::new(range(10, 20), 7i64);
    let bson::Bson::Document(document) = timed.to_bson() else {
      panic!("a timed payload writes a document");
    };

    assert_eq!(document.len(), 3);
    assert!(document.contains_key("start"));
    assert!(document.contains_key("end"));
    assert_eq!(document.get("data"), Some(&bson::Bson::Int64(7)));

    assert_eq!(
      TimeRanged::<i64>::extract(Some(&timed.to_bson())),
      Ok(timed)
    );
  }
}