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 `$or` a cursor becomes: the branch per tie-break level, the two null readings, and the
//! degenerate page.

use std::sync::Arc;

use bson::doc;

use super::MongoKeyset;
use crate::{
  Cursor, OrderDirection, RecordAddress, Walk,
  comparison::{At, ComplexComparison, mongo::MongoConjunction},
  query::mongo::{
    MongoOrder, MongoQuery,
    tests::{KeyframeOrder, ShotCursor, ShotMongo, ShotOrder, subjects, terms},
  },
};

/// The address every keyset below is rendered against — the fixture's, so `id` maps to `_id`.
const ADDRESS: RecordAddress = <ShotMongo as MongoQuery>::ADDRESS;

/// One branch per level, each carrying the levels above it as equalities — the module's own worked
/// example, asserted as the exact document a page-2 `$match` holds.
///
/// This is the PAGE-2 PIN. Breaking the fold — dropping an equality prefix, or writing the levels
/// in the wrong sequence — reds it, and nothing else would: every mutation of that shape renders a
/// perfectly good aggregation that answers without an error and returns the wrong documents.
#[test]
fn a_page_two_keyset_is_one_branch_per_tie_break_level() {
  let terms = terms(&[
    ShotOrder::Title(OrderDirection::Asc),
    ShotOrder::Score(OrderDirection::Desc),
  ]);
  let order = MongoOrder::new(&terms).expect("three terms");
  let cursor = Cursor::at(
    &terms,
    vec![
      Some(ShotCursor::Title("a red car".to_owned())),
      Some(ShotCursor::Score(0.5)),
      Some(ShotCursor::Id(12)),
    ],
  );
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! {
      "$or": [
        { "title": { "$gt": "a red car" } },
        {
          "title": { "$eq": "a red car" },
          // A DESCENDING term over a NULLABLE field: the nulls trail it, so they are after every
          // value — and `$lt` does not cross BSON types, so they have to be named.
          "$or": [
            { "score": { "$lt": 0.5 } },
            { "score": { "$eq": null } },
          ],
        },
        {
          "title": { "$eq": "a red car" },
          "score": { "$eq": 0.5 },
          "_id": { "$gt": 12i64 },
        },
      ]
    }
  );
}

/// A single-term order is the whole expansion at width one: one branch, one arm, and the id is the
/// term — so the `_id` mapping is visible in the smallest possible page.
#[test]
fn a_single_term_order_is_one_branch() {
  let terms = terms(&[]);
  let order = MongoOrder::new(&terms).expect("the id tail");
  let cursor = Cursor::at(&terms, vec![Some(ShotCursor::Id(12))]);
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! { "$or": [ { "_id": { "$gt": 12i64 } } ] }
  );
}

/// A BACKWARD walk inverts every comparator, and the trailing-null arm moves with the direction it
/// belongs to: the same term that trailed its nulls going forward now leads them.
#[test]
fn a_backward_walk_inverts_every_comparator() {
  let terms = terms(&[ShotOrder::Score(OrderDirection::Desc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let cursor = Cursor::at(
    &terms,
    vec![Some(ShotCursor::Score(0.5)), Some(ShotCursor::Id(12))],
  );
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Backward).expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! {
      "$or": [
        // Descending, walked backwards, is ascending — so `$gt` and no null arm at all: the nulls
        // are now BELOW every value and no document past this one is one.
        { "score": { "$gt": 0.5 } },
        { "score": { "$eq": 0.5 }, "_id": { "$lt": 12i64 } },
      ]
    }
  );
}

/// A cursor sitting ON a null, under an ASCENDING term: every value is above every null, and
/// `$ne: null` is exactly *present and not null* — because `$eq: null` is MongoDB's own
/// missing-or-null test.
#[test]
fn an_ascending_null_resumes_at_the_first_value() {
  let terms = terms(&[ShotOrder::Score(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let cursor = Cursor::at(&terms, vec![None, Some(ShotCursor::Id(12))]);
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! {
      "$or": [
        { "score": { "$ne": null } },
        // The tie group below still renders, which is what keeps a page resuming INSIDE a run of
        // nulls rather than jumping past it.
        { "score": { "$eq": null }, "_id": { "$gt": 12i64 } },
      ]
    }
  );
}

/// A cursor sitting on a null under a DESCENDING term has NO branch of its own: the nulls are that
/// term's last group, so no document sorts after one. The level below it still renders.
#[test]
fn a_descending_null_contributes_no_branch() {
  let terms = terms(&[ShotOrder::Score(OrderDirection::Desc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let cursor = Cursor::at(&terms, vec![None, Some(ShotCursor::Id(12))]);
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! { "$or": [ { "score": { "$eq": null }, "_id": { "$gt": 12i64 } } ] }
  );
}

/// A cursor no document can be after is an ANSWER — the page is empty — and it has to be a
/// predicate that matches nothing rather than `{$or: []}`, which the server refuses outright.
#[test]
fn a_cursor_nothing_follows_renders_the_contradiction() {
  // Every term descending on a null: the last group of the last group, walked forwards.
  let terms = [crate::OrderTerm::nullable(
    crate::TermName::new("score"),
    crate::FieldName::new("score"),
    OrderDirection::Desc,
  )];
  let order = MongoOrder::new(&terms).expect("one term");
  let cursor = Cursor::at(&terms, vec![None::<ShotCursor>]);
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  assert_eq!(keyset.to_document(&ADDRESS), doc! { "$alwaysFalse": 1 });
}

/// The keyset joins a `$match` through the accumulator, as a TOP-LEVEL conjunct — so a page beside
/// a filter is *the filter AND this* and neither conjunct has to know what the other was.
///
/// It goes under `$and` rather than being merged into a field's operator document, because `$or`
/// has no field key to be merged under. Breaking that — merging it — would put a `$or` inside a
/// field's operators, which the server reads as a field called `$or` and refuses.
#[test]
fn the_keyset_is_a_top_level_conjunct_beside_the_filter() {
  let terms = terms(&[]);
  let order = MongoOrder::new(&terms).expect("the id tail");
  let cursor = Cursor::at(&terms, vec![Some(ShotCursor::Id(12))]);
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  let filter = crate::query::mongo::tests::titled("a red car");
  let at = At::new(&ADDRESS);
  let builder = filter
    .apply(at, MongoConjunction::new())
    .expect("the filter lowers");
  let builder = keyset.apply(at, builder).expect("the keyset lowers");

  assert_eq!(
    builder.into_document(),
    doc! {
      "title": { "$eq": "a red car" },
      "$and": [ { "$or": [ { "_id": { "$gt": 12i64 } } ] } ],
    }
  );
}

/// One conjunct whatever the order holds — the count every caller reads through `is_empty`.
#[test]
fn a_keyset_is_always_one_conjunct() {
  let terms = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let cursor = Cursor::at(
    &terms,
    vec![
      Some(ShotCursor::Title("a red car".to_owned())),
      Some(ShotCursor::Id(12)),
    ],
  );
  let keyset = MongoKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");

  assert_eq!(ComplexComparison::<crate::Mongo>::conjuncts(&keyset), 1);
  assert!(!ComplexComparison::<crate::Mongo>::is_empty(&keyset));
}

/// A cursor minted under ANOTHER order is refused before any document is built, which is what keeps
/// every refusal this page can make out of the rendering.
#[test]
fn a_cursor_from_another_order_is_refused_at_construction() {
  let minted = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let asked = terms(&[ShotOrder::Score(OrderDirection::Asc)]);
  let cursor = Cursor::at(
    &minted,
    vec![
      Some(ShotCursor::Title("a red car".to_owned())),
      Some(ShotCursor::Id(12)),
    ],
  );
  let order = MongoOrder::new(&asked).expect("two terms");

  assert!(MongoKeyset::resume(order, &cursor, Walk::Forward).is_err());
}

/// **The NESTED keyset, verbatim.** Every leg names the field the join materialized — the
/// comparison arm, the equality prefix below it, and the trailing-null arm a descending nullable
/// term carries.
///
/// A nested term is nullable whatever the target's own field says, and descending is the direction
/// that makes that visible: the nulls trail, so the arm has to name them, and `$lt` does not cross
/// BSON types so nothing else would. Three occurrences of `__ig_ord0__` in one document, from one
/// authority — a term whose subject was forgotten in any of them would resume against `cover_id`,
/// which is a foreign key and a page of the wrong documents.
#[test]
fn a_nested_keyset_names_the_materialized_field_in_every_leg() {
  let written = [ShotOrder::Cover(Arc::new(KeyframeOrder::Title(
    OrderDirection::Desc,
  )))];
  let terms = terms(&written);
  let subjects = subjects(&written);
  let order = MongoOrder::new(&terms).expect("two terms");
  let cursor = Cursor::at(
    &terms,
    vec![
      Some(ShotCursor::CoverTitle("Autumn".to_owned())),
      Some(ShotCursor::Id(12)),
    ],
  );
  let keyset = MongoKeyset::resume_with(order, &cursor, Walk::Forward, &subjects)
    .expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! {
      "$or": [
        { "$or": [
          { "__ig_ord0__": { "$lt": "Autumn" } },
          { "__ig_ord0__": { "$eq": null } },
        ] },
        { "__ig_ord0__": { "$eq": "Autumn" }, "_id": { "$gt": 12i64 } },
      ]
    }
  );
}

/// A cursor whose nested slot is ABSENT resumes inside the run of documents whose reference is
/// missing or points at nothing — the two the `$lookup` leaves indistinguishable, and the two
/// `$eq: null` already holds as one.
#[test]
fn a_nested_cursor_at_nothing_resumes_where_the_join_found_none() {
  let written = [ShotOrder::Cover(Arc::new(KeyframeOrder::Title(
    OrderDirection::Asc,
  )))];
  let terms = terms(&written);
  let subjects = subjects(&written);
  let order = MongoOrder::new(&terms).expect("two terms");
  let cursor = Cursor::at(&terms, vec![None, Some(ShotCursor::Id(12))]);
  let keyset = MongoKeyset::resume_with(order, &cursor, Walk::Forward, &subjects)
    .expect("this order's cursor");

  assert_eq!(
    keyset.to_document(&ADDRESS),
    doc! {
      "$or": [
        { "__ig_ord0__": { "$ne": null } },
        { "__ig_ord0__": { "$eq": null }, "_id": { "$gt": 12i64 } },
      ]
    }
  );
}