ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! **THE KNOB SEAT**, read off the tokens: which doors grow one, what it is SPELLED as, where each
//! fold hands it, and the two absences that say the wiring was not done by copying a word around.
//!
//! Beside [`k_seat`](super::k_seat) and [`depth`](super::depth) on this directory's own precedent —
//! one file per thing being proved. The BEHAVIOURAL half is `ingraph`'s `tests/options_handdown.rs`,
//! where engines record the knobs they were handed; what only a token reading can prove is a TYPE
//! and an ABSENCE — *the seat is borrowed at every door* and *no door of the family asks its knobs
//! to clone* are claims about every site at once rather than about the ones a fixture walks.
//!
//! # The absences are the half worth having
//!
//! Two wrong emissions compile and answer correctly on every fixture. One owns the knobs — the door
//! takes `Option<E::SearchOptions>` and a fan clones the request package once per leg — which is the
//! shape #288's letter D refused by name. The other keeps the parameter and drops it, handing the
//! engine verb a fixed `None`, which is the state the k-seat round found the family in and the state
//! tier B and the ask road stayed in one round longer. Neither is visible to a test that only reads
//! what came back.

use super::{
  ElectionLabel, IndexModel,
  tests::{document, embedding_index, two_elections},
};

/// The SEAT, spelled as a tier-A door's own signature spells it — BORROWED, and projected off the
/// door's own engine parameter rather than off any type a declaration named.
const SEAT: &str = "options:::core::option::Option<&<__INGRAPH_ENGINE__as";

/// The seat a FUSED door carries per route, spelled off that route's own engine parameter.
const ROUTE_SEAT: &str = "::core::option::Option<&<__INGRAPH_ENGINE_CAPTION_EMBEDDING__as";

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

/// ONE door's own tokens, cut at the next item.
///
/// The cut is what makes a COUNT mean anything here: the emission holds every door TWICE — once
/// inside the observation gate and once outside it — so an unbounded tail doubles every number.
fn door<'a>(emission: &'a str, name: &str) -> &'a str {
  let at = emission
    .split(&format!("asyncfn{name}<"))
    .nth(1)
    .unwrap_or_else(|| panic!("`{name}` is emitted: {emission}"));
  let end = [at.find("#[doc"), at.find("asyncfn")]
    .into_iter()
    .flatten()
    .min()
    .unwrap_or(at.len());
  &at[..end]
}

/// The same model with its election relabelled a SET, which is what the two `_with` doors hang off.
fn as_set(mut model: IndexModel) -> IndexModel {
  for elected in &mut model.embeddings {
    elected.label = ElectionLabel::List;
    elected.ty = syn::parse_quote!(::std::vec::Vec<::ingraph::Embedding<f32, 4, Clip>>);
  }
  model
}

/// EVERY SEARCHING TIER-A DOOR of both kinds — the vector side's four under a SET election, and the
/// full-text side's two.
///
/// Counted rather than sampled, because the ruling's list is a LIST: a door left out of the wiring
/// is a door whose caller cannot spend a knob, and there is no assertion about the other five that
/// would notice.
fn searching() -> [(String, Vec<&'static str>); 2] {
  [
    (
      tight(&as_set(embedding_index())),
      vec![
        "retrieve_keys_by_image_embedding",
        "retrieve_similar_by_image_embedding",
        "retrieve_keys_by_image_embedding_with",
        "retrieve_similar_by_image_embedding_with",
      ],
    ),
    (
      tight(&document()),
      vec!["retrieve_keys", "retrieve_keys_by_title"],
    ),
  ]
}

/// **EVERY SEARCHING TIER-A DOOR TAKES THE SEAT, AND TAKES IT BORROWED.**
///
/// The positive half is the ruling's own list. The negative half is letter D read as a spelling: an
/// owned `Option<E::SearchOptions>` type-checks at every one of these doors and costs a copy per leg
/// at every fan, so *the seat is a reference* is the thing a token reading has to say out loud.
#[test]
fn every_searching_door_takes_the_seat_and_never_owns_it() {
  for (emission, doors) in searching() {
    for name in doors {
      let body = door(&emission, name);
      assert!(
        body.contains(SEAT),
        "`{name}` does not take the knob seat: {body}",
      );
      assert!(
        !body.contains("options:::core::option::Option<__INGRAPH_ENGINE__"),
        "`{name}` takes its knobs by value, which is a copy per leg at every fan: {body}",
      );
    }
  }
}

/// **THE SEAT IS THE LAST POSITIONAL**, which is where the seam's own verbs put it.
///
/// The parameter law is *positional = universal facts, options = backend knobs*, and an order is the
/// only way that law is observable at a door: `limit` is the last universal fact, so the knobs come
/// after it and nothing comes after them. Asserted at the two doors whose tails differ — the plain
/// one ends at `limit`, the set-by-example one ends at `depth` — so the claim is about the RULE
/// rather than about one signature.
#[test]
fn the_knobs_come_after_every_universal_fact() {
  let emission = tight(&as_set(embedding_index()));

  assert!(
    door(&emission, "retrieve_keys_by_image_embedding")
      .contains("limit:::core::num::NonZeroUsize,options:"),
    "{emission}",
  );
  assert!(
    door(&emission, "retrieve_similar_by_image_embedding_with")
      .contains("depth:::core::option::Option<::core::num::NonZeroUsize>,options:",),
    "the knobs did not follow the last number: {emission}",
  );
}

/// **NO DOOR OF THE FAMILY ASKS ITS KNOBS TO CLONE, AND NONE CLONES ONE** — letter D's posture, as
/// an absence over the whole emission.
///
/// Two spellings would satisfy every behavioural test in this workspace and both are refused here: a
/// `where` row demanding `SearchOptions: Clone`, and a `Clone::clone` applied to an options value
/// inside a fan. The emission clones read scopes and floors — a `Connected` is per-call and a floor
/// is owned — so the reading is narrowed to the two shapes that would name the knobs.
#[test]
fn the_knobs_are_never_cloned_and_no_door_demands_that_they_could_be() {
  for model in [document(), embedding_index(), two_elections()] {
    let emitted = tight(&model);
    assert!(
      !emitted.contains("SearchOptions:::core::clone::Clone"),
      "a door made its knobs clonable to spend them: {emitted}",
    );
    assert!(
      !emitted.contains("::core::clone::Clone::clone(&options)"),
      "a fan copied the request's knobs instead of lending them: {emitted}",
    );
  }
}

/// **THE SEAT IS SPENT AT THE ENGINE VERB, VERBATIM** — the door's own parameter arrives at the
/// crossing with nothing between it and the seam.
///
/// One reading per engine verb the family reaches: the full-text `search` at both its grains, and
/// the `knn` at the three the vector side has. The `None` that used to stand in each of these
/// positions is what makes the assertion a claim about WIRING rather than about arity — a door that
/// grew the parameter and went on handing the seam a fixed `None` has the same signature as this
/// one.
#[test]
fn every_engine_verb_is_handed_the_doors_own_knobs() {
  let vectors = tight(&as_set(embedding_index()));
  for (name, spent) in [
    ("retrieve_keys_by_image_embedding", "limit,options,)"),
    ("retrieve_similar_by_image_embedding", "limit,options,)"),
    (
      "retrieve_keys_by_image_embedding_with",
      "__ingraph_depth,options,)",
    ),
    (
      "retrieve_similar_by_image_embedding_with",
      "__ingraph_depth,options,)",
    ),
  ] {
    let body = door(&vectors, name);
    assert!(
      body.contains(spent),
      "`{name}` does not spend its own knobs at the `knn`: {body}",
    );
  }

  let text = tight(&document());
  for name in ["retrieve_keys", "retrieve_keys_by_title"] {
    let body = door(&text, name);
    assert!(
      body.contains("limit,options,)"),
      "`{name}` does not spend its own knobs at the `search`: {body}",
    );
  }
}

/// **TIER B AND THE ASK ROAD CARRY THE SEAT AND FORWARD IT VERBATIM** — the two LEFT-OUT pins,
/// flipped by the ruling they were written to wait for.
///
/// They read *the doors that are not wired hand the seam its own defaults, in writing*, and that was
/// the honest record of a state rather than a design: neither door was named by the k-seat round, so
/// each handed its tier A an explicit `None`, and *left out of the wiring* and *lost its caller's
/// knobs on the way down* are the same emission from the outside. The letter closed the blanks —
/// a wire resolver rides tier B for a hydrated answer and the ask road for a text question — so what
/// is asserted now is the FORWARD.
///
/// Three claims, and the third is what makes the pair a wiring claim rather than an arity one: the
/// seat is present, it is the door's own parameter that reaches the tier-A call, and the explicit
/// `None` that used to stand in that position is gone.
#[test]
fn tier_b_and_the_ask_road_forward_their_own_seat() {
  let emitted = tight(&embedding_index());

  let tier_b = door(&emitted, "retrieve_by_image_embedding");
  assert!(tier_b.contains(SEAT), "tier B carries no seat: {tier_b}");
  assert!(
    tier_b.contains("::core::num::NonZeroUsize::MAX,options,)"),
    "tier B hands its tier A something other than its own knobs: {tier_b}",
  );
  assert!(
    !tier_b.contains("::core::num::NonZeroUsize::MAX,::core::option::Option::None,"),
    "the explicit blank is still in the tier-B call: {tier_b}",
  );
}

/// **A FUSED DOOR CARRIES ONE SEAT PER ROUTE AND HANDS EACH ROUTE ITS OWN.**
///
/// The COUNT is the claim, exactly as it is for the depth: two routes and two seats, where a door
/// resolving one package and reusing it across its routes is the plausible wrong shape and lands at
/// one. Both fused doors are read, since the by-example twin is a second emitter of the same list.
#[test]
fn each_tier_route_carries_and_spends_its_own_seat() {
  let emitted = tight(&two_elections());

  for name in ["vector_fuse", "vector_fuse_similar"] {
    let body = door(&emitted, name);
    assert_eq!(
      body.matches(ROUTE_SEAT).count(),
      1,
      "`{name}` does not carry exactly one seat for the caption route: {body}",
    );
    assert!(
      body.contains("caption_embedding_options"),
      "`{name}` names no per-route seat: {body}",
    );
    assert!(
      body.contains("image_embedding_options"),
      "`{name}` names only one of its two routes' seats: {body}",
    );
    assert!(
      !body.contains("::core::option::Option::None,)"),
      "a route was handed the defaults where its own seat was in scope: {body}",
    );
  }
}

/// **A FUSED DOOR OPENS A ROUTE'S PACKAGE FOR NOTHING AT ALL** — the measured wall, RE-AIMED by the
/// ruling that emptied it.
///
/// It read *the one row a fused door reads out of a route's package is its `ceiling`*, and the
/// equation was the claim: `Route::options` reached twice, `::ceiling` following it twice, the two
/// counts EQUAL saying nothing else was taken out. The wall law retired that row — a protective
/// number never crosses the wire — so the door reads no row at all, and the assertion becomes the
/// stronger one it always implied: the package is not opened.
///
/// The row a door must never reach for is unchanged and is why this pin exists: the `engine` seat's
/// own `options`, typed on the CONCRETE engine a declaration named. Nothing proves that type is this
/// door's parameter, so an emission reaching for it does not compile, and one that found a way to
/// would be spending knobs written for another engine.
///
/// MUTATION-CHECKED: restore any read of a route's package row and the count parts from zero.
#[test]
fn a_fused_door_takes_no_row_out_of_a_routes_package() {
  let emitted = tight(&two_elections());

  for name in ["vector_fuse", "vector_fuse_similar"] {
    let body = door(&emitted, name);
    assert_eq!(
      body.matches("Route::options),").count(),
      0,
      "`{name}` opened a route's package: {body}",
    );
    assert_eq!(
      body.matches("::ceiling,").count(),
      0,
      "`{name}` read a ceiling off a request: {body}",
    );
  }
}

/// **THE CAPABILITY SEAT CARRIES THE KNOBS BESIDE THE FLOOR**, which is the same wall one grain up.
///
/// A root holds a member's package by projection and can read no row out of it — so the two facts
/// written in the ENGINE's own vocabulary, its `Score` and its `SearchOptions`, both ride the `Ctx`
/// a root hands down whole. The assertion is the tuple's own shape, since a `Ctx` that grew the seat
/// and left it unspent would destructure identically.
#[test]
fn the_members_own_seat_carries_its_knobs_and_spends_them() {
  let emitted = tight(&embedding_index());
  let capability = emitted
    .split("fnkeys<'__ingraph_ctx>(")
    .nth(1)
    .expect("a vector declaration answers a fused read");

  assert!(
    capability.contains("__ingraph_options_0"),
    "the seat carries no knobs: {capability}",
  );
  assert!(
    capability.contains("__ingraph_ceiling,__ingraph_options_0,)"),
    "the member's own door was handed something other than its seat's knobs: {capability}",
  );
  assert!(
    !capability.contains("__ingraph_ceiling,::core::option::Option::None,)"),
    "the seat was carried and then dropped: {capability}",
  );
}