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 three shipped citizens, and the two claims that would otherwise be prose: that a fold reads
//! its own absences, and that a fourth citizen costs one impl.

use std::sync::Arc;

use super::{FoldSemantics, Max, Sum, Weighted};
use crate::{Embedding, FoldedQuery};

const DIM: usize = 4;

fn embedding(coordinates: [f32; DIM]) -> Embedding<f32, DIM> {
  Embedding::new(Arc::from(coordinates.to_vec())).expect("the fixture declares DIM")
}

fn query(m: usize) -> FoldedQuery<f32, f32, DIM> {
  FoldedQuery::new(
    (0..m).map(|_| embedding([1.0, 0.0, 0.0, 0.0])).collect(),
    0.0,
  )
  .expect("the fixture asks with at least one vector")
}

/// `Σⱼ bⱼ`, over the slots that hold an answer.
#[test]
fn sum_adds_every_answered_slot() {
  let folded = Sum::new().score(&[Some(0.5_f32), Some(0.25), Some(0.125)]);

  assert!((folded - 0.875).abs() < f32::EPSILON, "{folded}");
}

/// **AN ABSENT SLOT ADDS NOTHING**, and nothing is not a zero: the fold starts from the first
/// PRESENT element, so no value the currency never produced enters the arithmetic.
#[test]
fn sum_starts_from_the_first_present_slot() {
  let folded = Sum::new().score(&[None, Some(0.5_f32), None, Some(0.25)]);

  assert!((folded - 0.75).abs() < f32::EPSILON, "{folded}");
}

/// `maxⱼ bⱼ` — and the running maximum keeps what it holds against a tie, which is the walk's own
/// posture toward a value that cannot be shown to be better.
#[test]
fn max_takes_the_best_answered_slot() {
  assert!((Max::new().score(&[Some(0.25_f32), Some(0.9), Some(0.5)]) - 0.9).abs() < f32::EPSILON);
  assert!((Max::new().score(&[None, Some(0.4_f32)]) - 0.4).abs() < f32::EPSILON);
}

/// An INCOMPARABLE value does not displace what is held — the same reading `ranked_keys` takes of a
/// score it cannot place.
#[test]
fn max_keeps_what_it_holds_against_a_value_it_cannot_place() {
  let folded = Max::new().score(&[Some(0.5_f32), Some(f32::NAN)]);

  assert!((folded - 0.5).abs() < f32::EPSILON, "{folded}");
}

/// The two citizens disagree exactly where the question does: one entity's numbers, two readings.
#[test]
fn the_two_shipped_folds_answer_the_same_slots_differently() {
  let slots = [Some(0.6_f32), Some(0.6), None];

  assert!((Sum::new().score(&slots) - 1.2).abs() < f32::EPSILON);
  assert!((Max::new().score(&slots) - 0.6).abs() < f32::EPSILON);
}

/// `Σⱼ wⱼ·bⱼ`, against numbers a reader can check by hand.
#[test]
fn the_weighted_fold_scales_each_query_vectors_own_best() {
  let weights = Weighted::for_query(&query(3), vec![2.0_f32, 1.0, 0.5])
    .expect("three weights for three vectors");

  // 2·0.5 + 1·0.25 + 0.5·0.5 = 1.5
  let folded = weights.score(&[Some(0.5), Some(0.25), Some(0.5)]);

  assert!((folded - 1.5).abs() < f32::EPSILON, "{folded}");
}

/// **AN UNANSWERED QUERY VECTOR SPENDS NO WEIGHT** — not a zero-valued term, which would be a score
/// the currency never produced, and not a shorter question either: the slot is there and it is
/// empty.
#[test]
fn an_unanswered_query_vector_contributes_no_term() {
  let weights =
    Weighted::for_query(&query(3), vec![2.0_f32, 100.0, 0.5]).expect("three weights for three");

  // The heavily weighted vector went unanswered: 2·0.5 + 0.5·0.5 = 1.25.
  let folded = weights.score(&[Some(0.5), None, Some(0.5)]);

  assert!((folded - 1.25).abs() < f32::EPSILON, "{folded}");
}

/// The ARITY is the CONSTRUCTOR's, so a mismatched pair is not a value of this type — and `score`
/// has nothing left to re-check.
#[test]
fn a_weight_list_that_is_not_the_querys_length_is_refused() {
  assert!(Weighted::for_query(&query(3), vec![1.0_f32, 1.0]).is_none());
  assert!(Weighted::for_query(&query(3), vec![1.0_f32, 1.0, 1.0, 1.0]).is_none());
  assert!(Weighted::for_query(&query(1), Vec::<f32>::new()).is_none());
  assert!(Weighted::for_query(&query(1), vec![1.0_f32]).is_some());
}

/// The weights read back in the order they were written, which is the order the query vectors are
/// asked in — the correspondence every part of this road keeps.
#[test]
fn the_weights_are_readable_in_the_order_the_vectors_were_asked() {
  let weights =
    Weighted::for_query(&query(2), vec![0.25_f32, 0.75]).expect("two weights for two vectors");

  assert_eq!(weights.weights(), &[0.25, 0.75]);
}

/// A NON-NEGATIVE weight does not move the per-query argmax, which is the identity that makes
/// weighting after the max the same as weighting inside it — and therefore correct on both
/// delegation paths. Pinned as arithmetic rather than left in prose.
#[test]
fn a_non_negative_weight_commutes_with_the_per_query_max() {
  let members = [0.25_f32, 0.75, 0.5];
  let weight = 3.0_f32;

  let weighted_after = weight * members.iter().copied().fold(f32::MIN, f32::max);
  let weighted_inside = members
    .iter()
    .map(|member| weight * member)
    .fold(f32::MIN, f32::max);

  assert!((weighted_after - weighted_inside).abs() < f32::EPSILON);
}

/// **A FOURTH CITIZEN IS ONE IMPL**, and nothing here widens to admit it: no arm, no match site, no
/// enum. This is the whole cost of the vocabulary being a trait.
#[test]
fn a_fold_this_module_never_heard_of_is_one_impl() {
  /// The FIRST answered question and no other — a reading nobody ruled, written by whoever wants it.
  struct Leading;

  impl<S: Clone + Send + Sync> FoldSemantics<S> for Leading {
    fn score(&self, bests: &[Option<S>]) -> S {
      bests
        .iter()
        .flatten()
        .next()
        .cloned()
        .expect("an entity reaches a fold with at least one answer")
    }

    fn name(&self) -> &str {
      "leading"
    }
  }

  assert!((Leading.score(&[None, Some(0.25_f32), Some(0.9)]) - 0.25).abs() < f32::EPSILON);
}

/// A currency this framework ships no row for folds anyway, because there is no row to ship: what
/// `Sum` asks of a score is [`Add`](core::ops::Add), which a composite currency implements for
/// itself.
#[test]
fn a_composite_currency_folds_without_a_framework_row() {
  #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
  struct Fused(f32, u32);

  impl core::ops::Add for Fused {
    type Output = Self;

    fn add(self, other: Self) -> Self {
      Self(self.0 + other.0, self.1 + other.1)
    }
  }

  let folded = Sum::new().score(&[Some(Fused(0.5, 1)), None, Some(Fused(0.25, 2))]);

  assert_eq!(folded, Fused(0.75, 3));
}