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 std::time::{Duration, SystemTime};

use super::{Timestamp, TimestampPartsError};

// The two halves of one instant — `2026-08-09T21:14:03.123456789Z` — spelled as components so that a
// test can assert each half arrived. A FULL nine digits of fraction, deliberately: a value ending in
// zeros would pass a round trip that dropped them.
const NANOS: i32 = 123_456_789;
const SECONDS: i64 = 1_786_310_043;

fn with_nanos() -> Timestamp {
  Timestamp::from(
    jiff::Timestamp::new(SECONDS, NANOS).expect("the fixture is inside the representable range"),
  )
}

/// The bounds the type's own documentation promises, asserted as the TEXT a reader is given —
/// ±9999 years rather than the ±292 an `i64` of nanoseconds would allow, so the doc's "no 2262
/// ceiling" is a fact this test would notice losing.
#[test]
fn the_range_is_the_documented_one() {
  assert_eq!(Timestamp::MIN.to_string(), "-009999-01-02T01:59:59Z");
  assert_eq!(Timestamp::MAX.to_string(), "9999-12-30T22:00:00.999999999Z");
  assert_eq!(Timestamp::UNIX_EPOCH.to_string(), "1970-01-01T00:00:00Z");
  assert_eq!(Timestamp::UNIX_EPOCH.get().as_nanosecond(), 0);
}

/// The order is the INSTANT's, and the pre-epoch value is the half that a seconds-and-remainder
/// comparison gets wrong: jiff gives a negative timestamp's fractional part a negative sign, so
/// anything comparing the two components independently sorts it above its own second.
#[test]
fn orders_by_the_instant() {
  let before_epoch = Timestamp::from(
    jiff::Timestamp::new(-1, -500_000_000).expect("half a second before the epoch is an instant"),
  );
  let mut instants = [
    Timestamp::MAX,
    with_nanos(),
    Timestamp::UNIX_EPOCH,
    before_epoch,
    Timestamp::MIN,
  ];
  instants.sort();

  assert_eq!(
    instants,
    [
      Timestamp::MIN,
      before_epoch,
      Timestamp::UNIX_EPOCH,
      with_nanos(),
      Timestamp::MAX
    ]
  );
}

/// **The pair sorts LEXICOGRAPHICALLY into the instant's own order** — the one property every
/// composite reading of this type rests on, pinned here once rather than in each of the three places
/// that spend it.
///
/// The SQL row value `("at_secs", "at_nanos") < (?, ?)` is lexicographic by SQL's own definition,
/// the keyset's tie-then-break expansion is lexicographic by construction, and BSON compares a
/// sub-document field by field in the order it was written. All three are the same claim about this
/// type: comparing the seconds first and the fraction only on a tie IS comparing the moment.
///
/// It holds because [`as_second`](Timestamp::as_second) truncates towards zero rather than flooring,
/// so within one second value every fraction carries that second's own sign — `-1.5s` is
/// `(-1, -500_000_000)` and not `(-1, 500_000_000)`. A floor/timespec encoding would sort the
/// pre-epoch values the other way inside their own second, which is the boundary this fixture set
/// straddles from both sides.
#[test]
fn the_pairs_lexicographic_order_is_the_instants() {
  let mut instants = [
    Timestamp::MAX,
    with_nanos(),
    Timestamp::from(jiff::Timestamp::new(0, 1).expect("a nanosecond after the epoch")),
    Timestamp::UNIX_EPOCH,
    Timestamp::from(jiff::Timestamp::new(0, -1).expect("a nanosecond before the epoch")),
    Timestamp::from(jiff::Timestamp::new(-1, -500_000_000).expect("half a second before it")),
    Timestamp::from(jiff::Timestamp::new(-1, 0).expect("a second before it")),
    Timestamp::MIN,
  ];
  let mut pairs = instants;

  instants.sort();
  pairs.sort_by_key(|instant| (instant.as_second(), instant.subsec_nanosecond()));

  assert_eq!(
    instants, pairs,
    "sorting the (secs, nanos) pairs left to right has to be sorting the instants"
  );
}

/// An OFFSET spelling normalises to the instant it names. The type holds no offset and no zone, so
/// the two strings below are one value — they compare equal, they hash equally, and the rendering is
/// the UTC one whichever was parsed.
///
/// The hash assertion is not decoration: `Eq` and `Hash` are both derived, so this is where the
/// derive's claim that they agree is actually exercised over two values reached by different routes.
#[test]
fn an_offset_spelling_normalises_to_the_instant() {
  use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
  };

  let east: Timestamp = "2026-08-09T21:14:03+09:00"
    .parse()
    .expect("an offset spelling parses");
  let utc: Timestamp = "2026-08-09T12:14:03Z"
    .parse()
    .expect("the UTC spelling parses");

  assert_eq!(east, utc);
  assert_eq!(east.to_string(), "2026-08-09T12:14:03Z");

  let hash = |instant: Timestamp| {
    let mut hasher = DefaultHasher::new();
    instant.hash(&mut hasher);
    hasher.finish()
  };
  assert_eq!(hash(east), hash(utc));
}

/// A civil datetime is REFUSED rather than read as UTC: an instant needs an offset, and supplying
/// the missing one would be this crate inventing the fact the input left out.
#[test]
fn a_string_without_an_offset_refuses() {
  assert!("2026-08-09T21:14:03".parse::<Timestamp>().is_err());
  assert!("2026-08-09".parse::<Timestamp>().is_err());
  assert!("not a time".parse::<Timestamp>().is_err());
  // The one refusal a client is most likely to test: seconds since the epoch, which is exactly the
  // form this type's wire face declines to speak.
  assert!("1786310043".parse::<Timestamp>().is_err());
}

/// The text round trip is EXACT to the nanosecond, both ways — the rendering carries all nine digits
/// and the parser reads all nine back.
#[test]
fn the_text_round_trip_keeps_the_nanoseconds() {
  let instant = with_nanos();

  assert_eq!(instant.to_string(), "2026-08-09T21:14:03.123456789Z");
  assert_eq!(
    instant
      .to_string()
      .parse::<Timestamp>()
      .expect("its own rendering parses"),
    instant
  );
  assert_eq!(instant.get().subsec_nanosecond(), NANOS);
}

/// The [`SystemTime`] crossing keeps the sub-second component, which is the whole of what "lossless"
/// means here — the platform type carries nanoseconds and so does this one, so nothing is rounded
/// on the way in or on the way back out.
///
/// The far end is asserted too, so the pair is a round trip rather than two half-measurements: a
/// crossing that dropped the fraction identically in both directions would still pass an
/// `at == back` assertion alone.
#[test]
fn a_system_time_crosses_with_its_nanoseconds() {
  let at = SystemTime::UNIX_EPOCH + Duration::new(SECONDS as u64, NANOS as u32);
  let instant = Timestamp::try_from(at).expect("a recent instant is inside the range");

  assert_eq!(instant.get().as_second(), SECONDS);
  assert_eq!(instant.get().subsec_nanosecond(), NANOS);
  assert_eq!(SystemTime::from(instant), at);
}

/// The one direction that refuses, and it refuses by RANGE. A [`SystemTime`] is not bounded by
/// ±9999 years, so a value outside the span has no instant to become — and the answer is an error
/// rather than a saturation, because a substituted instant is a wrong answer reported as a right
/// one.
#[test]
fn a_system_time_outside_the_range_refuses() {
  // Roughly the year 318000 — far outside ±9999 and comfortably inside what a `SystemTime` holds on
  // the platforms this crate builds for.
  let far = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000_000_000_000);
  assert!(Timestamp::try_from(far).is_err());
}

/// The two conversions to and from jiff's own type are each other's inverse, which is what makes
/// [`Timestamp::get`] an escape hatch rather than a projection: nothing is lost passing through this
/// crate's newtype in either direction.
#[test]
fn the_jiff_crossing_is_the_identity() {
  let instant = with_nanos();
  assert_eq!(Timestamp::from(instant.get()), instant);
  assert_eq!(jiff::Timestamp::from(instant), instant.get());
}

/// **The COLUMN round trip, over the whole range** — every instant this type admits is the pair its
/// own two accessors answer, and reading that pair back is the identity.
///
/// The extremes are the ones a fixed shape gets wrong: [`MIN`](Timestamp::MIN) has a zero fraction
/// beside the most negative second there is, [`MAX`](Timestamp::MAX) has a full nine digits beside
/// the largest, and the pre-epoch value in the middle is the one whose two halves are BOTH negative
/// — which is the pairing the whole encoding rests on.
#[test]
fn every_instant_is_the_pair_its_own_accessors_answer() {
  let before_epoch = Timestamp::from(
    jiff::Timestamp::new(-1, -500_000_000).expect("half a second before the epoch is an instant"),
  );

  for instant in [
    Timestamp::MIN,
    before_epoch,
    Timestamp::UNIX_EPOCH,
    with_nanos(),
    Timestamp::MAX,
  ] {
    assert_eq!(
      Timestamp::from_parts(instant.as_second(), instant.subsec_nanosecond())
        .expect("the pair this instant writes is a pair it reads"),
      instant,
      "{instant}"
    );
  }

  // The two halves of one pre-epoch instant, spelled out: both negative, which is jiff's own
  // arrangement and the reason a lexicographic comparison of the two columns is the instant's order.
  assert_eq!(before_epoch.to_string(), "1969-12-31T23:59:58.5Z");
  assert_eq!(before_epoch.as_second(), -1);
  assert_eq!(before_epoch.subsec_nanosecond(), -500_000_000);
  assert_eq!(with_nanos().as_second(), SECONDS);
  assert_eq!(with_nanos().subsec_nanosecond(), NANOS);
}

/// **THE TEETH.** A stored pair whose halves disagree in sign is one jiff would have NORMALISED
/// into another spelling of the same instant, and it is refused instead — which is what makes the
/// admitted pairs exactly the pairs this encoding writes.
///
/// `(2, -999_999_999)` is jiff's own documented example of the resolution, so this is the exact
/// value the constructor beneath would have accepted and quietly changed. `(1, 1)` is the instant it
/// would have become, and it is admitted — so the refusal is about the SPELLING and not about the
/// instant.
#[test]
fn a_pair_that_would_have_been_normalised_is_refused() {
  let refused =
    Timestamp::from_parts(2, -999_999_999).expect_err("a sign-crossing pair is not a spelling");
  assert!(
    matches!(
      refused,
      TimestampPartsError::Unnormalised {
        second: 2,
        nanosecond: -999_999_999
      }
    ),
    "{refused:?}"
  );
  assert!(refused.to_string().contains("(2, -999999999)"), "{refused}");

  // The instant that pair NAMES is perfectly storable — under the one spelling this encoding writes.
  let resolved = Timestamp::from_parts(1, 1).expect("the resolved pair is the written one");
  assert_eq!(resolved.to_string(), "1970-01-01T00:00:01.000000001Z");
  assert_eq!(
    jiff::Timestamp::new(2, -999_999_999).expect("jiff resolves it"),
    resolved.get(),
    "which is what the constructor beneath would have done in silence"
  );

  // And the mirror, so the refusal is not a one-sided rule about negative fractions.
  assert!(matches!(
    Timestamp::from_parts(-2, 999_999_999),
    Err(TimestampPartsError::Unnormalised { .. })
  ));
}

/// The other half of the refusal is JIFF'S OWN, surfaced with its message rather than reworded: a
/// fraction past a whole second, and a second outside the ±9999-year span.
#[test]
fn a_pair_outside_the_types_range_carries_jiffs_refusal() {
  for (second, nanosecond) in [
    (0, 1_000_000_000),
    (0, -1_000_000_000),
    (i64::MAX, 0),
    (i64::MIN, 0),
  ] {
    let refused = Timestamp::from_parts(second, nanosecond)
      .expect_err("neither a fraction past a second nor an instant past the span");
    assert!(
      matches!(refused, TimestampPartsError::Range(_)),
      "({second}, {nanosecond}) → {refused:?}"
    );
  }

  // The message is jiff's, kept whole, and the source chains to it — which is what a decode wraps
  // when it reports `ColumnDecode`.
  let refused = Timestamp::from_parts(0, 1_000_000_000).expect_err("a fraction past a second");
  assert!(
    std::error::Error::source(&refused).is_some(),
    "jiff's own error is the source"
  );
  assert!(
    refused
      .to_string()
      .starts_with("the stored pair is not an instant: "),
    "{refused}"
  );
}

/// A pair BEYOND the span is refused even where its two halves agree in sign, which is the case the
/// identity check alone would not catch: jiff answers `Err` first, so the two clauses cover
/// different inputs rather than one covering the other.
#[test]
fn the_two_refusals_cover_different_pairs() {
  // Inside the span, agreeing in sign: admitted.
  assert!(Timestamp::from_parts(Timestamp::MAX.as_second(), 999_999_999).is_ok());
  // One nanosecond past the top of the span: jiff's refusal, not the identity check's.
  assert!(matches!(
    Timestamp::from_parts(Timestamp::MAX.as_second() + 1, 0),
    Err(TimestampPartsError::Range(_))
  ));
  // Inside the span, disagreeing in sign: the identity check's refusal, not jiff's.
  assert!(matches!(
    Timestamp::from_parts(1, -1),
    Err(TimestampPartsError::Unnormalised { .. })
  ));
}