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
//! [`SlotHandle`] — the SLOT BRAND: an engine handle that carries, in its type, which declaration's
//! slot it was opened for.

use core::{future::Future, marker::PhantomData, num::NonZeroUsize};

use super::{
  AsyncFulltextRead, AsyncFulltextWrite, AsyncVectorRead, AsyncVectorWrite, Connected,
  FulltextSubset, Hits, VectorColumn,
};

/// An engine handle BRANDED with the SLOT it was opened for.
///
/// # What `T` is, and that it MOVED
///
/// It was the DECLARATION, while a declaration was a slot. Under the engine grammar a slot is
/// `(elected field × declared engine)` and `T` is the marker naming that pair — see
/// [`Slot`](super::Slot), which a derived index emits one of per slot. Nothing here changed to carry
/// it: `T: ?Sized` was already unbounded, so the brand narrowed for free, and a declaration is still
/// what a slot marker names ([`Slot::Of`](super::Slot::Of)).
///
/// # What it stops, and why that is corpus corruption rather than a mix-up
///
/// A slot is the grain of storage isolation, and for the shipped engine it is load-bearing
/// arithmetic: ONE Tantivy index per slot, because BM25's corpus statistics — `docfreq` over
/// `numdocs`, and the average document length the length normalization divides by — are INDEX-wide.
/// A write that lands in another slot's index does not merely put a row in the wrong place;
/// it moves that index's scores, which moves them out from under the MANDATORY FLOOR the retrieve
/// face is calibrated against. The repair is a reindex, not a code change. `store::tantivy`'s own
/// three laws state the same fact from the engine's side.
///
/// The re-keying makes that guarantee FINER rather than different: a title and a body of one
/// declaration are now two corpora, so writing one cannot move the other's scores either.
///
/// The same class exists one engine over — a Lance table inside a shared instance is the same wrong
/// write — so the brand is engine-kind-agnostic and the vector face wears it identically.
///
/// # It PROPAGATES the pairing; it does not PROVE it
///
/// This is the honest sentence and it is the whole contract. [`mint`](Self::mint) is where a lie can
/// enter: nothing in the type system checks that the engine handed to `mint::<_, Transcript>` was
/// opened on `Transcript::SLOT`. What the brand buys is that the fact, once stated, TRAVELS — every
/// site downstream of the mint carries the declaration in its type, so a handle cannot be quietly
/// swapped for another slot's on the way to a write or a read.
///
/// That makes the mint the one place to audit, and production has exactly ONE: the launch walk that
/// opens `options[T::SLOT]`'s path. Tests hand-mint deliberately, which is what lets a fixture
/// build the wrong pairing on purpose and prove it is refused.
///
/// A runtime slot-name assertion is NOT replaced by this and may later join INSIDE `mint` as
/// belt-and-braces — brand against directory — which is a launch-round detail rather than a
/// substitute.
///
/// # It adds ZERO impl rows, which is why it resurrects no wall
///
/// A′'s walls were the per-(record × engine) IMPL FAMILIES an R-generic engine trait forced: the
/// `E0117` orphan wall on a key trait over foreign types, and the `trivial_bounds` `E0277` an
/// expansion could not satisfy. This is a STRUCT, not a trait: engines stay R-free, a key's
/// [`Field`](super::Field) row names no engine at all, and nothing anywhere gains an impl per
/// declaration. A brand is a fact carried through the types, and carrying costs no rows.
///
/// # `PhantomData<fn() -> T>` and not `PhantomData<T>`
///
/// The marker must not make the handle's own auto-traits depend on the declaration. `PhantomData<T>`
/// would make `SlotHandle<E, T>: Send` require `T: Send`, so a declaration that is not `Send` would
/// silently cost the write seam its `+ Send` future — a bound arriving from a type that reaches no
/// byte here. The `fn() -> T` form is `Send + Sync` for every `T`, so the handle's auto-traits are
/// exactly the engine's, and it stays covariant in `T`, which is what a marker should be.
///
/// `T: ?Sized`, because a declaration is only ever NAMED here.
pub struct SlotHandle<E, T: ?Sized> {
  engine: E,
  slot: PhantomData<fn() -> T>,
}

impl<E, T: ?Sized> SlotHandle<E, T> {
  /// Brand `engine` as `T`'s slot — the ONE place the pairing is asserted.
  ///
  /// Production's caller is the launch walk, which opened this engine on `T::SLOT`'s own path and is
  /// therefore the one site that KNOWS the pairing. A test mints by hand, deliberately.
  ///
  /// It is `const` and takes the engine by value: a brand owns what it brands, so there is no second
  /// unbranded handle left beside it for a caller to reach for.
  #[inline]
  #[must_use]
  pub const fn mint(engine: E) -> Self {
    Self {
      engine,
      slot: PhantomData,
    }
  }

  /// The engine, borrowed — for a read that needs no exclusivity of its own.
  #[inline]
  #[must_use]
  pub const fn engine(&self) -> &E {
    &self.engine
  }

  /// The engine, borrowed exclusively.
  #[inline]
  #[must_use]
  pub const fn engine_mut(&mut self) -> &mut E {
    &mut self.engine
  }

  /// Take the engine, dropping the brand — the deliberate un-branding, for a caller that has left
  /// the seam and is doing something the brand has no opinion about.
  ///
  /// It is the escape the openness doctrine owes, and it is loud: a name at the call site says the
  /// pairing was let go of, where a silent `Deref` would have let it leak.
  #[inline]
  #[must_use]
  pub fn into_engine(self) -> E {
    self.engine
  }
}

/// Cloning PRESERVES the brand — `T` is unchanged — so it costs the guarantee nothing and it is what
/// a second concurrent reader takes. The bound is on `E` alone, the marker being `Copy` for every
/// `T`.
impl<E: Clone, T: ?Sized> Clone for SlotHandle<E, T> {
  #[inline]
  fn clone(&self) -> Self {
    Self::mint(self.engine.clone())
  }
}

impl<E: core::fmt::Debug, T: ?Sized> core::fmt::Debug for SlotHandle<E, T> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    // The declaration is a TYPE and has no value to print; what identifies the handle at runtime is
    // the engine it brands.
    f.debug_struct("SlotHandle")
      .field("engine", &self.engine)
      .finish()
  }
}

/// The BRANDED full-text WRITE door — where a declaration's own write crosses into its engine.
///
/// The verb is a thin forward to the engine's own, and the forwarding IS the mechanism: the
/// signature is where the declaration is named, so handing `T`'s write another declaration's handle
/// is `E0308` naming both. The engine seam itself is untouched and stays R-free.
///
/// It takes `&mut self`, which for a write is the act's own law — a keyed replace must not
/// interleave against its own slot.
///
/// # Why the door is TWO impl blocks per family
///
/// The verbs live on their FACES, and the two directions are two traits — so the bound that reaches
/// `upsert` is not the bound that reaches `search`, and a branded door written over one trait would
/// demand the other of every engine it brands. Two blocks is the division the seam already has,
/// carried here: an engine that only writes wears this door and never the read one.
///
/// The face named is the ASYNC one on every block, which is where every caller of these doors stands
/// today. The blocking pair is spellable at the face itself, and a branded blocking door is a
/// mode-selection question rather than a brand question.
///
/// # Why the two kinds' write verbs are spelled apart
///
/// `upsert_document` and [`upsert_vector`](Self::upsert_vector) name their engine kind because two
/// inherent methods of ONE name on one type are `E0592` — duplicate definitions — regardless of the
/// bounds their impl blocks carry, and an engine implementing BOTH faces is perfectly legal. The
/// read verbs need no such care: `search` and `knn` were already two words.
impl<E: AsyncFulltextWrite, T: ?Sized> SlotHandle<E, T> {
  /// Index one entry into `T`'s slot.
  #[inline]
  pub fn upsert_document(
    &mut self,
    ctx: Connected<'_, E::Connection, E::WriteContext<'_>>,
    doc: E::Doc,
  ) -> impl Future<Output = Result<(), E::Error>> + Send {
    self.engine.upsert(ctx, doc)
  }
}

/// The BRANDED full-text READ door — the search, over the face that answers it.
///
/// `&mut self` here is the seam's rather than the act's, the emitted retrieve being spelled
/// `&mut SlotHandle<E, Self>`; a caller wanting two concurrent reads clones the handle, which
/// preserves the brand.
impl<E: AsyncFulltextRead, T: ?Sized> SlotHandle<E, T> {
  /// Search `T`'s slot, within `subset` of its ELECTED COLUMNS.
  ///
  /// ONE SLOT, several searchable columns: the brand still says which declaration's corpus this is,
  /// and `subset` says which of that declaration's elected fields answer. The two facts are at
  /// different grains and neither substitutes for the other — a wrong slot is `E0308` naming both
  /// declarations, and a column the slot does not hold is the engine's own named refusal.
  ///
  /// `k` is HOW MANY, forwarded verbatim — the brand adds nothing to it and defaults nothing about
  /// it, which is the whole of what a thin forward means here.
  ///
  /// `options` is the request's own per-query knobs, or [`None`] to run under the engine's defaults
  /// — see [`FulltextEngine::SearchOptions`](super::FulltextEngine::SearchOptions).
  #[inline]
  pub fn search(
    &mut self,
    ctx: Connected<'_, E::Connection, E::ReadContext<'_>>,
    subset: FulltextSubset<'_>,
    query: &str,
    k: NonZeroUsize,
    options: Option<&E::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<E::Address, E::Score>, E::Error>> + Send {
    self.engine.search(ctx, subset, query, k, options)
  }
}

/// The BRANDED vector WRITE door — the same stroke on the other engine kind, for the same reason: a
/// Lance table inside a shared instance is the same wrong-write corpus class as a Tantivy index
/// inside a shared root.
///
/// Two blocks per family, for the reason [`upsert_document`](Self::upsert_document)'s door states.
impl<E: AsyncVectorWrite, T: ?Sized> SlotHandle<E, T> {
  /// Index one entry into `T`'s slot.
  #[inline]
  pub fn upsert_vector(
    &mut self,
    ctx: Connected<'_, E::Connection, E::WriteContext<'_>>,
    doc: E::Doc,
  ) -> impl Future<Output = Result<(), E::Error>> + Send {
    self.engine.upsert(ctx, doc)
  }
}

/// The BRANDED vector READ door — [`knn`](Self::knn) and the by-key read, over the face that
/// answers them.
impl<E: AsyncVectorRead, T: ?Sized> SlotHandle<E, T> {
  /// Nearest neighbours within `T`'s slot, in the ELECTED COLUMN `column`.
  ///
  /// ONE SLOT, several vector columns: the brand still says which declaration's storage this is, and
  /// `column` says which of that declaration's elected embeddings answers. The two facts are at
  /// different grains and neither substitutes for the other — a wrong slot is `E0308` naming both
  /// declarations, and a wrong column is a name this slot does not hold.
  ///
  /// `k` is HOW MANY NEIGHBOURS, forwarded verbatim — [`search`](Self::search)'s twin, for its
  /// reason.
  ///
  /// `options` is the request's own per-query knobs, or [`None`] to run under the engine's defaults
  /// — see [`VectorEngine::SearchOptions`](super::VectorEngine::SearchOptions).
  #[inline]
  pub fn knn(
    &mut self,
    ctx: Connected<'_, E::Connection, E::ReadContext<'_>>,
    column: VectorColumn,
    query: &[E::Element],
    k: NonZeroUsize,
    options: Option<&E::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<E::Address, E::Score>, E::Error>> + Send {
    self.engine.knn(ctx, column, query, k, options)
  }

  /// This entity's OWN vectors within `T`'s slot, in the ELECTED COLUMN `column`, at `address` —
  /// the branded by-key read.
  ///
  /// `get_vectors` rather than the seam's own `get`, and the suffix is bought by the same collision
  /// [`upsert_vector`](Self::upsert_vector) pays for: the two engine faces are two traits and may be
  /// worn by ONE type, so a name shared by both impl blocks is two inherent methods on one handle.
  /// `search` and `knn` were already two words and needed none of this; a bare `get` would need it
  /// the day a full-text index answers *what did you store for this key*, which is the `stored`
  /// marker's own question. The suffix is paid now rather than renamed then.
  #[inline]
  pub fn get_vectors(
    &mut self,
    ctx: Connected<'_, E::Connection, E::ReadContext<'_>>,
    column: VectorColumn,
    address: &E::Address,
  ) -> impl Future<Output = Result<Vec<Vec<E::Element>>, E::Error>> + Send {
    self.engine.get(ctx, column, address)
  }
}

#[cfg(test)]
mod tests;