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 [`DetectedLanguage`] pair: what a detector decided a track is in, and how sure it was.

use core::fmt;

use crate::{
  CompositeFilterMarker, CompositeMarker, ConfidenceFilter, DefaultMarker, DefaultVecMarker,
  QuantifiedMarker, Score,
};

use super::{LanguageId, LanguageIdFilter};

#[cfg(feature = "sqlx")]
mod comparison;
mod storage;

#[cfg(test)]
mod tests;

#[cfg(feature = "sqlx")]
pub use comparison::SqlDetectedLanguageComparison;

/// One detection: which language a track was decided to be in, and how confident the detector was.
///
/// The pair is deliberate, for the reason every DETECTION type's is. A detector emits several
/// candidates per track, each with its own confidence, so a row that recorded only the language
/// would lose the one number that says whether to believe it — and a query narrowing on language and
/// on confidence separately would let a track where German scored `0.2` answer a question about
/// German above `0.8`, on the strength of some other language scoring `0.9`.
///
/// # The carrier is a whole [`LanguageId`], and that is what makes the type outlast its detectors
///
/// Whisper emits a bare two-letter code and nothing else, so today every value here has a
/// `LanguageId` with three empty seats. Carrying the composite anyway costs one word per absent seat
/// and buys the thing a narrower carrier would have to be redesigned for: the day a detector
/// distinguishes simplified from traditional Chinese — which is a REAL detector's real output rather
/// than a hypothetical — its answer lands in the script seat and nothing here, in storage or on the
/// wire, changes shape.
///
/// It is also lossless in the other direction. A bare `zh` from a detector and a `zh-Hans` from a
/// container are two identities, not one identity and a note; the type that holds them is the same
/// type, so nothing has to decide which of the two a column is for.
///
/// # TOP-K is the FIELD's shape, not this type's
///
/// A detector's *k* candidates are a `Vec<DetectedLanguage>`, and that is a decision made where the
/// field is declared rather than here: this type is ONE detection, so nothing about it knows or
/// cares whether it is the best one. What the collection reading buys is stated on this type's
/// [`DefaultVecMarker`] row — `any` over one whole detection and `count` over the collection's
/// length, and none of the seven operators a sequence reading would add.
///
/// # Equality is the PAIR
///
/// The same language detected twice at different confidences is two detections, so the confidence
/// is part of the identity rather than a payload hanging off it. That is every detection type's
/// rule, and it holds here for the same reason.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DetectedLanguage {
  language: LanguageId,
  confidence: Score,
}

impl DetectedLanguage {
  /// A detection of a language at a confidence.
  ///
  /// Infallible, because both halves have already been validated: a [`LanguageId`] cannot hold a
  /// subtag its own door refused, and a [`Score`] cannot exist outside `[0.0, 1.0]`.
  #[inline]
  #[must_use]
  pub const fn new(language: LanguageId, confidence: Score) -> Self {
    Self {
      language,
      confidence,
    }
  }

  /// The language that was detected.
  #[inline]
  #[must_use]
  pub const fn language(&self) -> &LanguageId {
    &self.language
  }

  /// How confident the detector was, in `[0.0, 1.0]`.
  #[inline]
  #[must_use]
  pub const fn confidence(&self) -> Score {
    self.confidence
  }
}

/// The tag and the confidence, which is the whole of what a detection is.
impl fmt::Debug for DetectedLanguage {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DetectedLanguage")
      .field("language", &self.language.to_string())
      .field("confidence", &self.confidence.get())
      .finish()
  }
}

/// The tag, then the confidence in brackets — `zh-Hans (0.94)`.
///
/// A rendering rather than a round trip, and it is worth saying which: nothing parses this back.
/// [`LanguageId`]'s own [`Display`](fmt::Display) IS an inverse of its parse, and a detection's is
/// not, because the pair has no spelling any standard defines.
impl fmt::Display for DetectedLanguage {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{} ({})", self.language, self.confidence.get())
  }
}

/// **The crossing OUT** — a BORROW, resolved by the `#[Object]` this type publishes: the four seats
/// of its identity FLATTENED, and the confidence beside them.
///
/// There is no [`ToGraphqlInput`](crate::ToGraphqlInput) row beside it, and the absence is the
/// filter's shape rather than an omission. A client never SENDS a whole detection: what it sends is a
/// [`DetectedLanguageFilter`], whose operands are a [`LanguageIdOperand`](super::LanguageIdOperand),
/// the three subtags and a confidence threshold. A whole-detection `eq` would be an exact float
/// equality against a number a client typed, which is the question this type's
/// [`DefaultVecMarker`] row already argues cannot be asked honestly.
///
/// So the two directions are deliberately unequal here, where they are equal for every other type in
/// this house — and the row that would have made them equal is the one that would have published a
/// question with no true answer.
impl crate::ToGraphqlOutput for DetectedLanguage {
  type Output<'a> = &'a Self;

  #[inline]
  fn to_graphql_output(marked: &Self) -> &Self {
    marked
  }
}

/// What guards a [`DetectedLanguage`] column — [`LanguageId`]'s row, and the same reading of it: a
/// detection stores every field it declares, so the two seats name one predicate.
///
/// [`LanguageId`]: super::LanguageId
impl CompositeFilterMarker for DetectedLanguage {
  type Filter = DetectedLanguageFilter;
  type ColumnFilter = DetectedLanguageFilter;
}

/// The interpretation a [`DetectedLanguage`] field is read under — [`LanguageId`]'s reading, and
/// this crate no longer mints either: a detection occupies five columns OF ITS OWN, so all five can
/// be absent together, which is exactly the VALUE family [`CompositeMarker`] names.
///
/// [`LanguageId`]: super::LanguageId
impl DefaultMarker for DetectedLanguage {
  type Marker = CompositeMarker<DetectedLanguage>;
}

/// **A COLLECTION of detections is asked through the QUANTIFIERS alone** — the reading
/// [`QuantifiedMarker`] names, and the one this element could not have had from the wide kinds.
///
/// A detector emits *k* candidates per track, so a `Vec<DetectedLanguage>` is what a row actually
/// holds — and the operators [`ListFilter`](crate::ListFilter) would publish over it are seven
/// questions this pair cannot answer honestly. Each of the seven holds a whole DETECTION as its
/// operand, and a detection carries a float:
///
/// * `hasElement` is exact equality against a confidence a client typed, so it answers *no rows* to
///   the question a caller believed they had asked — *was this language detected at about this
///   confidence*.
/// * `eq` and `ne` are that same falseness per element, multiplied by the collection's length.
/// * `gt`, `gte`, `lt` and `lte` compare two whole collections lexicographically, under an order
///   composed of a TAG's alphabetical one and a float's. This family already documents the first as
///   good for exactly one thing — a cursor — and nothing makes it mean more inside a collection
///   comparison than it does outside one.
///
/// What is left is `any` and `count`, and `any` loses nothing: it carries the whole
/// [`DetectedLanguageFilter`], so every question this family CAN ask about one detection — the
/// identity, the three components and the confidence — is askable of a collection's members.
/// `any: { language: { eq: "zh" }, confidence: { gte: 0.8 } }` is *some Chinese was detected, and
/// confidently*, which is the question `hasElement` was pretending to be able to ask.
///
/// **This is where TOP-K lives.** A ranked list of candidates is a collection, `count` asks how many
/// there were, and `any` asks about each — so the ruling's *k* is the field's `Vec` and the two
/// quantifiers, with nothing about ranking in the element type.
impl DefaultVecMarker for DetectedLanguage {
  type Marker = QuantifiedMarker<Vec<DetectedLanguage>>;
}

/// The filter that guards a [`DetectedLanguage`] column: the whole IDENTITY axis flattened, and the
/// CONFIDENCE nested beside it.
///
/// | facet | slots | operand | asks about |
/// |---|---|---|---|
/// | IDENTITY | `eq`, `ne`, `in`, `notIn` | [`LanguageIdOperand`](super::LanguageIdOperand) | the whole detected tag |
/// | COMPONENT | `language`, `script`, `region` | the three subtags | one seat of it |
/// | CONFIDENCE | `confidence` | [`Score`] | how sure the detector was |
///
/// # The identity axis FLATTENS and the confidence does not
///
/// A client writes `{ language: { eq: "zh" } }` where it writes `{ confidence: { gte: 0.8 } }`, and
/// the asymmetry is the one every detection filter makes and for its reason. What a detection IS is
/// the language: that is the crossing, and a whole-identity `eq` on a
/// face carrying both would have nothing to disambiguate. The confidence is an ATTRIBUTE of that
/// identity, and a bare `eq` on a face carrying both would have to pick which of them it meant.
///
/// The flattened component is `LanguageIdFilter` WHOLE, so all seven of its slots arrive — the four
/// identity words and the three component filters, `isNull` included. Nothing is restated here and
/// nothing can drift: a slot added to that filter appears on this face with it.
///
/// # The two guard ONE detection, and that is why they share a filter
///
/// A track carries *k* (language, confidence) pairs. Were the two questions asked of the track
/// separately, *German above 0.8* would be answered by a track where German scored `0.2` and English
/// scored `0.9` — each half true of a different detection. Holding both in one filter over one
/// detection makes that unrepresentable rather than merely wrong.
///
/// # `confidence` takes the framework's SIX confidence words
///
/// The facet is [`ConfidenceFilter`] — `eq`, `ne`, `gt`, `gte`, `lt`, `lte` — and every one of them
/// is well-defined, because [`Score`]'s constructor refuses `NaN` and the resulting order is total.
/// `eq` and `ne` earn their place: `eq: 1.0` is a saturated detector and `ne: 0.0` is *was it a
/// candidate at all*, both exactly representable and both genuinely asked.
///
/// `in` and `notIn` are ABSENT FROM THE KIND rather than declined here — a membership list over a
/// continuous measurement resolves each member at a width the client cannot see, so it answers *no
/// rows* to a question the caller believed they had asked. See [`ConfidenceFilter`], where the
/// framework argues it.
///
/// # The wire face is DECLARED, not written
///
/// `#[ingraph(composed)]`, and the identity component carries `#[ingraph(flatten)]`. Declaration
/// order IS publication order, so the confidence is published last, after the seven the splice
/// brings.
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed)]
pub struct DetectedLanguageFilter {
  #[ingraph(flatten)]
  language: LanguageIdFilter,
  confidence: Option<ConfidenceFilter>,
}

impl DetectedLanguageFilter {
  /// The empty filter — no operator set on either facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      language: LanguageIdFilter::new(),
      confidence: None,
    }
  }

  /// True while NO operator slot is set on EITHER facet.
  ///
  /// NOT `const`, for the reason [`LanguageIdFilter::is_empty`] is not: a nullable component's own
  /// emptiness is the framework's arithmetic and not a `const fn`.
  pub fn is_empty(&self) -> bool {
    self.language.is_empty()
      && self
        .confidence
        .as_ref()
        .is_none_or(ConfidenceFilter::is_empty)
  }

  /// The detected identity's filter — the axis the wire face publishes FLATTENED.
  #[inline]
  pub const fn language(&self) -> &LanguageIdFilter {
    &self.language
  }

  /// The confidence's filter.
  #[inline]
  pub const fn confidence(&self) -> Option<&ConfidenceFilter> {
    self.confidence.as_ref()
  }

  /// Replace the identity's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_language(mut self, language: LanguageIdFilter) -> Self {
    self.set_language(language);
    self
  }

  /// Replace the identity's filter (in place).
  #[inline]
  pub fn set_language(&mut self, language: LanguageIdFilter) -> &mut Self {
    self.language = language;
    self
  }

  /// Replace the confidence's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_confidence(mut self, confidence: ConfidenceFilter) -> Self {
    self.set_confidence(confidence);
    self
  }

  /// Replace the confidence's filter (in place).
  #[inline]
  pub fn set_confidence(&mut self, confidence: ConfidenceFilter) -> &mut Self {
    self.confidence = Some(confidence);
    self
  }
}

impl Default for DetectedLanguageFilter {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}