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
//! The [`MediaTimestamp`] primitive: the newtype, its filter, that filter's storage-side comparison,
//! and the overflow both nanosecond crossings raise.

use core::fmt;

use crate::{CompositeFilterMarker, CompositeMarker, DefaultMarker, ScalarFilter, ToGraphqlInput};
use mediatime as mt;

use super::TimebaseFilter;
use crate::graphql::filter::opt_accessor;

#[cfg(feature = "sqlx")]
mod comparison;
#[cfg(feature = "async-graphql")]
mod graphql;
mod storage;

pub use storage::MediaTimestampLeaf;

#[cfg(test)]
mod tests;

#[cfg(feature = "sqlx")]
pub use comparison::{MediaTimestampCrossingError, SqlMediaTimestampComparison};

/// A presentation timestamp — an integer PTS in units of its own [`Timebase`], wrapping
/// [`mediatime::Timestamp`].
///
/// [`Ord`] is `mediatime`'s: two timestamps compare by the exact rational instant, across
/// timebases, by 128-bit cross-multiplication rather than by `pts`.
///
/// [`Timebase`]: super::Timebase
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MediaTimestamp(mt::Timestamp);

impl MediaTimestamp {
  /// Wrap a [`mediatime::Timestamp`].
  ///
  /// The `const` route in; [`From`] is the other one and is not `const`.
  #[inline]
  pub const fn new(timestamp: mt::Timestamp) -> Self {
    Self(timestamp)
  }

  /// The wrapped [`mediatime::Timestamp`].
  #[inline]
  pub const fn get(&self) -> mt::Timestamp {
    self.0
  }

  /// The storage form: the instant in NANOSECONDS since the timebase's origin.
  ///
  /// Normalizing at the crossing is what makes an ordering operator mean what it says. Two
  /// timestamps in different timebases are not comparable by `pts` at all, so a filter that lowered
  /// `gt` to `WHERE pts > ?` would be silently wrong whenever the stored timebase differed from the
  /// one the query was written in. There is exactly one unit in the column, and it is this one.
  ///
  /// Rounds toward zero, as `mediatime`'s own rescaling does, so the map is not injective — see the
  /// module docs for which way that leans.
  ///
  /// # Errors
  ///
  /// [`NanosecondOverflow`] when the instant does not fit `i64` nanoseconds, which spans about
  /// ±292 years. A real media timestamp always fits; a garbage one must not become a wrong number,
  /// so this neither panics nor saturates.
  ///
  /// The product `pts × 10⁹ × num` is computed in `i128` and cannot overflow THERE. `|pts|` is
  /// bounded by `2⁶³` and `num` by `i32::MAX`, the latter because `mediatime`'s constructor pins a
  /// numerator non-negative and its type caps it at `2³¹ − 1`; the largest magnitude is therefore
  /// `2⁶³ × 10⁹ × (2³¹ − 1) ≈ 1.98 × 10³⁷` against an `i128` ceiling of `≈ 1.70 × 10³⁸`, a factor
  /// of about 8.6 clear. The only range check that can fail is the one back into `i64`.
  #[inline]
  pub const fn to_nanos(self) -> Result<i64, NanosecondOverflow> {
    let timebase = self.0.timebase();
    let nanos = (self.0.pts() as i128) * NANOS_PER_SECOND * (timebase.num() as i128)
      / (timebase.den().get() as i128);

    if nanos < i64::MIN as i128 || nanos > i64::MAX as i128 {
      Err(NanosecondOverflow { nanos })
    } else {
      Ok(nanos as i64)
    }
  }
}

impl From<mt::Timestamp> for MediaTimestamp {
  #[inline]
  fn from(timestamp: mt::Timestamp) -> Self {
    Self(timestamp)
  }
}

impl From<MediaTimestamp> for mt::Timestamp {
  #[inline]
  fn from(timestamp: MediaTimestamp) -> Self {
    timestamp.0
  }
}

/// A whole timestamp, on its way IN as an IDENTITY operand — the exact pair, and nothing that merely
/// names a position.
///
/// A type of its own rather than [`MediaTimestamp`], and GraphQL's shared name namespace is what forces
/// it — the same wall [`TimebaseOperand`](super::TimebaseOperand) is on the other side of.///
/// Declared UNGATED, beside the type it carries, and the reason is the ungated-operand rule
/// this house's note states for its whole roster: a crossing says which FORM an operand takes and asks nothing about who parses that form. The binding's half
/// — the `#[Scalar]` that reads the arms and writes the canonical one — is in `graphql`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MediaTimestampOperand(MediaTimestamp);

impl MediaTimestampOperand {
  /// Wrap a [`MediaTimestamp`] as an identity operand.
  #[inline]
  #[must_use]
  pub const fn new(timestamp: MediaTimestamp) -> Self {
    Self(timestamp)
  }

  /// The wrapped [`MediaTimestamp`].
  #[inline]
  #[must_use]
  pub const fn get(&self) -> MediaTimestamp {
    self.0
  }
}

impl From<MediaTimestamp> for MediaTimestampOperand {
  #[inline]
  fn from(timestamp: MediaTimestamp) -> Self {
    Self(timestamp)
  }
}

impl From<MediaTimestampOperand> for MediaTimestamp {
  #[inline]
  fn from(operand: MediaTimestampOperand) -> Self {
    operand.0
  }
}

/// A position on the timeline, on its way IN as a BOUND — every exact form, plus the three that name
/// a position without naming a value.
///
/// Holds a [`MediaTimestamp`] like its identity twin. A wide form lands in `mediatime`'s `NANOS` timebase,
/// which is a value like any other and is exactly what a position with no declared unit is.
///
/// Declared UNGATED, beside the type it carries, and the reason is the ungated-operand rule
/// this house's note states for its whole roster: a crossing says which FORM an operand takes and asks nothing about who parses that form. The binding's half
/// — the `#[Scalar]` that reads the arms and writes the canonical one — is in `graphql`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MediaInstantBound(MediaTimestamp);

impl MediaInstantBound {
  /// Wrap a [`MediaTimestamp`] as a bound.
  #[inline]
  #[must_use]
  pub const fn new(timestamp: MediaTimestamp) -> Self {
    Self(timestamp)
  }

  /// The wrapped [`MediaTimestamp`].
  #[inline]
  #[must_use]
  pub const fn get(&self) -> MediaTimestamp {
    self.0
  }

  /// A bare nanosecond position, as the timestamp it is: a count in `mediatime`'s `NANOS`.
  #[inline]
  #[must_use]
  pub const fn of_nanos(nanos: i64) -> Self {
    Self(MediaTimestamp::new(mt::Timestamp::new(
      nanos,
      mt::Timebase::NANOS,
    )))
  }
}

impl From<MediaTimestamp> for MediaInstantBound {
  #[inline]
  fn from(timestamp: MediaTimestamp) -> Self {
    Self(timestamp)
  }
}

impl From<MediaInstantBound> for MediaTimestamp {
  #[inline]
  fn from(bound: MediaInstantBound) -> Self {
    bound.0
  }
}

/// The OPERAND's own crossing, so a `[MediaTimestamp]` column knows what one element looks like.
///
/// The identity door is the one a collection element goes through: a list of timestamps is a list of
/// VALUES.
impl ToGraphqlInput for MediaTimestamp {
  type Input = MediaTimestampOperand;
  type Error = core::convert::Infallible;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Ok(input.into())
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    MediaTimestampOperand::new(*operand)
  }
}
/// The BOUND door's own crossing — and the reason this type is the slot's carrier rather than
/// [`MediaTimestamp`].
///
/// One Rust type serves two doors here: `exact`/`eq`/`ne`/`in`/`notIn` name a VALUE and register
/// [`MediaTimestampOperand`], while `gt`/`gte`/`lt`/`lte` name a POSITION and register `MediaInstantBound` —
/// a wider grammar, since a bound may be written as a clock or a count of seconds where an equality
/// may not. A crossing is ONE row per type, so the two doors cannot both be spelled on `MediaTimestamp`;
/// the bound slots hold this newtype instead, and it crosses as ITSELF.
impl ToGraphqlInput for MediaInstantBound {
  type Input = Self;
  type Error = core::convert::Infallible;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Ok(input)
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    *operand
  }
}

/// What guards a [`MediaTimestamp`] column — [`Timebase`]'s row, and the same reading of it: a timestamp
/// stores every field it declares, so the two seats name one predicate.
///
/// [`Timebase`]: super::Timebase
impl CompositeFilterMarker for MediaTimestamp {
  type Filter = MediaTimestampFilter;
  type ColumnFilter = MediaTimestampFilter;
}

/// The interpretation a [`MediaTimestamp`] field is read under — [`Timebase`]'s reading, and this crate
/// no longer mints either: a timestamp occupies columns of its own and all of them can be absent
/// together, which is exactly the VALUE family [`CompositeMarker`] names.
///
/// [`Timebase`]: super::Timebase
impl DefaultMarker for MediaTimestamp {
  type Marker = CompositeMarker<MediaTimestamp>;
}

/// **A COLLECTION of positions is asked through the QUANTIFIERS**, and the reason is the ELEMENT's
/// shape rather than its order.
///
/// This type HAS a total order — unlike a span, whose three orderings are why neither range citizen
/// derives one — so the four lexicographic list operators would at least be well defined over it.
/// They are still not offered, because the reading a [`ListFilter`](crate::ListFilter) publishes is
/// the SCALAR one: its operators hold a whole element as a single value, and a media instant is
/// three columns whose identity question already has two answers — `exact` on the encoding, `eq` on
/// the derived position. A list operator would have to pick one silently.
///
/// [`MediaTimestampFilter`] holds both, so `any` carries the choice WHOLE: *is there a cue at this
/// exact pts* and *is there a cue at this instant* are two questions the quantifier keeps apart, and
/// `count` is *how many cues are there*.
impl crate::DefaultVecMarker for MediaTimestamp {
  type Marker = crate::QuantifiedMarker<Vec<MediaTimestamp>>;
}

/// The filter that guards a [`MediaTimestamp`] column: an IDENTITY facet, a BOUND facet, and the two
/// components a timestamp is made of.
///
/// # Four groups, and TWO of them are identities
///
/// | facet | slots | operand | columns | asks |
/// |---|---|---|---|---|
/// | STRUCTURAL | `exact` | an EXACT timestamp | `pts`, `timebase_*` | which ENCODING a row holds |
/// | SEMANTIC | `eq`, `ne`, `in_`, `not_in` | an EXACT timestamp | `nanos` | which INSTANT it is at |
/// | BOUND | `gt`, `gte`, `lt`, `lte` | any nameable POSITION | `nanos` | where it sits on the timeline |
/// | COMPONENT | `pts`, `timebase` | that half's own filter | one column each | one column, on its own terms |
///
/// # `exact` and `eq` are two identities, and neither is the other's approximation
///
/// | | `exact: "1 @ 1/1000"` | `eq: "1 @ 1/1000"` |
/// |---|---|---|
/// | lowers to | `pts = 1 AND tb_num = 1 AND tb_den = 1000` | `nanos = 1000000` |
/// | admits `1000 @ 1/1000000` | **no** — a different encoding | **yes** — the same instant |
/// | admits a sub-nanosecond neighbour | **no** | **yes** — they share a position |
/// | truncation | NONE: the columns are the value | inherits it: a position is a bucket |
/// | cross-timebase | no, by construction | yes, by construction |
///
/// Both take the SAME operand — a `{pts, timebase}` pair or the text that spells one — and a clock
/// string is refused by both, for the reason below. What differs is which columns the operand
/// reaches, and therefore which question is being asked. `exact` is *find the row I wrote*; `eq` is
/// *find what happened then*.
///
/// **Neither subsumes the other and both are exact about what they are.** `eq` is coarser in two
/// directions at once — across timebases and below the nanosecond — and that is not a defect to be
/// fixed by `exact`, it is what a position IS. A client de-duplicating rows wants `exact`; a client
/// asking what was playing at an instant wants `eq`, and would be wrong to be handed structural
/// equality instead, since the row it is looking for was very likely written in another timebase.
///
/// **ENDORSED, 2026-08-29.** PR #453's 呈裁 5 put the two-slot design up for a ruling — whether
/// `eq`/`ne`/`in`/`notIn` should stay SEMANTIC beside a STRUCTURAL `exact`, or whether one of them
/// should have been the other — and the ruling kept both slots exactly as the table above reads:
/// the identity four stay on the derived position, `exact` stays the value-leaf tuple, and neither
/// moves. The general law ruled beside it says the same thing one level up and for every citizen —
/// *a derived leaf serves the SEMANTIC order only; every STRUCTURAL judgment walks VALUE leaves
/// only*, written out at [`ColumnShape`](crate::ColumnShape) — so this house's two slots are that
/// law's two sides rather than a local arrangement. What the law DID move is where a structural
/// judgment is spelled elsewhere: pagination's null test and an element's row-value equality both
/// walked the whole width and now walk the value leaves (ingraph #454, #455).
///
/// **There is no `notExact`, and the omission is reasoned.** Its complement is a set nobody asks
/// for: excluding ONE encoding while keeping every other encoding of the same instant. A client
/// wanting "not this instant" already has `ne`, which is the wider and the useful exclusion. If a
/// use appears it is one slot and one `NOT ( … )` conjunct — the shape the timebase citizen's
/// `excluded` already has — and the same argument extends to `in`/`notIn` twins, which would double
/// the identity surface for a question asked once.
///
/// Both groups hold the same Rust type — a [`MediaTimestamp`] — and the difference is entirely in what
/// the DOOR admits. An identity operand must be an exact `{pts, timebase}` pair or the exact text
/// that spells one; a bound operand may additionally be `{seconds}`, `{nanos}`, or a CLOCK STRING
/// such as `"0:01:30.5"`. A wide form lands as a timestamp in nanoseconds, which is a value like any
/// other.
///
/// # Why the BOUND facet takes more shapes than either identity
///
/// **The asymmetry is the same law the timebase's reduction states, transposed.** Both sides of a
/// crossing must go through ONE function or they select nothing: a stored row's sort key is
/// [`MediaTimestamp::to_nanos`] applied to the pair the stream declared, so an identity operand that goes
/// through that same function matches exactly, by construction. A clock string does not go through
/// it — it is an independent route to a number — so an equality against one is a numeric
/// COINCIDENCE rather than an identity, and it lands or misses on sub-nanosecond rounding nobody
/// wrote. `mediatime` says the same thing about its own rendering: the clock *is lossy and has no
/// inverse*.
///
/// As a BOUND the objection evaporates. "Everything after 0:01:30.5" is exactly the question a clock
/// string asks, and a boundary moved by a fraction of a nanosecond selects the same rows.
///
/// **A bare number is refused in both groups**, for the reason it is refused at a timebase: `90` could
/// be a `pts`, a count of seconds or a count of nanoseconds, and those are three different instants.
/// A parser that picked one would be guessing at what a client meant, silently.
///
/// # The components are recursive
///
/// `timebase` is a whole [`TimebaseFilter`] — a citizen nested inside a citizen — so every facet
/// that filter has is reachable here: `timebase: { eq: "MPEG_90K" }` selects the rows counted on the
/// MPEG clock whatever instant they name, and `timebase: { numerator: { gt: 1 } }` reaches two
/// levels down. `pts` is the raw stored count, which is a question about the ENCODING rather than
/// about time — two rows at one instant in different timebases have different `pts`.
///
/// # The wire face is DECLARED, not written
///
/// `#[ingraph(composed)]` reads the eleven slots below once and emits the registration, the parse
/// and the render from them. The four BOUND slots hold [`MediaInstantBound`] rather than [`MediaTimestamp`],
/// and that is this face's one shape rule: a crossing is one row per type, so the value door and
/// the wider bound door cannot both be spelled on `MediaTimestamp` — see the crossing on `MediaInstantBound`,
/// which is where the argument is.
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed)]
pub struct MediaTimestampFilter {
  exact: Option<MediaTimestamp>,
  eq: Option<MediaTimestamp>,
  ne: Option<MediaTimestamp>,
  in_: Option<Box<[MediaTimestamp]>>,
  not_in: Option<Box<[MediaTimestamp]>>,
  gt: Option<MediaInstantBound>,
  gte: Option<MediaInstantBound>,
  lt: Option<MediaInstantBound>,
  lte: Option<MediaInstantBound>,
  pts: Option<ScalarFilter<i64>>,
  timebase: Option<TimebaseFilter>,
}

impl MediaTimestampFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      exact: None,
      eq: None,
      ne: None,
      in_: None,
      not_in: None,
      gt: None,
      gte: None,
      lt: None,
      lte: None,
      pts: None,
      timebase: None,
    }
  }

  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
  /// field.
  ///
  /// Inherent as well as [`GraphqlFilter::is_empty`]; see [`TimebaseFilter::is_empty`].
  ///
  /// [`TimebaseFilter::is_empty`]: super::TimebaseFilter::is_empty
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.exact.is_none()
      && self.eq.is_none()
      && self.ne.is_none()
      && self.in_.is_none()
      && self.not_in.is_none()
      && self.gt.is_none()
      && self.gte.is_none()
      && self.lt.is_none()
      && self.lte.is_none()
      && match &self.pts {
        Some(pts) => pts.is_empty(),
        None => true,
      }
      && match &self.timebase {
        Some(timebase) => timebase.is_empty(),
        None => true,
      }
  }

  /// The stored count's own filter — the ENCODING rather than the instant.
  #[inline]
  pub const fn pts(&self) -> Option<&ScalarFilter<i64>> {
    self.pts.as_ref()
  }

  /// The timebase's own filter, whole — the nested citizen.
  #[inline]
  pub const fn timebase(&self) -> Option<&TimebaseFilter> {
    self.timebase.as_ref()
  }

  opt_accessor!(exact: MediaTimestamp => with_exact, set_exact, maybe_exact, update_exact);
  opt_accessor!(eq: MediaTimestamp => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: MediaTimestamp => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(in_: [MediaTimestamp] => with_in_, set_in_, maybe_in_, update_in_);
  opt_accessor!(not_in: [MediaTimestamp] => with_not_in, set_not_in, maybe_not_in, update_not_in);
  opt_accessor!(gt: MediaInstantBound => with_gt, set_gt, maybe_gt, update_gt);
  opt_accessor!(gte: MediaInstantBound => with_gte, set_gte, maybe_gte, update_gte);
  opt_accessor!(lt: MediaInstantBound => with_lt, set_lt, maybe_lt, update_lt);
  opt_accessor!(lte: MediaInstantBound => with_lte, set_lte, maybe_lte, update_lte);

  /// Replace the stored count's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_pts(mut self, pts: ScalarFilter<i64>) -> Self {
    self.set_pts(pts);
    self
  }

  /// Replace the stored count's filter (in place).
  #[inline]
  pub fn set_pts(&mut self, pts: ScalarFilter<i64>) -> &mut Self {
    self.pts = Some(pts);
    self
  }

  /// Replace the timebase's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_timebase(mut self, timebase: TimebaseFilter) -> Self {
    self.set_timebase(timebase);
    self
  }

  /// Replace the timebase's filter (in place).
  #[inline]
  pub fn set_timebase(&mut self, timebase: TimebaseFilter) -> &mut Self {
    self.timebase = Some(timebase);
    self
  }
}

impl Default for MediaTimestampFilter {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// An instant does not fit `i64` nanoseconds.
///
/// Raised by [`MediaTimestamp::to_nanos`] and [`MediaTimeRange::to_nanos`], which neither panic nor saturate:
/// `i64` nanoseconds span about ±292 years, so a value outside them is not a large media timestamp
/// but a wrong one, and the storage boundary is the last place it can still be refused rather than
/// silently turned into a different instant.
///
/// [`MediaTimeRange::to_nanos`]: super::MediaTimeRange::to_nanos
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NanosecondOverflow {
  nanos: i128,
}

impl NanosecondOverflow {
  /// The nanosecond count that did not fit.
  ///
  /// Exact rather than clamped: the conversion computes in `i128`, which the product cannot
  /// overflow, so the number reported here is the one the caller asked for.
  #[inline]
  pub const fn nanos(&self) -> i128 {
    self.nanos
  }
}

impl fmt::Display for NanosecondOverflow {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{} nanoseconds does not fit an i64", self.nanos)
  }
}

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

/// The nanosecond conversion's multiplier, as the `i128` the whole product is computed in.
const NANOS_PER_SECOND: i128 = 1_000_000_000;