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 FOLD DOOR: where an emitted SET-similarity resolver gets the fold its `m` per-stream bests
//! are folded by.
//!
//! ```text
//! Schema::build(root, …)
//!   .data(Shared::<Lance>::new(lance))                            // WHERE the search runs
//!   .data(FoldDoor::<Lance, ShotsByClip>::installed(Max::new()))  // HOW its m streams combine
//!         │
//!         ▼
//! ctx.data_opt::<FoldDoor<Lance, ShotsByClip>>()  →  Some(fold)  |  None → the ELECTION's own
//! ```
//!
//! # The fold is a POLICY, and a policy has exactly one seat
//!
//! Ruled 2026-08-16. Three parties could have chosen which fold a set answer is scored by, and two
//! of them are refused:
//!
//! - **the REQUEST never chooses.** A fold changes what the answer MEANS — `sum` rewards a result
//!   that answered many query vectors adequately, `max` rewards one that answered a single vector
//!   perfectly — and a client able to swap that per query is a client able to make two answers of
//!   one corpus that cannot be compared or cached against each other. It is the same posture every
//!   other policy in this framework takes, and a request arm remains purely additive on the day one
//!   is ruled.
//! - **the DECLARATION chooses the DEFAULT**, through `semantics(fold = "…")`, which is the word
//!   that already exists and the one the emitted `fold_by_<field>()` accessor hands back — `Sum`
//!   where an election declared none. No word is minted here.
//! - **the DEPLOYMENT overrides it at launch**, which is this module. The same act that installs
//!   the door a resolver searches through installs the fold it scores through, and a deployment that
//!   installs none runs the election's own.
//!
//! # THE SEAT IS A WIRE DOOR, and the family that proves it is the DOOR family
//!
//! Re-ruled 2026-08-16 (甲″), after a ruling had sent this citizen to `PolicyShelf` and three
//! measurements sent it back. The argument for the move was *policy-family uniformity*; all three of
//! its premises are false in this tree, and each is checkable:
//!
//! - `PolicyShelf` is an EMPTY trait by an explicit prior ruling — its own note refuses a knob now
//!   because *a block that accepted a knob would be a knob whose meaning the selection mechanism
//!   would then have to preserve*. `options ▸ policies.fold` was exactly that refused knob.
//! - NO emitted code reads any policy. The policy family serves the DRIVE layer's residents —
//!   retry, overflow, deadline, tick — and the wire layer never meets it, so there was no *read it
//!   exactly as the other policies are read* to follow.
//! - [`Policies`](crate::Policies) is currency-BLIND (`Arc<dyn TickPolicy>` and its siblings, none
//!   generic) while [`FoldSemantics<S>`](crate::FoldSemantics) is currency-GENERIC and keyed per
//!   (engine × election). Seating it there costs either a `TypeId` downcast or a new parameter on
//!   `Policies`, and either way the keying below is lost.
//!
//! So the uniformity argument survives its own refutation, pointing the other way: **the wire
//! layer's uniform assembly mechanism is the ctx CITIZEN family** — [`Shared<R>`](crate::Shared),
//! [`BlobDoor`](crate::BlobDoor), [`SqlDoor`](crate::SqlDoor) — and a fold installed at launch and
//! read from a request's context is a wire fact assembled the way every other wire fact is. This
//! citizen sat in the right family from birth.
//!
//! What is genuinely still owed is the CONFIGURATION LINE: options reaching this door's
//! construction, with the fold's config in the door's OWN options section rather than in a policy
//! block. That lands with R5's emitted install glue, whose territory it always was — and it is a
//! line about how a door is BUILT, not about where the seat lives.
//!
//! # ONE DOOR PER (ENGINE × ELECTION), which is one grain finer than the search road
//!
//! The search road's citizen is keyed by the RESOURCE alone, a corpus being named per read. A fold
//! is a fact about ONE ELECTED COLUMN — a declaration electing a set of frames and a
//! set of captions has two sets of query vectors and no reason to fold them alike — so the key here
//! is the emitted ELECTION MARKER, `<Index>By<Field>`, which is the same type a lane serving that
//! column is already parameterized by. `Context::data` is a `TypeId` lookup, so the parameters ARE
//! the routing: there is no registry and no way for one election's resolver to reach another's fold.
//!
//! # It holds the fold ERASED, and the emitted door still dispatches statically
//!
//! What a resolver looks up is a concrete type, so the fold inside it is `Arc<dyn FoldSemantics<…>>`
//! — the openness living inside the citizen, exactly as a mount's own
//! [`FulltextMount`](crate::FulltextMount) impl and [`SqlDoor`](super::SqlDoor)'s pool do. The virtual call is paid ONCE PER ENTITY at the fold,
//! which is where a `Box<dyn …>` was refused for the `_with` door's own `fold` parameter — but there
//! the alternative was a caller naming the type, and here there is no caller: the type is a
//! deployment's, chosen after the schema was compiled. The Rust door beneath is untouched and still
//! takes its fold by value: `&dyn FoldSemantics<S>` folds, through the borrow's own forwarding impl.

use core::marker::PhantomData;
use std::sync::Arc;

use crate::{retrieve::FoldSemantics, store::VectorEngine};

/// The DOOR an emitted set-similarity resolver reads its fold out of — one per (engine × election) a
/// schema serves, and ABSENT wherever a deployment is content with the election's own.
///
/// Cloneable and cheap: the fold is behind an [`Arc`], so installing one costs a refcount.
///
/// # `T` is the ELECTION MARKER and carries no data
///
/// `FoldDoor<Lance, ShotsByClip>`. The marker is emitted beside the declaration and is the same type
/// the retrieve lanes are keyed by, so a deployment spells a name it already has rather than a
/// string this module would have had to invent. It is held as `PhantomData<fn(&T)>` — the crate's
/// marker spelling, holding nothing and leaving every auto trait independent of `T`.
pub struct FoldDoor<E: VectorEngine<Score: 'static>, T: ?Sized> {
  fold: Arc<dyn FoldSemantics<E::Score>>,
  election: PhantomData<fn(&T)>,
}

impl<E, T> FoldDoor<E, T>
where
  E: VectorEngine<Score: 'static>,
  T: ?Sized,
{
  /// Fold this election's streams with `fold`.
  ///
  /// The fold BY VALUE — a fold is a value a deployment builds once, and the shipped citizens are
  /// ZSTs. A stateful one (a [`Weighted`](crate::Weighted) read out of configuration, a tenant's
  /// own) is built the same way and costs the same single allocation.
  #[must_use]
  #[inline]
  pub fn installed<F>(fold: F) -> Self
  where
    F: FoldSemantics<E::Score> + 'static,
  {
    Self::new(Arc::new(fold))
  }

  /// A door onto a fold an application already holds behind an [`Arc`] — for the deployment that
  /// installs one fold at several pairings without building it twice.
  #[must_use]
  #[inline]
  pub const fn new(fold: Arc<dyn FoldSemantics<E::Score>>) -> Self {
    Self {
      fold,
      election: PhantomData,
    }
  }

  /// The fold, BORROWED — what an emitted resolver hands to the `_with` door.
  ///
  /// `&dyn` rather than a clone of the [`Arc`], because the resolver's own call is the whole of the
  /// borrow's life: the door outlives the request that found it.
  #[must_use]
  #[inline]
  pub fn semantics(&self) -> &dyn FoldSemantics<E::Score> {
    &*self.fold
  }

  /// The installed fold's own stable name — `"sum"`, `"max"`, whatever a deployment's own carries.
  ///
  /// Beside [`semantics`](Self::semantics) because a caller wanting only the name should not have to
  /// spell the trait to reach it: the name is what a span field, a refusal and a log line take.
  #[must_use]
  #[inline]
  pub fn name(&self) -> &str {
    self.fold.name()
  }
}

/// Written out rather than derived, for the reason every parameterised handle in this crate writes
/// its own: a derive would bound `E: Clone` — which nothing here requires — and `T: Clone`, which is
/// an election marker and never a value.
impl<E, T> Clone for FoldDoor<E, T>
where
  E: VectorEngine<Score: 'static>,
  T: ?Sized,
{
  #[inline]
  fn clone(&self) -> Self {
    Self {
      fold: Arc::clone(&self.fold),
      election: PhantomData,
    }
  }
}

/// Written out because a trait object carries no [`Debug`](core::fmt::Debug). What a reader wants
/// from this line is WHICH door it is and WHAT is installed in it, and the fold's own name is the
/// second half — which is one of the three places that row is spent.
impl<E, T> core::fmt::Debug for FoldDoor<E, T>
where
  E: VectorEngine<Score: 'static>,
  T: ?Sized,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("FoldDoor")
      .field("engine", &core::any::type_name::<E>())
      .field("election", &core::any::type_name::<T>())
      .field("fold", &self.name())
      .finish()
  }
}

#[cfg(feature = "async-graphql")]
impl<E, T> FoldDoor<E, T>
where
  E: VectorEngine<Score: 'static> + Send + Sync + 'static,
  T: ?Sized + Send + Sync + 'static,
{
  /// INSTALL this door on a schema being built — the one act a deployment performs for it.
  ///
  /// ```ignore
  /// let schema = Schema::build(MediaQuery::default(), EmptyMutation, EmptySubscription)
  ///   .data(Shared::<Lance>::new(lance))
  ///   .finish();                       // and, where the shipped default is not wanted:
  /// FoldDoor::<Lance, ShotsByClip>::installed(Max::new()).install(builder)
  /// ```
  ///
  /// A named act rather than a bare `.data(door)`, and the reason is the KEYING: so a schema serving two set elections calls this twice
  /// and each resolver reaches the fold its own election was branded for.
  #[must_use]
  pub fn install<Q, M, S>(
    self,
    builder: async_graphql::SchemaBuilder<Q, M, S>,
  ) -> async_graphql::SchemaBuilder<Q, M, S>
  where
    Q: async_graphql::ObjectType + 'static,
    M: async_graphql::ObjectType + 'static,
    S: async_graphql::SubscriptionType + 'static,
  {
    builder.data(self)
  }
}

/// THE FOLD one emitted set resolver runs under, or [`None`] where the deployment installed none.
///
/// # It answers `Option` rather than falling back here, and the emission is why
///
/// The fallback is the ELECTION's own — `semantics(fold = "…")`, or the shipped
/// [`Sum`](crate::Sum) where the election declared none — and that is a type only the EMISSION can
/// spell: this module has never seen the declaration. So the lookup answers whether a deployment
/// overrode it, and the resolver picks between two folds it can both name. A default invented here
/// would be this crate deciding what a declaration meant.
///
/// No refusal either, unlike [`search_slot`](super::search_slot): a missing search door is a
/// deployment that forgot to open its engine, and a missing fold door is a deployment that was
/// content with the fold its declaration elected — which is the ordinary case rather than a mistake.
#[cfg(feature = "async-graphql")]
#[must_use]
pub fn installed_fold<'ctx, E, T>(
  ctx: &'ctx async_graphql::Context<'_>,
) -> Option<&'ctx FoldDoor<E, T>>
where
  E: VectorEngine<Score: 'static> + Send + Sync + 'static,
  T: ?Sized + Send + Sync + 'static,
{
  async_graphql::Context::data_opt::<FoldDoor<E, T>>(ctx)
}

#[cfg(all(test, feature = "async-graphql"))]
mod tests;