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 HIT: one retrieved result as a client reads it — the score it matched at, where the engine
//! put it, and the thing itself.
//!
//! ```text
//! <someSearch>(…) {           <someHydratedSearch>(…) {
//!   score                       score      # the ENGINE's own currency, comparable INSIDE one list
//!   rank                        rank       # where the engine put it, holes left in
//!   node { … }                  node { … }
//! }                           }
//! ```
//!
//! # THE ROW WORD IS `node` AT BOTH TIERS, AND WHAT THE NODE *IS* IS THE TIER'S ANSWER
//!
//! Ruled 2026-08-18, closing the family alignment: one word across the whole Match family — tier A's
//! node is the ADDRESS and tier B's is the ENTITY — which is the design this module's Rust half has
//! carried since it was written, [`Match`]'s third field having always been called `node`. It
//! replaces the 2026-08-15 split (`key` at tier A, `entity` at tier B), which had put two spellings
//! on one position and left the wire disagreeing with the type it renders.
//!
//! **`node` is not overloaded by this, and the two other homes it has are why.** The arrangement
//! grammar's `upstream(node = "…")` names a graph node in a DECLARATION, which is a Rust-facing
//! word a client never reads; and [`Connection`](super::Connection)'s edges carry Relay's own `node`,
//! where a page's element is exactly what this row is one shape over. A client that reads a page and
//! a client that reads a ranking now spell the thing itself the same way.
//!
//! # ONE TYPE AT BOTH TIERS, AND `N` IS THE WHOLE OF THE DIFFERENCE
//!
//! Ruled 2026-08-19, retiring the `EntityMatch` newtype the 2026-08-18 alignment had emptied: the
//! two tiers are [`Match<N, S>`](Match) at two INSTANTIATIONS, not two types. The claim the newtype
//! rested on — *an `#[Object]` impl publishes one row TYPE per method, so the entity tier needs a
//! face of its own* — is true about the METHOD and false about the type: `#[Object]` is written once
//! over a generic impl, and `node`'s return type is `&N`, so the row's type is whatever the tier
//! instantiated. `Match<KeyframeKey, f32>` publishes `node: KeyframeKey!` and
//! `Match<Keyframe, f32>` publishes `node: Keyframe!` off the SAME impl, which is the mechanism
//! [`Connection<N, V>`](super::Connection) has always named its own node through.
//!
//! The newtype was observationally identical to what it wrapped, and the [`TypeName`] impl it
//! carried is where that stopped being an opinion: it DELEGATED, `<Match<N, S>>::type_name()`, so
//! both tiers already computed one formula. What the deletion removes is a second constructor, a
//! second crossing, a second `#[Object]` and a third accessor spelling (`entity_ref` beside
//! `node_ref`) — four ways to write the same three fields, each free to drift from the others.
//!
//! Their SDL names still cannot collide, and that is a fact about the DECLARATION rather than about
//! the type: `N` is an address object at one tier and an entity object at the other, and a
//! declaration publishing one type at both positions would already be publishing an entity as its
//! own address.
//!
//! The FIELD is left unnamed above because its name is COMPUTED rather than fixed —
//! `<subject>By<Election>Keys`, off the declaration's own base and the elected field — so no single
//! word could stand at that position. The face itself IS EMITTED: `mediaByTitleKeys` and
//! `mediaByBodyKeys` are two of them, and `ingraph/tests/resource_wire_road.rs` answers a client's
//! own query through one over a real Tantivy corpus, end to end.
//!
//! The blocker this paragraph used to record — *an index declaration carries no engine, so nothing
//! in its expansion can spell the `E` its own retrieve is generic over* — was ANSWERED rather than
//! worked around, by the resource word. `#[ingraph(resource)]` on a graph root's field and
//! `engines(<word> = "path::To::Engine")` on the root itself name a concrete engine at the
//! DECLARATION, so the expansion spells it; and the resolver never has to be generic, because its
//! context lookup is a `TypeId` on the resource's own type — which is exactly the concrete thing it
//! wanted. `ingraph/tests/retrieve_wire.rs` still writes the crossing out BY HAND, which is the
//! Rust surface underneath the emitted face rather than a stand-in for it.
//!
//! # It is [`Ranked`]'s wire face, and it adds nothing to it
//!
//! The Rust item was closed before this module existed: score first because it is the more important
//! of the two numbers, rank second as the ENGINE's own ordinal, node third. This type is those three
//! fields at a wire position, in that order, and the one crossing between them is
//! [`From<Ranked>`](Match::from) — so a face that renders a retrieve cannot pick a number up from
//! anywhere but the answer it is rendering.
//!
//! A SEPARATE type rather than an `#[Object]` on `Ranked` itself, for the reason the whole crate
//! splits declaration from face: `Ranked` is the Rust answer and exists in a build with no GraphQL
//! binding at all, and an inherent `#[Object]` impl would put async-graphql's name in the middle of
//! it. The same split [`Connection`](super::Connection) draws between `query::Page` and what a page
//! becomes on the wire.
//!
//! # The SDL name is the NODE's, plus `Match`
//!
//! `TranscriptKeyMatch`, `SegmentMatch` — computed off `N`'s own published name through async-graphql's
//! [`TypeName`] hook, which is the identical mechanism `Connection<N, V>` already names
//! `<Node>Connection` and `<Node>Edge` through. GraphQL's flat type namespace has no generics, so a
//! generic wire type either names itself off its parameter or is written out once per instantiation;
//! the first is the library's own answer and the one this crate already spends.
//!
//! # THE TWO PARAMETERS ARRIVE DIFFERENTLY, AND THE ASYMMETRY IS THE CURRENCY'S
//!
//! `N` is `OutputType` — already wire-shaped — exactly as `Connection<N, V>` takes an `OutputType`
//! node: a tier's address or entity is a type the DECLARATION already published a face for, and
//! this module has nothing to add to it.
//!
//! `S` is [`WireScore`](super::WireScore), which is the crossing every declared column travels. It
//! was `OutputType` too, and that left the one row on a hit that IS a measurement reaching
//! async-graphql's own float rows — which publish `f32` and `f64` alike as `Float` — beside columns
//! whose widths the SCALAR SUITE had already made honest. So a score now says which width it is
//! measured in, and what stays exactly as it was is COMPARABILITY: the doctrine below is unchanged,
//! and a width is precision rather than permission.

use std::borrow::Cow;

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

use super::WireScore;
use crate::retrieve::Ranked;

#[cfg(test)]
mod tests;

/// ONE HIT on the wire, at either tier: its score, its engine ordinal, and the NODE that matched —
/// the ADDRESS at tier A, the whole upstream ENTITY at tier B.
///
/// The wire projection of [`Ranked<N, S>`](Ranked), field for field and in the same order. See the
/// module note for why it is a type of its own and for where its SDL name comes from.
///
/// # `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 ranked 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-18 alignment they share the third row's NAME, and
/// since the 2026-08-19 retirement they share the TYPE that carries it: the tier is an
/// instantiation, not a second face. See the module note.
///
/// # The `__async_graphql_` PREFIX on the face below, and the collision that proves the pin
///
/// Every function of the `#[Object]` impl is `__async_graphql_`-prefixed with its wire name written
/// out beside it, which is the law an emitted face already wears — and this type is where the
/// reason stops being hypothetical. `#[Object]` methods ARE inherent methods, so the unprefixed
/// spelling puts a second `rank` on `Match` beside [`Match::rank`], inside an attribute expansion.
///
/// **MEASURED on 2026-08-19 rather than asserted**, by deleting the prefix and reading what rustc
/// said. Three errors, and the note that stood here had the count right and the shape wrong:
///
/// | | |
/// |---|---|
/// | `E0592` *duplicate definitions with name `rank`* | 1, on the inherent fn |
/// | `E0034` *multiple applicable items in scope* | 2 — at the `#[Object]` method's own declaration, and at the `self.rank()` inside it |
///
/// ONE row collides and not three: the borrows are `score_ref` and `node_ref`, so `score` and `node`
/// have nothing to be a second definition OF. The pin is real and it is `rank`'s alone — which is
/// enough, because the prefix is a rule about a NAMESPACE and a rule that held for two rows out of
/// three would be no rule at all. An accessor renamed `score` tomorrow would collide the same way
/// with no edit to this impl, and the prefix is why that stays a non-event.
///
/// The prefix names the BACKEND rather than merely being ugly, per the ruling of 2026-08-13: a
/// second GraphQL binding mounted on `Match` mints `__smear_score` beside `__async_graphql_score`,
/// so the two faces are the two namespaces and the collision this section is about cannot recur one
/// backend later. `ingraph-codegen`'s `method::wire_method` is where an emitted face reads the same
/// shape from.
///
/// # WHERE THE DOCS GO, because async-graphql publishes one of these two
///
/// This type's own note is a Rust reader's; the `#[Object]` impl's note is a CLIENT's, because
/// async-graphql reads the impl block's rustdoc and publishes it as the SDL type's description. So
/// everything a schema explorer should not have to read — this section included — is written here,
/// and the impl carries only what a client is owed.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Match<N, S> {
  score: S,
  rank: u64,
  node: N,
}

impl<N, S> Match<N, S> {
  /// Pair what matched with the score it matched at and the ordinal the engine gave it.
  ///
  /// Arguments in field order, as [`Ranked::new`] takes them, so the two constructors cannot be
  /// confused for each other at a call site that has both in view.
  #[inline]
  pub const fn new(score: S, rank: u64, node: N) -> Self {
    Self { score, rank, node }
  }

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

  /// The hit's 1-based position in the ENGINE's raw stream, holes included.
  #[inline]
  pub const fn rank(&self) -> u64 {
    self.rank
  }

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

/// The ONE crossing from the Rust answer to the wire one.
///
/// Written as a conversion rather than as three field reads at each face, for
/// [`Ranked::map_node`]'s own reason one layer down: the two numbers belong to the engine's answer
/// about this hit, and a face that assembled them by hand is a face that can assemble them from the
/// wrong hit.
impl<N, S> From<Ranked<N, S>> for Match<N, S> {
  #[inline]
  fn from(ranked: Ranked<N, S>) -> Self {
    let (score, rank, node) = ranked.into_components();
    Self { score, rank, node }
  }
}

/// `<Node>Match`, off the node's own published name.
///
/// `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. It is
/// [`WireScore`](super::WireScore) and no longer `OutputType`, which is the whole of the currency
/// correction: the score seat travels the crossing map like every declared column beside it.
impl<N, S> TypeName for Match<N, S>
where
  N: OutputType,
  S: WireScore,
{
  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Owned(format!("{}Match", N::type_name()))
  }
}

/// One result of a search: what matched, how well, and where the engine put it.
///
/// The list this belongs to is ALREADY the ranking — its order is the engine'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> Match<N, S>
where
  N: OutputType,
  S: WireScore,
{
  /// How well this matched, in the SEARCH ENGINE'S OWN CURRENCY, at that currency's own WIDTH.
  ///
  /// **Scores compare INSIDE one result list and nowhere else.** Each engine measures in its own
  /// unit, at its own scale, in its own direction — a BM25 relevance is unbounded above and moves
  /// with the corpus it was computed against, a cosine face answers a distance where smaller is
  /// closer — so a score from one search is not a quantity that can be ranked against, averaged
  /// with, or thresholded by a score from another. Two lists that must be merged are merged by a
  /// conversion somebody writes down.
  ///
  /// The TYPE says which width the engine measures in — `F32!` where its currency is an `f32`,
  /// `F64!` where it is an `f64` — because the row crosses through the same map every declared
  /// column does. It is a fact about precision and not about comparability: two scores at one width
  /// are still two currencies unless one list produced both.
  ///
  /// It is NON-NULL and every hit carries one, because the minimum score a query is required to
  /// state is a number in this same currency: a caller cannot calibrate a floor for a corpus whose
  /// score landscape it cannot see.
  #[graphql(name = "score")]
  async fn __async_graphql_score(&self) -> <S as WireScore>::Wire<'_> {
    <S as WireScore>::wire_score(self.score_ref())
  }

  /// This hit's 1-based position in the engine's RAW result stream.
  ///
  /// **Not its position in this list, and the two disagree wherever the pipeline dropped a hit** —
  /// a duplicate key, a row a filter pruned, a row the store no longer holds. The holes are left
  /// exactly where they fell rather than closed up, because the number's whole value is that it
  /// means *where the engine put it*: ask the same query with a wider budget, discard everything at
  /// or below the last rank seen, and the remainder is the continuation.
  #[graphql(name = "rank")]
  async fn __async_graphql_rank(&self) -> u64 {
    self.rank()
  }

  /// What matched — the ADDRESS a hydrating read is asked with, or the WHOLE entity a hydrated one
  /// already read out of the system of record.
  ///
  /// Which of the two it is, is the TIER's answer and the schema says so by TYPE: a keys road
  /// publishes the declaration's address object here and a hydrated road publishes its entity
  /// object, and neither road publishes both.
  #[graphql(name = "node")]
  async fn __async_graphql_node(&self) -> &N {
    self.node_ref()
  }
}

/// A whole ranked answer, crossed.
///
/// The shape a retrieve face's body ends in, written once here rather than as a `map` at each of
/// them — 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, which is three moves and asks nothing
/// of what it is moving. The answer is a `Vec` because the ranking IS the order — the sequence is
/// the whole of the answer's structure, and no page wraps it HERE: a paged road cuts its stretch
/// off the kept ranking BEFORE this crossing, so what reaches this function is one stretch's rows
/// and the claim on the next rides beside them rather than around them.
#[inline]
pub fn matches<I, N, S>(ranked: I) -> Vec<Match<N, S>>
where
  I: IntoIterator<Item = Ranked<N, S>>,
{
  ranked.into_iter().map(Match::from).collect()
}