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 constructors every citizen's tests build values with, and the family-scale claims no single
//! citizen's module can make.
//!
//! `pub(super)` rather than private, so each household's own test module reaches these rather than
//! keeping a copy — the arrangement [`geometry`](crate::primitives::geometry)'s own fixtures take.

use crate::{BoundingBox, CursorValue, NormCoord, Score};

use super::{Detection, Label, LocatedDetection};

pub(super) fn label(word: &str) -> Label {
  Label::new(word).expect("the fixture's labels are words")
}

pub(super) fn score(value: f32) -> Score {
  Score::new(value).expect("the fixture's confidences are in range")
}

pub(super) fn detection(word: &str, confidence: f32) -> Detection {
  Detection::new(label(word), score(confidence))
}

/// A finding whose every field is DISTINGUISHABLE from its siblings, so a transposition anywhere in
/// the family changes a value rather than merely rearranging equal ones.
pub(super) fn located() -> LocatedDetection<NormCoord> {
  LocatedDetection::new(
    detection("person", 0.94),
    BoundingBox::try_unit(0.10, 0.21, 0.32, 0.43).expect("the fixture's box is inside the frame"),
  )
}

/// **THE WIDTHS, pinned** — what a declaration of each citizen costs in columns.
///
/// The numbers are what the two [`StoredAs`](crate::StoredAs) rows are written against: both are
/// FIXED-length arrays, so a part that came to span a different number of columns would leave them
/// describing a row that is no longer the row being written.
#[test]
fn each_citizen_states_how_many_columns_it_spans() {
  const fn spans<T: crate::ColumnKind>() -> usize {
    crate::width(T::SEGMENTS)
  }

  assert!(
    <Label as crate::ColumnKind>::SEGMENTS.is_empty(),
    "a SCALAR joins by stating nothing, so its column comes from the field that names it"
  );
  assert_eq!(spans::<Detection>(), 2, "label, confidence");
  assert_eq!(
    spans::<LocatedDetection<NormCoord>>(),
    7,
    "the classification's two, flattened, and the box's FIVE — four it holds and one it derives"
  );
  assert_eq!(
    crate::value_width(<LocatedDetection<NormCoord> as crate::ColumnKind>::SEGMENTS),
    6,
    "…and a finding IS six numbers-and-a-word, whatever it is written into"
  );
}

/// **The width is the COMPONENT-INDEPENDENT half of the promise**: the arity is the holder's shape
/// and not the geometry component's.
#[test]
fn a_findings_width_does_not_move_with_its_component() {
  const fn spans<T: crate::ColumnKind>() -> usize {
    crate::width(T::SEGMENTS)
  }

  assert_eq!(spans::<LocatedDetection<f32>>(), 7);
  assert_eq!(spans::<LocatedDetection<f64>>(), 7);
  assert_eq!(spans::<LocatedDetection<u32>>(), 7);
  assert_eq!(spans::<LocatedDetection<i64>>(), 7);
}

/// **THE INHERITED INDEX LEAF, and the sequence this citizen owes because of it.**
///
/// A located finding derives nothing. What it HOLDS is a box, and the box derives its area — so this
/// type acquired an index leaf from a COMPONENT, which is the case a wide term cannot see: a term
/// that stated no sequence would put `subject_bbox_area` inside a keyset row value, and the 2026-08-29
/// law says every structural judgment walks value leaves only.
///
/// So the ledger is asserted at both ends: SIX levels over SEVEN leaves, and the seventh answering
/// `None` because it is the box's own derived one.
#[test]
fn a_located_findings_order_names_its_six_value_leaves_and_never_the_boxs_index() {
  let levels: Vec<_> = <LocatedDetection<NormCoord> as crate::ColumnKind>::ORDER
    .iter()
    .map(|level| level.leaf())
    .collect();
  assert_eq!(levels, [0, 1, 2, 3, 4, 5]);

  let subject = LocatedDetection::new(
    Detection::new(
      Label::new("person").expect("a word"),
      crate::Score::new(0.94).expect("a confidence"),
    ),
    BoundingBox::try_unit(0.1, 0.2, 0.3, 0.6).expect("a rectangle"),
  );

  assert!(matches!(
    crate::OrderLeaves::leaf(&subject, 0),
    Some(crate::LocatedDetectionLeaf::Label(_))
  ));
  assert!(matches!(
    crate::OrderLeaves::leaf(&subject, 4),
    Some(crate::LocatedDetectionLeaf::Bbox(
      crate::BoundingBoxLeaf::Width(_)
    ))
  ));
  assert_eq!(
    crate::OrderLeaves::leaf(&subject, 6),
    None,
    "leaf 6 is the box's derived area, which is no level of the box and none of this holder"
  );
}

/// **THE ADMISSION** — a `Vec` of either composite is what a detector emits, so the rows that admit
/// one are load-bearing rather than decorative.
///
/// The admission is a bound rather than a value, so what a test can reach is its supertrait's
/// answer.
#[test]
fn each_admitted_element_states_the_columns_one_row_of_it_holds() {
  const fn admitted<E: crate::CollectionElement>() -> usize {
    crate::width(E::SEGMENTS)
  }

  assert_eq!(admitted::<Detection>(), 2);
  assert_eq!(admitted::<LocatedDetection<NormCoord>>(), 7);
}

/// **THE CLASSIFICATION IS FLATTENED AND THE BOX IS NOT**, which is what the six column names
/// depend on — a change here moves `subject_label` to `subject_detection_label` and every DDL,
/// `SELECT` and `WHERE` with it.
#[test]
fn a_located_detection_splices_its_classification_and_names_its_box() {
  let [classification, geometry] = <LocatedDetection<NormCoord> as crate::ColumnKind>::SEGMENTS
  else {
    panic!("a located detection is a classification and a box");
  };

  assert!(
    matches!(
      classification,
      crate::ColumnShape::Composite { field: None, .. }
    ),
    "the classification lends NO name, so its two columns join the holder's own namespace"
  );
  assert!(
    matches!(
      geometry,
      crate::ColumnShape::Composite {
        field: Some(named),
        ..
      } if named.declared().as_str() == "bbox"
    ),
    "the box KEEPS its name, so four coordinate names cannot collide with a future facet"
  );
}

/// **EVERY CITIZEN HERE IS A CURSOR SLOT**, which is what makes each of them a declarable column: a
/// stored column a record does not flatten is an ORDER SUBJECT, and an order subject is a cursor
/// slot.
///
/// The LEAF writes its bytes bare, the two composites FRAME their members, and all three re-validate
/// on the way back — a cursor is a string a client hands back.
#[test]
fn every_citizen_round_trips_a_position_and_refuses_a_forged_one() {
  fn round_trip<T: CursorValue + PartialEq + core::fmt::Debug>(value: &T) {
    let mut written = Vec::new();
    value.write_cursor(&mut written);

    assert_eq!(T::read_cursor(&written).as_ref(), Some(value));
  }

  round_trip(&label("golden retriever"));
  round_trip(&detection("cat", 0.87));
  round_trip(&located());

  assert_eq!(
    Label::read_cursor(b"   "),
    None,
    "a forged cursor is refused rather than turned into a label the type says cannot exist"
  );
}

/// **A FRAME THIS TYPE DID NOT WRITE IS REFUSED** — which is the whole reason the members carry four
/// bytes of length rather than being divided by a constant.
///
/// Trailing bytes are the case a fixed-width division could not have caught: they belong to no
/// member, and a row that ignored them would resume a page at a value nobody wrote.
#[test]
fn a_frame_with_bytes_no_member_owns_is_refused() {
  let mut written = Vec::new();
  detection("cat", 0.87).write_cursor(&mut written);

  assert!(Detection::read_cursor(&written).is_some());

  let mut trailing = written.clone();
  trailing.push(0);
  assert_eq!(
    Detection::read_cursor(&trailing),
    None,
    "bytes no member owns"
  );

  let truncated = &written[..written.len() - 1];
  assert_eq!(
    Detection::read_cursor(truncated),
    None,
    "a frame that ends inside a member's payload"
  );

  // The interval is re-checked THROUGH the frame: the confidence member's own row refuses it, so a
  // forged detection cannot carry a number the type says cannot exist.
  let mut forged = Vec::new();
  crate::cursor::write_member(&label("cat"), &mut forged);
  forged.extend_from_slice(&(size_of::<f32>() as u32).to_be_bytes());
  forged.extend_from_slice(&1.5_f32.to_be_bytes());
  assert_eq!(Detection::read_cursor(&forged), None);
}

/// **THE PAIR IS THE IDENTITY**, at both arities: the same word at two confidences is two findings,
/// and the same finding in two places is two findings.
#[test]
fn the_whole_value_is_the_identity() {
  assert_ne!(detection("cat", 0.90), detection("cat", 0.91));
  assert_ne!(detection("cat", 0.90), detection("dog", 0.90));

  let here = located();
  let there = LocatedDetection::new(
    detection("person", 0.94),
    BoundingBox::try_unit(0.50, 0.21, 0.32, 0.43).expect("inside the frame"),
  );

  assert_ne!(here, there);
  assert_eq!(here, located());
}

/// **THE HOUSE'S DERIVED-LEAF LEDGER**, in one place — which citizens inherit the geometry house's
/// index leaf, and which do not.
///
/// The law is [`ColumnShape`](crate::ColumnShape)'s: *a derived leaf serves the semantic order only;
/// every structural judgment walks value leaves only.* What a HOLDER owes because of it is a
/// sequence of its own, and what a holder of a quad owes is nothing. Reading the whole house at once
/// is what makes the rule legible rather than four separate assertions that each look arbitrary.
#[test]
fn every_citizen_that_holds_a_rectangle_states_a_sequence_and_the_one_that_holds_a_quad_does_not() {
  fn ledger<T: crate::ColumnKind>() -> (usize, usize, usize) {
    (
      crate::width(T::SEGMENTS),
      crate::value_width(T::SEGMENTS),
      T::ORDER.len(),
    )
  }

  assert_eq!(
    ledger::<Detection>(),
    (2, 2, 0),
    "a classification holds no geometry, so it derives nothing and states nothing"
  );
  assert_eq!(ledger::<LocatedDetection<NormCoord>>(), (7, 6, 6));
  assert_eq!(
    ledger::<crate::TextDetection<NormCoord>>(),
    (7, 6, 6),
    "a reading is the located form's shape with a payload where the label is"
  );
  assert_eq!(ledger::<crate::BarcodeDetection<NormCoord>>(), (8, 7, 7));
  assert_eq!(
    ledger::<crate::DocumentSegment<NormCoord>>(),
    (9, 9, 0),
    "a segment holds a QUAD, which derives nothing — so its columns are all value and it keeps \
     the non-reordering word"
  );

  // The two numbers agreeing is what says the citizen has no index leaf; a sequence being stated is
  // what says it has one and has kept it out of the structural judgments. Neither is a substitute
  // for the other, so both are read.
  for (columns, value, levels) in [
    ledger::<LocatedDetection<NormCoord>>(),
    ledger::<crate::TextDetection<NormCoord>>(),
    ledger::<crate::BarcodeDetection<NormCoord>>(),
  ] {
    assert_eq!(
      columns - value,
      1,
      "exactly one column of each is the box's derived area"
    );
    assert_eq!(
      levels, value,
      "…and the sequence names every VALUE leaf and no index one"
    );
  }
}

/// **THE PAYLOAD TRIO'S MARKERS**, which is what decides whether a field is a column or a table.
///
/// All three are read as COMPOSITES and a `Vec` of any of them through the QUANTIFIERS — a page's
/// transcript, a frame's codes and a scan's segments are each a collection whose elements are asked
/// about one at a time, for the reason [`Detection`]'s own row gives: every element carries a float.
#[test]
fn the_payload_trio_is_read_as_composites_and_quantified_in_collections() {
  fn marker<T: crate::DefaultMarker>() -> &'static str {
    core::any::type_name::<T::Marker>()
  }
  fn over<T>() -> &'static str
  where
    T: crate::DefaultVecMarker,
    T::Marker: crate::ToGraphqlFilter,
  {
    core::any::type_name::<<T::Marker as crate::ToGraphqlFilter>::Filter>()
  }

  assert!(marker::<crate::TextDetection<NormCoord>>().contains("CompositeMarker"));
  assert!(marker::<crate::BarcodeDetection<NormCoord>>().contains("CompositeMarker"));
  assert!(marker::<crate::DocumentSegment<NormCoord>>().contains("CompositeMarker"));

  assert!(
    marker::<crate::Symbology>().contains("EnumMarker"),
    "a VOCABULARY is not a composite"
  );

  for quantified in [
    over::<crate::TextDetection<NormCoord>>(),
    over::<crate::BarcodeDetection<NormCoord>>(),
    over::<crate::DocumentSegment<NormCoord>>(),
  ] {
    assert!(quantified.contains("QuantifiedFilter"), "{quantified}");
  }
}