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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! The expansion, per polarity and per nullability.
//!
//! Asserting on the rendered text is right here for the clause machine's reason: the deliverable IS
//! the text, and every operand goes through one bind that the text cannot show. What the text has to
//! show is that each comparator followed its OWN column's direction and that the nullable arms are
//! where the framework's pinned `NULL` position puts them.
//!
//! The predicate's MEANING is checked against real engines rather than here — see the module note in
//! `comparison::sql::keyset` — because a keyset that skips or repeats a row renders perfectly
//! well-formed SQL, which is the one thing about it that does not matter.

#![cfg(feature = "sqlite")]

use super::{OrderSubjects, SqlKeyset, SubjectShape, SubjectSlot, TermColumns};
use crate::{
  At, Carrier, ComplexComparison, Cursor, CursorError, FieldName, OrderDirection, OrderTerm,
  TermName, Walk,
  comparison::sql::{
    SqlConjunction, SqlOrder,
    tests::{Probe, ROW},
  },
};

const A: &TermName = TermName::new("a");
const B: &TermName = TermName::new("b");
const ID: &TermName = TermName::new("id");

/// `a ASC, b DESC, id ASC` over `NOT NULL` columns.
fn required() -> [OrderTerm; 3] {
  [
    OrderTerm::new(A, FieldName::new("a"), OrderDirection::Asc),
    OrderTerm::new(B, FieldName::new("b"), OrderDirection::Desc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ]
}

/// The same order with `a` NULLABLE.
fn optional() -> [OrderTerm; 3] {
  [
    OrderTerm::nullable(A, FieldName::new("a"), OrderDirection::Asc),
    OrderTerm::new(B, FieldName::new("b"), OrderDirection::Desc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ]
}

/// The keyset predicate for `terms` resumed at `values`, as a bare fragment beside `lead`.
fn rendered_with(
  terms: &[OrderTerm],
  values: &[Option<i64>],
  walk: Walk,
  lead: &'static str,
) -> String {
  let order = SqlOrder::<sqlx::Sqlite>::new(terms).expect("a renderable order");
  let cursor = Cursor::at(terms, values.to_vec());
  let keyset = SqlKeyset::resume(order, &cursor, walk).expect("this cursor is this order's");
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let accumulator = SqlConjunction::with_lead(&mut qb, lead);
    assert_eq!(keyset.conjuncts(), 1);
    keyset
      .apply(At::new(&ROW), accumulator)
      .expect("a constructed keyset cannot refuse");
  }
  qb.into_string()
}

/// The keyset predicate as a bare fragment.
fn rendered(terms: &[OrderTerm], values: &[Option<i64>], walk: Walk) -> String {
  rendered_with(terms, values, walk, "")
}

/// [`rendered`] over an order whose terms compare what `subjects` writes, with the BIND COUNT
/// beside the text.
///
/// The count is the half a subject's rendering cannot be read off the text for: a subject carrying
/// operands is written once per occurrence, so a lowering that rendered one and reused it would
/// produce this very string with fewer binds behind it.
///
/// Written out rather than folded into [`rendered_with`], because what those eleven assertions are
/// worth depends on their route being the one the column keyset actually takes.
fn rendered_over<S: OrderSubjects<sqlx::Sqlite>>(
  terms: &[OrderTerm],
  values: &[Option<i64>],
  walk: Walk,
  subjects: S,
) -> (String, usize) {
  use sqlx::Execute;

  let order = SqlOrder::<sqlx::Sqlite>::new(terms).expect("a renderable order");
  let cursor = Cursor::at(terms, values.to_vec());
  let keyset =
    SqlKeyset::resume_with(order, &cursor, walk, subjects).expect("this cursor is this order's");
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let accumulator = SqlConjunction::with_lead(&mut qb, "");
    assert_eq!(keyset.conjuncts(), 1);
    keyset
      .apply(At::new(&ROW), accumulator)
      .expect("a constructed keyset cannot refuse");
  }
  let mut built = qb.build();
  let binds = match built.take_arguments() {
    Ok(Some(arguments)) => sqlx::Arguments::len(&arguments),
    Ok(None) | Err(_) => 0,
  };
  (built.sql().as_str().to_owned(), binds)
}

/// Term 0's subject is a correlated scalar SUBQUERY and every other term's is its column, which is
/// the mixed order a nested ordering term produces rather than a whole order of expressions.
///
/// The subquery carries a BIND of its own — the half of a subject the rendered text cannot show —
/// and the probe records where each one landed.
struct CoverTitle<'a> {
  bound: &'a core::cell::RefCell<Vec<i64>>,
}

impl OrderSubjects<sqlx::Sqlite> for CoverTitle<'_> {
  fn push_subject(
    &self,
    slot: SubjectSlot<'_, sqlx::Sqlite>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
  ) {
    if level > 0 {
      TermColumns.push_subject(slot, at, terms, level);
      return;
    }
    // The BODY and no brackets: the pair is the slot's, and without it this predicate's own outer
    // one becomes the start of a scalar subquery — which two of the three engines answer with an
    // empty page and no error.
    slot.write(|qb| {
      qb.push("SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ");
      Probe {
        value: 9,
        bound: self.bound,
      }
      .push_bind(qb);
    });
  }

  /// Level 0 is the subquery and every other level is its own column — stated rather than delegated
  /// to [`TermColumns`], whose answer is the trait's default and names no `Db` for inference to find.
  fn shape(&self, _: &[OrderTerm], level: usize) -> SubjectShape {
    if level > 0 {
      return SubjectShape::Column;
    }
    SubjectShape::SubSelect
  }
}

/// **The seam at its default.** A column keyset is [`TermColumns`] written out, so the expansion
/// every assertion above renders is reached by both ways in and is one text.
#[test]
fn the_column_expansion_is_the_seam_at_its_default() {
  let values = [Some(1), Some(2), Some(3)];

  assert_eq!(
    rendered_over(&required(), &values, Walk::Forward, TermColumns),
    (
      rendered(&required(), &values, Walk::Forward),
      // Five comparisons, one operand each: `2n - 1` for a three-term order.
      5
    )
  );
}

/// **The expression in subject position.** The same `2n - 1` expansion, every bracket and every
/// comparator where the column form puts them, with one term's left-hand side a correlated
/// subquery.
///
/// Its two occurrences — the arm and the tie the level below breaks — each bind, which is why the
/// probe reads twice and the count is the column form's five plus two.
#[test]
fn an_expression_subject_renders_the_whole_expansion_around_it() {
  let bound = core::cell::RefCell::new(Vec::new());

  assert_eq!(
    rendered_over(
      &required(),
      &[Some(1), Some(2), Some(3)],
      Walk::Forward,
      CoverTitle { bound: &bound }
    ),
    (
      "((SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) > ? \
       OR ((SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) = ? \
       AND (\"b\" < ? OR (\"b\" = ? AND (\"id\" > ?)))))"
        .to_owned(),
      7
    )
  );
  assert_eq!(*bound.borrow(), [9, 9]);
}

/// A descending NULLABLE term names its subject three times — the comparison, the trailing `NULL`s
/// after it, and the tie — and an expression subject is written out at each, binds and all.
///
/// This is the arm a subject rendered ONCE and reused would still produce the right text for while
/// binding two operands instead of three, and the count is what sees it.
#[test]
fn a_descending_nullable_expression_subject_is_written_at_every_occurrence() {
  let bound = core::cell::RefCell::new(Vec::new());

  assert_eq!(
    rendered_over(
      &optional(),
      &[Some(1), Some(2), Some(3)],
      Walk::Backward,
      CoverTitle { bound: &bound }
    ),
    (
      "((SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) < ? \
       OR (SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) IS NULL \
       OR ((SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) = ? \
       AND (\"b\" > ? OR (\"b\" = ? AND (\"id\" < ?)))))"
        .to_owned(),
      8
    )
  );
  assert_eq!(*bound.borrow(), [9, 9, 9]);
}

/// **The general form.** Each comparator follows its OWN column's direction, and each level's tie is
/// broken by the level below it — the key tail at the end being what makes the order total.
#[test]
fn the_forward_expansion_follows_each_column_s_own_direction() {
  assert_eq!(
    rendered(&required(), &[Some(1), Some(2), Some(3)], Walk::Forward),
    "(\"a\" > ? OR (\"a\" = ? AND (\"b\" < ? OR (\"b\" = ? AND (\"id\" > ?)))))"
  );
}

/// The backward walk is the SAME expansion with every comparator inverted — `last`/`before`, whose
/// rows the engine re-reverses after they come back.
#[test]
fn the_backward_expansion_inverts_every_comparator() {
  assert_eq!(
    rendered(&required(), &[Some(1), Some(2), Some(3)], Walk::Backward),
    "(\"a\" < ? OR (\"a\" = ? AND (\"b\" > ? OR (\"b\" = ? AND (\"id\" < ?)))))"
  );
}

/// A NULLABLE column whose cursor value is PRESENT changes nothing under an ascending term: `NULL`
/// sorts below every value, so `"a" > ?` excludes the `NULL`s for free — which is right, because
/// they are on the other side of the boundary.
#[test]
fn an_ascending_nullable_term_with_a_value_needs_no_extra_arm() {
  assert_eq!(
    rendered(&optional(), &[Some(1), Some(2), Some(3)], Walk::Forward),
    "(\"a\" > ? OR (\"a\" = ? AND (\"b\" < ? OR (\"b\" = ? AND (\"id\" > ?)))))"
  );
}

/// …and under a DESCENDING term it needs one, for the same pinning read the other way: the `NULL`s
/// trail a descending term, so they are AFTER every value — and `NULL < ?` is unknown rather than
/// true, so they have to be named.
///
/// This is the backward walk of the order above, which is what makes it the same fact twice: the
/// pinning is a total order on the domain, so inverting the walk inverts the arm.
#[test]
fn a_descending_nullable_term_with_a_value_admits_the_nulls_after_it() {
  assert_eq!(
    rendered(&optional(), &[Some(1), Some(2), Some(3)], Walk::Backward),
    "(\"a\" < ? OR \"a\" IS NULL OR (\"a\" = ? AND (\"b\" > ? OR (\"b\" = ? AND (\"id\" < ?)))))"
  );
}

/// A cursor sitting ON a `NULL` under an ascending term resumes two ways at once: every non-null row
/// is after it, and inside the run of `NULL`s the tie breaks on the levels below — which is what
/// keeps a page from restarting at the first `NULL` every time.
#[test]
fn a_null_cursor_value_under_an_ascending_term_admits_every_value_and_ties_on_the_rest() {
  assert_eq!(
    rendered(&optional(), &[None, Some(2), Some(3)], Walk::Forward),
    "(\"a\" IS NOT NULL OR (\"a\" IS NULL AND (\"b\" < ? OR (\"b\" = ? AND (\"id\" > ?)))))"
  );
}

/// **The absent arm.** Under a DESCENDING term the `NULL`s are the last group, so no row is after
/// one — and `A OR false` IS `A`, so the arm contributes nothing rather than a constant the planner
/// would have to fold. The tie group below it still renders, which is what resumes the page inside
/// the run of `NULL`s.
#[test]
fn a_null_cursor_value_under_a_descending_term_has_no_arm_and_still_ties() {
  assert_eq!(
    rendered(&optional(), &[None, Some(2), Some(3)], Walk::Backward),
    "((\"a\" IS NULL AND (\"b\" > ? OR (\"b\" = ? AND (\"id\" < ?)))))"
  );
}

/// A one-term order is the general form degenerating rather than a case of its own: no tie group,
/// because there is no level below to break one into — and the outer pair is still there, because a
/// bracket emitted only when something else is present is a bracket decided by a caller this
/// comparison cannot see.
#[test]
fn a_one_term_order_is_the_general_form_degenerating() {
  let terms = [OrderTerm::new(
    ID,
    FieldName::new("id"),
    OrderDirection::Asc,
  )];

  assert_eq!(rendered(&terms, &[Some(3)], Walk::Forward), "(\"id\" > ?)");
}

/// A cursor no row can be after renders `1 = 0` — an ANSWER (the page is empty) rather than a
/// refusal, which is the same asymmetry `push_in` gives an empty list.
///
/// It is unreachable through the framework's own orders, whose key tail is `NOT NULL`, so the order
/// here is one a caller wrote by hand: every term descending, every value `NULL`.
#[test]
fn a_cursor_no_row_can_be_after_renders_the_empty_page() {
  let terms = [
    OrderTerm::nullable(A, FieldName::new("a"), OrderDirection::Desc),
    OrderTerm::nullable(B, FieldName::new("b"), OrderDirection::Desc),
  ];

  assert_eq!(rendered(&terms, &[None, None], Walk::Forward), "1 = 0");
}

/// The predicate joins a `WHERE` beside a filter's own conjuncts through the accumulator every
/// comparison threads — a page is *the client's filter AND this*, and nothing here knows what the
/// filter was.
///
/// # This test asserted the DEFECT, and the lead is why
///
/// It used to expect ` AND "a" > ? OR (…)`, which reads as `(<filter> AND "a" > ?) OR (…)` because
/// `AND` binds tighter than `OR` — so a page beside a filter returned rows the filter had
/// excluded. Every other assertion in this file renders the predicate ALONE, where the missing
/// outer pair changes nothing; this one has the lead that makes it visible, and it pinned the wrong
/// text. The outer bracket is now always emitted, and this is the assertion that says so.
#[test]
fn the_expansion_is_one_conjunct_beside_a_filter_s_own() {
  assert_eq!(
    rendered_with(
      &required(),
      &[Some(1), Some(2), Some(3)],
      Walk::Forward,
      " AND "
    ),
    " AND (\"a\" > ? OR (\"a\" = ? AND (\"b\" < ? OR (\"b\" = ? AND (\"id\" > ?)))))"
  );
}

/// **The refusal, reaching the construction.** A cursor minted under another order never becomes a
/// predicate at all — so there is no rendering to be wrong, and no accumulator was ever touched.
#[test]
fn a_cursor_from_another_order_never_becomes_a_predicate() {
  let terms = required();
  let other = [
    OrderTerm::new(B, FieldName::new("b"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ];
  let order = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");
  let cursor = Cursor::at(&other, [Some(2i64), Some(3)]);

  assert!(matches!(
    SqlKeyset::resume(order, &cursor, Walk::Forward),
    Err(CursorError::Order(_))
  ));
}

/// A column name reaches the statement through the backend's own column seam, so a name holding the
/// bracket character is doubled rather than closing its quoting — and the keyset carries no escaping
/// rule of its own.
#[test]
fn a_column_is_bracketed_by_the_seam_that_already_brackets_one() {
  let terms = [OrderTerm::new(
    ID,
    FieldName::new("a\"b"),
    OrderDirection::Asc,
  )];

  assert_eq!(
    rendered(&terms, &[Some(3)], Walk::Forward),
    "(\"a\"\"b\" > ?)"
  );
}

/// **The COLLECTION boundary, end to end on the dialect that has one.**
///
/// A page over an array-stored collection is the whole line the array cursor opened, and the pieces
/// meet here: the capability frame lets the term through, the sum's slot holds the list, the codec
/// writes it into one slot with its own inner framing, and the carrier binds it as ONE array
/// parameter.
///
/// The cursor value is written out rather than derived, exactly as this crate's other engine
/// fixtures are: what the derive emits is a tag byte and a delegation, and writing it here is what
/// makes this a test of the ENGINE rather than of the emitter.
#[cfg(feature = "postgres")]
mod collection_boundary {
  use super::{A, ID};
  use crate::{
    At, Carrier, ComplexComparison, Cursor, CursorError, CursorValue, FieldName, OrderDirection,
    OrderTerm, TermSubject, Walk,
    comparison::sql::{SqlConjunction, SqlKeyset, SqlOrder, tests::ROW},
    query::{CollectionBoundary, OrderCapability, partition},
  };

  /// `tags ASC, id ASC` — a collection term with the key tail that makes the order total.
  fn ascending() -> [OrderTerm; 2] {
    [
      OrderTerm::array(A, FieldName::new("tags"), OrderDirection::Asc),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
    ]
  }

  /// The same order running the other way.
  fn descending() -> [OrderTerm; 2] {
    [
      OrderTerm::array(A, FieldName::new("tags"), OrderDirection::Desc),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Desc),
    ]
  }

  /// One slot of a cursor over a row whose `tags` column is a `text[]` — the emitted sum's shape,
  /// hand-written: a tag byte per column, then the value's own bytes.
  #[derive(Debug, Clone, PartialEq)]
  enum Slot {
    Tags(Vec<String>),
    Id(i64),
  }

  impl CursorValue for Slot {
    fn write_cursor(&self, out: &mut Vec<u8>) {
      match self {
        Self::Tags(value) => {
          out.push(0);
          value.write_cursor(out);
        }
        Self::Id(value) => {
          out.push(1);
          value.write_cursor(out);
        }
      }
    }

    fn read_cursor(bytes: &[u8]) -> Option<Self> {
      let (tag, rest) = bytes.split_first()?;
      match *tag {
        0 => <Vec<String> as CursorValue>::read_cursor(rest).map(Self::Tags),
        1 => <i64 as CursorValue>::read_cursor(rest).map(Self::Id),
        _ => None,
      }
    }
  }

  impl Carrier<sqlx::Postgres> for Slot {
    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Postgres>) {
      match self {
        Self::Tags(value) => value.push_bind(qb),
        Self::Id(value) => value.push_bind(qb),
      }
    }
  }

  /// The keyset predicate for `terms` resumed at `values`, and the number of parameters behind it.
  fn rendered(terms: &[OrderTerm], values: Vec<Option<Slot>>, walk: Walk) -> (String, usize) {
    use sqlx::Execute;

    let order = SqlOrder::<sqlx::Postgres>::new(terms).expect("a renderable order");
    let cursor = Cursor::at(terms, values);
    let keyset = SqlKeyset::resume(order, &cursor, walk).expect("this cursor is this order's");
    let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
    {
      let accumulator = SqlConjunction::with_lead(&mut qb, "");
      keyset
        .apply(At::new(&ROW), accumulator)
        .expect("a constructed keyset cannot refuse");
    }
    let mut built = qb.build();
    let binds = match built.take_arguments() {
      Ok(Some(args)) => sqlx::Arguments::len(&args),
      Ok(None) | Err(_) => 0,
    };
    (built.sql().as_str().to_owned(), binds)
  }

  /// A boundary list at `tags` and `id` behind it.
  fn boundary(tags: &[&str], id: i64) -> Vec<Option<Slot>> {
    vec![
      Some(Slot::Tags(
        tags.iter().map(|tag| (*tag).to_owned()).collect(),
      )),
      Some(Slot::Id(id)),
    ]
  }

  /// **The frame lets it through, on the backend that binds one.**
  ///
  /// The term is `TermSubject::Array`, the partition is whole, and the page is served — which is the
  /// ruling, read off the shipped Postgres row rather than off a fixture.
  #[test]
  fn a_postgres_page_over_an_array_stored_collection_is_served() {
    let terms = ascending();

    assert_eq!(terms[0].subject(), TermSubject::Array);
    assert_eq!(
      <sqlx::Postgres as OrderCapability>::COLLECTION_BOUNDARY,
      CollectionBoundary::Bindable
    );
    assert_eq!(
      partition::<sqlx::Postgres>(&terms).paging::<sqlx::Postgres>(),
      Ok(&terms[..])
    );
  }

  /// **Both polarities, and the list is ONE parameter in each.**
  ///
  /// Three arms name a bind — the collection's own comparator, its tie, and the key tail — so THREE
  /// is the count whatever the list holds. An element expansion would make it grow with the
  /// boundary, which is the failure the `Carrier` row exists not to have.
  #[test]
  fn the_expansion_binds_the_whole_list_once_per_arm() {
    assert_eq!(
      rendered(&ascending(), boundary(&["hdr", "sdr"], 7), Walk::Forward),
      (
        "(\"tags\" > $1 OR (\"tags\" = $2 AND (\"id\" > $3)))".to_owned(),
        3
      )
    );
    assert_eq!(
      rendered(&descending(), boundary(&["hdr", "sdr"], 7), Walk::Forward),
      (
        "(\"tags\" < $1 OR (\"tags\" = $2 AND (\"id\" < $3)))".to_owned(),
        3
      )
    );

    // A longer boundary is the same text and the same count, which is the whole claim.
    assert_eq!(
      rendered(
        &ascending(),
        boundary(&["a", "b", "c", "d", "e", "f"], 7),
        Walk::Forward
      ),
      (
        "(\"tags\" > $1 OR (\"tags\" = $2 AND (\"id\" > $3)))".to_owned(),
        3
      )
    );
  }

  /// A BACKWARD walk inverts every comparator, collection arm included — the property the whole page
  /// rests on, and the one a forward-only test cannot see.
  #[test]
  fn the_backward_walk_inverts_the_collection_arm_too() {
    assert_eq!(
      rendered(&ascending(), boundary(&["hdr"], 7), Walk::Backward).0,
      "(\"tags\" < $1 OR (\"tags\" = $2 AND (\"id\" < $3)))"
    );
    assert_eq!(
      rendered(&descending(), boundary(&["hdr"], 7), Walk::Backward).0,
      "(\"tags\" > $1 OR (\"tags\" = $2 AND (\"id\" > $3)))"
    );
  }

  /// **The EMPTY list is a boundary and not an absence.**
  ///
  /// A collection has no null state, so the slot is PRESENT and the comparison is `>` against the
  /// empty array — which is the least value PostgreSQL's own array ordering has, so the page after
  /// it is every row with any element. `IS NOT NULL` would be the wrong predicate and would render
  /// without complaint.
  #[test]
  fn the_empty_list_is_a_present_boundary() {
    assert_eq!(
      rendered(&ascending(), boundary(&[], 7), Walk::Forward),
      (
        "(\"tags\" > $1 OR (\"tags\" = $2 AND (\"id\" > $3)))".to_owned(),
        3
      )
    );
  }

  /// **The whole crossing: mint, encode, decode, resume.** The boundary survives the one string a
  /// client ever holds, list and all, and comes back as the same values.
  #[test]
  fn the_boundary_list_survives_the_opaque_string() {
    let terms = ascending();
    let values = boundary(&["hdr", "", "sdr"], 7);
    let cursor = Cursor::at(&terms, values.clone());

    let decoded = Cursor::<Slot>::decode(&cursor.encode()).expect("this crate wrote it");
    assert_eq!(decoded, cursor);
    assert_eq!(decoded.resume(&terms), Ok(&values[..]));

    // …and the EMPTY list is the same round trip, which is the boundary a first page mints.
    let empty = Cursor::at(&terms, boundary(&[], 1));
    assert_eq!(
      Cursor::<Slot>::decode(&empty.encode()).expect("this crate wrote it"),
      empty
    );
  }

  /// A cursor minted under ANOTHER order is refused before anything renders, collection or not — the
  /// signature check is what makes the inner framing readable at all, since only the minting server
  /// knows which slot holds a list.
  #[test]
  fn a_cursor_from_another_order_is_still_refused() {
    let terms = ascending();
    let other = [OrderTerm::new(
      ID,
      FieldName::new("id"),
      OrderDirection::Asc,
    )];
    let order = SqlOrder::<sqlx::Postgres>::new(&terms).expect("a renderable order");
    let cursor = Cursor::at(&other, [Some(Slot::Id(7))]);

    assert!(matches!(
      SqlKeyset::resume(order, &cursor, Walk::Forward),
      Err(CursorError::Order(_))
    ));
  }
}

/// **The expansion over a term whose column spans SEVERAL** — one term, one cursor slot, two
/// columns compared as a ROW VALUE.
///
/// The general per-column expansion already IS the lexicographic comparison an instant needs; what
/// the composite adds is that ONE of its levels compares a pair rather than a scalar. The pair's own
/// comparison is the row value, because the cursor slot is one value binding two placeholders — and
/// a level that flattened it into `"at_secs" < ? AND "at_nanos" < ?` would be the AND-wrongness
/// `SqlKeyIn` names: a different question, well-formed, answering without an error.
mod spanning {
  use super::{ID, ROW, rendered_with};
  use crate::{
    At, ComplexComparison, Cursor, CursorValue, FieldName, OrderDirection, OrderTerm, TermName,
    Walk,
    comparison::sql::{SqlConjunction, SqlKeyset, SqlOrder},
  };

  const AT: &TermName = TermName::new("at");

  /// `at ASC, id ASC` where `at` is the framework's instant.
  fn instant() -> [OrderTerm; 2] {
    [
      OrderTerm::spanning(
        AT,
        FieldName::new("at"),
        <crate::Timestamp as crate::ColumnKind>::SEGMENTS,
        <crate::Timestamp as crate::ColumnKind>::ORDER,
        OrderDirection::Asc,
      ),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
    ]
  }

  /// The boundary instant, and the id beside it.
  fn at() -> crate::Timestamp {
    "2026-08-09T21:14:03.123456789Z"
      .parse()
      .expect("the fixture parses")
  }

  /// One slot of a cursor over an order whose first term is an instant and whose second is an id —
  /// the record's own sum, written by hand here because this module has no declaration.
  #[derive(Debug, Clone, PartialEq)]
  enum Slot {
    At(crate::Timestamp),
    Id(i64),
  }

  impl CursorValue for Slot {
    fn write_cursor(&self, out: &mut Vec<u8>) {
      match self {
        Self::At(value) => {
          out.push(0);
          value.write_cursor(out);
        }
        Self::Id(value) => {
          out.push(1);
          value.write_cursor(out);
        }
      }
    }

    fn read_cursor(bytes: &[u8]) -> Option<Self> {
      let (tag, rest) = bytes.split_first()?;
      match *tag {
        0 => CursorValue::read_cursor(rest).map(Self::At),
        1 => CursorValue::read_cursor(rest).map(Self::Id),
        _ => None,
      }
    }
  }

  impl crate::Carrier<sqlx::Sqlite> for Slot {
    fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>) {
      match self {
        Self::At(value) => crate::Carrier::push_bind(value, qb),
        Self::Id(value) => crate::Carrier::push_bind(value, qb),
      }
    }
  }

  /// The keyset over `instant()` resumed at the boundary, with the BIND COUNT beside the text — the
  /// half a row value's text cannot show, since two placeholders and one operand look alike.
  fn rendered(values: &[Option<Slot>], walk: Walk) -> (String, usize) {
    use sqlx::Execute;

    let terms = instant();
    let order = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");
    let cursor = Cursor::at(&terms, values.to_vec());
    let keyset = SqlKeyset::resume(order, &cursor, walk).expect("this cursor is this order's");
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    {
      let accumulator = SqlConjunction::with_lead(&mut qb, "");
      keyset
        .apply(At::new(&ROW), accumulator)
        .expect("a constructed keyset cannot refuse");
    }
    let mut built = qb.build();
    let binds = match built.take_arguments() {
      Ok(Some(args)) => sqlx::Arguments::len(&args),
      Ok(None) | Err(_) => 0,
    };
    (built.sql().as_str().to_owned(), binds)
  }

  /// **The composite level compares a PAIR, and the level below it breaks the tie.**
  ///
  /// The instant's arm is `("at_secs", "at_nanos") > (?, ?)` and its equality leg is the same row
  /// value — so `secs` and `nanos` are never compared independently anywhere in the expansion, which
  /// is what keeps a pre-epoch boundary on the right side of its own second.
  #[test]
  fn an_instant_level_is_a_row_value_at_both_of_its_occurrences() {
    assert_eq!(
      rendered(&[Some(Slot::At(at())), Some(Slot::Id(7))], Walk::Forward),
      (
        "((\"at_secs\", \"at_nanos\") > (?, ?) OR ((\"at_secs\", \"at_nanos\") = (?, ?) AND \
         (\"id\" > ?)))"
          .to_owned(),
        // The instant is bound TWICE — once in the arm, once in the tie — at two placeholders each,
        // and the id once: five, where a level that bound its pair as one operand would show three.
        5
      )
    );
  }

  /// A backward walk inverts the composite comparator with everything else, so the pair travels as
  /// one subject in both polarities.
  #[test]
  fn a_backward_walk_inverts_the_pairs_comparator() {
    assert_eq!(
      rendered(&[Some(Slot::At(at())), Some(Slot::Id(7))], Walk::Backward).0,
      "((\"at_secs\", \"at_nanos\") < (?, ?) OR ((\"at_secs\", \"at_nanos\") = (?, ?) AND \
       (\"id\" < ?)))"
    );
  }

  /// A NULL at a composite level renders CONJUNCTIVELY over the leaves rather than as a row-value
  /// null test, which is not a preference: measured on SQLite 3.51.0, `(a, b) IS NULL` is
  /// *row value misused*. A declaration cannot reach this state — `Option<Timestamp>` is `E0277` at
  /// the composite's own `Assemble` — so the term is built by hand, which is exactly the party the
  /// rendering has to be total for.
  #[test]
  fn a_null_at_a_composite_level_tests_the_leaves() {
    let terms = [
      OrderTerm::spanning_nullable(
        AT,
        FieldName::new("at"),
        <crate::Timestamp as crate::ColumnKind>::SEGMENTS,
        <crate::Timestamp as crate::ColumnKind>::ORDER,
        OrderDirection::Asc,
      ),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
    ];
    let order = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");
    let cursor = Cursor::at(&terms, vec![None, Some(Slot::Id(7))]);
    let keyset = SqlKeyset::resume(order, &cursor, Walk::Forward).expect("this order's cursor");
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    {
      let accumulator = SqlConjunction::with_lead(&mut qb, "");
      keyset
        .apply(At::new(&ROW), accumulator)
        .expect("a constructed keyset cannot refuse");
    }
    assert_eq!(
      qb.into_string(),
      "((\"at_secs\" IS NOT NULL AND \"at_nanos\" IS NOT NULL) OR \
       ((\"at_secs\" IS NULL AND \"at_nanos\" IS NULL) AND (\"id\" > ?)))"
    );
  }

  /// The ORDINARY order is untouched by any of it: a term with no segments renders exactly the
  /// column and the bare operand it always did.
  #[test]
  fn a_scalar_level_is_unchanged() {
    assert_eq!(
      rendered_with(
        &[OrderTerm::new(
          ID,
          FieldName::new("id"),
          OrderDirection::Asc
        )],
        &[Some(7i64)],
        Walk::Forward,
        "",
      ),
      "(\"id\" > ?)"
    );
  }
}

/// **THE TERM WHOSE COMPOSITE CARRIES A DERIVED LEAF** — ingraph #454, and the two numberings one
/// subject is read through.
///
/// The shape is the shipped media instant's: a declared count, the unit it is counted in, and a
/// DERIVED position beside them that is `NULL` for a value past its type's ceiling. It is built by
/// hand rather than imported, for the reason the nullable-composite case above is: this module's
/// lane carries no citizen vocabulary, and the rendering has to be total over the shapes a person
/// can write.
///
/// What the two tests below pin is the SPLIT. A null test asks whether the term's VALUE is at this
/// row, so it walks the value leaves; a comparison has to name exactly what the `ORDER BY` sorted
/// by, so it stays the whole width. Narrowing both would break the page at every boundary; narrowing
/// neither is the defect.
mod derived_leaf {
  use super::{ID, rendered_with};
  use crate::{
    ColumnName, ColumnShape, FieldName, OrderDirection, OrderTerm, TermName, Walk,
    comparison::sql::SqlOrder,
  };

  const AT: &TermName = TermName::new("at");

  /// A citizen shaped as `MediaTimestamp` is: three columns that hold the value and one derived
  /// beside them, with the unit itself a nested composite so the walk descends on the way.
  const SEGMENTS: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("pts")),
    ColumnShape::Composite {
      field: Some(ColumnName::new("timebase")),
      segments: &[
        ColumnShape::Plain(ColumnName::new("num")),
        ColumnShape::Plain(ColumnName::new("den")),
      ],
    },
    ColumnShape::Nullable(ColumnName::new("nanos")),
  ];

  /// `at ASC, id ASC`, the instant NULLABLE — the order an optional citizen reaches.
  fn terms() -> [OrderTerm; 2] {
    [
      OrderTerm::spanning_nullable(AT, FieldName::new("at"), SEGMENTS, &[], OrderDirection::Asc),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
    ]
  }

  /// **THE WIDTHS ARE TWO NUMBERS**, which is the whole mechanism the repair rests on.
  #[test]
  fn the_term_counts_its_columns_and_its_value_columns_apart() {
    let [at, id] = terms();

    assert_eq!(at.width(), 4, "pts, num, den, nanos");
    assert_eq!(
      at.value_width(),
      3,
      "and the derived position is not one of them"
    );

    assert_eq!(id.width(), 1, "a scalar term's one column");
    assert_eq!(id.value_width(), 1, "is also its value");
  }

  /// **THE NULL TEST NAMES THE VALUE COLUMNS AND NOT THE DERIVED ONE — ingraph #454.**
  ///
  /// A cursor whose instant slot is absent renders the ascending null arm — *every row above the
  /// `NULL`s* — and its equality leg, and both are presence questions. With `"at_nanos"` in them, a
  /// row past the ±292-year ceiling satisfies NEITHER: it is not in the `NULL` group, its value
  /// columns being present, and it is not above the group, its derived column being `NULL`. So no
  /// page could reach it, while the decode read it back whole and the presence filter called it
  /// present. Three readers, one row, two answers.
  ///
  /// The text is asserted rather than the row set for this module's own reason — the meaning is
  /// measured against engines elsewhere — and what the text has to show is exactly which columns
  /// each test names.
  #[test]
  fn a_null_test_over_a_derived_composite_skips_the_derived_leaf() {
    let rendered = rendered_with(&terms(), &[None, Some(7i64)], Walk::Forward, "");

    assert_eq!(
      rendered,
      "((\"at_pts\" IS NOT NULL AND \"at_timebase_num\" IS NOT NULL AND \"at_timebase_den\" IS NOT \
       NULL) OR ((\"at_pts\" IS NULL AND \"at_timebase_num\" IS NULL AND \"at_timebase_den\" IS \
       NULL) AND (\"id\" > ?)))"
    );
    assert!(
      !rendered.contains("at_nanos"),
      "the derived column is absent from a presence question by name, which is the claim the \
       column list above could satisfy by accident"
    );
  }

  /// **AND THE COMPARISON IS STILL THE WHOLE WIDTH**, which is not an oversight but the other half
  /// of the same law.
  ///
  /// The `ORDER BY` renders one entry per COLUMN of the term, derived leaf included, and this
  /// predicate resumes that order — so a row value that named three columns where the ordering
  /// sorted by four would skip or repeat exactly the rows at a boundary, which is the one failure
  /// [`SqlOrder`] exists to prevent. Pinned so that narrowing it later is a red test rather than a
  /// silent page.
  #[test]
  fn a_comparison_over_a_derived_composite_names_every_column() {
    let terms = terms();
    let _ = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");

    let rendered = rendered_with(&terms, &[Some(1i64), Some(7i64)], Walk::Forward, "");

    assert!(
      rendered.contains("(\"at_pts\", \"at_timebase_num\", \"at_timebase_den\", \"at_nanos\") > ("),
      "the arm compares what the ORDER BY sorted by: {rendered}"
    );
  }
}