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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! WHEN IT HAPPENED, AND WHAT WAS THERE: [`TimeRange`], the stretch of the timeline a thing occupies,
//! and [`TimeRanged<T>`](TimeRanged), the thing beside its stretch.
//!
//! [`super`]'s law is ONE NAME PER INVARIANT, arriving when a caller asks for it, and this house is
//! that law with TWO names arriving together — for [`lang`](super::lang)'s reason read at a smaller
//! scale. The invariant is one sentence, `start <= end`, and the second name is not a second
//! invariant: [`TimeRanged<T>`](TimeRanged) is a range and a payload, so everything it promises about
//! the timeline it promises BY HOLDING the first type rather than by restating it. A pair whose range
//! half were two loose [`Timestamp`](crate::Timestamp)s would be a place for the invariant to be
//! missing.
//!
//! ```text
//!   TimeRange       start, end                  two instants — four columns
//!   TimeRanged<T>   the range, and a payload    four columns, and T's
//! ```
//!
//! # The COMPONENT is [`Timestamp`](crate::Timestamp), and every face composes ITS face
//!
//! Not one line here spells an instant's storage, its wire form or its comparison words a second
//! time. The columns are `Timestamp::SEGMENTS` twice under two names, the binds are its binds, the
//! decode is its decode, the sub-document is its sub-document, and the two component filters are
//! `ScalarFilter<Timestamp>` — the same `TimestampFilter` a bare instant column publishes. What this
//! house adds is the PAIR: an invariant between two instants, and the words that ask about the
//! stretch between them.
//!
//! # HALF-OPEN, `[start, end)` — and the convention is the FAMILY's rather than this crate's
//!
//! `start` is IN the stretch and `end` is NOT. That is `mediatime`'s own ruling on the type of the
//! same name — *"A half-open time range `[start, end)` in a given `Timebase`"*, `mediatime`
//! `src/lib.rs:1886` — and it is binding here rather than persuasive: every span these citizens will
//! STORE arrives from that convention. `mediagraph` carries the same reading one crate further out,
//! on its own wrapper (`types/time/timerange/mod.rs:25`) and on the sound-event span its message
//! layer emits. A closed twin in this crate would flip the boundary instant's membership silently at
//! the storage crossing, which is a wrong answer reported as a right one.
//!
//! What half-openness BUYS is the thing a timeline needs most: two ABUTTING spans do not overlap.
//! `[0, 10)` and `[10, 20)` share no instant, so a segmentation that tiles a track produces no
//! spurious meets — and a stored instant belongs to exactly ONE of two abutting spans.
//!
//! # The interval vocabulary is CLOSED at three, and the three ARE the family's table
//!
//! `overlaps`, `contains`, `within` — ruled 2026-08-28 as the minimal closed set, with no Allen-13
//! behind it. The predicates are not derived afresh here: `mediagraph`'s own `TimeRangeFilter`
//! states them (`types/time/timerange/mod.rs:519-533`) and renders exactly these operators
//! (`comparison.rs:294-311`), so what follows is that table read into this crate's spelling.
//!
//! | word | operand | true when |
//! |---|---|---|
//! | `contains` | an instant `t` | `start <= t AND end > t` |
//! | `contains` | a span `[a, b)` | `start <= a AND end >= b` |
//! | `overlaps` | a span `[a, b)` | `start < b AND end > a` |
//! | `within` | a span `[a, b)` | `start >= a AND end <= b` |
//!
//! **Three asymmetries in that table are the half-openness showing through**, and all three are
//! load-bearing:
//!
//! * `contains` an INSTANT admits `t == start` and refuses `t == end`, which is membership of a
//!   half-open set said exactly.
//! * `contains` a SPAN admits `end == b`, because the operand's own end is excluded from it too —
//!   `[0, 10)` does contain `[0, 10)`.
//! * `overlaps` is STRICT ON BOTH SIDES, so the abutting pair above answers false. An intersection
//!   of width zero is empty, and that is the one word open ends change.
//!
//! Every one of the four rows is still expressible in the two component filters this same face
//! publishes, and that is the honest statement of what the words are FOR: `overlaps` is the CROSSED
//! pair — the operand's END against the column's start — and a caller hand-deriving it writes the
//! uncrossed pair about half the time, which is `within` and answers rows. Naming them makes the
//! crossing the framework's to get right once, at the right strictness.
//!
//! Closed means additive: a fourth word arrives by being added, never by reshaping these three.
//!
//! # `contains` takes ONE OPERAND OF TWO SHAPES, which is how the point question stays inside three
//!
//! [`Contained`] is an instant or a span, and `mediagraph`'s own `Contained` is the same enum with
//! the same two variants and the same argument: *one operator over two operand shapes rather than
//! two operators, because a client asking "does this range contain that" means one thing and the
//! answer differs only in how many endpoints the question has*.
//!
//! It is what a CLOSED reading would have got for free and half-openness takes away. Under closed
//! intervals a point is a zero-width range and `contains` subsumes it; under half-open ones it does
//! not — `[t, t)` is degenerate, and neither `contains([t, t))` nor `overlaps([t, t))` is the
//! membership test `start <= t AND end > t`. So the shape that was implicit becomes explicit, and
//! the ruled set stays at three words because the second shape rides the operand rather than a
//! fourth name.
//!
//! # The DEGENERATE range is ADMITTED, and `mediatime` is what settles it
//!
//! `start == end` is legal. That is not a reading of half-openness — under half-openness `[t, t)`
//! covers nothing — it is the family's POSTURE, stated twice: *"When `start == end`, the range is
//! degenerate (an instant); see `Self::instant`"* (`mediatime` `src/lib.rs:1888`) and *"Accepts
//! `start == end` (degenerate instant range)"* on its `try_new` (`src/lib.rs:1973`). It ships
//! `TimeRange::instant(ts)` and `is_instant()` as first-class rows, so the value is a MARKER rather
//! than nothing, and this crate matches that posture exactly — the same two names, the same
//! admission.
//!
//! **Where the two readings part company is worth stating rather than smoothing.** The two-inequality
//! forms decide the relation between two NON-degenerate half-open extents exactly; handed a
//! degenerate operand they treat it as its POSITION rather than as the empty set, and the answers
//! differ:
//!
//! | asked | the form answers | strict set semantics would answer |
//! |---|---|---|
//! | `[0, 10)`.overlaps(`[10, 10)`) | false (`10 < 10` fails) | false (empty ∩ anything) |
//! | `[0, 10)`.overlaps(`[5, 5)`) | true (`0 < 5 AND 10 > 5`) | false (empty ∩ anything) |
//! | `[0, 10)`.contains(`[10, 10)`) | true (`0 <= 10 AND 10 >= 10`) | true (empty ⊆ anything) |
//! | `[0, 10)`.contains(`[20, 20)`) | false (`10 >= 20` fails) | true (empty ⊆ anything) |
//!
//! The FORM's column is what this crate answers, on both backends, and it is the reading the family's
//! own naming asks for: a degenerate range is an *instant*, so a word handed one answers about that
//! instant. A caller that means the membership test writes `contains` with an INSTANT operand, which
//! is the row that exists for it. Each of the four is pinned by a test.
//!
//! # `start > end` REFUSES, at construction
//!
//! [`InvertedTimeRange`] — a struct rather than a one-variant enum, which is the shape
//! [`NegativeCount`](crate::NegativeCount) and
//! [`OutsideTheInterval`](crate::OutsideTheInterval) already have for a type with exactly one way to
//! be refused. It carries the PAIR, for [`TimestampPartsError::Unnormalised`]'s reason: either
//! instant alone is unremarkable and the two together are the fact a reader needs.
//!
//! `mediatime` refuses the same pair and answers differently — its `new` PANICS and its `try_new`
//! hands back an [`Option`] (`src/lib.rs:1934`, `1973`). The divergence is deliberate and recorded:
//! that type's door is a CONSTRUCTOR, where this one is also a DECODE door — the SQL row, the BSON
//! document and the cursor all re-validate through it — and a decode has to NAME what it refused.
//! An `Option` at a decode is a refusal with the reason thrown away.
//!
//! Every reader re-validates through that one door, which is [`lang`](super::lang)'s own three-reader
//! discipline applied to an invariant BETWEEN columns rather than inside one.
//!
//! [`TimestampPartsError::Unnormalised`]: crate::TimestampPartsError::Unnormalised

use core::fmt;

use crate::{
  CompositeFilterMarker, CompositeMarker, DefaultMarker, DefaultVecMarker, QuantifiedMarker,
  ScalarFilter, Timestamp, ToGraphqlFilter,
};

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

#[cfg(test)]
mod tests;

pub use ranged::{TimeRanged, TimeRangedFilter};

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

#[cfg(feature = "mongo")]
pub use mongo::{MongoTimeRangeComparison, MongoTimeRangedComparison};

/// A HALF-OPEN stretch of the UTC timeline, `[start, end)`: `start` is in it and `end` is not.
///
/// # The reading is the FAMILY's — `mediatime` `src/lib.rs:1886`
///
/// *"A half-open time range `[start, end)` in a given `Timebase`."* Every span this type will store
/// arrives from that convention, so it is inherited rather than chosen. What it buys is that two
/// ABUTTING stretches share no instant: `[0, 10)` and `[10, 20)` do not overlap, and a stored
/// instant belongs to exactly one of them. See the module note for the whole predicate table and for
/// the three places the open end shows through.
///
/// # The invariant is `start <= end`, and it holds because nothing else can build one
///
/// [`new`](Self::new) is the only fallible door and [`instant`](Self::instant) is the only other
/// door at all, so a value of this type has passed the check. There are no public fields and no
/// setters: a range is replaced rather than edited, because a setter for either end would be a
/// moment at which the pair is not a range.
///
/// A DEGENERATE stretch — `start == end` — is admitted, which is `mediatime`'s posture and not a
/// consequence of half-openness: that type calls the value *a degenerate (instant) range* and ships
/// `instant` and `is_instant` for it. See [`instant`](Self::instant).
///
/// # There is NO [`Ord`], and the reason is `mediatime`'s own
///
/// *"Ranges have no single order to derive: by start, by end and by length are three different
/// answers, and overlapping ranges are not ordered at all"* — `mediatime` `src/lib.rs:1904`. This
/// crate takes the same posture and for the same reason, and it declines [`PartialOrd`] with it: a
/// partial order here would be a claim about which of two spans comes first, which is exactly the
/// question that has three answers. Compare the part you mean — [`start`](Self::start) and
/// [`end`](Self::end) hand back [`Timestamp`]s, which are ordered.
///
/// [`Eq`] and [`Hash`] stay, as they do there: two stretches are the same stretch when both
/// endpoints are.
///
/// **A KEYSET still needs a total order, and it is a STORAGE order rather than a semantic one.** It
/// is stated once, at [`CursorValue`](crate::CursorValue)'s row in this house's `storage` module —
/// start then end, which is what the cursor's bytes, the SQL row value and the BSON sub-document all
/// read off this struct's field order. Keeping it there rather than on the type is the whole of the
/// distinction: a page needs *an* order, and a caller must not be handed one dressed as *the* order.
///
/// # Examples
///
/// ```
/// use ingraph::{TimeRange, Timestamp};
///
/// let start: Timestamp = "2026-08-28T09:00:00Z".parse().unwrap();
/// let end: Timestamp = "2026-08-28T09:01:00Z".parse().unwrap();
///
/// let minute = TimeRange::new(start, end).unwrap();
/// assert_eq!(minute.start(), start);
///
/// // The start is IN the stretch and the end is NOT.
/// assert!(minute.holds(start));
/// assert!(!minute.holds(end));
///
/// // Inverted refuses; degenerate does not.
/// assert!(TimeRange::new(end, start).is_err());
/// assert!(TimeRange::new(start, start).is_ok());
/// assert!(TimeRange::instant(start).is_instant());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimeRange {
  start: Timestamp,
  end: Timestamp,
}

impl TimeRange {
  /// The stretch from `start` up to but not including `end`, or the reason the two are not one.
  ///
  /// # Errors
  ///
  /// [`InvertedTimeRange`] when `end` is EARLIER than `start`. Equal instants ARE a stretch — see
  /// [`instant`](Self::instant), where the family's posture is cited.
  #[inline]
  pub fn new(start: Timestamp, end: Timestamp) -> Result<Self, InvertedTimeRange> {
    if end < start {
      return Err(InvertedTimeRange { start, end });
    }
    Ok(Self { start, end })
  }

  /// The DEGENERATE stretch at one instant — `start == end`.
  ///
  /// `mediatime` ships this constructor under this name and calls the value *a degenerate (instant)
  /// range* (`src/lib.rs:1888`, `1987`), so it is a MARKER rather than nothing: a cue with no
  /// duration, a scene boundary, a chapter mark.
  ///
  /// **It is not the way to ask a POINT question.** Under half-openness `[t, t)` covers no instant
  /// at all, so neither [`contains`](Self::contains) nor [`overlaps`](Self::overlaps) handed one is
  /// the membership test — see [`holds`](Self::holds), and [`Contained::Instant`], which is the
  /// operand shape a filter asks it with.
  ///
  /// Infallible, and it is the one door that can be: `at <= at` needs no check.
  #[inline]
  #[must_use]
  pub const fn instant(at: Timestamp) -> Self {
    Self { start: at, end: at }
  }

  /// The first instant of the stretch, which IS in it.
  #[inline]
  #[must_use]
  pub const fn start(&self) -> Timestamp {
    self.start
  }

  /// The instant the stretch stops BEFORE, which is NOT in it.
  #[inline]
  #[must_use]
  pub const fn end(&self) -> Timestamp {
    self.end
  }

  /// True while the two ends coincide — the DEGENERATE stretch, `mediatime`'s own name and predicate.
  #[inline]
  #[must_use]
  pub fn is_instant(&self) -> bool {
    self.start == self.end
  }

  /// **MEMBERSHIP: is `at` in this stretch** — `start <= at AND end > at`.
  ///
  /// Half-open said exactly: the start is admitted and the end is refused, so a stored instant
  /// belongs to exactly one of two abutting stretches. It is the family's `contains`-an-INSTANT row
  /// (`mediagraph` `types/time/timerange/mod.rs:521`), and the filter reaches it through
  /// [`Contained::Instant`] rather than through a fourth word.
  ///
  /// A degenerate stretch holds NOTHING: `[t, t).holds(t)` is false, because `t > t` is false. That
  /// is half-openness applied to itself, and it is why a degenerate range cannot stand in for a
  /// point question.
  #[inline]
  #[must_use]
  pub fn holds(&self, at: Timestamp) -> bool {
    self.start <= at && self.end > at
  }

  /// **The two stretches MEET** — their half-open extents intersect: `self.start < other.end AND
  /// self.end > other.start`.
  ///
  /// STRICT ON BOTH SIDES, and that is the open end showing through: an intersection of width zero
  /// is empty, so `[0, 10)` and `[10, 20)` ABUT rather than overlap. It is the one word of the three
  /// that a closed reading would have got wrong.
  ///
  /// The CROSSED inequality is the other half of why the word exists — the operand's END against
  /// this stretch's start — and reversing either side gives [`within`](Self::within), which is a
  /// different question that answers rows.
  ///
  /// Symmetric. It is the Rust half of the predicate
  /// [`SqlTimeRangeComparison`](crate::SqlTimeRangeComparison) lowers, and the two are checked
  /// against each other on a live engine rather than trusted to agree.
  #[inline]
  #[must_use]
  pub fn overlaps(&self, other: &Self) -> bool {
    self.start < other.end && self.end > other.start
  }

  /// **`other` is entirely inside this stretch** — `self.start <= other.start AND self.end >=
  /// other.end`.
  ///
  /// Both comparisons NON-STRICT, and the equal end is the half-openness showing through a SECOND
  /// time: the operand's own end is excluded from the operand too, so `[0, 10)` does contain
  /// `[0, 10)`. Containment compares LIKE boundaries — a closed start against a closed start, an
  /// open end against an open end — and coincident like boundaries are contained.
  ///
  /// Handed a DEGENERATE stretch this answers about its POSITION rather than about the empty set —
  /// see the module note's table, where the four boundary truths are derived. The membership test is
  /// [`holds`](Self::holds).
  #[inline]
  #[must_use]
  pub fn contains(&self, other: &Self) -> bool {
    self.start <= other.start && self.end >= other.end
  }

  /// **This stretch is entirely inside `other`** — [`contains`](Self::contains) read from the other
  /// end, and non-strict for its reason.
  ///
  /// Both directions are named because a FILTER can only ask about the column: `within` is *this
  /// row's stretch is inside the operand* and `contains` is *the operand is inside this row's
  /// stretch*, which are two questions rather than one question twice.
  #[inline]
  #[must_use]
  pub fn within(&self, other: &Self) -> bool {
    other.contains(self)
  }
}

/// The half-open interval notation, both endpoints RFC 3339 — `[2026-08-28T09:00:00Z,
/// 2026-08-28T09:01:00Z)`.
///
/// **The mismatched brackets are the point rather than decoration**, which is `mediatime`'s own
/// sentence for its own rendering (`src/lib.rs:2136`): this type is closed at `start` and open at
/// `end`, and `[…)` is the notation that says so where a dash or a slash would leave a reader to
/// guess whether `end` is inside. The rendering therefore teaches the semantics the type documents.
///
/// It is a ROUND TRIP: [`FromStr`](core::str::FromStr) reads exactly this form back, which is what
/// [`ContainedOperand`]'s scalar door spends — a client sends one of these strings for a SPAN and a
/// bare RFC 3339 instant for a POSITION, and the syntax says which it meant.
///
/// Each endpoint is rendered by [`Timestamp`]'s own `Display` and inherits everything it documents.
impl fmt::Display for TimeRange {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "[{}, {})", self.start, self.end)
  }
}

/// The inverse of [`Display`](fmt::Display), and the door [`ContainedOperand`] reads a SPAN through.
///
/// Each endpoint goes through [`Timestamp`]'s own parser, so every spelling that type admits is
/// admitted here and there is no second grammar; the PAIR is then built through
/// [`new`](TimeRange::new), so a text naming an inverted stretch is refused rather than held.
impl core::str::FromStr for TimeRange {
  type Err = ParseTimeRangeError;

  fn from_str(text: &str) -> Result<Self, Self::Err> {
    let inner = text
      .strip_prefix('[')
      .and_then(|rest| rest.strip_suffix(')'))
      .ok_or(ParseTimeRangeError::Notation)?;
    let (start, end) = inner.split_once(',').ok_or(ParseTimeRangeError::Notation)?;

    let start = start
      .trim()
      .parse::<Timestamp>()
      .map_err(ParseTimeRangeError::Endpoint)?;
    let end = end
      .trim()
      .parse::<Timestamp>()
      .map_err(ParseTimeRangeError::Endpoint)?;

    Self::new(start, end).map_err(ParseTimeRangeError::Inverted)
  }
}

/// Why a string is not a stretch.
///
/// Three arms because there are three places one can fail, and each names a different fix: the
/// NOTATION is this crate's, an ENDPOINT's grammar is [`Timestamp`]'s, and the ORDER is the pair's.
/// An enum rather than [`InvertedTimeRange`]'s struct for exactly that reason — a type with one way
/// to be refused publishes a struct, and this has three.
#[derive(Debug, Clone)]
pub enum ParseTimeRangeError {
  /// The text is not `[<start>, <end>)` — the half-open notation this type renders.
  Notation,
  /// An endpoint does not name an instant. Carries jiff's own error, which names the component it
  /// refused and where in the input.
  Endpoint(jiff::Error),
  /// Both endpoints are instants and the second precedes the first.
  Inverted(InvertedTimeRange),
}

impl fmt::Display for ParseTimeRangeError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Notation => f.write_str(
        "a time range is written `[<start>, <end>)` — the brackets are the half-open reading rather \
         than decoration",
      ),
      Self::Endpoint(cause) => write!(f, "an endpoint is not an instant: {cause}"),
      Self::Inverted(refused) => fmt::Display::fmt(refused, f),
    }
  }
}

impl core::error::Error for ParseTimeRangeError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Notation => None,
      Self::Endpoint(cause) => Some(cause),
      Self::Inverted(refused) => Some(refused),
    }
  }
}

/// Why two instants are not a range: the later one is EARLIER.
///
/// A struct rather than a one-variant enum, which is [`NegativeCount`](crate::NegativeCount)'s shape
/// and for its reason — a type with exactly one way to be refused publishes one, and a variant list
/// of length one is a vocabulary pretending to be open.
///
/// It carries the PAIR because either instant alone is unremarkable: what is wrong is the ORDER, and
/// an error naming one end would leave a reader to guess the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InvertedTimeRange {
  start: Timestamp,
  end: Timestamp,
}

impl InvertedTimeRange {
  /// The instant offered as the start.
  #[inline]
  #[must_use]
  pub const fn start(&self) -> Timestamp {
    self.start
  }

  /// The instant offered as the end, which is earlier than the start.
  #[inline]
  #[must_use]
  pub const fn end(&self) -> Timestamp {
    self.end
  }
}

impl fmt::Display for InvertedTimeRange {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "a time range ends no earlier than it starts, and this one ends at {} having started at {}",
      self.end, self.start
    )
  }
}

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

/// **The OPERAND**, and it is a newtype for exactly [`LanguageIdOperand`]'s reason: GraphQL keeps
/// objects and input types in ONE namespace, and [`TimeRange`] is an object.
///
/// What it publishes is an input object of two required instants — see this house's
/// `graphql` module, where the door is written and where the construction refusal is spent. There is
/// no second grammar in it: the two seats are [`Timestamp`]'s own scalar, and the pair is handed to
/// [`TimeRange::new`].
///
/// [`LanguageIdOperand`]: crate::LanguageIdOperand
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimeRangeOperand(TimeRange);

impl TimeRangeOperand {
  /// Wrap a range as an operand.
  #[inline]
  #[must_use]
  pub const fn new(range: TimeRange) -> Self {
    Self(range)
  }

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

impl From<TimeRange> for TimeRangeOperand {
  #[inline]
  fn from(range: TimeRange) -> Self {
    Self(range)
  }
}

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

/// **What `contains` was handed: one INSTANT, or a whole SPAN.**
///
/// One operator over two operand shapes rather than two operators, which is `mediagraph`'s own
/// `Contained` — the same enum, the same two variants, and its argument verbatim: *a client asking
/// "does this range contain that" means one thing, and the answer differs only in how many endpoints
/// the question has* (`types/time/timerange/mod.rs:328`).
///
/// It is what HALF-OPENNESS makes necessary. Under a closed reading a position is a zero-width range
/// and one span-shaped operand answers both questions; under this one `[t, t)` covers nothing, so
/// neither `contains([t, t))` nor `overlaps([t, t))` is the membership test. The second shape is
/// therefore explicit — and the ruled vocabulary stays CLOSED AT THREE, because what grew is the
/// operand rather than the word list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Contained {
  /// A single position: the stretch HOLDS it — `start <= t AND end > t`.
  Instant(Timestamp),
  /// A whole stretch: this one holds all of it — `start <= a AND end >= b`.
  Span(TimeRange),
}

impl From<Timestamp> for Contained {
  #[inline]
  fn from(at: Timestamp) -> Self {
    Self::Instant(at)
  }
}

impl From<TimeRange> for Contained {
  #[inline]
  fn from(span: TimeRange) -> Self {
    Self::Span(span)
  }
}

/// **THE TWO-SHAPE OPERAND**, and a newtype for [`TimeRangeOperand`]'s reason one door over: a
/// crossing is one row per type, so a shape serving a second door has to spell that door on a type
/// of its own.
///
/// Its wire face is a SCALAR rather than an input object, which is the one place this house's two
/// operand doors differ and the difference is the shapes: `overlaps` and `within` take exactly one
/// shape, so an input object publishes its two seats and omits nothing; `contains` takes two, and
/// GraphQL has no input union — so the shapes ride one scalar whose SYNTAX says which arrived, a
/// bare RFC 3339 instant or the `[start, end)` a stretch renders. That is `mediagraph`'s
/// `ContainedOperand` exactly (`types/time/timerange/graphql.rs:167`), under its name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ContainedOperand(Contained);

impl ContainedOperand {
  /// Wrap a [`Contained`] as an operand.
  #[inline]
  #[must_use]
  pub const fn new(contained: Contained) -> Self {
    Self(contained)
  }

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

impl From<Contained> for ContainedOperand {
  #[inline]
  fn from(contained: Contained) -> Self {
    Self(contained)
  }
}

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

/// What guards a [`TimeRange`] column: the three INTERVAL words, and the two ENDS.
///
/// | facet | slots | operand | asks about |
/// |---|---|---|---|
/// | INTERVAL | `overlaps`, `within` | [`TimeRangeOperand`] | the stretch as a whole |
/// | INTERVAL | `contains` | [`ContainedOperand`] | a position OR a whole stretch |
/// | COMPONENT | `start`, `end` | `TimestampFilter` | one end of it |
///
/// # The predicates are the FAMILY's table, and half-openness is what shapes them
///
/// | word | operand | true when |
/// |---|---|---|
/// | `contains` | an instant `t` | `start <= t AND end > t` |
/// | `contains` | a span `[a, b)` | `start <= a AND end >= b` |
/// | `overlaps` | a span `[a, b)` | `start < b AND end > a` |
/// | `within` | a span `[a, b)` | `start >= a AND end <= b` |
///
/// It is `mediagraph`'s own (`types/time/timerange/mod.rs:519`), read into this crate's spelling
/// rather than re-derived — and the three asymmetries it names are argued in this house's module
/// note. In one line each: an instant at `start` is IN and an instant at `end` is OUT; a span whose
/// end equals the column's end IS contained, the operand's own end being excluded from it too; and
/// `overlaps` is strict on both sides, so two abutting stretches do not meet.
///
/// # `overlaps` is the CROSSED pair, and it is the word this face exists for
///
/// The operand's END against the column's start and the operand's START against the column's end. A
/// caller deriving it by hand writes the uncrossed pair about half the time, which is `within` and
/// returns rows; a caller who gets the crossing right still has the STRICTNESS to get right, and
/// getting that wrong is a query that reports two abutting spans as meeting. Both are the
/// framework's to hold once.
///
/// # `contains` carries TWO SHAPES, which is how the point question stays inside three words
///
/// See [`Contained`]. Under half-openness a degenerate stretch covers nothing, so the closed
/// reading's *a point is a zero-width range* argument does not survive — and rather than a fourth
/// word, the second shape rides the operand, which is the family's own answer.
///
/// # The two ENDS take [`Timestamp`]'s OWN words, whole
///
/// `start` and `end` are `ScalarFilter<Timestamp>` — the `TimestampFilter` a bare instant column
/// already publishes, with all eight of its operators. Nothing is restated and nothing can drift: a
/// slot added to the instant's filter appears on both of these with it.
///
/// They are what makes the interval vocabulary honest rather than total. *Everything starting after
/// noon* is not an interval relation at all, and it is asked here without any word being invented
/// for it.
///
/// # There is NO shorthand, and the absence is a RULING rather than an omission
///
/// A bare operand at this face would have to mean one of the three interval words, and there is no
/// reading under which it means one rather than the others: the operand does not say whether the
/// client meant *meets*, *covers* or *is covered by*. That is the full-form law's own case — sugar
/// only where nothing is omitted — so a bare value is REFUSED here and named, where every scalar
/// face in this crate reads one as its `eq`. `mediagraph` writes the same refusal as
/// `#[ingraph(composed(shorthand = false))]`.
#[derive(Debug, Clone, PartialEq)]
pub struct TimeRangeFilter {
  pub(crate) overlaps: Option<TimeRangeOperand>,
  pub(crate) contains: Option<ContainedOperand>,
  pub(crate) within: Option<TimeRangeOperand>,
  pub(crate) start: Option<ScalarFilter<Timestamp>>,
  pub(crate) end: Option<ScalarFilter<Timestamp>>,
}

impl TimeRangeFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      overlaps: None,
      contains: None,
      within: None,
      start: None,
      end: None,
    }
  }

  /// True while NO operator slot is set on ANY facet.
  ///
  /// NOT `const`, for the reason [`DetectedLanguageFilter::is_empty`] is not: a nullable component's
  /// own emptiness is the framework's arithmetic and not a `const fn`.
  ///
  /// [`DetectedLanguageFilter::is_empty`]: crate::DetectedLanguageFilter::is_empty
  pub fn is_empty(&self) -> bool {
    self.overlaps.is_none()
      && self.contains.is_none()
      && self.within.is_none()
      && self.start.as_ref().is_none_or(ScalarFilter::is_empty)
      && self.end.as_ref().is_none_or(ScalarFilter::is_empty)
  }

  /// The stretch this column must MEET, where one was asked for.
  #[inline]
  #[must_use]
  pub const fn overlaps(&self) -> Option<&TimeRangeOperand> {
    self.overlaps.as_ref()
  }

  /// The position or stretch this column must HOLD, where one was asked for.
  #[inline]
  #[must_use]
  pub const fn contains(&self) -> Option<&ContainedOperand> {
    self.contains.as_ref()
  }

  /// The stretch this column must be INSIDE, where one was asked for.
  #[inline]
  #[must_use]
  pub const fn within(&self) -> Option<&TimeRangeOperand> {
    self.within.as_ref()
  }

  /// The filter over the stretch's first instant.
  #[inline]
  #[must_use]
  pub const fn start(&self) -> Option<&ScalarFilter<Timestamp>> {
    self.start.as_ref()
  }

  /// The filter over the stretch's last instant.
  #[inline]
  #[must_use]
  pub const fn end(&self) -> Option<&ScalarFilter<Timestamp>> {
    self.end.as_ref()
  }

  /// Ask that this column MEET `range` (consuming).
  #[must_use]
  #[inline]
  pub fn with_overlaps(mut self, range: TimeRange) -> Self {
    self.set_overlaps(range);
    self
  }

  /// Ask that this column MEET `range` (in place).
  #[inline]
  pub fn set_overlaps(&mut self, range: TimeRange) -> &mut Self {
    self.overlaps = Some(TimeRangeOperand::new(range));
    self
  }

  /// Ask that this column HOLD a position or a whole stretch (consuming).
  ///
  /// The argument is anything that is a [`Contained`], so `with_contains(instant)` and
  /// `with_contains(span)` both read as themselves — the two shapes are one word at the call site
  /// as they are one word on the wire.
  #[must_use]
  #[inline]
  pub fn with_contains(mut self, held: impl Into<Contained>) -> Self {
    self.set_contains(held);
    self
  }

  /// Ask that this column HOLD a position or a whole stretch (in place).
  #[inline]
  pub fn set_contains(&mut self, held: impl Into<Contained>) -> &mut Self {
    self.contains = Some(ContainedOperand::new(held.into()));
    self
  }

  /// Ask that this column be INSIDE `range` (consuming).
  #[must_use]
  #[inline]
  pub fn with_within(mut self, range: TimeRange) -> Self {
    self.set_within(range);
    self
  }

  /// Ask that this column be INSIDE `range` (in place).
  #[inline]
  pub fn set_within(&mut self, range: TimeRange) -> &mut Self {
    self.within = Some(TimeRangeOperand::new(range));
    self
  }

  /// Replace the filter over the first instant (consuming).
  #[must_use]
  #[inline]
  pub fn with_start(mut self, start: ScalarFilter<Timestamp>) -> Self {
    self.set_start(start);
    self
  }

  /// Replace the filter over the first instant (in place).
  #[inline]
  pub fn set_start(&mut self, start: ScalarFilter<Timestamp>) -> &mut Self {
    self.start = Some(start);
    self
  }

  /// Replace the filter over the last instant (consuming).
  #[must_use]
  #[inline]
  pub fn with_end(mut self, end: ScalarFilter<Timestamp>) -> Self {
    self.set_end(end);
    self
  }

  /// Replace the filter over the last instant (in place).
  #[inline]
  pub fn set_end(&mut self, end: ScalarFilter<Timestamp>) -> &mut Self {
    self.end = Some(end);
    self
  }
}

/// The bound's row: [`is_empty`](TimeRangeFilter::is_empty), reached where the kind is a parameter
/// rather than a spelling — which is what a [`TimeRangedFilter`] holding one asks of it, and what
/// every filter kind in this crate publishes.
impl crate::GraphqlFilter for TimeRangeFilter {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

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

/// What guards a [`TimeRange`] column — its own filter at both seats, and the same reading
/// [`DetectedLanguage`](crate::DetectedLanguage)'s row takes: a range stores every field it declares,
/// so the two seats name one predicate.
impl CompositeFilterMarker for TimeRange {
  type Filter = TimeRangeFilter;
  type ColumnFilter = TimeRangeFilter;
}

/// The interpretation a [`TimeRange`] field is read under — the framework's COMPOSITE reading, which
/// is the honest one for a value occupying FOUR columns OF ITS OWN: all four can be absent together,
/// which is exactly the VALUE family [`CompositeMarker`] names.
impl DefaultMarker for TimeRange {
  type Marker = CompositeMarker<TimeRange>;
}

/// **A COLLECTION of stretches is asked through the QUANTIFIERS alone**, and the argument is the
/// VOCABULARY's rather than [`DetectedLanguage`](crate::DetectedLanguage)'s.
///
/// That element declines the wide list reading because it carries a FLOAT, so `hasElement` is an
/// exact equality a client cannot mean. A range carries no float and its equality is exact — so the
/// reason here is a different one, and it is about which questions a collection of spans is actually
/// asked.
///
/// Every question this house can ask about ONE stretch lives in [`TimeRangeFilter`], and `any`
/// carries that filter WHOLE — so *is there a span meeting the first minute* is
/// `any: { overlaps: { start: …, end: … } }`, and `count` is *how many spans are there*. Those two
/// are what a caller asks of a speech-segment list, a scene list or a cue list.
///
/// What [`ListFilter`](crate::ListFilter) would add over them is seven operators holding a WHOLE
/// RANGE, and each is either already reachable or is not a question:
///
/// * `hasElement` is exact equality on both endpoints to the nanosecond, which `any: { start: { eq:
///   … }, end: { eq: … } }` already asks and asks more legibly.
/// * `eq` and `ne` are that same equality multiplied by the collection's length, which pins a whole
///   segmentation rather than asking about one.
/// * `gt`, `gte`, `lt` and `lte` compare two collections LEXICOGRAPHICALLY under an order over the
///   ELEMENT, and a stretch HAS no such order — [`TimeRange`] declines [`Ord`] for `mediatime`'s own
///   reason, that by start, by end and by length are three different answers. So those four are not
///   operators this element could publish honestly even if the reading admitted them.
impl DefaultVecMarker for TimeRange {
  type Marker = QuantifiedMarker<Vec<TimeRange>>;
}

/// **The crossing OUT** — a BORROW, resolved by the `#[Object]` this type publishes: the two instants
/// under their own names.
///
/// Unlike [`DetectedLanguage`](crate::DetectedLanguage) there IS an input row beside it — see
/// [`TimeRangeOperand`] — because a client genuinely SENDS a whole range: all three interval words
/// take one, and every instant in it is a value a client can spell exactly. The asymmetry that type
/// records is about a FLOAT operand, and there is none here.
impl crate::ToGraphqlOutput for TimeRange {
  type Output<'a> = &'a Self;

  #[inline]
  fn to_graphql_output(marked: &Self) -> &Self {
    marked
  }
}

/// **The crossing IN** — the operand newtype, and [`TimeRange::new`]'s refusal is spent at its door
/// rather than here.
///
/// [`Infallible`](core::convert::Infallible) for that reason: a [`TimeRangeOperand`] cannot hold a
/// pair the constructor refused, so by the time one exists there is nothing left to check. It is the
/// same division [`LanguageId`](crate::LanguageId)'s row makes — the grammar is checked where the
/// text is read, and the crossing is a move.
impl crate::ToGraphqlInput for TimeRange {
  type Input = TimeRangeOperand;
  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 {
    TimeRangeOperand::new(*operand)
  }
}

/// The filter a payload of type `T` is guarded by, resolved the way the FRAMEWORK resolves one:
/// through `T`'s own [`DefaultMarker`] and that marker's [`ToGraphqlFilter`] row.
///
/// It is written as an alias because [`TimeRanged<T>`](TimeRanged)'s marker rows and its crossing
/// both name it, and a path this long spelled twice is a path that can be spelled two ways.
///
/// **Framework-open by construction**: any `T` a declaration can put in a column has a default
/// marker, so any such `T` can be time-ranged. Nothing here lists which payloads are admitted.
pub type PayloadFilter<T> = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter;