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 retrieve is ASKED with: [`FulltextQuery`] and [`VectorQuery`] — a subject, and the score
//! floor every retrieve must carry.

use smol_bytes::Utf8Bytes;

use crate::{Anon, Embedding};

/// The floor a query DEFERRED — what stands in the floor's position while the number is still
/// somebody else's to supply.
///
/// # It is the floor's TYPE, which is what makes the deferral structural
///
/// A query is `Query<…, S, …>` where `S` is the engine's score currency, and a deferred one is
/// `Query<…, Deferred, …>`. So *this query has no floor yet* is a fact about its TYPE rather than a
/// state inside it: an engine-facing door names `<E as VectorEngine>::Score` in that position and a
/// deferred query does not unify with it, which is `E0308` at the call. **The engine boundary
/// therefore cannot be reached with an unresolved floor**, and nothing along the way has to check
/// that it was not.
///
/// The alternative measured against it was an `Option<S>` inside the query. It moves the same
/// question to run time, makes `floor()` an `Option` for every caller including the ones that
/// supplied a number, and leaves the door with a `None` arm it has no honest answer for — a floor
/// is MANDATORY at the engine, so the arm would have to invent one, panic, or grow an error nobody
/// ruled.
///
/// # Who resolves it
///
/// [`VectorQuery::floored`] / [`FoldedQuery::floored`](super::FoldedQuery::floored) — the chain's second
/// step, ruled *查询层传入 > attr 默认*: a caller who wrote a number at the query has one already,
/// and a caller who deferred is answered by the DECLARATION's own floor. The declaration's half is
/// the word an election has not got yet, so today the resolving party is whoever holds a number;
/// the seam is the same either way and is what the emitted face will call.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Deferred(());

impl Deferred {
  /// The marker.
  ///
  /// A constructor rather than a bare unit struct, which is this crate's law for every empty type
  /// it ships: the private `()` funnels construction through here from day one, so a field can be
  /// added later without breaking a downstream that built the value literally.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self(())
  }
}

/// A full-text retrieve: the query text, and the minimum score a hit must reach to be returned.
///
/// # The floor is MANDATORY, and the constructor is what enforces it
///
/// It is a positional parameter of [`new`](Self::new) rather than an [`Option`] with a default,
/// because *必须指定* is a property of the signature or it is a property of the documentation. A
/// retrieve is an imprecise search, so an answer with no floor pads its tail with matches nobody
/// would call results; the floor is what makes a SHORT page the honest answer instead.
///
/// # Its type is the ENGINE's, not the framework's
///
/// `S` is [`FulltextEngine::Score`](crate::FulltextEngine::Score) — BM25's `f32` here, a double there, a
/// fused shape at a layer that ranks rather than measures. So the framework never reinterprets it
/// and never normalises it, and the floor's SEMANTICS follow the engine's: a BM25 floor is
/// corpus-relative and a cosine floor is absolute, which is the caller's calibration to make. What
/// the framework asks of the type is one thing, [`PartialOrd`], and it asks it where the comparison
/// happens rather than here.
///
/// # Language is not a parameter HERE, because it is SPENT UPSTREAM
///
/// Multilingual retrieval is still the posture, and its first claim is unchanged: the text may be
/// `"sunset"` and a German transcript carrying that word is a first-class hit, which the retrieve
/// tests assert over a live corpus. What has moved since that posture was written is WHERE language
/// is answered.
///
/// It rides the QUESTION — an annotation stage may fill it in for a caller who wrote none — and it
/// is spent twice before a read reaches this type: at ROUTING, where it chooses the lane, and at
/// WIDENING, where it decides the target list. By the time a question is lowered to a
/// [`FulltextQuery`] it is ONE LANE'S QUESTION ASKED OF ONE ENGINE, and the language has already
/// done all of its work. The missing seat here is therefore a DIVISION OF LABOUR rather than an
/// absence of the concept — and there IS a gate on this path, one layer up:
/// [`lane_for`](crate::lane_for) is it.
///
/// Analyzers are not the ENGINE's configuration either. A lane's EXISTENCE is a declaration fact —
/// the `lanes(…)` word inside a backend block, which mints the roster [`Lanes`](crate::Lanes)
/// publishes — and its analyzer is an assembly one, bound per `(slot, lane)` at boot. Tokenization
/// is chosen by the declaration and the deployment together, and never by a word written at a
/// query.
///
/// The cross-lingual claim keeps its rank and loses its overreach. A multilingual embedding space
/// does put *sunset* and *Sonnenuntergang* in one neighbourhood, so the crossing HOLDS AT RANK, and
/// the vector flavour is still where it lives. At SCORE it is CONDITIONAL: a cross-language pair
/// sits systematically below a same-language one, so a floor calibrated on same-language hits
/// prunes exactly the crossings the claim is about. This number therefore does two jobs at once —
/// it keeps the tail clean, and it is what a cross-lingual reader has to calibrate against the
/// CROSSING rather than against the corpus.
#[derive(Debug, Clone, PartialEq)]
pub struct FulltextQuery<S> {
  text: Utf8Bytes,
  floor: S,
}

impl<S> FulltextQuery<S> {
  /// Ask `text` of a full-text engine, returning nothing that scores below `floor`.
  ///
  /// The text is taken through [`Utf8Bytes`] rather than borrowed, so a query built from a wire
  /// argument, a `String` or a `&'static str` is one type at the seam and none of them is a
  /// lifetime a caller has to thread through a fill loop that awaits.
  #[inline]
  pub fn new(text: impl Into<Utf8Bytes>, floor: S) -> Self {
    Self {
      text: text.into(),
      floor,
    }
  }

  /// The query text, as [`FulltextRead::search`](crate::FulltextRead::search) takes it — a `&str`,
  /// because every full-text engine already has a query grammar and naming one here would elect it
  /// for the engines that have not arrived.
  #[inline]
  pub fn text(&self) -> &str {
    &self.text
  }

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

/// A vector retrieve: the query embedding, and the minimum score a neighbour must reach.
///
/// # The input rides [`Embedding<E, N, Space>`](Embedding), so the width is checked where it is BUILT
///
/// `knn` takes a bare `&[R::Element]` at the store seam and checks nothing about its length — the
/// width is the declared column's, and the one place a runtime length meets a compile-time width is
/// [`Embedding::new`]. A query built as an `Embedding<f32, 768>` has 768 coordinates or was never
/// constructed, so this type carries that proof to the seam rather than re-deriving it.
///
/// # The SPACE rides through untouched, and the door is where it is spent
///
/// `Space` is the embedding's third parameter carried forward and defaulted the same way ([`Anon`]),
/// so `VectorQuery<f32, f32, 768>` is the type it always was and every existing query is unchanged.
/// What it buys is at the far end: an emitted `retrieve_by_<field>` names the space its own elected
/// column was declared in, so asking a `Clip` column with a query somebody built in another space is
/// `E0308` AT THE CALL — the same refusal the width already gives, one axis over, for the mismatch a
/// width cannot see.
///
/// The parameter is spelled `Space` here rather than `S` because `S` is taken, by the SCORE — the
/// letter follows [`FulltextQuery<S>`](FulltextQuery)'s and the axis keeps its full name where they
/// would collide.
///
/// # The floor is what makes `k` a ceiling instead of a promise
///
/// An ANN search always answers with `k` neighbours however poor they are — that is what nearest
/// means. The floor is the whole quality gate: it converts *k results* into *at most k results,
/// none of them noise*, and a page coming back under-full is the ruling's own intent rather than a
/// defect to pad around.
pub struct VectorQuery<E, S, const N: usize, Space = Anon> {
  input: Embedding<E, N, Space>,
  floor: S,
}

impl<E, const N: usize, Space> VectorQuery<E, Deferred, N, Space> {
  /// Ask for the neighbours of `input`, DEFERRING the floor — [`new`](Self::new)'s floorless twin.
  ///
  /// The ruled chain is *查询层传入 > attr 默认*, and this is how a caller declines the first step:
  /// the query carries the question and the number comes from the declaration that owns the column.
  /// What comes back is a [`Deferred`]-floored query, which is not the type an engine-facing door
  /// takes — [`floored`](Self::floored) is the one move from here.
  #[inline]
  #[must_use]
  pub const fn of(input: Embedding<E, N, Space>) -> Self {
    Self {
      input,
      floor: Deferred::new(),
    }
  }

  /// RESOLVE the deferred floor — the chain's second step, and the seam an emitted face calls with
  /// the declaration's own number.
  ///
  /// Consuming, because the resolved query is the same question at a different type and keeping the
  /// deferred one beside it would be keeping a query nobody may ask.
  #[inline]
  #[must_use]
  pub fn floored<S>(self, floor: S) -> VectorQuery<E, S, N, Space> {
    VectorQuery {
      input: self.input,
      floor,
    }
  }
}

impl<E, S, const N: usize, Space> VectorQuery<E, S, N, Space> {
  /// Ask for the neighbours of `input`, returning nothing that scores below `floor`.
  #[inline]
  pub const fn new(input: Embedding<E, N, Space>, floor: S) -> Self {
    Self { input, floor }
  }

  /// The query coordinates, as [`VectorRead::knn`](crate::VectorRead::knn) takes them.
  #[inline]
  pub fn coordinates(&self) -> &[E] {
    self.input.coordinates()
  }

  /// The embedding itself, borrowed.
  #[inline]
  pub const fn input(&self) -> &Embedding<E, N, Space> {
    &self.input
  }

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

/// The three are written rather than derived, for [`Embedding`]'s own reason: a derive bounds every
/// parameter it sees, and `Space` is a marker holding nothing that a sealed `pub struct Clip(());`
/// derives nothing for. A derived trio would take [`Debug`], [`Clone`] and equality off exactly the
/// queries that name a space.
impl<E: core::fmt::Debug, S: core::fmt::Debug, const N: usize, Space> core::fmt::Debug
  for VectorQuery<E, S, N, Space>
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("VectorQuery")
      .field("input", &self.input)
      .field("floor", &self.floor)
      .finish()
  }
}

impl<E, S: Clone, const N: usize, Space> Clone for VectorQuery<E, S, N, Space> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      // The embedding's own `Clone` is a refcount bump and carries no `E: Clone`, so this one does
      // not either — the derived body would have demanded it of both.
      input: self.input.clone(),
      floor: self.floor.clone(),
    }
  }
}

impl<E: PartialEq, S: PartialEq, const N: usize, Space> PartialEq for VectorQuery<E, S, N, Space> {
  #[inline]
  fn eq(&self, other: &Self) -> bool {
    self.input == other.input && self.floor == other.floor
  }
}

#[cfg(test)]
mod tests;