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
//! THE SET HIT: one entity of a SET-similarity answer as a client reads it — the folded score, what
//! each query vector's own stream said, and the thing itself.
//!
//! ```text
//! <someSetSearch>(…) {          <someHydratedSetSearch>(…) {
//!   score                         score      # the FOLD's answer, in the engine's own currency
//!   streams {                     streams {  # one nullable slot per query vector, in ASKED order
//!     score                         score    # that vector's own best — the PRE-FOLD number
//!     ordinal                       ordinal  # where that vector's own stream put the entity
//!   }                             }
//!   node { … }                    node { … }
//! }                             }
//! ```
//!
//! # It is [`Match`](super::Match)'s family, and the plural is the whole difference
//!
//! A single-vector answer has one score and one rank, so [`Match`](super::Match) carries `score` and
//! `rank` beside its address. A set answer has `m` engine streams and **no order between them**, so
//! there is no one rank to carry: the fold authors the answer's order, and no cross-stream ordinal
//! is ever minted. What replaces the row is the LIST — `streams`, positional over the query vectors
//! in the order they were asked, each slot carrying that stream's own two numbers.
//!
//! The rows follow the family's ruled words: since the 2026-08-18 alignment BOTH tiers spell the
//! third row `node` — tier A's node is the address and tier B's is the entity — and the SDL name is
//! the node's own plus `FoldedMatch`. [`Match`](super::Match)'s module note carries the ruling whole.
//!
//! # `From<Folded>` IS THE ONLY CROSSING, and that is the provenance lock
//!
//! [`Match::from`](super::Match::from) states it for the single-vector road and every word transfers:
//! a face that assembled these fields by hand is a face that can assemble them from the wrong
//! answer. The fold produced the score, the walk produced each slot, and this type is those values
//! at a wire position. There is no constructor beside the conversion, at either tier.
//!
//! # The score is the ENGINE's currency at BOTH grains, and it crosses at that currency's WIDTH
//!
//! [`FoldSemantics`](crate::FoldSemantics) is `S → S`: it takes the per-stream bests in the engine's
//! own currency and answers in that same currency. So the top-level `score` and each slot's `score`
//! are the same type, and both reach the wire through [`WireScore`](super::WireScore) — the crossing
//! every declared column already travels — so an `f32` cosine publishes `F32!` and an `f64` one
//! `F64!`. Coercing either to a framework `Float` would be this module having an opinion about an
//! arithmetic that belongs to the fold, and publishing the two widths under ONE name was that
//! opinion taken by omission.
//!
//! What the two grains do NOT share is comparability. A slot's score is a PRE-FOLD number about one
//! pair of vectors — the grain the query's floor is stated at, and the only grain a person has seen
//! a number in. The top-level score has been through a fold, so it is in the currency's units
//! without being in its range: a sum of `m` cosines is not a cosine. Both are comparable INSIDE
//! this one answer and nowhere else, which is the existing currency doctrine read at two grains.
//!
//! # WHICH fold ran is not published here, and the reason is the schema's clock
//!
//! The fold is a POLICY the deployment installs at launch (see [`FoldDoor`](super::FoldDoor)), and
//! SDL descriptions are built at compile time — so a row naming the installed fold would be a
//! string the schema cannot know. The name a [`FoldSemantics`](crate::FoldSemantics) carries is
//! spent where a runtime value can be read instead: the door's own span, its refusals, and the
//! emitted field's documentation of what a deployment may install.

use core::marker::PhantomData;
use std::borrow::Cow;

use async_graphql::{Object, OutputType, TypeName};

use super::WireScore;
use crate::retrieve::{Folded, StreamBest};

#[cfg(test)]
mod tests;

/// ONE QUERY VECTOR'S SIGHTING on the wire: its own best score in the entity's set, and where its
/// own stream put the entity.
///
/// The wire projection of [`StreamBest<S>`], field for field and in the same order. `null` in the
/// `streams` list it sits in means that query vector matched nothing of this entity's above the
/// floor — the slot is there either way, so the POSITION stays the query vector's ordinal and a
/// client can read *question three went unanswered* rather than counting a shorter list.
///
/// # `N` carries no data and names the type, and the alternative was MEASURED
///
/// Nothing in this shape depends on the node: the two rows are the score and the ordinal, so the
/// obvious spelling is `StreamSighting<S>` naming itself off the currency. That spelling COLLIDES.
/// async-graphql publishes both `f32` and `f64` as `Float`, so two declarations scoring in the two
/// widths would mint two Rust types under one SDL name, in one registry, silently. Carrying the node
/// puts this type on the same naming axis as the [`FoldedMatch`] that owns it — `<Node>StreamSighting`
/// beside `<Node>FoldedMatch` — so a slot's name moves with its owner and two owners never share a name
/// they could disagree about.
///
/// The cost is stated rather than hidden: the keys tier and the hydrated tier publish two slot types
/// of identical shape, `KeyframeKeyStreamSighting` and `KeyframeStreamSighting`. That is the same
/// pair [`Match`](super::Match) publishes at its own two instantiations, and for the same reason —
/// the tier's node is what the two answers differ in.
///
/// # THE SILENT COLLISION CLASS IS EXTINCT AT BOTH ENDS NOW, AND THE NODE AXIS STILL STANDS
///
/// The paragraph above describes the collision as it WAS, and both halves of it are now gone. The
/// SCALAR SUITE ([`scalar`](super::scalar)) gave every Rust width its own SDL name, so `f32` and
/// `f64` are two schema types; and the currency reroute put THIS SEAT on the crossing that publishes
/// them — `S` is bound [`WireScore`](super::WireScore) rather than `OutputType`, so an `f32` score
/// renders `f32!` and an `f64` one `f64!` at every grain of this family. The note that stood here
/// recorded the second half as still open, and it is closed: `graphql::folded_matches`'s own tests read
/// `score: f32!` off a schema whose currency is an `f32`.
///
/// **The node is still carried, and its reason is no longer the collision.** What the parameter buys
/// now is that a slot's name moves with its OWNER — `<Node>StreamSighting` beside `<Node>FoldedMatch` —
/// so a client reading a set answer holds one naming axis rather than two, and a declaration that
/// renames its family renames the slot with it. Naming the slot off the currency instead would put
/// `F32StreamSighting` in a schema beside `KeyframeFoldedMatch`, which is a name a reader has to
/// assemble from two unrelated facts.
///
/// The rest of the posture is unchanged and belongs to the family rather than to this type: two
/// declarations whose slot types are IDENTICAL share one, and two whose currencies DIVERGE under
/// one name are a LOUD REFUSAL rather than a second silent registration. That refusal is
/// async-graphql's own and it is a panic at schema build — `Registry::create_type` refuses one
/// GraphQL name held by two Rust types with a `rust_typename`, which is the mechanism
/// [`EnumFilter`](crate::EnumFilter)'s note already names one module over.
///
/// `PhantomData<fn() -> N>` is this crate's own marker spelling: it holds nothing, is variance-safe,
/// and leaves every derive and every auto trait independent of `N`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StreamSighting<N, S> {
  score: S,
  ordinal: u64,
  node: PhantomData<fn() -> N>,
}

impl<N, S> StreamSighting<N, S> {
  /// This stream's best score, BORROWED, in the engine's own currency — the PRE-FOLD number.
  #[inline]
  pub const fn score_ref(&self) -> &S {
    &self.score
  }

  /// The entity's 1-based position in THIS query vector's own raw stream, holes included.
  #[inline]
  pub const fn ordinal(&self) -> u64 {
    self.ordinal
  }
}

/// The ONE crossing, from the slot the fold filled — [`FoldedMatch`]'s own lock, one grain down.
impl<N, S> From<StreamBest<S>> for StreamSighting<N, S> {
  #[inline]
  fn from(best: StreamBest<S>) -> Self {
    let (score, ordinal) = best.into_components();
    Self {
      score,
      ordinal,
      node: PhantomData,
    }
  }
}

/// `<Node>StreamSighting`, off the node's own published name — see the type's note for why the node
/// is here at all.
impl<N, S> TypeName for StreamSighting<N, S>
where
  N: OutputType,
  S: WireScore,
{
  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Owned(format!("{}StreamSighting", N::type_name()))
  }
}

/// What ONE of the query vectors said about this result.
///
/// Its position in the `streams` list is the query vector's own ordinal, counted in the order the
/// vectors were asked.
#[Object(name_type)]
impl<N, S> StreamSighting<N, S>
where
  N: OutputType,
  S: WireScore,
{
  /// This query vector's BEST match in the result's own set, in the SEARCH ENGINE'S OWN CURRENCY.
  ///
  /// The number BEFORE any folding, which is what makes it the one comparable to the floor the
  /// query stated: a floor is a fact about one pair of vectors, and so is this.
  ///
  /// **Scores compare INSIDE one result list and nowhere else** — each engine measures in its own
  /// unit, at its own scale, in its own direction.
  #[graphql(name = "score")]
  async fn __async_graphql_score(&self) -> <S as WireScore>::Wire<'_> {
    <S as WireScore>::wire_score(self.score_ref())
  }

  /// This result's 1-based position in THIS query vector's raw result stream.
  ///
  /// **Not its position in the answer, which no single stream decides** — the fold authors the
  /// answer's order, so there is no cross-stream ordinal to read here. The holes are left where they
  /// fell: ask this query vector again with a wider budget, discard everything at or below the
  /// ordinal you last saw, and the remainder is that stream's continuation.
  #[graphql(name = "ordinal")]
  async fn __async_graphql_ordinal(&self) -> u64 {
    self.ordinal()
  }
}

/// ONE FOLDED hit on the wire, at either tier: the folded score, every query vector's own sighting,
/// and the NODE that matched — the ADDRESS at tier A, the whole upstream ENTITY at tier B.
///
/// The wire projection of [`Folded<N, S>`](Folded), field for field and in the same order. See the
/// module note for why it is a type of its own, for where its SDL name comes from, and for the two
/// grains its two scores live at.
///
/// # `N` is what a TIER decided, not what this type did
///
/// Tier A retrieves KEYS and tier B retrieves the WHOLE upstream entity, and both are folded lists
/// of the same shape — so `N` is the tier's answer and the two tiers share one wire vocabulary
/// rather than growing one each. Since the 2026-08-19 retirement they share this TYPE too: the tier
/// is an INSTANTIATION of it, `FoldedMatch<FrameKey, f32>` at one road and
/// `FoldedMatch<Frame, f32>` at the other, and [`Match`](super::Match)'s own module note carries the
/// whole of why one generic `#[Object]` publishes both.
///
/// # The `__async_graphql_` PREFIX on the face below
///
/// [`Match`](super::Match)'s own measurement, and its correction with it: `#[Object]` methods ARE
/// inherent methods, so an unprefixed method collides with an inherent one of the SAME NAME. At THIS
/// type no row collides today — the borrows are `score_ref`, `streams` and `node_ref`, and `streams`
/// is the one that WOULD, being spelled identically on both sides. The prefix is what keeps the two
/// namespaces apart before any of that is a question, and it names the BACKEND rather than merely
/// being ugly, so a second GraphQL binding mounted here is a second namespace.
#[derive(Debug, Clone, PartialEq)]
pub struct FoldedMatch<N, S> {
  score: S,
  streams: Box<[Option<StreamSighting<N, S>>]>,
  node: N,
}

impl<N, S> FoldedMatch<N, S> {
  /// The FOLDED score, BORROWED, in the engine's own currency.
  #[inline]
  pub const fn score_ref(&self) -> &S {
    &self.score
  }

  /// What each query vector's own stream said, in the order the vectors were asked.
  ///
  /// `m` long, [`None`] where that vector matched nothing of this entity's above the floor.
  #[inline]
  pub fn streams(&self) -> &[Option<StreamSighting<N, S>>] {
    &self.streams
  }

  /// The ADDRESS that matched, BORROWED.
  #[inline]
  pub const fn node_ref(&self) -> &N {
    &self.node
  }
}

/// The ONE crossing from the Rust answer to the wire one.
///
/// [`Match::from`](super::Match::from)'s reason, at the set grain: the folded score and every slot
/// belong to the fold's answer about this entity, and a face that assembled them by hand is a face
/// that can assemble them from the wrong one. The slots cross through
/// [`StreamSighting::from`](StreamSighting#impl-From<StreamBest<S>>-for-StreamSighting<N,+S>) so the
/// per-stream numbers have exactly one road too.
impl<N, S> From<Folded<N, S>> for FoldedMatch<N, S> {
  #[inline]
  fn from(folded: Folded<N, S>) -> Self {
    let (score, streams, node) = folded.into_components();
    Self {
      score,
      streams: Vec::from(streams)
        .into_iter()
        .map(|slot| slot.map(StreamSighting::from))
        .collect(),
      node,
    }
  }
}

/// `<Node>FoldedMatch`, off the node's own published name — [`Match`](super::Match)'s rule, unchanged.
///
/// `N`'s bound is `OutputType` because that is what carries a published name; `S` is bounded here too
/// so the two halves of the face demand the same thing and a missing row is `E0277` at ONE place
/// rather than at whichever of them the compiler reached first.
impl<N, S> TypeName for FoldedMatch<N, S>
where
  N: OutputType,
  S: WireScore,
{
  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Owned(format!("{}FoldedMatch", N::type_name()))
  }
}

/// One result of a SET search: what matched, how well the whole set answered, and what each of the
/// asked vectors said on its own.
///
/// The list this belongs to is ALREADY the ranking — its order is the fold's — so a client that
/// wants the best result takes the first element and needs no comparison of its own.
#[Object(name_type)]
impl<N, S> FoldedMatch<N, S>
where
  N: OutputType,
  S: WireScore,
{
  /// How well the whole query SET matched, in the SEARCH ENGINE'S OWN CURRENCY, folded.
  ///
  /// **This list's order is this number's order, and the number compares nowhere else.** It is the
  /// engine's currency after a fold, so it is in that currency's units without being in its range: a
  /// sum of several cosines is not a cosine. Nothing thresholds on it either — the minimum score a
  /// query states is a floor at the PER-VECTOR grain, which is `streams { score }` below.
  #[graphql(name = "score")]
  async fn __async_graphql_score(&self) -> <S as WireScore>::Wire<'_> {
    <S as WireScore>::wire_score(self.score_ref())
  }

  /// What each of the asked query vectors said, one slot per vector, IN THE ORDER THEY WERE ASKED.
  ///
  /// `null` means that vector matched nothing of this result's above the floor. The slot stays, so a
  /// position in this list is always the query vector's own ordinal.
  ///
  /// **There is no rank for the result as a whole, and there will not be one**: a set search runs
  /// the engine once per query vector, those streams have no order between them, and the fold is
  /// what authors this answer's order. Every ordinal here is one stream's own.
  #[graphql(name = "streams")]
  async fn __async_graphql_streams(&self) -> &[Option<StreamSighting<N, S>>] {
    self.streams()
  }

  /// The ADDRESS that matched — what a hydrating read is asked with, and what a client holds on to.
  #[graphql(name = "node")]
  async fn __async_graphql_node(&self) -> &N {
    self.node_ref()
  }
}

/// A whole folded answer, crossed.
///
/// [`matches`](super::matches)' reason at the set grain: a face has one line for the crossing and no
/// opportunity to write the loop differently from its neighbour. NO bound on either parameter — the
/// crossing is [`From`]'s.
#[inline]
pub fn folded_matches<I, N, S>(folded: I) -> Vec<FoldedMatch<N, S>>
where
  I: IntoIterator<Item = Folded<N, S>>,
{
  folded.into_iter().map(FoldedMatch::from).collect()
}