ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! **THE SET ELECTION'S QUESTION WIRE ROAD** — which door the published question field reaches, what
//! its arm carries, and the guard that is emitted only where a declaration wrote one.
//!
//! ```text
//!   #[ingraph(embedding,       knn, toy(resource=…))]  →  shotsByClipKeys → retrieve_keys_by_clip
//!   #[ingraph(list(embedding), knn, toy(resource=…))]  →  shotsByClipKeys → retrieve_keys_by_clip_with
//! ```
//!
//! Beside [`similar_set_wire`](super::similar_set_wire) on this directory's one-file-per-thing
//! precedent: that file proves the BY-EXAMPLE road's routing, and this one proves everything the
//! QUESTION road grew when the `m`-vector surface landed. The ROUTING half stays there, as
//! [`the_question_road_is_routed_by_the_label_too`](super::similar_set_wire::the_question_road_is_routed_by_the_label_too),
//! because it is the same claim that file already makes one road over — it used to assert the
//! opposite, with its reason written into its own name.
//!
//! # The claim is a PAIR, and half of it is about what did NOT move
//!
//! The set arm must not reach the single-vector door, the unit arm must not reach the `_with` one,
//! the field NAME must be the same string either way, and the UNIT road's arm must still be a flat
//! list. A suite that only read the set arm would pass for an emission that had deepened every
//! question in the workspace.
//!
//! # What is asserted HERE and nowhere else
//!
//! | the ruling | the assertion |
//! |---|---|
//! | the LABEL picks the question door | [`the_label_picks_the_question_door`] |
//! | one field NAME per (declaration × election) | [`the_label_moves_the_road_and_never_the_name`] |
//! | the SAME arm, one list deeper | [`the_coordinates_arm_is_one_list_deeper_on_a_set`] |
//! | empty list = refusal, width names the index | [`the_two_refusals_a_point_list_can_earn`] |
//! | `streams = N` guards the `_with` road ONLY | [`the_stream_guard_lands_on_the_with_road_alone`] |
//! | the election's guard beats the container's | [`the_elections_guard_beats_the_containers`] |
//! | the guard is never a request row | [`the_guard_is_no_argument_and_no_answer_row`] |
//! | the roster gains nothing | [`the_question_road_lands_no_type_of_its_own`] |
//!
//! The EXECUTING half — that `m` points reach `m` streams, that the fold's order arrives, and that
//! each refusal is a sentence a client can act on — is `ingraph/tests/set_question_wire.rs`, which is
//! the only place a schema can be built and asked.

use super::{Dedup, Elected, ElectionLabel, IndexGraphql, IndexModel, Numbers, Upstream};
use crate::{
  engine::{Engine, FieldEngines},
  model::{GraphqlKind, NodeKind},
  prefix::EmissionPrefix,
};

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// A count as the head writes one.
fn count(written: u32) -> core::num::NonZeroU32 {
  core::num::NonZeroU32::new(written).expect("a declared count is not zero")
}

/// ONE ELECTED FIELD at one label, with the type the label implies.
fn elected(field: &str, label: ElectionLabel) -> Elected {
  let ty: syn::Type = match label {
    ElectionLabel::List => syn::parse_quote!(::std::vec::Vec<::ingraph::Embedding<f32, 4, Clip>>),
    ElectionLabel::Embedding => syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
  };
  Elected::new(ident(field), label, ty, None)
}

/// A dressed vector declaration over ONE typed election, at whatever label and head numbers a case
/// hands it.
fn declared(label: ElectionLabel, numbers: Numbers) -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers,
    field_numbers: Vec::new(),
    index: ident("Shots"),
    kind: NodeKind::Vector,
    vis: syn::parse_quote!(pub),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(Keyframe),
      projections: Vec::new(),
    },
    dedup: Dedup::Hash,
    embeddings: vec![elected("clip", label)],
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: vec![FieldEngines {
      field: ident("clip"),
      engines: vec![Engine {
        resource: Some(syn::parse_quote!(crate::Store)),
        ..Engine::bare(ident("toy"))
      }],
      fanout: false,
    }],
    stores: Vec::new(),
    data: false,
    keys: true,
    subscribe: false,
    extension: None,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    fields: Vec::new(),
  }
}

/// The whole expansion with the spaces taken out — what a claim about a call or a row is read off.
fn tight(model: &IndexModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

/// The UNIT election's expansion, and the SET one's, both unguarded.
fn both() -> (String, String) {
  (
    tight(&declared(ElectionLabel::Embedding, Numbers::default())),
    tight(&declared(ElectionLabel::List, Numbers::default())),
  )
}

/// ONE RESOLVER's tokens, cut at the next one — so a claim about a body is not answered by a
/// neighbour's.
fn resolver<'a>(emission: &'a str, method: &str) -> &'a str {
  let at = emission
    .split(&format!("asyncfn{method}("))
    .nth(1)
    .unwrap_or_else(|| panic!("`{method}` is emitted: {emission}"));
  let end = [at.find("#[doc"), at.find("asyncfn")]
    .into_iter()
    .flatten()
    .min()
    .unwrap_or(at.len());
  &at[..end]
}

/// ONE EMITTED DOOR CALL, spelled the way the wire road spells it — see
/// [`similar_set_wire`](super::similar_set_wire)'s own note for why the turbofish is the HANDLE.
fn door(method: &str, extra: &str) -> String {
  format!(
    "Shots::{method}::<<crate::Storeas::ingraph::__private::store::VectorMount>::Handle{extra}>"
  )
}

/// **THE LABEL PICKS THE QUESTION DOOR**, and each arm reaches its own and only its own.
///
/// The exclusions carry the weight: routing that reached BOTH doors would ask twice, and routing
/// that reached the wrong one is a set election answering a whole-set question with one vector.
#[test]
fn the_label_picks_the_question_door() {
  let (unit, set) = both();
  let unit_leg = resolver(&unit, "__async_graphql_shots_by_clip_keys");
  let set_leg = resolver(&set, "__async_graphql_shots_by_clip_keys");

  assert!(
    unit_leg.contains(&door("retrieve_keys_by_clip", "")),
    "the unit road left the single-vector door: {unit_leg}",
  );
  assert!(
    !unit_leg.contains("retrieve_keys_by_clip_with"),
    "the unit road reached the set door: {unit_leg}",
  );

  assert!(
    set_leg.contains(&door("retrieve_keys_by_clip_with", ",_")),
    "the set road did not reach the `_with` door: {set_leg}",
  );
  assert!(
    !set_leg.contains("retrieve_keys_by_clip::<"),
    "the set road also reached the single-vector door: {set_leg}",
  );
}

/// **THE LABEL MOVES THE ROAD AND NEVER THE NAME** — one field name per (declaration × election),
/// whichever door answers.
#[test]
fn the_label_moves_the_road_and_never_the_name() {
  let (unit, set) = both();
  for (label, emission) in [("unit", &unit), ("set", &set)] {
    assert_eq!(
      emission
        .matches("graphql(name=\"shotsByClipKeys\")")
        .count(),
      1,
      "the {label} road does not mint the question field exactly once: {emission}",
    );
  }
  // AND THE ANSWER IS THE ROAD'S: a folded hit where the label says several, the single-vector one
  // where it says one.
  assert!(set.contains("graphql::FoldedMatch<"), "{set}");
  assert!(set.contains("graphql::folded_matches("), "{set}");
  assert!(!set.contains("graphql::Match<"), "{set}");
  assert!(unit.contains("graphql::Match<"), "{unit}");
  assert!(!unit.contains("FoldedMatch"), "{unit}");
}

/// **THE SAME `coordinates` ARM, ONE LIST DEEPER** — the arm word is reused and the depth is the
/// label's, which is the whole of what the ruling minted.
#[test]
fn the_coordinates_arm_is_one_list_deeper_on_a_set() {
  let (unit, set) = both();

  assert!(
    set.contains("Coordinates(::std::vec::Vec<::std::vec::Vec<"),
    "the set question's arm is not a list of lists: {set}",
  );
  assert!(
    unit.contains("Coordinates(::std::vec::Vec<<<::ingraph::Embedding"),
    "the unit question's arm stopped being a flat list: {unit}",
  );
  // ONE ARM at both labels, under the framework's own word: the depth moved and the vocabulary did
  // not.
  for (label, emission) in [("unit", &unit), ("set", &set)] {
    assert_eq!(
      emission.matches("String::from(\"coordinates\")").count(),
      2,
      "the {label} question does not name its one arm twice (registry + parse): {emission}",
    );
  }
}

/// **THE TWO REFUSALS A POINT LIST CAN EARN** — an EMPTY list, which is `FoldedQuery`'s own law, and a
/// MIS-WIDTHED point, which names WHICH one it was.
#[test]
fn the_two_refusals_a_point_list_can_earn() {
  let (unit, set) = both();

  assert!(
    set.contains("noqueryvectors"),
    "the empty list earns no named refusal: {set}",
  );
  assert!(
    set.contains("queryvector{at}"),
    "the width refusal does not name the offending index: {set}",
  );
  // THE UNIT ROAD'S WIDTH REFUSAL IS UNCHANGED — one point, so there is no index to name.
  assert!(
    !unit.contains("queryvector{at}"),
    "the unit road grew an index it has no list to index: {unit}",
  );
}

/// **`streams = N` GUARDS THE `_with` ROAD ALONE** — the ruled scope, read as an emission.
///
/// The by-example set road's `m` comes out of the deployment's own stored set, so a guard there
/// would bound a corpus rather than a request. The assertion is therefore about WHICH resolver
/// carries the count, not about whether the count is anywhere.
#[test]
fn the_stream_guard_lands_on_the_with_road_alone() {
  let guarded = tight(&declared(
    ElectionLabel::List,
    Numbers {
      streams: Some(count(2)),
      ..Numbers::default()
    },
  ));
  let question = resolver(&guarded, "__async_graphql_shots_by_clip_keys");
  let by_example = resolver(&guarded, "__async_graphql_shots_similar_by_clip_keys");

  assert!(
    question.contains("__ingraph_asked>2"),
    "the question road carries no guard: {question}",
  );
  assert!(
    question.contains("atmost2queryvectors"),
    "the refusal does not name the count: {question}",
  );
  assert!(
    !by_example.contains("__ingraph_asked>"),
    "the by-example road was guarded too: {by_example}",
  );

  // AND AN UNGUARDED DECLARATION EMITS NO GUARD AT ALL — the word's absence is openness rather than
  // a default, so the resolver is byte-for-byte what it was before the word existed.
  let (_, open) = both();
  assert!(
    !open.contains("__ingraph_asked>"),
    "a declaration that wrote no guard got one: {open}",
  );
}

/// **THE ELECTION'S GUARD BEATS THE CONTAINER'S** — the two-tier chain `declared_ceiling` already
/// resolves by, at the second protective word.
///
/// Both tiers are written at once and they DISAGREE, which is the only shape that can tell a chain
/// from a coincidence: a reader taking the container's number would emit `4`, and one taking
/// whichever it found first would depend on the order a fixture happened to write them in.
#[test]
fn the_elections_guard_beats_the_containers() {
  let mut model = declared(
    ElectionLabel::List,
    Numbers {
      streams: Some(count(4)),
      ..Numbers::default()
    },
  );
  model.field_numbers.push(super::FieldNumbers {
    field: ident("clip"),
    numbers: Numbers {
      streams: Some(count(2)),
      ..Numbers::default()
    },
    skins: Vec::new(),
  });
  let emission = tight(&model);
  let question = resolver(&emission, "__async_graphql_shots_by_clip_keys");

  assert!(
    question.contains("__ingraph_asked>2"),
    "the container's number won: {question}",
  );
  assert!(
    !question.contains("__ingraph_asked>4"),
    "both tiers reached the guard: {question}",
  );
}

/// **THE GUARD IS NO ARGUMENT AND NO ANSWER ROW** — protection never crosses, which is `ceiling`'s
/// own law read at the second protective word.
#[test]
fn the_guard_is_no_argument_and_no_answer_row() {
  let guarded = tight(&declared(
    ElectionLabel::List,
    Numbers {
      streams: Some(count(2)),
      ..Numbers::default()
    },
  ));

  assert!(
    !guarded.contains("graphql(name=\"streams\")"),
    "the guard became a request row: {guarded}",
  );
}

/// **THE QUESTION ROAD LANDS NO TYPE OF ITS OWN** — the deepened arm is one type parameter, not a
/// second question type, so the roster the collision refusals are measured against is unmoved.
#[test]
fn the_question_road_lands_no_type_of_its_own() {
  let roster = |label| -> Vec<String> {
    declared(label, Numbers::default())
      .emitted_types()
      .into_iter()
      .map(|declared| declared.name.to_string())
      .collect()
  };
  let unit = roster(ElectionLabel::Embedding);
  let set = roster(ElectionLabel::List);

  for name in &unit {
    assert!(
      set.contains(name),
      "the label dropped `{name}` from the roster: {set:?}",
    );
  }
  for roster in [&unit, &set] {
    assert_eq!(
      roster
        .iter()
        .filter(|name| *name == "ShotsClipQuestion")
        .count(),
      1,
      "{roster:?}",
    );
  }
}