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
//! What a stored [`MediaTimestamp`] occupies, binds and reads back — and the DERIVED column the ordering
//! questions are actually answered on.
//!
//! ```text
//!   ts_pts             i64        the count the stream declared
//!   ts_timebase_num    i32   ┐    the units it counted in — the nested citizen's own two
//!   ts_timebase_den    i32   ┘
//!   ts_nanos           i64?       the position on the timeline, DERIVED and NULLABLE
//! ```
//!
//! # Three columns are the VALUE and one is an INDEX
//!
//! `pts` and the timebase pair are what a row holds; `nanos` is what a row is ordered by. The split
//! is not a convenience — it is the only way both questions can be answered exactly:
//!
//! - **The value has to survive.** A timestamp is a count in a unit, and both halves matter: two
//!   rows at the same instant in different timebases are different values, and a column holding only
//!   an instant could not tell them apart or hand either one back.
//! - **The order cannot be answered by the value.** Two timestamps in different timebases are not
//!   comparable by `pts` at all, so a `gt` lowered onto that column would be silently wrong whenever
//!   a stored timebase differed from the one the query was written in. There is exactly ONE unit a
//!   comparison can be made in, and [`MediaTimestamp::to_nanos`] is the crossing into it.
//!
//! The decode reads the VALUE and never the index — see [`Assemble`](crate::Assemble) below. A
//! derived column that could redefine the value it was derived from is a second authority, and the
//! whole point of deriving it is that there is one.
//!
//! # The overflow posture, stated
//!
//! [`MediaTimestamp::to_nanos`] refuses past `i64` nanoseconds — about ±292 years — and the three places
//! that refusal can land each take it differently:
//!
//! | where | posture |
//! |---|---|
//! | the WRITE | the value columns are exact whatever the instant; the derived column binds `NULL` |
//! | the READ | unaffected — the decode rebuilds from `pts` and the timebase, which never overflow |
//! | the QUERY | an OPERAND that overflows is REFUSED at the crossing, loudly |
//!
//! `NULL` is the honest answer for the index and not a failure to store one: the column models a
//! position on a timeline the value does not have a representable position on. SQL's three-valued
//! logic then does the rest for free — `nanos > ?` is UNKNOWN for such a row, so it is absent from
//! every ordering and identity predicate, which is exactly right, while the row stays present,
//! readable, and reachable through the component facets. Saturating instead would put a garbage
//! instant at the far end of every ordered query and report it as a real one.
//!
//! A cursor takes the same line one step further: it carries the VALUE columns, not the index, so a
//! page boundary is exact for every instant including the ones with no key.

use crate::{
  ColumnEq, ColumnKind, ColumnName, ColumnShape, CursorValue, FieldName, OrderLevel,
  column::column_eq,
};
use mediatime as mt;

use super::{super::Timebase, MediaTimestamp};

#[cfg(test)]
mod tests;

/// The declared count's segment.
pub(super) const PTS: &FieldName = FieldName::new("pts");

/// The nested timebase's segment — the frame the citizen below pushes its own two onto.
pub(super) const TIMEBASE: &FieldName = FieldName::new("timebase");

/// The derived sort key's segment.
pub(super) const NANOS: &FieldName = FieldName::new("nanos");

/// **The columns a timestamp spans**, and the one authority the width, the bind, the decode and
/// every lowering read.
///
/// The middle entry is a COMPOSITE, which is what makes this a citizen holding a citizen rather than
/// a type that happens to have three numbers: the timebase's own segments are read off its
/// [`ColumnKind`] row instead of being restated, so a rename there moves these columns too and
/// nothing here has to know that a timebase is two of them.
///
/// **The last entry is [`Nullable`](ColumnShape::Nullable), and it is this module's posture spelled
/// where a renderer can read it.** The table above says the derived column binds `NULL` past the
/// ±292-year ceiling; under a nullability that was the FIELD's, a required `at: MediaTimestamp`
/// declared `at_nanos NOT NULL` and the engine refused the very row the write path promised to
/// store. The bit is the LEAF's, so the promise and the schema are one statement — and the same bit
/// keeps `nanos` out of the value, which is what the decode below and an optional citizen's `None`
/// test both already assume.
pub(super) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(PTS)),
  ColumnShape::Composite {
    field: Some(ColumnName::of(TIMEBASE)),
    segments: <Timebase as ColumnKind>::SEGMENTS,
  },
  ColumnShape::Nullable(ColumnName::of(NANOS)),
];

/// **The order those four columns MEAN**, which is not the order they are written in.
///
/// The leaves are numbered as [`width`](crate::width) counts them — `pts` is `0`, the timebase's
/// `num` and `den` are `1` and `2`, and the derived `nanos` is `3` — so this sequence is
/// *nanos, pts, num, den*.
///
/// # Why the derived leaf LEADS
///
/// `pts` is a count in a unit the row itself declares, so two rows on different timebases are not
/// comparable through it at all: `900` at `1/1000` is earlier than `30` at `1/25`, and a sort that
/// led with the count would put them the other way round. The one quantity every stored instant
/// shares is the derived nanosecond position, which is what `to_nanos` computes and this column
/// holds — so the SEMANTIC order leads with it, and the value leaves follow as the tie-break that
/// gives two rows at the same instant with different spellings a stable total order.
///
/// # It is the 2026-08-29 law's SEMANTIC half
///
/// *A derived leaf serves the semantic order only; every structural judgment walks value leaves
/// only.* The structural half is landed — the keyset's null test walks
/// [`value_width`](crate::value_width) and this column is not in it, which is ingraph #454's repair
/// — and this const is the semantic half stated where a renderer can read it. Ordering by a derived
/// leaf is the lawful side of that discipline rather than an exception to it: participation in the
/// ORDER is exactly what the leaf is computed for.
///
/// **The renderers READ it**, through [`OrderTerm::levels`](crate::OrderTerm::levels): a term over
/// this citizen becomes four ordinary terms, one per level, so the `ORDER BY` runs
/// `at_nanos, at_pts, at_timebase_num, at_timebase_den` and the keyset resumes the same four. The
/// pin that says so is `ingraph/tests/mediatime_optional.rs`, whose composite-order test asserts
/// this clause AND walks a live page across the `NULL` partition in both directions.
pub(super) const ORDER: &[OrderLevel] = &[
  OrderLevel::new(3),
  OrderLevel::new(0),
  OrderLevel::new(1),
  OrderLevel::new(2),
];

impl ColumnKind for MediaTimestamp {
  const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
  const ORDER: &'static [OrderLevel] = ORDER;
}

/// **A media instant is one column value when its ENCODING is — the count it declares and the
/// timebase it counts in — and NOT merely when the two name the same instant.**
///
/// `mediatime::Timestamp`'s own `PartialEq` is `cmp_semantic`: a cross-timebase comparison of the
/// exact rational instant, so `900 @ 1/1000` and `1_800_000 @ 1/2_000_000_000` are ONE value under
/// `==` despite storing two different `pts` columns. That is exactly the SEMANTIC identity this
/// citizen's own `eq` filter slot asks for — see [`MediaTimestampFilter`]'s table, where `exact`
/// and `eq` are two different questions on purpose. A row's stored columns hold the ENCODING, so
/// folding `==` here would make a record's row equality answer the semantic question instead of
/// the structural one the columns actually hold.
///
/// So this row is written by hand: the count, exactly as stored, and the timebase through its own
/// (reduction-consistent) row.
///
/// [`MediaTimestampFilter`]: super::MediaTimestampFilter
impl ColumnEq for MediaTimestamp {
  #[inline]
  fn column_eq(&self, other: &Self) -> bool {
    self.get().pts().column_eq(&other.get().pts())
      && Timebase::new(self.get().timebase()).column_eq(&Timebase::new(other.get().timebase()))
  }
}

/// **The VALUE one of those four levels compares** — the per-leaf vocabulary the citizen publishes
/// beside its sequence, and the type an emitted cursor's slot is minted with for a column of this
/// type.
///
/// One member per leaf, each carrying that leaf's own Rust type, in the SEGMENT numbering rather
/// than the level one: `pts` is `0`, the timebase's halves are `1` and `2`, and the derived `nanos`
/// is `3`. The permutation is spent before this is reached — a level holds the leaf ordinal its
/// [`OrderLevel`] named — so one numbering serves the tree, the vocabulary and the renderer.
///
/// # It binds ONE placeholder, through the leaf type's own row
///
/// Which is the whole reason a level's operand needs nothing new: `pts` is an `i64` and binds as an
/// `i64` always has. Nothing here is a second bind face — the [`Carrier`](crate::Carrier) below
/// dispatches to the scalar row the leaf's type already had, and both of that trait's faces are the
/// same one placeholder, a leaf having no derived leaf of its own to leave out.
///
/// # The timebase's halves are the REDUCED pair
///
/// What the columns hold, which is what [`Carrier`](crate::Carrier) binds and what
/// [`CursorValue`](crate::CursorValue) writes for the whole instant. A boundary carrying the
/// DECLARED pair would compare against a value no column has — the same miss the storage note
/// records for the write, read at one leaf.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MediaTimestampLeaf {
  /// Leaf `0` — the count the stream declared.
  Pts(i64),
  /// Leaf `1` — the reduced timebase's numerator.
  TimebaseNum(i32),
  /// Leaf `2` — the reduced timebase's denominator.
  TimebaseDen(i32),
  /// Leaf `3` — the DERIVED position on the timeline, recomputed rather than carried.
  Nanos(i64),
}

// One leaf is the same as another leaf when it is the SAME leaf holding the same bytes — each
// member already a plain reduced scalar by the time it is built, so the derived `PartialEq` is
// exactly this row.
column_eq! { MediaTimestampLeaf }

/// **The four leaves, and the derived one RECOMPUTED at the call.**
///
/// `nanos` is a function of the value leaves and is stored by nobody — not by the decode, not by the
/// whole instant's own [`CursorValue`] row. A level over it asks [`MediaTimestamp::to_nanos`], which
/// is the same computation the write binds, so a boundary is the value the statement sorted by.
/// Past the ±292-year ceiling it answers [`None`], which is the same `NULL` the write writes and
/// becomes the cursor slot's own absence — and the keyset's `NULL` arms then place the row where the
/// `ORDER BY` put it.
impl crate::OrderLeaves for MediaTimestamp {
  type Leaf = MediaTimestampLeaf;

  fn leaf(&self, at: usize) -> Option<MediaTimestampLeaf> {
    let (num, den) = Timebase::new(self.get().timebase()).reduced();
    match at {
      0 => Some(MediaTimestampLeaf::Pts(self.get().pts())),
      1 => Some(MediaTimestampLeaf::TimebaseNum(num)),
      2 => Some(MediaTimestampLeaf::TimebaseDen(den.get())),
      3 => self.to_nanos().ok().map(MediaTimestampLeaf::Nanos),
      _ => None,
    }
  }
}

/// **The KEYSET position of ONE leaf**: which leaf, then that leaf's own bytes.
///
/// The tag is what makes the read total. A slot is length-delimited by the cursor and holds nothing
/// else, so a sum has to say which member it is — the same argument the emitted cursor's own codec
/// makes one level out, and for the same reason: the bytes are a CLIENT's, so a byte naming no leaf
/// is refused rather than read as the nearest one.
///
/// The value's own encoding is the leaf type's, so a leaf holds the bytes its column's type holds
/// and there is no second encoding to drift from.
impl CursorValue for MediaTimestampLeaf {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Pts(pts) => {
        out.push(0);
        CursorValue::write_cursor(pts, out);
      }
      Self::TimebaseNum(num) => {
        out.push(1);
        CursorValue::write_cursor(num, out);
      }
      Self::TimebaseDen(den) => {
        out.push(2);
        CursorValue::write_cursor(den, out);
      }
      Self::Nanos(nanos) => {
        out.push(3);
        CursorValue::write_cursor(nanos, out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, value) = bytes.split_first()?;
    match tag {
      0 => <i64 as CursorValue>::read_cursor(value).map(Self::Pts),
      1 => <i32 as CursorValue>::read_cursor(value).map(Self::TimebaseNum),
      2 => <i32 as CursorValue>::read_cursor(value).map(Self::TimebaseDen),
      3 => <i64 as CursorValue>::read_cursor(value).map(Self::Nanos),
      _ => None,
    }
  }
}

/// **ONE BIND OUT**, through the row the leaf's own type already had.
///
/// A level names one column, so its operand is one placeholder — and which scalar row answers is the
/// member's, dispatched here and nowhere else. [`push_value_bind`](crate::Carrier::push_value_bind)
/// takes its default: a leaf has no derived leaf inside it to leave out, so the value bind and the
/// whole bind are the same one placeholder.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for MediaTimestampLeaf
where
  Db: sqlx::Database,
  i32: crate::Carrier<Db>,
  i64: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    match self {
      Self::Pts(value) | Self::Nanos(value) => <i64 as crate::Carrier<Db>>::push_bind(value, qb),
      Self::TimebaseNum(value) | Self::TimebaseDen(value) => {
        <i32 as crate::Carrier<Db>>::push_bind(value, qb);
      }
    }
  }
}

/// **The DECLARED half — FOUR words**, the middle two read off the timebase's own row exactly as the
/// segments above read its shapes.
///
/// A `pts` and a derived `nanos` are `i64`, the timebase between them is its own two, and this row
/// restates none of them: the composite is a citizen holding a citizen on this face too, so a
/// dialect changing its word for either part moves this declaration and there is no second list to
/// drift from.
impl<Db> crate::StoredAs<Db> for MediaTimestamp
where
  i64: crate::StoredAs<Db>,
  Timebase: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <i64 as crate::StoredAs<Db>>::WORDS[0],
    <Timebase as crate::StoredAs<Db>>::WORDS[0],
    <Timebase as crate::StoredAs<Db>>::WORDS[1],
    <i64 as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION.** A media instant is a tick count and the unit it is counted in; it carries no
/// collection, so it is one element of one.
///
/// The row a list of POSITIONS needs — chapter marks, cue points, the keyframe table — where the
/// span house's is the row a list of EXTENTS needs. Both descend the same way a direct column does.
impl crate::CollectionElement for MediaTimestamp {}

/// **The KEYSET position**: the VALUE columns, big-endian — the count, then the reduced timebase.
///
/// The derived key is deliberately absent. A page resumes by comparing a boundary against what it
/// was cut at, and an instant with no representable key would have no boundary to be cut at; the
/// pair always has one. It also keeps the cursor exactly as wide as the value it names.
impl CursorValue for MediaTimestamp {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    CursorValue::write_cursor(&self.get().pts(), out);
    CursorValue::write_cursor(&Timebase::new(self.get().timebase()), out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (pts, timebase) = bytes.split_at_checked(size_of::<i64>())?;
    let pts = <i64 as CursorValue>::read_cursor(pts)?;
    let timebase = <Timebase as CursorValue>::read_cursor(timebase)?;

    Some(Self::new(mt::Timestamp::new(pts, timebase.get())))
  }
}

/// **FOUR BINDS OUT** — three that carry the value and one that carries its position.
///
/// The derived one is written as `NULL` rather than bound when the instant has no `i64` nanosecond
/// position, which is the shape `ingraph`'s own nullable carrier takes and for its reason: a `None`
/// has no value to hand sqlx, and the column's type is decided by the DDL rather than by a
/// placeholder.
///
/// **AND THREE FOR A STRUCTURAL JUDGMENT.** The `NULL` above is exactly why the value-leaf bind
/// exists: an equality that spent it would compare `NULL = NULL`, which is UNKNOWN, so an instant
/// past the ceiling could never be matched by the very pair that wrote it — ingraph #455, over
/// `Vec<MediaTimestamp>`. The narrow bind is the WRITE's own first three pushes, and its width is
/// `value_width(SEGMENTS)`, which is the pairing this method owes its column list.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for MediaTimestamp
where
  Db: sqlx::Database,
  i64: crate::Carrier<Db>,
  Timebase: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    self.push_value_bind(qb);
    qb.push(", ");
    match self.to_nanos() {
      Ok(nanos) => <i64 as crate::Carrier<Db>>::push_bind(&nanos, qb),
      Err(_) => {
        qb.push("NULL");
      }
    }
  }

  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <i64 as crate::Carrier<Db>>::push_bind(&self.get().pts(), qb);
    qb.push(", ");
    <Timebase as crate::Carrier<Db>>::push_bind(&Timebase::new(self.get().timebase()), qb);
  }
}

/// **AND THE VALUE BACK IN** — the count and the timebase, by name, and never the derived key.
///
/// Reading the key would give a row two ways to say what instant it holds, and a derived column
/// exists precisely so that there is one. It also means a row whose key is `NULL` decodes exactly
/// like any other, which is what keeps the overflow posture above a fact about ORDERING alone.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for MediaTimestamp
where
  i64: crate::Assemble<'a, R>,
  Timebase: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let pts: i64 = crate::assembled(row, PTS, under)?;
    let timebase: Timebase = crate::assembled(row, TIMEBASE, under)?;

    Ok(Self::new(mt::Timestamp::new(pts, timebase.get())))
  }
}