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
//! The PACKAGE each lane renders, asserted as the exact stage list a caller would run.
//!
//! # A golden here is a VALUE, which is what the second backend buys over the first
//!
//! A SQL lane's test compares a string, so a whitespace change is a diff and a structural change
//! may not be. A pipeline is BSON, so these compare documents: key order is preserved by
//! [`bson::Document`] and is part of what is asserted, because a pipeline's stage order decides the
//! answer.

use bson::{Document, doc};

use super::{MongoPipeline, address, ordered, ordered_with, scan};
use crate::{
  Cursor, FieldName, OrderDirection, OrderTerm, TermName, Walk,
  comparison::mongo::{Mongo, MongoLoweringError},
  query::{
    DEPTH_CEILING, Unpushable,
    mongo::{
      MongoKeyset, MongoOrder, MongoQueryError,
      tests::{
        DeepSubjects, ShotCursor, ShotFilter, ShotMongo, ShotOrder, by_cover_title, covering,
        subjects, terms, titled,
      },
    },
    partition,
  },
};

/// The `$match` every filtered golden below opens with.
fn matched() -> Document {
  doc! { "$match": { "title": { "$eq": "a red car" } } }
}

/// Lane 1 — the whole set, in whatever sequence the engine answers in. NO `$sort`, which is the
/// ruling: a sort nobody asked for is work every document pays for.
#[test]
fn an_unordered_scan_is_one_match_stage() {
  let filter = titled("a red car");
  let package = scan::<ShotMongo>(Some(&filter), None).expect("the filter lowers");

  assert_eq!(package.collection(), FieldName::new("shot"));
  assert_eq!(package.pipeline(), [matched()]);
}

/// An empty filter still writes its `$match`, because `{$match: {}}` matches every document and one
/// shape is what makes a package a thing a reader can check.
#[test]
fn an_unfiltered_scan_still_writes_its_match() {
  let package = scan::<ShotMongo>(None, None).expect("nothing to lower");

  assert_eq!(package.pipeline(), [doc! { "$match": {} }]);
}

/// Lane 2 — any N documents, asked for honestly: a ceiling and still no order.
#[test]
fn a_ceiling_adds_a_limit_and_no_sort() {
  let filter = titled("a red car");
  let package = scan::<ShotMongo>(Some(&filter), Some(25)).expect("the filter lowers");

  assert_eq!(package.pipeline(), [matched(), doc! { "$limit": 25i64 }]);
}

/// Lane 3 — the ordered scan: the completed order, no ceiling, no resume predicate. The `_id: 1`
/// tail is the completed order's, and it is what every page of this query resumes on.
#[test]
fn an_ordered_scan_is_a_match_and_a_sort() {
  let filter = titled("a red car");
  let terms = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package =
    ordered::<ShotMongo, ShotCursor>(Some(&filter), order, None, Walk::Forward, None, None)
      .expect("the filter lowers");

  assert_eq!(
    package.pipeline(),
    [matched(), doc! { "$sort": { "title": 1, "_id": 1 } }]
  );
}

/// THE FLAT PAGE — page one of a walk, and the shape the module note promises: `$match`, `$sort`,
/// `$limit`, in that order and no other.
///
/// The `$limit` is the page size PLUS ONE, which is what answers *is there another one this way*.
/// The `+1` is the lane's rather than this function's, so what is pinned here is that the number
/// the caller bound is the number the stage carries.
#[test]
fn the_first_page_is_match_sort_limit() {
  let filter = titled("a red car");
  let terms = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package =
    ordered::<ShotMongo, ShotCursor>(Some(&filter), order, None, Walk::Forward, Some(3), None)
      .expect("the filter lowers");

  assert_eq!(
    package.pipeline(),
    [
      matched(),
      doc! { "$sort": { "title": 1, "_id": 1 } },
      doc! { "$limit": 3i64 },
    ]
  );
}

/// PAGE TWO — the resume predicate folded into the SAME `$match` as the filter, and the rest of the
/// pipeline unchanged.
///
/// One `$match` rather than two, which is what threading both through one accumulator buys: a
/// second stage would be the same predicate with a boundary the planner has to fuse back together,
/// and the two conjuncts would be free to disagree about which document they were addressed at.
#[test]
fn the_second_page_folds_the_keyset_into_the_same_match() {
  let filter = titled("a red car");
  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");
  let package = ordered::<ShotMongo, ShotCursor>(
    Some(&filter),
    order,
    Some(&keyset),
    Walk::Forward,
    Some(3),
    None,
  )
  .expect("the filter lowers");

  assert_eq!(
    package.pipeline(),
    [
      doc! {
        "$match": {
          "title": { "$eq": "a red car" },
          "$and": [ {
            "$or": [
              { "title": { "$gt": "a red car" } },
              { "title": { "$eq": "a red car" }, "_id": { "$gt": 12i64 } },
            ]
          } ],
        }
      },
      doc! { "$sort": { "title": 1, "_id": 1 } },
      doc! { "$limit": 3i64 },
    ]
  );
}

/// A `$skip` sits BETWEEN the sort and the limit, and the order of the three is the only order that
/// answers: a skip after the limit skips inside the page, and a limit before the sort sorts an
/// arbitrary N.
#[test]
fn an_offset_page_skips_before_it_limits() {
  let terms = terms(&[]);
  let order = MongoOrder::new(&terms).expect("the id tail");
  let package =
    ordered::<ShotMongo, ShotCursor>(None, order, None, Walk::Forward, Some(3), Some(40))
      .expect("nothing to lower");

  assert_eq!(
    package.pipeline(),
    [
      doc! { "$match": {} },
      doc! { "$sort": { "_id": 1 } },
      doc! { "$skip": 40i64 },
      doc! { "$limit": 3i64 },
    ]
  );
}

/// A skip past what `$skip` can hold is a typed refusal rather than a panic or a silent clamp — the
/// wound `SqlQueryError::Skip` is the scar of, arrived at from the other backend's wire type.
#[test]
fn a_skip_past_the_ceiling_is_refused() {
  let terms = terms(&[]);
  let order = MongoOrder::new(&terms).expect("the id tail");
  let refused =
    ordered::<ShotMongo, ShotCursor>(None, order, None, Walk::Forward, Some(3), Some(u64::MAX));

  assert!(matches!(refused, Err(MongoQueryError::Skip(u64::MAX))));
}

/// `get` is one `$match` on `_id` and NO `$limit`: `_id` is unique by the server's own
/// construction, so the predicate names at most one document by the storage engine's law.
#[test]
fn an_address_is_one_match_on_the_underscore_id() {
  let package = address::<ShotMongo>(&12).expect("the id crosses");

  assert_eq!(package.collection(), FieldName::new("shot"));
  assert_eq!(
    package.pipeline(),
    [doc! { "$match": { "_id": { "$eq": 12i64 } } }]
  );
}

/// A flat query READS one collection — its own — which is what the execution lane's default read
/// concern is chosen on.
#[test]
fn a_flat_package_reads_one_collection() {
  let package = scan::<ShotMongo>(None, None).expect("nothing to lower");

  assert_eq!(package.reads(), [FieldName::new("shot")]);
  assert!(!package.spans_collections());
}

/// **A RELATION in the filter joins, and the reads grow with it** — which is what flips the
/// execution lane's read concern to a snapshot.
///
/// The stage order is the whole pin: the `$match` on this document's own fields runs FIRST, so the
/// join is over fewer documents; the join runs before the `$sort` and the `$limit`, so a document it
/// excludes is never ordered and never counted toward the page. A `$lookup` after the `$limit`
/// renders perfectly well and pages a set the filter refuses.
#[test]
fn a_relation_joins_before_the_sort_and_grows_the_reads() {
  let filter = covering("Autumn");
  let terms = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package =
    ordered::<ShotMongo, ShotCursor>(Some(&filter), order, None, Walk::Forward, Some(3), None)
      .expect("the filter lowers");

  assert_eq!(
    package.pipeline(),
    [
      doc! { "$match": {} },
      doc! { "$lookup": {
        "from": "keyframe",
        "localField": "cover_id",
        "foreignField": "_id",
        "as": "__ig_keyframe_1__",
        "pipeline": [ { "$match": { "title": { "$eq": "Autumn" } } } ],
      } },
      doc! { "$match": { "__ig_keyframe_1__": { "$ne": [] } } },
      doc! { "$project": { "__ig_keyframe_1__": 0 } },
      doc! { "$sort": { "title": 1, "_id": 1 } },
      doc! { "$limit": 3i64 },
    ]
  );

  assert_eq!(
    package.reads(),
    [FieldName::new("shot"), FieldName::new("keyframe")]
  );
  assert!(
    package.spans_collections(),
    "a joined package runs under the snapshot concern"
  );
}

/// The SAME record with its relation position UNASKED joins nothing and reads one collection — which
/// is what keeps the policy a fact about the QUERY rather than about the declaration.
#[test]
fn an_unasked_relation_position_neither_joins_nor_spans() {
  let package = scan::<ShotMongo>(Some(&titled("a red car")), None).expect("the filter lowers");

  assert_eq!(package.pipeline(), [matched()]);
  assert_eq!(package.reads(), [FieldName::new("shot")]);
  assert!(!package.spans_collections());
}

/// A package built by HAND over two collections — the escape hatch a caller assembling their own
/// stages goes through — spans them by the same rule the rendered one does.
#[test]
fn a_package_over_two_collections_spans_them() {
  let package = MongoPipeline::new(
    FieldName::new("shot"),
    vec![doc! { "$match": {} }, doc! { "$unionWith": "keyframe" }],
    vec![FieldName::new("shot"), FieldName::new("keyframe")],
  );

  assert_eq!(package.reads().len(), 2);
  assert!(package.spans_collections());
}

/// **THE NESTED PAGE ONE, verbatim.** The join in front, then the sequence every lane writes — and
/// the `$sort` naming the field `$addFields` materialized rather than the reference the term
/// carries.
///
/// The `$match` sits BEHIND the join, which is the one thing a nested pipeline moves: the resume
/// predicate compares the materialized value, and there is nothing to compare until `$addFields`
/// has written it. Page one has no predicate to resume with and keeps the position anyway, so the
/// two pages of one walk are one shape.
#[test]
fn a_nested_first_page_joins_before_it_matches() {
  let filter = titled("a red car");
  let written = by_cover_title();
  let terms = terms(&written);
  let subjects = subjects(&written);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package = ordered_with::<ShotMongo, ShotCursor, _>(
    Some(&filter),
    order,
    None,
    Walk::Forward,
    Some(3),
    None,
    &subjects,
  )
  .expect("the filter lowers");

  assert_eq!(
    package.pipeline(),
    [
      doc! { "$lookup": {
        "from": "keyframe",
        "localField": "cover_id",
        "foreignField": "_id",
        "as": "__ig_keyframe_1__",
      } },
      doc! { "$addFields": { "__ig_ord0__": { "$first": "$__ig_keyframe_1__.title" } } },
      doc! { "$project": { "__ig_keyframe_1__": 0 } },
      matched(),
      doc! { "$sort": { "__ig_ord0__": 1, "_id": 1 } },
      doc! { "$limit": 3i64 },
    ]
  );
}

/// **THE NESTED PAGE TWO, verbatim.** The keyset resumes on `__ig_ord0__`, which it can because the
/// `$match` is behind the `$addFields` that wrote it — so the whole resume predicate is expressible
/// in the ordinary place and no second `$match` is needed.
///
/// This is the PIN for the one-authority claim: the `$sort` entry, the comparison arm and the
/// equality leg all name `__ig_ord0__`, and they do so because none of the three spells the name
/// itself. A term whose subject was forgotten in any one of them would resume against the
/// `cover_id` reference — a perfectly good aggregation that answers, with the wrong documents.
#[test]
fn a_nested_second_page_resumes_on_the_materialized_field() {
  let written = by_cover_title();
  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");
  let package = ordered_with::<ShotMongo, ShotCursor, _>(
    None,
    order,
    Some(&keyset),
    Walk::Forward,
    Some(3),
    None,
    &subjects,
  )
  .expect("nothing to lower");

  assert_eq!(
    package.pipeline(),
    [
      doc! { "$lookup": {
        "from": "keyframe",
        "localField": "cover_id",
        "foreignField": "_id",
        "as": "__ig_keyframe_1__",
      } },
      doc! { "$addFields": { "__ig_ord0__": { "$first": "$__ig_keyframe_1__.title" } } },
      doc! { "$project": { "__ig_keyframe_1__": 0 } },
      doc! { "$match": {
        "$and": [ {
          "$or": [
            { "__ig_ord0__": { "$gt": "Autumn" } },
            { "__ig_ord0__": { "$eq": "Autumn" }, "_id": { "$gt": 12i64 } },
          ]
        } ],
      } },
      doc! { "$sort": { "__ig_ord0__": 1, "_id": 1 } },
      doc! { "$limit": 3i64 },
    ]
  );
}

/// A nested order READS the collection it joined, and the package says so — which is what the
/// execution lane's read concern is chosen on. The party that added the stage is the party that
/// named the collection, so the fact cannot be left behind by a stage that was.
#[test]
fn a_nested_package_reads_the_collection_it_joined() {
  let written = by_cover_title();
  let terms = terms(&written);
  let subjects = subjects(&written);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package = ordered_with::<ShotMongo, ShotCursor, _>(
    None,
    order,
    None,
    Walk::Forward,
    None,
    None,
    &subjects,
  )
  .expect("nothing to lower");

  assert_eq!(
    package.reads(),
    [FieldName::new("shot"), FieldName::new("keyframe")]
  );
  assert!(package.spans_collections());
}

/// A FLAT order still reads one collection through the same builder, so the concern a plain page
/// runs at is unchanged by the seam existing.
#[test]
fn a_flat_order_through_the_subjects_builder_still_reads_one_collection() {
  let terms = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package = ordered::<ShotMongo, ShotCursor>(None, order, None, Walk::Forward, None, None)
    .expect("nothing to lower");

  assert_eq!(package.reads(), [FieldName::new("shot")]);
  assert!(!package.spans_collections());
}

/// **The CEILING at the package.** A nesting past the depth the target's join fields were minted
/// for refuses the whole package rather than half a pipeline, and the refusal is the RELATION
/// family's own — the same sentence, naming the same collection, that a relation nested that deep
/// gets.
#[test]
fn a_nested_order_past_the_ceiling_refuses_the_package() {
  let terms = terms(&by_cover_title());
  let order = MongoOrder::new(&terms).expect("two terms");
  let refused = ordered_with::<ShotMongo, ShotCursor, _>(
    None,
    order,
    None,
    Walk::Forward,
    None,
    None,
    &DeepSubjects::crossing(DEPTH_CEILING),
  );

  assert!(matches!(
    refused,
    Err(MongoQueryError::Lowering(MongoLoweringError::RelationDepth(depth)))
      if depth.table() == FieldName::new("shot") && depth.ceiling() == DEPTH_CEILING
  ));
}

/// The stages are handed over by value, which is what the driver's `aggregate` consumes.
#[test]
fn a_package_gives_its_stages_up() {
  let package = scan::<ShotMongo>(None, Some(5)).expect("nothing to lower");
  let stages = package.into_pipeline();

  assert_eq!(stages, [doc! { "$match": {} }, doc! { "$limit": 5i64 }]);
}

/// The filter's own type is not narrowed by any of this — a package is built from the record's
/// vocabulary binding rather than from a slot of the engine's.
#[test]
fn the_filter_is_the_records_own_comparison() {
  let filter: ShotFilter = titled("a red car");
  let package = scan::<ShotMongo>(Some(&filter), None).expect("the filter lowers");

  assert_eq!(package.pipeline(), [matched()]);
}

/// **THE COLLISION SHAPE, answered.** One pipeline carrying BOTH a relation filter and a nested
/// order into the SAME collection at the SAME depth — which is the only shape in which the two
/// join-field mints could land one document key twice.
///
/// They mint the same name, `__ig_keyframe_1__`, because there is only one mint: a hop takes its
/// field from the target's own `ALIASES` exactly as a relation at that depth does. What keeps the
/// repeat harmless is that neither run holds its field open — the ordering's `$project` closes it
/// before the `$match`, and the relation's closes it before anything after the relation opens. The
/// two runs are disjoint in time, so the second `$lookup` writes into a document where the first's
/// field no longer exists.
///
/// The only minted key that SURVIVES is `__ig_ord0__`, and it is injective against every join field
/// by the frame law stated at the mint.
///
/// Breaking either `$project` reds this, and it is the assertion to read first if one is ever
/// dropped as redundant.
#[test]
fn a_relation_and_a_nested_order_into_one_collection_do_not_hold_one_name_twice() {
  let filter = covering("Autumn");
  let written = by_cover_title();
  let terms = terms(&written);
  let subjects = subjects(&written);
  let order = MongoOrder::new(&terms).expect("two terms");
  let package = ordered_with::<ShotMongo, ShotCursor, _>(
    Some(&filter),
    order,
    None,
    Walk::Forward,
    Some(3),
    None,
    &subjects,
  )
  .expect("the filter lowers");

  assert_eq!(
    package.pipeline(),
    [
      // The ORDERING's run: opened, read, closed — all before the `$match`.
      doc! { "$lookup": {
        "from": "keyframe",
        "localField": "cover_id",
        "foreignField": "_id",
        "as": "__ig_keyframe_1__",
      } },
      doc! { "$addFields": { "__ig_ord0__": { "$first": "$__ig_keyframe_1__.title" } } },
      doc! { "$project": { "__ig_keyframe_1__": 0 } },
      doc! { "$match": {} },
      // The RELATION's run: the same name, opened after the ordering's was dropped.
      doc! { "$lookup": {
        "from": "keyframe",
        "localField": "cover_id",
        "foreignField": "_id",
        "as": "__ig_keyframe_1__",
        "pipeline": [ { "$match": { "title": { "$eq": "Autumn" } } } ],
      } },
      doc! { "$match": { "__ig_keyframe_1__": { "$ne": [] } } },
      doc! { "$project": { "__ig_keyframe_1__": 0 } },
      doc! { "$sort": { "__ig_ord0__": 1, "_id": 1 } },
      doc! { "$limit": 3i64 },
    ]
  );

  // One collection joined twice is still one collection, which is what the read concern asks.
  assert_eq!(
    package.reads(),
    [FieldName::new("shot"), FieldName::new("keyframe")]
  );
  assert!(package.spans_collections());
}

/// A written order this backend cannot carry whole — `title` named twice, which an `ORDER BY` reads
/// as a redundant entry and a `$sort` document cannot hold at all.
fn repeated() -> [OrderTerm; 3] {
  [
    OrderTerm::new(
      TermName::new("title"),
      FieldName::new("title"),
      OrderDirection::Asc,
    ),
    OrderTerm::new(
      TermName::new("caption"),
      FieldName::new("title"),
      OrderDirection::Desc,
    ),
    OrderTerm::new(
      TermName::new("id"),
      FieldName::new("id"),
      OrderDirection::Asc,
    ),
  ]
}

/// One document as the degrade path sees it: the field the statement sorted by, and the id the
/// completion breaks its ties with.
#[derive(Debug)]
struct Returned {
  title: &'static str,
  id: i64,
}

/// The value a document holds at one term — the caller's half of the completion.
///
/// ONE sum across the slots, which is what a real cursor value is. Its derived [`Ord`] compares the
/// VARIANT first, and that is harmless here for the reason it is harmless there: a term yields one
/// variant, so two values being compared are always the same variant and the discriminant never
/// decides.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Sortable {
  Text(&'static str),
  Number(i64),
}

/// **THE DEGRADE PATH, end to end on the backend that has one.** The frame splits the order, the
/// statement carries the PREFIX, and the remainder is applied in memory to the documents that came
/// back.
///
/// The `$sort` holding `title` alone is what makes the split visible: the id tail is in the
/// remainder, so the server returns the `title` groups in whatever sequence it chose and the
/// completion is what puts them in the written order. A degrade that silently kept the whole order
/// in the statement would render `{title: 1, _id: 1}` and this would red.
#[test]
fn a_repeated_order_degrades_into_a_prefix_sort_and_a_memory_completion() {
  let written = repeated();
  let split = partition::<Mongo>(&written);

  assert_eq!(split.cause(), Some(Unpushable::Repetition));
  assert!(
    MongoOrder::new(&written).is_err(),
    "the whole order has no `$sort` — which is the backstop, not the plan"
  );

  let order = MongoOrder::new(split.pushable()).expect("the frame's own prefix");
  let package = ordered::<ShotMongo, ShotCursor>(None, order, None, Walk::Forward, None, None)
    .expect("nothing to lower");

  assert_eq!(
    package.pipeline(),
    [doc! { "$match": {} }, doc! { "$sort": { "title": 1 } }]
  );

  // The `title` groups are the statement's; inside them the sequence is the server's, which is what
  // the completion is for. `alpha` stays ahead of `beta` because the completion walks the PREFIX
  // first — a sort by the remainder alone would make its leading `title DESC` the primary key and
  // hand back `[2, 3, 1]`.
  let mut returned = vec![
    Returned {
      title: "alpha",
      id: 3,
    },
    Returned {
      title: "alpha",
      id: 1,
    },
    Returned {
      title: "beta",
      id: 2,
    },
  ];
  split.apply(&mut returned, |row, term| match term.column().as_ref() {
    "title" => Some(Sortable::Text(row.title)),
    _ => Some(Sortable::Number(row.id)),
  });

  assert_eq!(
    returned.iter().map(|row| row.id).collect::<Vec<_>>(),
    [1, 3, 2]
  );
}

/// **THE (i) LAW.** The same order with a cursor is REFUSED rather than degraded, and it is refused
/// twice over: by name, before anything renders, and by the cursor itself, which was minted under an
/// order the prefix is not.
///
/// Breaking the named refusal — serving the prefix and completing in memory anyway — leaves the
/// second one standing and turns a clear sentence into `CursorError::Order`, which is why both are
/// asserted here.
#[test]
fn a_page_over_a_degraded_order_is_refused_and_not_completed() {
  let written = repeated();
  let split = partition::<Mongo>(&written);
  let refusal = split
    .paging::<Mongo>()
    .expect_err("a page's order is the statement's");

  assert_eq!(refusal.term(), TermName::new("caption"));
  assert_eq!(refusal.cause(), Unpushable::Repetition);

  let cursor = Cursor::at(
    &written,
    vec![
      Some(ShotCursor::Title("alpha".to_owned())),
      Some(ShotCursor::Title("alpha".to_owned())),
      Some(ShotCursor::Id(12)),
    ],
  );
  let order = MongoOrder::new(split.pushable()).expect("the frame's own prefix");

  assert!(
    MongoKeyset::resume(order, &cursor, Walk::Forward).is_err(),
    "a cursor minted under the whole order is not the prefix's"
  );
}