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
use core::{future::Future, pin::Pin};

use super::{
  ArmWeights, AsyncQueryExpander, ExpandOrigin, Expanded, Expansion, QueryExpander, TextualQuestion,
};

/// A synonym table, the cheapest expander there is — BLOCKING, and reaching the call seat through
/// the lift bridge alone.
struct Synonyms(Vec<(&'static str, &'static str)>);

impl<Q: TextualQuestion> QueryExpander<Q> for Synonyms {
  fn expand(&self, question: &Q) -> Vec<Expanded<Q>> {
    self
      .0
      .iter()
      .filter(|(word, _)| question.text().contains(word))
      .map(|(word, stand_in)| {
        Expanded::minted(
          question.with_text(&question.text().replace(word, stand_in)),
          "synonyms",
        )
      })
      .collect()
  }
}

/// AN EXPANDER WHOSE MODEL IS DOWN — the fail-open lane's subject. Trouble is digested here and the
/// seam sees an empty list, which is the only shape the contract has for it.
struct Broken;

impl QueryExpander<String> for Broken {
  fn expand(&self, _question: &String) -> Vec<Expanded<String>> {
    // Whatever a real body does with the refusal — count it, tap it, log it — and then answer with
    // the honest nothing rather than taking the search down with it.
    Vec::new()
  }
}

/// An expander written on the AWAITED face directly, which is what a model-backed one is.
struct Awaited;

impl AsyncQueryExpander<String> for Awaited {
  fn expand_async<'a>(
    &'a self,
    question: &'a String,
  ) -> Pin<Box<dyn Future<Output = Vec<Expanded<String>>> + Send + 'a>> {
    Box::pin(async move { vec![Expanded::minted(question.to_uppercase(), "shout")] })
  }
}

#[test]
fn origin_registers_read_back() {
  assert!(ExpandOrigin::Original.is_original());
  assert_eq!(ExpandOrigin::Original.as_str(), "original");
  assert_eq!(ExpandOrigin::Original.to_string(), "original");

  let minted = ExpandOrigin::expander("synonyms");
  assert!(!minted.is_original());
  assert_eq!(minted.as_str(), "synonyms");
  assert_eq!(minted.to_string(), "synonyms");
  assert_eq!(minted, ExpandOrigin::expander("synonyms"));
  assert_ne!(minted, ExpandOrigin::expander("translation"));
}

#[test]
fn expanded_carries_the_four_piece_vocabulary() {
  // The general constructor, and both registers' own doors.
  let general = Expanded::new("a good film".to_owned(), ExpandOrigin::Original);
  let original = Expanded::original("a good film".to_owned());
  let minted = Expanded::minted("a good movie".to_owned(), "synonyms");

  assert_eq!(general, original);
  assert_eq!(original.query(), "a good film");
  assert_eq!(original.origin(), &ExpandOrigin::Original);
  assert_eq!(minted.origin(), &ExpandOrigin::expander("synonyms"));

  // The consuming forms.
  let rewritten = original.clone().with_query("a decent film".to_owned());
  assert_eq!(rewritten.query(), "a decent film");
  assert_eq!(rewritten.origin(), &ExpandOrigin::Original);

  let reattributed = original
    .clone()
    .with_origin(ExpandOrigin::expander("fixup"));
  assert_eq!(reattributed.query(), "a good film");
  assert_eq!(reattributed.origin(), &ExpandOrigin::expander("fixup"));

  // The in-place forms, which are what a holder narrowing a road it was handed spends.
  let mut held = original.clone();
  held
    .set_query("a decent film".to_owned())
    .set_origin(ExpandOrigin::expander("fixup"));
  assert_eq!(held, reattributed.with_query("a decent film".to_owned()));

  // And both seats, owned.
  let (query, origin) = minted.into_components();
  assert_eq!(query, "a good movie");
  assert_eq!(origin, ExpandOrigin::expander("synonyms"));
  assert_eq!(original.into_query(), "a good film");
}

#[test]
fn the_shipped_textual_question_reads_and_rebuilds() {
  let question = "a good film".to_owned();

  assert_eq!(question.text(), "a good film");
  assert_eq!(question.with_text("a good movie"), "a good movie");
  // REBUILT, never mutated: the caller's own value is left standing.
  assert_eq!(question, "a good film");
}

#[test]
fn the_bare_seat_is_the_identity_road() {
  let bare = Expansion::<String>::new();

  assert!(!bare.is_mounted());
  assert!(bare.expander().is_none());
  assert_eq!(format!("{bare:?}"), "Expansion { mounted: false }");
  // One source of truth for the shipped state.
  assert!(!Expansion::<String>::default().is_mounted());
}

#[tokio::test]
async fn nothing_mounted_answers_the_question_alone() {
  let road = Expansion::<String>::new()
    .expand("a good film".to_owned())
    .await;

  assert_eq!(road, vec![Expanded::original("a good film".to_owned())]);
}

#[tokio::test]
async fn a_mounted_expander_follows_the_pinned_original() {
  let road = Expansion::new()
    .with_expander(Box::new(Synonyms(vec![
      ("film", "movie"),
      ("good", "fine"),
    ])))
    .expand("a good film".to_owned())
    .await;

  assert_eq!(
    road,
    vec![
      Expanded::original("a good film".to_owned()),
      Expanded::minted("a good movie".to_owned(), "synonyms"),
      Expanded::minted("a fine film".to_owned(), "synonyms"),
    ]
  );
}

#[tokio::test]
async fn an_expander_with_nothing_to_add_degrades_to_the_identity_road() {
  let road = Expansion::new()
    .with_expander(Box::new(Broken))
    .expand("a good film".to_owned())
    .await;

  // THE FAIL-OPEN LANE: the search still answers, and it answers what it would have answered with
  // nothing mounted at all.
  assert_eq!(road, vec![Expanded::original("a good film".to_owned())]);
  assert_eq!(
    road,
    Expansion::<String>::new()
      .expand("a good film".to_owned())
      .await
  );
}

#[tokio::test]
async fn the_awaited_face_is_mounted_the_same_way() {
  let road = Expansion::new()
    .with_expander(Box::new(Awaited))
    .expand("a good film".to_owned())
    .await;

  assert_eq!(
    road,
    vec![
      Expanded::original("a good film".to_owned()),
      Expanded::minted("A GOOD FILM".to_owned(), "shout"),
    ]
  );
}

#[tokio::test]
async fn a_mount_can_be_named_back_to_nothing() {
  let mut road = Expansion::new().with_expander(Box::new(Synonyms(vec![("film", "movie")])));
  assert!(road.is_mounted());

  road.set_expander(None);

  assert!(!road.is_mounted());
  assert_eq!(
    road.expand("a good film".to_owned()).await,
    vec![Expanded::original("a good film".to_owned())]
  );
}

#[tokio::test]
async fn a_road_is_cloned_rather_than_rebuilt() {
  let road = Expansion::new().with_expander(Box::new(Synonyms(vec![("film", "movie")])));
  let shared = road.clone();

  assert!(shared.is_mounted());
  assert_eq!(
    shared.expand("a good film".to_owned()).await,
    road.expand("a good film".to_owned()).await
  );
}

/// THE OBJECT-SAFETY PIN, spent rather than asserted: the seat is held erased and answered through.
#[tokio::test]
async fn the_call_seat_is_held_as_a_handle() {
  let handles: Vec<Box<dyn AsyncQueryExpander<String>>> = vec![
    Box::new(Synonyms(vec![("film", "movie")])),
    Box::new(Awaited),
    Box::new(Broken),
  ];
  let question = "a good film".to_owned();
  let mut answered = Vec::new();

  for handle in &handles {
    answered.push(handle.expand_async(&question).await.len());
  }

  assert_eq!(answered, vec![1, 1, 0]);
}

/// THE BRIDGE LAW: a type that wrote only the blocking face answers through the awaited one, and the
/// two answers are the same list.
#[tokio::test]
async fn a_blocking_expander_answers_through_the_awaited_seat() {
  let table = Synonyms(vec![("film", "movie")]);
  let question = "a good film".to_owned();

  let blocking = QueryExpander::expand(&table, &question);
  let awaited = AsyncQueryExpander::expand_async(&table, &question).await;

  assert_eq!(blocking, awaited);
  assert_eq!(
    blocking,
    vec![Expanded::minted("a good movie".to_owned(), "synonyms")]
  );
}

/// **TIER 3 OVER TIER 2** — the request's paraphrase weight wins where it named one, and the
/// deployment's stands where it did not.
#[test]
fn a_request_that_names_the_arm_weight_beats_the_deployments() {
  let deployment = ArmWeights::new().with_paraphrase(0.8);

  assert_eq!(
    ArmWeights::new()
      .with_paraphrase(0.2)
      .over(&deployment)
      .paraphrase(),
    Some(0.2),
  );
  assert_eq!(ArmWeights::new().over(&deployment).paraphrase(), Some(0.8));
}

/// **THE ABSENT TIER DEFERS RATHER THAN DEFAULTING**, which is the whole reason the field is an
/// `Option` and the constant is read at the end of the chain.
///
/// The counter-case is what would break: if `over` filled a silent request with
/// `DEFAULT_ARM_WEIGHT`, this deployment's `0.8` would lose to a request that never mentioned the
/// knob, and the launch override would be unusable by anybody who did not restate it per query.
#[test]
fn a_silent_request_does_not_overwrite_the_deployment_with_the_shipped_number() {
  let deployment = ArmWeights::new().with_paraphrase(0.8);
  let effective = ArmWeights::new().over(&deployment);

  assert_eq!(effective.paraphrase(), Some(0.8));
  assert!((effective.weight(&ExpandOrigin::expander("synonyms")) - 0.8).abs() < 1e-12);

  // And where NEITHER tier named one, the shipped constant is still what the walk reads — the
  // composition stayed out of the way rather than resolving early.
  let neither = ArmWeights::new().over(&ArmWeights::DEFAULT);
  assert_eq!(neither.paraphrase(), None);
  assert!(
    (neither.weight(&ExpandOrigin::expander("synonyms")) - ArmWeights::DEFAULT_ARM_WEIGHT).abs()
      < 1e-12
  );
}

/// The ORIGINAL arm is untouched by either tier — it is not a knob, so no composition can move it.
#[test]
fn no_tier_can_move_what_the_caller_actually_asked() {
  let composed = ArmWeights::new()
    .with_paraphrase(0.2)
    .over(&ArmWeights::new().with_paraphrase(0.8));

  assert!((composed.weight(&ExpandOrigin::Original) - ArmWeights::ORIGINAL).abs() < 1e-12);
}