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 super::*;
use crate::primitives::geometry::tests::{bbox, coord};

/// **THE THREE REFUSALS, each by its own name.**
///
/// The vocabulary is what makes them actionable: a producer clamping into the unit square hits
/// `Degenerate`, one that forgot to normalise hits `OutOfBounds`, and one handing on a glitched
/// float hits `Component`. A single `Err(())` would tell all three the same useless thing.
#[test]
fn a_unit_box_names_which_of_its_three_rules_refused() {
  assert_eq!(
    BoundingBox::try_unit(f32::NAN, 0.1, 0.5, 0.5),
    Err(RefusedBox::Component)
  );
  assert_eq!(
    BoundingBox::try_unit(0.1, 0.1, 1.5, 0.5),
    Err(RefusedBox::Component),
    "an extent outside the interval is the COMPONENT's refusal, not the frame's"
  );

  assert_eq!(
    BoundingBox::try_unit(0.1, 0.1, 0.0, 0.5),
    Err(RefusedBox::Degenerate)
  );
  assert_eq!(
    BoundingBox::try_unit(0.1, 0.1, 0.5, 0.0),
    Err(RefusedBox::Degenerate)
  );

  assert_eq!(
    BoundingBox::try_unit(0.8, 0.1, 0.5, 0.5),
    Err(RefusedBox::OutOfBounds)
  );
  assert_eq!(
    BoundingBox::try_unit(0.1, 0.8, 0.5, 0.5),
    Err(RefusedBox::OutOfBounds)
  );
}

/// **The ORDER of the three checks**, which is the order they depend on each other in: a sum is
/// meaningless until both addends are numbers, so a box that is both degenerate and out of range
/// reports the range.
#[test]
fn the_component_refusal_comes_before_the_frames_two() {
  assert_eq!(
    BoundingBox::try_unit(0.9, 0.1, f32::NAN, 0.5),
    Err(RefusedBox::Component),
    "a non-number extent is refused before the sum it could not have been added to"
  );
  assert_eq!(
    BoundingBox::try_unit(0.9, 0.1, 0.0, 0.5),
    Err(RefusedBox::Degenerate),
    "a zero extent is refused before the sum it would have satisfied"
  );
}

/// **The whole frame is admitted**, which is the boundary the `>` rather than `>=` in the sum check
/// is there to keep: a box filling the unit square exactly is a real detection, not an escape.
#[test]
fn a_box_filling_the_whole_frame_is_admitted() {
  let full = BoundingBox::try_unit(0.0, 0.0, 1.0, 1.0).expect("the unit square is inside itself");

  assert_eq!(full.x(), NormCoord::ZERO);
  assert_eq!(full.width(), NormCoord::ONE);
  assert_eq!(full.right(), NormCoord::ONE);
  assert_eq!(full.bottom(), NormCoord::ONE);
}

/// The two DERIVED edges, and the fact that they are readings rather than stored columns: each is
/// recomputed from the pair beside it, so nothing can put them out of step with the values.
#[test]
fn the_far_edges_are_the_sums_the_constructor_proved() {
  let region = bbox(0.10, 0.20, 0.50, 0.40);

  assert_eq!(region.right(), coord(0.60));
  assert_eq!(region.bottom(), coord(0.60));
}

/// **The GENERIC holder checks NOTHING**, which is the family's ruling rather than a gap: a pixel
/// rectangle has no unit square to leave, and a holder that refused one would hold an opinion about
/// a unit it was never told.
#[test]
fn the_generic_constructor_admits_what_no_unit_square_would() {
  let pixels = BoundingBox::new(1_920_u32, 1_080, 4_096, 4_096);
  assert_eq!(pixels.width(), 4_096);

  let metres = BoundingBox::new(-3.5_f64, 12.0, 400.0, 0.0);
  assert_eq!(
    metres.height(),
    0.0,
    "a zero extent is the caller's business here"
  );
}

/// The component-wise carry, which is what a caller crossing between frames spends. It does no
/// arithmetic of its own — the function is the caller's, applied four times in field order.
#[test]
fn a_box_carries_every_component_through_one_function() {
  let frame = 100.0_f32;
  let pixels = bbox(0.10, 0.20, 0.50, 0.40).map(|component| (component.get() * frame) as u32);

  assert_eq!(pixels.x(), 10);
  assert_eq!(pixels.y(), 20);
  assert_eq!(pixels.width(), 50);
  assert_eq!(pixels.height(), 40);
}

/// **THE SEGMENT NAMES AND THEIR ORDER**, which every half of the crossing reads: the bind pushes
/// five placeholders in this order and the decode fetches the FIRST FOUR names in it, so a
/// transposition here is a value landing in the wrong column with no type error anywhere.
///
/// The fifth is the DERIVED one and it is asserted as such on BOTH bits: `holds_value` is the one
/// every structural reader consults — `x`, `y`, `width` and `height` hold the value and `area` does
/// not — and `self_nullable` is the DDL's, which the area answers `false` to because the
/// multiplication is total. The two are asserted together because the second is exactly the bit the
/// two-word vocabulary could not state (ingraph #475), and a regression that collapsed them back
/// into one would show here as a nullable area.
#[test]
fn a_box_names_its_five_columns_in_bind_order_and_the_last_holds_no_value() {
  let segments = <BoundingBox<NormCoord> as ColumnKind>::SEGMENTS;
  let names: Vec<_> = segments
    .iter()
    .map(|segment| {
      segment
        .field()
        .expect("every segment here is named")
        .declared()
        .as_str()
    })
    .collect();

  assert_eq!(names, ["x", "y", "width", "height", "area"]);

  let holds: Vec<_> = segments
    .iter()
    .map(crate::ColumnShape::holds_value)
    .collect();
  assert_eq!(
    holds,
    [true, true, true, true, false],
    "the area is an INDEX beside the rectangle rather than part of it"
  );
  assert!(
    !segments[4].self_nullable(),
    "…and the DDL's own bit is the OTHER one: the area is always computable, so it takes NOT NULL"
  );
  assert!(
    matches!(segments[4], crate::ColumnShape::Derived(_)),
    "the two bits together ARE the third word, and the leaf is spelled with it"
  );
}

/// **THE ORDER A RECTANGLE'S COLUMNS MEAN, and the derived leaf is in NO level of it.**
///
/// Four levels over five leaves. The sequence itself is the declaration order — this type publishes
/// no `Ord` and claims no semantics for it — and what stating it BUYS is the expansion: a term over
/// a box becomes four one-column terms, so no keyset row value can contain the area.
///
/// Asserted rather than assumed, because the failure is silent. A rectangle wearing the
/// non-reordering word instead would keep a WIDE term whose row value is its whole width, which puts
/// a derived leaf inside a pagination cursor — ingraph #454/#455's own shape.
#[test]
fn a_rectangles_order_names_its_four_value_leaves_and_never_its_index() {
  let levels: Vec<_> = <BoundingBox<NormCoord> as ColumnKind>::ORDER
    .iter()
    .map(|level| level.leaf())
    .collect();
  assert_eq!(levels, [0, 1, 2, 3]);

  let boxed = bbox(0.10, 0.20, 0.50, 0.40);
  assert_eq!(
    crate::OrderLeaves::leaf(&boxed, 2),
    Some(super::BoundingBoxLeaf::Width(coord(0.50)))
  );
  assert_eq!(
    crate::OrderLeaves::leaf(&boxed, 4),
    None,
    "leaf 4 is the derived area, which is no level and therefore no cursor slot"
  );
}

/// **ONE LEAF, ONE PLACEHOLDER, AND THE TAG THAT MAKES A FORGED SLOT REFUSABLE.**
///
/// A cursor slot is length-delimited and holds nothing else, so the leaf vocabulary has to say WHICH
/// member it is — the bytes are a client's, and a byte naming no leaf is refused rather than read as
/// the nearest one. There are four tags and no fifth, which is the `ORDER` const said in bytes.
#[test]
fn a_leafs_cursor_position_names_which_leaf_it_is() {
  use crate::CursorValue as _;

  for leaf in [
    super::BoundingBoxLeaf::X(coord(0.1)),
    super::BoundingBoxLeaf::Y(coord(0.2)),
    super::BoundingBoxLeaf::Width(coord(0.5)),
    super::BoundingBoxLeaf::Height(coord(0.4)),
  ] {
    let mut bytes = Vec::new();
    leaf.write_cursor(&mut bytes);
    assert_eq!(
      <super::BoundingBoxLeaf<NormCoord> as crate::CursorValue>::read_cursor(&bytes),
      Some(leaf)
    );
  }

  let mut forged = Vec::new();
  super::BoundingBoxLeaf::X(coord(0.1)).write_cursor(&mut forged);
  forged[0] = 4;
  assert_eq!(
    <super::BoundingBoxLeaf<NormCoord> as crate::CursorValue>::read_cursor(&forged),
    None,
    "a tag naming no leaf of this citizen is refused"
  );
}

/// **THE CURSOR ROUND TRIP**, and the two ways a forged one is refused: a length that is not four
/// components, and a component the constructor would not admit.
#[test]
fn a_box_round_trips_through_a_cursor_and_refuses_a_forged_one() {
  let mut bytes = Vec::new();
  let written = bbox(0.10, 0.20, 0.50, 0.40);
  crate::CursorValue::write_cursor(&written, &mut bytes);

  assert_eq!(
    <BoundingBox<NormCoord> as crate::CursorValue>::read_cursor(&bytes),
    Some(written)
  );

  assert_eq!(
    <BoundingBox<NormCoord> as crate::CursorValue>::read_cursor(&bytes[..bytes.len() - 1]),
    None,
    "a length that is not four components is not a box"
  );
  assert_eq!(
    <BoundingBox<NormCoord> as crate::CursorValue>::read_cursor(&[]),
    None
  );
}

/// **EMPTINESS is the conjunction of the facets'**, which is what a caller asks before deciding
/// whether a predicate is worth rendering at all.
#[test]
fn a_filter_is_empty_until_one_of_its_four_facets_is_set() {
  let bare = BoundingBoxFilter::<crate::ScalarFilter<NormCoord>>::new();
  assert!(crate::GraphqlFilter::is_empty(&bare));

  let asked = bare.with_x(crate::ScalarFilter::new().with_gte(coord(0.5)));
  assert!(!crate::GraphqlFilter::is_empty(&asked));

  let emptily = BoundingBoxFilter::<crate::ScalarFilter<NormCoord>>::new()
    .with_width(crate::ScalarFilter::new());
  assert!(
    crate::GraphqlFilter::is_empty(&emptily),
    "a facet holding an empty filter asks nothing"
  );
}

/// **THE AREA IS `width × height`, AT EVERY COMPONENT THAT MULTIPLIES.**
///
/// The three instantiations are three different arithmetics reached through one method: the unit
/// interval's closed product, a raw float's, and an integer's. What the assertion pins is that the
/// method reaches the COMPONENT's `*` rather than a width this house chose — a `u32` box's area is a
/// `u32`, not a float somebody widened it into.
#[test]
fn the_area_is_the_product_of_the_two_extents() {
  assert_eq!(bbox(0.1, 0.2, 0.5, 0.4).area(), coord(0.2));
  assert_eq!(bbox(0.0, 0.0, 1.0, 1.0).area(), NormCoord::ONE);

  assert_eq!(BoundingBox::new(1.5_f64, 2.5, 4.0, 3.0).area(), 12.0);
  assert_eq!(BoundingBox::new(12_u32, 40, 200, 150).area(), 30_000);
}

/// **THE POSITION TAKES NO PART IN IT** — two rectangles of one size at two places have one area.
///
/// Written because the method reads two of four fields, and a slip that reached `x` or `y` would
/// still typecheck, still return a component, and be wrong everywhere. The fixtures make such a slip
/// VISIBLE: the first pair shares both extents and shares neither corner, and the second shares the
/// corner and differs in one extent.
///
/// `width` and `height` cannot be told apart HERE, and the product's own commutativity is why — a
/// transposition of the two is invisible to any area. The SEAT road is where that pair is pinned
/// instead: `geometry_columns.rs` asserts each leaf by name through a database.
#[test]
fn the_area_reads_the_extents_and_never_the_corner() {
  assert_eq!(
    bbox(0.0, 0.0, 0.5, 0.4).area(),
    bbox(0.5, 0.6, 0.5, 0.4).area(),
    "one size at two places is one area"
  );
  assert_ne!(
    bbox(0.1, 0.2, 0.5, 0.4).area(),
    bbox(0.1, 0.2, 0.5, 0.3).area(),
    "…and a changed extent is a changed area"
  );
}

/// **THE UNIT INTERVAL IS CLOSED UNDER THE PRODUCT**, which is what makes the component's `Mul` row
/// total and this method infallible at the normalized width.
///
/// The extremes are the cases a rounding argument has to survive: the largest product a unit box can
/// have is exactly `1.0`, and the smallest is `+0.0` — neither of which leaves the interval, so the
/// `expect` in `NormCoord`'s own row is discharged rather than hopeful.
#[test]
fn a_normalized_area_never_leaves_the_interval_it_was_multiplied_in() {
  let extremes = [
    (NormCoord::ONE, NormCoord::ONE, 1.0),
    (NormCoord::ONE, NormCoord::ZERO, 0.0),
    (coord(0.999_999), coord(0.999_999), 0.999_998),
  ];

  for (width, height, expected) in extremes {
    let area = BoundingBox::new(NormCoord::ZERO, NormCoord::ZERO, width, height).area();
    assert!(
      (0.0..=1.0).contains(&area.get()),
      "{area} left the interval"
    );
    assert!((area.get() - expected).abs() < 1e-5);
  }
}