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 decode table, and the ROUND TRIP that holds it against the carrier table it reads backwards.

use bson::{Binary, Bson, doc, spec::BinarySubtype};

use super::{MongoExtract, field};
use crate::{
  BeI128, BeU64, BeU128, Count, Score,
  comparison::mongo::MongoCarrier,
  query::mongo::{MongoExtractionError, MongoTypeError},
};

/// Every row, written and read back — which is what makes the two tables ONE encoding rather than
/// two that agree today.
///
/// A carrier that changed its BSON arm without this file moving is a failing test rather than a
/// document nothing can read, and that is the whole reason this is a round trip rather than a list
/// of expected values.
fn round_trip<T>(value: T)
where
  T: MongoCarrier + MongoExtract + core::fmt::Debug + PartialEq,
{
  let written = value.to_bson();
  assert_eq!(T::extract(Some(&written)), Ok(value), "wrote {written:?}");
}

#[test]
fn every_storage_type_round_trips_through_its_own_bson() {
  round_trip(true);
  round_trip(false);
  round_trip(-1i8);
  round_trip(-300i16);
  round_trip(i32::MIN);
  round_trip(i64::MIN);
  round_trip(255u8);
  round_trip(u16::MAX);
  round_trip(u32::MAX);
  round_trip(0.5f32);
  round_trip(f64::MIN);
  round_trip("a red car".to_owned());
  round_trip(vec![1u8, 2, 3]);
  round_trip(Score::new(0.25).expect("in range"));
  round_trip(BeU64(u64::MAX));
  round_trip(BeU128(u128::MAX));
  round_trip(BeI128(i128::MIN));
  // A cardinality, over the ordinary case and the ceiling `Count::to_signed` saturates at — the one
  // magnitude where the stored `long` and the count that wrote it are the SAME number by
  // construction rather than by the round trip alone.
  round_trip(Count::new(0));
  round_trip(Count::new(7));
  round_trip(Count::new(i64::MAX.unsigned_abs()));
  // The framework's own instant, over the extremes and over the pre-epoch case whose two halves are
  // both negative — the one place a rebasing encoding would differ from this one.
  round_trip(crate::Timestamp::MIN);
  round_trip(crate::Timestamp::MAX);
  round_trip(crate::Timestamp::UNIX_EPOCH);
  round_trip::<crate::Timestamp>("2026-08-09T21:14:03.123456789Z".parse().unwrap());
  round_trip::<crate::Timestamp>("1969-12-31T23:59:58.5Z".parse().unwrap());
}

/// **A NEGATIVE STORED `long` IS REFUSED BY NAME, NOT REINTERPRETED** — the same posture the SQL
/// decode takes over the same `i64`, through the same [`Count::from_signed`].
///
/// Nothing that wrote through [`Count::to_signed`] can produce a negative `long` — the narrowing
/// saturates at [`i64::MAX`] and has no negative arm — so this is a document a hand edit, a shared
/// column or a bit flip left behind, and reading it as a huge unsigned count would be the silent
/// reinterpretation this crate refuses everywhere else a stored value outgrows its type.
#[test]
fn a_negative_count_is_refused_rather_than_reinterpreted() {
  assert_eq!(
    Count::extract(Some(&Bson::Int64(-1))),
    Err(MongoTypeError::Range(super::NEGATIVE))
  );
  assert_eq!(
    Count::extract(Some(&Bson::Int64(i64::MIN))),
    Err(MongoTypeError::Range(super::NEGATIVE))
  );

  // …and the ceiling itself still reads, which is what the round trip above pins as an identity
  // rather than an edge case that happens to pass.
  assert_eq!(
    Count::extract(Some(&Bson::Int64(i64::MAX))),
    Ok(Count::new(i64::MAX.unsigned_abs()))
  );
}

/// The `u32` row is the one the carrier table had to MEASURE: bson's serializer widens every `u32`
/// to `Int64` where `From<u32> for Bson` narrows a small one to `Int32`. The read has to agree with
/// the WRITE, so a small `u32` comes back out of an `Int64`.
#[test]
fn a_small_u32_is_stored_and_read_as_a_long() {
  assert_eq!(7u32.to_bson(), Bson::Int64(7));
  assert_eq!(u32::extract(Some(&Bson::Int64(7))), Ok(7));
  assert_eq!(
    u32::extract(Some(&Bson::Int32(7))),
    Err(MongoTypeError::wrong_type("long", "int"))
  );
}

/// A MISSING field and a `null` are ONE answer for an `Option`, which is MongoDB's own reading:
/// `{f: {$eq: null}}` matches both and `$sort` orders them together, so a decode that told them
/// apart would carry a distinction no query over the same field can express.
#[test]
fn a_missing_field_and_a_null_are_one_answer() {
  assert_eq!(<Option<i64>>::extract(None), Ok(None));
  assert_eq!(<Option<i64>>::extract(Some(&Bson::Null)), Ok(None));
  assert_eq!(<Option<i64>>::extract(Some(&Bson::Int64(7))), Ok(Some(7)));
}

/// A NON-optional type refuses both, and refuses them differently — two sentences for two
/// situations a reader will want to tell apart even though the query language will not.
#[test]
fn a_required_field_refuses_both_absences_by_name() {
  assert_eq!(i64::extract(None), Err(MongoTypeError::Absent));
  assert_eq!(
    i64::extract(Some(&Bson::Null)),
    Err(MongoTypeError::wrong_type("long", "null"))
  );
}

/// The mismatch names BSON's own `$type` alias at both ends, so the message and a query that would
/// find the offending documents spell the type the same way.
#[test]
fn a_type_mismatch_names_the_alias_the_query_language_uses() {
  assert_eq!(
    String::extract(Some(&Bson::Int32(7))),
    Err(MongoTypeError::wrong_type("string", "int"))
  );
  assert_eq!(
    i64::extract(Some(&Bson::Document(doc! {}))),
    Err(MongoTypeError::wrong_type("long", "object"))
  );
  assert_eq!(
    i64::extract(Some(&Bson::Document(doc! {})))
      .expect_err("an object is not a long")
      .to_string(),
    "this field holds a object where a long was stored"
  );
}

/// Three Rust widths share BSON's `Int32`, so a document written by anything else can hold a legal
/// `Int32` this field cannot take — and a silent truncation would put a different value in the
/// record than the one that was stored.
#[test]
fn a_narrowing_integer_is_refused_rather_than_truncated() {
  assert_eq!(i8::extract(Some(&Bson::Int32(300))), Err(range()));
  assert_eq!(u8::extract(Some(&Bson::Int32(-1))), Err(range()));
  assert_eq!(u16::extract(Some(&Bson::Int32(-1))), Err(range()));
  assert_eq!(u32::extract(Some(&Bson::Int64(-1))), Err(range()));
  // …and the values that DO fit still read.
  assert_eq!(i8::extract(Some(&Bson::Int32(127))), Ok(127));
}

/// `f32` is stored in BSON's only binary float, which is 64-bit, so the read back is a narrowing
/// too — checked by the round trip rather than rounded, because a `double` this carrier did not
/// write is a value the document holds and the record would not.
#[test]
fn a_double_that_no_f32_wrote_is_refused() {
  assert_eq!(f32::extract(Some(&Bson::Double(0.5))), Ok(0.5));
  assert_eq!(f32::extract(Some(&Bson::Double(0.1))), Err(range()));
}

/// `NaN` survives both directions and is a value a float column can legitimately carry, which is
/// why the check is written on the BITS rather than with `==`.
#[test]
fn a_nan_survives_the_narrowing_check() {
  let written = f32::NAN.to_bson();
  assert!(
    f32::extract(Some(&written))
      .expect("a NaN is a float")
      .is_nan()
  );
}

/// A [`Score`]'s `[0.0, 1.0]` invariant is the DOMAIN's, so a double outside it is refused rather
/// than clamped: a clamped value is one nothing ever stored.
#[test]
fn a_score_outside_its_range_is_refused() {
  assert_eq!(
    Score::extract(Some(&Bson::Double(2.0))),
    Err(MongoTypeError::Range(super::DOMAIN))
  );
}

/// A fixed-width carrier reads through its OWN `from_blob`, so a blob of the wrong length is a
/// refusal rather than a zero-extended number that looks plausible.
#[test]
fn a_blob_of_the_wrong_width_is_refused() {
  let short = Bson::Binary(Binary {
    subtype: BinarySubtype::Generic,
    bytes: vec![1, 2, 3],
  });

  assert_eq!(
    BeU64::extract(Some(&short)),
    Err(MongoTypeError::Range(super::WIDTH))
  );
}

/// A blob of another SUBTYPE is not this column's, and BSON's own comparison order puts subtype
/// ahead of bytes — so reading one as a generic blob would compare unequal to everything the
/// carrier wrote.
#[test]
fn a_blob_of_another_subtype_is_not_this_column() {
  let uuid = Bson::Binary(Binary {
    subtype: BinarySubtype::Uuid,
    bytes: vec![0; 16],
  });

  assert_eq!(
    BeU128::extract(Some(&uuid)),
    Err(MongoTypeError::wrong_type("binData", "binData"))
  );
}

/// [`field`] is the ONE call an emitted extraction makes, and the field name it adds is the whole of
/// what it adds — a refusal that says *expected long, found string* over a twenty-field document is
/// a search rather than a report.
#[test]
fn the_field_wrapper_names_the_key_on_every_failure() {
  let document = doc! { "title": "a red car" };

  assert_eq!(
    field::<i64>(&document, "title"),
    Err(MongoExtractionError::new(
      "title",
      MongoTypeError::wrong_type("long", "string")
    ))
  );
  assert_eq!(
    field::<i64>(&document, "score"),
    Err(MongoExtractionError::new("score", MongoTypeError::Absent))
  );
  assert_eq!(
    field::<String>(&document, "title"),
    Ok("a red car".to_owned())
  );
}

/// The narrowing refusal, spelled once so the assertions above read as what they check rather than
/// as a string comparison.
fn range() -> MongoTypeError {
  MongoTypeError::Range(super::NARROW)
}

/// **The instant's read, and the three ways a stored sub-document is not one.**
///
/// The refusals are what the round trip above cannot show: a document written by something else —
/// another driver, a migration, an older declaration — can be perfectly good BSON and not a value
/// this type holds. Each is answered loudly, and the sign-crossing pair is answered rather than
/// RESOLVED, which is the same decision the SQL decode makes over the same two numbers.
#[test]
fn an_instant_refuses_a_sub_document_that_is_not_a_pair() {
  use crate::Timestamp;

  let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
  assert_eq!(
    Timestamp::extract(Some(
      &doc! { "secs": 1_786_310_043i64, "nanos": 123_456_789i32 }.into()
    )),
    Ok(at)
  );

  // Not a sub-document at all: the alias is `$type`'s own word, so a query could find the offenders.
  assert_eq!(
    Timestamp::extract(Some(&Bson::Int64(1_786_310_043))),
    Err(MongoTypeError::wrong_type("object", "long"))
  );
  // A sub-document whose halves are at the wrong BSON widths — `nanos` as a `long` is the near miss,
  // since the two integers are only told apart by their arms.
  assert!(matches!(
    Timestamp::extract(Some(&doc! { "secs": 1i64, "nanos": 1i64 }.into())),
    Err(MongoTypeError::Range(_))
  ));
  assert!(matches!(
    Timestamp::extract(Some(&doc! { "secs": 1i64 }.into())),
    Err(MongoTypeError::Range(_))
  ));
  // And the pair jiff would have resolved: refused here exactly as it is refused in a column.
  assert!(matches!(
    Timestamp::extract(Some(
      &doc! { "secs": 2i64, "nanos": -999_999_999i32 }.into()
    )),
    Err(MongoTypeError::Range(_))
  ));

  // An ABSENT field is absence rather than a range refusal, which is the two-state reading applied
  // to a composite: `Option<Timestamp>` is what a declaration writes for a column that may be null.
  assert_eq!(Timestamp::extract(None), Err(MongoTypeError::Absent));
  assert_eq!(Option::<Timestamp>::extract(None), Ok(None));
}

/// The instant reaches a document THROUGH `field`, which is the one call an emitted extraction
/// makes per column — so a refusal names the field the document holds it at.
#[test]
fn an_instants_refusal_names_its_field() {
  use crate::Timestamp;

  let document = doc! { "at": { "secs": 2i64, "nanos": -999_999_999i32 } };
  let refused = field::<Timestamp>(&document, "at").expect_err("the pair is not an instant");
  assert_eq!(refused.field(), "at");
}