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
//! The two relation kinds' rendering, their refusals, and the collapse.
//!
//! # The goldens are VALUES, and every one of them names the mutation it catches
//!
//! A pipeline is BSON, so these compare `bson::Document`s rather than text: key order is preserved
//! and is part of what is asserted, because a stage's order decides the answer. What a relation gets
//! wrong renders perfectly well — a join matching `_id` against `_id`, an `all` whose `$nor` sits
//! outside the join's own pipeline, a `$project` that drops the field before the `$match` reads it —
//! so each pin below says which of those it would catch.
//!
//! # The ANSWERS are prose, and [`corpus`] is where they are
//!
//! `ci/test-matrix.sh` provisions no server — the SQL family's engine walks were run by hand and
//! recorded beside the code they measure — so what runs here is the RENDERING. The two-table corpus
//! the SQL family answers against is replayed as expected sets in [`corpus`]'s note, computed by
//! hand, with the one quantifier whose answer DIFFERS between the backends stated as a difference
//! rather than left to be discovered.

use bson::{Document, doc};

use super::{MongoDerivedComparison, MongoRefComparison, MongoRelatedDocument};
use crate::{
  At, FieldName, RecordAddress, ScalarFilter,
  comparison::{
    Backend, CollapsibleComparison, ComplexComparison, TryFromFilter,
    mongo::{
      Mongo, MongoConjunction, MongoCountComparison, MongoLoweringError, MongoPredicate,
      MongoScalarComparison, RelationDepthError, RelationWidthError,
    },
  },
};

/// The document every predicate here constrains: a `shot`, keyed by `id`, carrying a `cover_id` that
/// points at a keyframe.
const SHOT: RecordAddress = RecordAddress::new(FieldName::new("shot"), &[FieldName::new("id")]);
/// The collection a `cover_id` points AT, and — read the other way — the one whose `shot_id` points
/// back.
const KEYFRAME: MongoRelatedDocument = MongoRelatedDocument::new(
  RecordAddress::new(FieldName::new("keyframe"), &[FieldName::new("id")]),
  &[
    "__ig_keyframe_0__",
    "__ig_keyframe_1__",
    "__ig_keyframe_2__",
  ],
);
/// A document addressed by two fields — what neither kind has a second name for, and what has no
/// `_id` for a join to meet.
const SPLICE: MongoRelatedDocument = MongoRelatedDocument::new(
  RecordAddress::new(
    FieldName::new("splice"),
    &[FieldName::new("media_id"), FieldName::new("splice_id")],
  ),
  &["__ig_splice_0__", "__ig_splice_1__"],
);
/// A record that refers to its OWN kind. Two names past depth zero, which is what the two-level pin
/// needs.
const SCENE: MongoRelatedDocument = MongoRelatedDocument::new(
  RecordAddress::new(FieldName::new("scene"), &[FieldName::new("id")]),
  &["__ig_scene_0__", "__ig_scene_1__", "__ig_scene_2__"],
);
/// The same collection with ONE name minted, so depth one is already past the ceiling — what the
/// refusal is exercised against without nesting eight levels of fixture.
const SHALLOW: MongoRelatedDocument = MongoRelatedDocument::new(
  RecordAddress::new(FieldName::new("scene"), &[FieldName::new("id")]),
  &["__ig_scene_0__"],
);
/// The `scene` field carrying its parent's id.
const PARENT_ID: &FieldName = FieldName::new("parent_id");
/// The `keyframe` field carrying a shot's id, which is what a reverse position joins on.
const SHOT_ID: &FieldName = FieldName::new("shot_id");

type Scalar = MongoScalarComparison<i64>;
type Text = MongoScalarComparison<String>;
type Ref = MongoRefComparison<Keyframe>;
type Derived = MongoDerivedComparison<Keyframe>;

/// A stand-in for a generated ENTITY comparison: two fields walked below whatever document it is
/// applied at, plus the id projection a relation collapses through.
///
/// Written by hand because the emission that would write one is blocked on a fact this expansion
/// cannot reach — see `ingraph-codegen`'s `emit::query` note — and because the two things a relation
/// asks of a target comparison are exactly these: render at an address, and say whether the id is
/// all it constrains.
#[derive(Debug, Clone, PartialEq)]
struct Keyframe {
  id: Scalar,
  title: Text,
  /// Whether the id's operators SURVIVE the collapse — the second half of
  /// [`CollapsibleComparison`]'s law, which a generated comparison answers from the operators it set
  /// and this fixture answers from a field.
  referential: bool,
}

impl Keyframe {
  fn new() -> Self {
    Self {
      id: Scalar::new(),
      title: Text::new(),
      referential: true,
    }
  }

  fn with_id(mut self, id: i64) -> Self {
    self.id = Scalar::try_from_filter(ScalarFilter::<i64>::new().with_eq(id)).unwrap();
    self
  }

  fn with_title(mut self, title: &str) -> Self {
    self.title =
      Text::try_from_filter(ScalarFilter::<std::string::String>::new().with_eq(title.to_owned()))
        .unwrap();
    self
  }

  /// The id is constrained and the shape does NOT survive a dangling reference, so the target
  /// declines the collapse and the relation pays for its join.
  const fn unreferential(mut self) -> Self {
    self.referential = false;
    self
  }
}

impl ComplexComparison<Mongo> for Keyframe {
  fn conjuncts(&self) -> usize {
    self.id.conjuncts() + self.title.conjuncts()
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    let id = at.frame(FieldName::new("id"));
    let builder = self.id.apply(id.at(), builder)?;
    let title = at.frame(FieldName::new("title"));
    self.title.apply(title.at(), builder)
  }
}

impl CollapsibleComparison<Mongo> for Keyframe {
  type Id = Scalar;

  fn only_id(&self) -> Option<&Scalar> {
    (self.referential && self.title.is_empty()).then_some(&self.id)
  }
}

/// A comparison whose whole content is ONE nested relation, so a forward hop can carry a reverse one
/// and the depths compose.
///
/// It renders the nested predicate at the address it is handed and nothing else — which is what
/// makes the join fields in the assertions below the ENGINE's rather than the fixture's.
#[derive(Debug, Clone, PartialEq)]
struct Nesting(Derived);

impl ComplexComparison<Mongo> for Nesting {
  fn conjuncts(&self) -> usize {
    ComplexComparison::conjuncts(&self.0)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Mongo as Backend>::Builder<'q>,
  ) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
    self.0.apply(at, builder)
  }
}

impl CollapsibleComparison<Mongo> for Nesting {
  type Id = Scalar;

  /// Never — a relation inside a relation is not a constraint on the outer target's id, so the
  /// collapse must not swallow it. Answering `Some` here would drop the whole inner predicate.
  fn only_id(&self) -> Option<&Scalar> {
    None
  }
}

/// What a lowering answered with at `at`: its `$match` document, the stages its joins contributed,
/// and what those read — or the refusal instead.
fn lowered(
  at: At<'_>,
  comparison: &impl ComplexComparison<Mongo>,
) -> Result<MongoPredicate, MongoLoweringError> {
  Ok(
    comparison
      .apply(at, MongoConjunction::new())?
      .into_predicate(),
  )
}

/// [`lowered`] at a named field of [`SHOT`] — what the forward kind needs, the reference being a
/// field of this document.
fn at_field(field: &str, comparison: &impl ComplexComparison<Mongo>) -> MongoPredicate {
  let frame = At::new(&SHOT).frame(FieldName::new(field));
  lowered(frame.at(), comparison).expect("a rendered predicate")
}

/// The `$lookup` a forward reference over [`KEYFRAME`] opens, given the pipeline it runs.
fn forward_lookup(pipeline: bson::Bson) -> Document {
  doc! { "$lookup": {
    "from": "keyframe",
    "localField": "cover_id",
    "foreignField": "_id",
    "as": "__ig_keyframe_1__",
    "pipeline": pipeline,
  } }
}

/// The `$lookup` a reverse position over [`KEYFRAME`] opens, with no pipeline of its own.
fn reverse_lookup() -> Document {
  doc! { "$lookup": {
    "from": "keyframe",
    "localField": "_id",
    "foreignField": "shot_id",
    "as": "__ig_keyframe_1__",
  } }
}

/// The same, running `pipeline` over the joined documents.
fn reverse_lookup_with(pipeline: bson::Bson) -> Document {
  doc! { "$lookup": {
    "from": "keyframe",
    "localField": "_id",
    "foreignField": "shot_id",
    "as": "__ig_keyframe_1__",
    "pipeline": pipeline,
  } }
}

/// `{$project: {<the keyframe join field>: 0}}` — the stage that drops the array again, and the one
/// that makes a repeated join field harmless.
fn dropped() -> Document {
  doc! { "$project": { "__ig_keyframe_1__": 0 } }
}

/// **The forward reference is a `$lookup` semi-join through the reference field**, and every name in
/// it comes from a different party: the `localField` from the address it was applied at, the
/// `foreignField` and the `from` from the target this comparison holds.
///
/// The mutations this catches all build a legal pipeline: joining `_id` to `_id` (which would answer
/// *the shot whose own id is a matching keyframe's*), joining from the parent collection, and
/// testing the join field for `$eq: []` (which is the same relation negated).
#[test]
fn a_forward_reference_renders_a_semi_join_through_the_reference() {
  let cover = Ref::new(KEYFRAME, Keyframe::new().with_title("Autumn"));
  let predicate = at_field("cover_id", &cover);

  assert_eq!(predicate.filter(), &Document::new());
  assert_eq!(
    predicate.joins(),
    [
      forward_lookup(bson::bson!([{ "$match": { "title": { "$eq": "Autumn" } } }])),
      doc! { "$match": { "__ig_keyframe_1__": { "$ne": [] } } },
      dropped(),
    ]
  );
  assert_eq!(predicate.reads(), [FieldName::new("keyframe")]);
  assert_eq!(ComplexComparison::conjuncts(&cover), 1);
}

/// **The join's own pipeline carries the predicate and NOTHING else** — no `$sort`, no `$limit`, no
/// second `$match`.
///
/// A `$limit` inside would bound the join GLOBALLY per parent document, which changes the answer by
/// admitting parents whose matching children fell outside it; per-parent top-N is a different
/// construct this seam never had. A `$sort` inside would be work paid for an answer that is about
/// existence.
#[test]
fn the_join_pipeline_holds_the_predicate_alone() {
  let cover = Ref::new(KEYFRAME, Keyframe::new().with_title("Autumn"));
  let predicate = at_field("cover_id", &cover);
  let pipeline = predicate.joins()[0]
    .get_document("$lookup")
    .expect("a lookup body")
    .get_array("pipeline")
    .expect("a sub-pipeline");

  assert_eq!(pipeline.len(), 1);
  assert_eq!(
    pipeline[0].as_document().expect("a stage").keys().count(),
    1
  );
  assert!(
    pipeline[0]
      .as_document()
      .expect("a stage")
      .contains_key("$match")
  );
}

/// **A predicate naming only the target's id renders NO join**, and it merges the id's own operators
/// at the reference field's key.
///
/// The two twins below are what make this an optimisation rather than a coincidence: the same
/// relation and the same id, once with a target that declines the substitution and once with a
/// second field set, each paying for one join.
#[test]
fn a_predicate_on_the_targets_id_alone_collapses_onto_the_reference() {
  let collapsing = Ref::new(KEYFRAME, Keyframe::new().with_id(10));
  let predicate = at_field("cover_id", &collapsing);
  assert_eq!(predicate.filter(), &doc! { "cover_id": { "$eq": 10i64 } });
  assert!(predicate.joins().is_empty(), "the collapse opens no join");
  assert!(
    predicate.reads().is_empty(),
    "and reads no second collection"
  );
  assert_eq!(ComplexComparison::conjuncts(&collapsing), 1);

  let declining = Ref::new(KEYFRAME, Keyframe::new().with_id(10).unreferential());
  let predicate = at_field("cover_id", &declining);
  assert_eq!(predicate.filter(), &Document::new());
  assert_eq!(
    predicate.joins()[0],
    forward_lookup(bson::bson!([{ "$match": { "_id": { "$eq": 10i64 } } }]))
  );

  let narrowed = Ref::new(KEYFRAME, Keyframe::new().with_id(10).with_title("Autumn"));
  assert_eq!(
    at_field("cover_id", &narrowed).joins()[0],
    forward_lookup(bson::bson!([{
      "$match": { "_id": { "$eq": 10i64 }, "title": { "$eq": "Autumn" } }
    }]))
  );
}

/// An EMPTY nested predicate opens no join — no degenerate field-to-field lookup, which would be
/// *this reference is live* rather than *nothing*.
///
/// It is what keeps a record carrying relation slots queryable at all: a filter document is
/// assembled from every field, so a client that asked about none of them must get the empty
/// predicate for each.
#[test]
fn an_empty_relation_position_writes_nothing() {
  let empty = Ref::new(KEYFRAME, Keyframe::new());
  assert_eq!(ComplexComparison::conjuncts(&empty), 0);
  assert_eq!(at_field("cover_id", &empty), MongoPredicate::default());

  let position = Derived::new(KEYFRAME, SHOT_ID);
  assert_eq!(position.conjuncts(), 0);
  assert!(position.is_empty());
  assert_eq!(
    lowered(At::new(&SHOT), &position).expect("nothing to lower"),
    MongoPredicate::default()
  );
}

/// **A wide address is refused before anything is written**, and the refusal is a property of the
/// RELATION — so the collapsing predicate is refused too.
///
/// Both directions: the forward kind refuses its TARGET, whose `_id` the join meets, and the reverse
/// kind refuses the PARENT, whose `_id` the child's reference meets. It bites twice on this backend,
/// since a document addressed by several fields has no `_id` at all.
#[test]
fn a_relation_whose_address_is_wide_is_refused_and_writes_nothing() {
  let frame = At::new(&SHOT).frame(FieldName::new("splice_id"));
  let wide_target = MongoRefComparison::new(SPLICE, Keyframe::new().with_title("Autumn"));
  assert_eq!(
    lowered(frame.at(), &wide_target),
    Err(MongoLoweringError::RelationWidth(RelationWidthError::new(
      FieldName::new("splice"),
      2
    )))
  );

  let collapsing = MongoRefComparison::new(SPLICE, Keyframe::new().with_id(10));
  assert!(lowered(frame.at(), &collapsing).is_err());

  let reverse = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new());
  assert_eq!(
    lowered(At::new(SPLICE.address()), &reverse),
    Err(MongoLoweringError::RelationWidth(RelationWidthError::new(
      FieldName::new("splice"),
      2
    )))
  );
}

/// **Each quantifier opens a join of its own**, and the four render in the order the vocabulary
/// declares them.
///
/// The rendering to watch is `all`'s: the `$nor` sits INSIDE the join's own pipeline, around the
/// predicate alone, and the emptiness test outside it. Moved outside — the predicate unnegated and
/// the field required empty — it becomes `none` under another name, which is a legal pipeline
/// answering a different question.
#[test]
fn every_quantifier_opens_a_join_of_its_own() {
  let autumn = bson::bson!([{ "$match": { "title": { "$eq": "Autumn" } } }]);

  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new().with_title("Autumn"));
  assert_eq!(
    lowered(At::new(&SHOT), &any).unwrap().joins(),
    [
      reverse_lookup_with(autumn.clone()),
      doc! { "$match": { "__ig_keyframe_1__": { "$ne": [] } } },
      dropped(),
    ]
  );

  let none = Derived::new(KEYFRAME, SHOT_ID).with_none(Keyframe::new().with_title("Autumn"));
  assert_eq!(
    lowered(At::new(&SHOT), &none).unwrap().joins(),
    [
      reverse_lookup_with(autumn.clone()),
      doc! { "$match": { "__ig_keyframe_1__": { "$eq": [] } } },
      dropped(),
    ]
  );

  let all = Derived::new(KEYFRAME, SHOT_ID).with_all(Keyframe::new().with_title("Autumn"));
  assert_eq!(
    lowered(At::new(&SHOT), &all).unwrap().joins(),
    [
      reverse_lookup_with(bson::bson!([{
        "$match": { "$nor": [ { "title": { "$eq": "Autumn" } } ] }
      }])),
      doc! { "$match": { "__ig_keyframe_1__": { "$eq": [] } } },
      dropped(),
    ]
  );

  let count = Derived::new(KEYFRAME, SHOT_ID).with_count(
    MongoCountComparison::try_from_filter(ScalarFilter::<usize>::new().with_gt(2)).unwrap(),
  );
  assert_eq!(
    lowered(At::new(&SHOT), &count).unwrap().joins(),
    [
      reverse_lookup(),
      doc! { "$match": { "$and": [ { "$expr": { "$and": [
        { "$isArray": "$__ig_keyframe_1__" },
        { "$gt": [ { "$size": "$__ig_keyframe_1__" }, 2i64 ] },
      ] } } ] } },
      dropped(),
    ]
  );
}

/// **The cardinality's join asks the children NOTHING**, which is `count` counting the position
/// rather than the matches — the same reading a collection's own `count` has.
///
/// An EMPTY cardinality opens no join at all: it asks nothing, so a join followed by `{$match: {}}`
/// would be work paid for a stage that excludes no document.
#[test]
fn the_cardinality_counts_the_position_and_an_empty_one_opens_nothing() {
  let count = Derived::new(KEYFRAME, SHOT_ID).with_count(
    MongoCountComparison::try_from_filter(ScalarFilter::<usize>::new().with_gt(2)).unwrap(),
  );
  assert!(
    !lowered(At::new(&SHOT), &count).unwrap().joins()[0]
      .get_document("$lookup")
      .expect("a lookup body")
      .contains_key("pipeline"),
    "the cardinality's join runs no pipeline"
  );

  let unasked = Derived::new(KEYFRAME, SHOT_ID).with_count(MongoCountComparison::new());
  assert_eq!(unasked.conjuncts(), 0);
  assert!(
    lowered(At::new(&SHOT), &unasked)
      .unwrap()
      .joins()
      .is_empty()
  );
}

/// **`all` over an EMPTY predicate is vacuously true**, and it needs no special case: `{$nor: [{}]}`
/// parses, matches no document, and leaves the join field empty for every parent.
///
/// That is the same answer the SQL family reaches by rendering `1 = 1`, which it has to because
/// `NOT ( )` does not parse. The other two quantifiers need no case either: an empty predicate leaves
/// the join's pipeline off, so `any` becomes *this document has a child* and `none` its negation.
#[test]
fn an_empty_predicate_is_vacuous_under_all_and_a_presence_test_under_the_others() {
  let all = Derived::new(KEYFRAME, SHOT_ID).with_all(Keyframe::new());
  assert_eq!(all.conjuncts(), 1);
  assert_eq!(
    lowered(At::new(&SHOT), &all).unwrap().joins()[0],
    reverse_lookup_with(bson::bson!([{ "$match": { "$nor": [ {} ] } }]))
  );

  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new());
  assert_eq!(
    lowered(At::new(&SHOT), &any).unwrap().joins(),
    [
      reverse_lookup(),
      doc! { "$match": { "__ig_keyframe_1__": { "$ne": [] } } },
      dropped(),
    ]
  );

  let none = Derived::new(KEYFRAME, SHOT_ID).with_none(Keyframe::new());
  assert_eq!(
    lowered(At::new(&SHOT), &none).unwrap().joins()[1],
    doc! { "$match": { "__ig_keyframe_1__": { "$eq": [] } } }
  );
}

/// **Two SIBLING joins at one depth mint the same field, and each consumes it before the next
/// opens.**
///
/// This is the whole reason the run is `$lookup`, `$match`, `$project` rather than every join hoisted
/// to the front of the pipeline. Hoisted, the second `$lookup` would write the key the first one
/// already holds — MongoDB overwrites it, with no error anywhere — and the `$match` reading it would
/// then be testing a set the filter never asked about.
///
/// Six stages, and the third is what makes the fourth safe.
#[test]
fn sibling_joins_reuse_one_field_and_each_consumes_it_first() {
  let both = Derived::new(KEYFRAME, SHOT_ID)
    .with_any(Keyframe::new())
    .with_none(Keyframe::new().with_title("Autumn"));
  let joins = lowered(At::new(&SHOT), &both).unwrap();

  assert_eq!(
    joins.joins(),
    [
      reverse_lookup(),
      doc! { "$match": { "__ig_keyframe_1__": { "$ne": [] } } },
      dropped(),
      reverse_lookup_with(bson::bson!([{ "$match": { "title": { "$eq": "Autumn" } } }])),
      doc! { "$match": { "__ig_keyframe_1__": { "$eq": [] } } },
      dropped(),
    ]
  );
  // One collection, joined twice — which the read set counts ONCE, because the read concern's
  // question is whether the pipeline spans more than one.
  assert_eq!(joins.reads(), [FieldName::new("keyframe")]);
}

/// **A SELF-RELATION lands its documents in a field the enclosing document has not got**, which is
/// what the naming closes: the collection joined and the collection joined ONTO are the same one
/// here, so a join field named after the collection alone would be a field of the very documents it
/// is joining.
#[test]
fn a_self_relation_lands_its_documents_in_a_minted_field() {
  let any = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new());

  assert_eq!(
    lowered(At::new(SCENE.address()), &any).unwrap().joins(),
    [
      doc! { "$lookup": {
        "from": "scene",
        "localField": "_id",
        "foreignField": "parent_id",
        "as": "__ig_scene_1__",
      } },
      doc! { "$match": { "__ig_scene_1__": { "$ne": [] } } },
      doc! { "$project": { "__ig_scene_1__": 0 } },
    ]
  );
}

/// **Two levels of one collection take two join fields**, and the inner run is a STAGE of the outer
/// lookup's own pipeline.
///
/// The forward kind is the outer hop and the reverse kind the inner, so this also pins that the two
/// kinds agree about what depth they are at. One field for both levels would put the inner
/// `$lookup`'s output where the outer one's belongs, inside the very pipeline the outer one is
/// filling — which is a legal pipeline answering the one-level question.
#[test]
fn two_levels_of_one_collection_take_two_join_fields() {
  let inner = Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new().with_title("Autumn"));
  let outer = MongoRefComparison::new(SCENE, Nesting(inner));
  let frame = At::new(SCENE.address()).frame(PARENT_ID);
  let predicate = lowered(frame.at(), &outer).unwrap();

  assert_eq!(
    predicate.joins(),
    [
      doc! { "$lookup": {
        "from": "scene",
        "localField": "parent_id",
        "foreignField": "_id",
        "as": "__ig_scene_1__",
        "pipeline": [
          { "$lookup": {
            "from": "scene",
            "localField": "_id",
            "foreignField": "parent_id",
            "as": "__ig_scene_2__",
            "pipeline": [ { "$match": { "title": { "$eq": "Autumn" } } } ],
          } },
          { "$match": { "__ig_scene_2__": { "$ne": [] } } },
          { "$project": { "__ig_scene_2__": 0 } },
        ],
      } },
      doc! { "$match": { "__ig_scene_1__": { "$ne": [] } } },
      doc! { "$project": { "__ig_scene_1__": 0 } },
    ]
  );
  assert_eq!(predicate.reads(), [FieldName::new("scene")]);
}

/// **Past the last minted field the lowering REFUSES**, naming the collection, the depth and the
/// ceiling.
///
/// Reusing a name is the alternative, and it is the silent one: a join field is a KEY of the document
/// being joined onto, so a repeat past its `$project` would have the second `$lookup` overwrite the
/// first. The fixture mints ONE name so the ceiling is reached at the first hop rather than the
/// ninth.
#[test]
fn a_relation_deeper_than_its_join_fields_is_refused() {
  let any = Derived::new(SHALLOW, PARENT_ID).with_any(Keyframe::new());
  assert_eq!(
    lowered(At::new(SHALLOW.address()), &any),
    Err(MongoLoweringError::RelationDepth(RelationDepthError::new(
      FieldName::new("scene"),
      1,
      1
    )))
  );

  // The FORWARD kind refuses on the same ground, and refuses before it writes.
  let forward = MongoRefComparison::new(SHALLOW, Keyframe::new().with_title("x"));
  let frame = At::new(SHALLOW.address()).frame(PARENT_ID);
  assert_eq!(
    lowered(frame.at(), &forward),
    Err(MongoLoweringError::RelationDepth(RelationDepthError::new(
      FieldName::new("scene"),
      1,
      1
    )))
  );
}

/// **A relation nested inside `all` is REFUSED**, and its three neighbours nest without complaint.
///
/// `all` negates the predicate it is given with `$nor`, which takes filter documents; a predicate
/// that is itself a join has stages, and a stage inside a query operator has no reading. Leaving them
/// outside the `$nor` would apply them unnegated, which renders and answers a different question.
#[test]
fn a_relation_inside_all_is_refused_and_inside_its_neighbours_is_not() {
  let nested = || Nesting(Derived::new(SCENE, PARENT_ID).with_any(Keyframe::new()));

  let all = MongoDerivedComparison::new(KEYFRAME, SHOT_ID).with_all(nested());
  assert_eq!(
    lowered(At::new(&SHOT), &all),
    Err(MongoLoweringError::NegatedRelation)
  );

  for position in [
    MongoDerivedComparison::new(KEYFRAME, SHOT_ID).with_any(nested()),
    MongoDerivedComparison::new(KEYFRAME, SHOT_ID).with_none(nested()),
  ] {
    let predicate = lowered(At::new(&SHOT), &position).expect("a nested join renders");
    assert_eq!(
      predicate.reads(),
      [FieldName::new("keyframe"), FieldName::new("scene")]
    );
  }
}

/// **A relation inside an ELEMENT SCOPE is refused**, which is the one position with no pipeline to
/// hold a stage.
///
/// The refusal is DEFERRED exactly as the scope's other three are: the accumulator writes and does
/// not answer, so what it noticed comes back when the scope document is finished.
#[test]
fn a_relation_inside_an_element_scope_is_refused() {
  let cover = Ref::new(KEYFRAME, Keyframe::new().with_title("Autumn"));
  let frame = At::new(&SHOT).frame(FieldName::new("cover_id"));
  let scope = cover
    .apply(frame.at(), MongoConjunction::element())
    .expect("the relation writes and the scope remembers");

  assert_eq!(
    scope.into_element_document(),
    Err(MongoLoweringError::ElementRelation)
  );
}

/// The reverse kind reads the DOCUMENT and not the field, so the same comparison renders identically
/// at the top level, at one frame and at two.
///
/// It is the opposite of the correlated COLLECTION kinds, which derive their scope FROM the path —
/// and it is why a reverse position, which is stored nowhere, needs no field of its own.
#[test]
fn a_derived_position_reads_the_document_and_leaves_the_path_unread() {
  let any = Derived::new(KEYFRAME, SHOT_ID).with_any(Keyframe::new().with_title("Autumn"));
  let outer = At::new(&SHOT).frame(FieldName::new("covers"));
  let inner = outer.at().frame(FieldName::new("deeper"));

  let top = lowered(At::new(&SHOT), &any).unwrap();
  assert_eq!(top, at_field("covers", &any));
  assert_eq!(top, lowered(inner.at(), &any).unwrap());
}

/// Every refusal names what is missing rather than an operator, which is what tells a reader whether
/// the answer is a schema fact or a spelling.
#[test]
fn the_refusals_say_what_is_missing() {
  let messages = [
    MongoLoweringError::ElementRelation.to_string(),
    MongoLoweringError::NegatedRelation.to_string(),
    MongoLoweringError::RelationWidth(RelationWidthError::new(FieldName::new("splice"), 2))
      .to_string(),
    MongoLoweringError::RelationDepth(RelationDepthError::new(FieldName::new("scene"), 9, 8))
      .to_string(),
  ];

  assert!(messages[0].contains("$lookup"), "{}", messages[0]);
  assert!(messages[1].contains("$nor"), "{}", messages[1]);
  assert!(
    messages[2].contains("`splice` is addressed by 2 columns"),
    "{}",
    messages[2]
  );
  assert!(
    messages[3].contains("nests 9 levels deep and its join fields are minted for 8"),
    "{}",
    messages[3]
  );
}

/// The SQL family's two-table corpus, replayed as the pipelines this backend renders for it — and
/// the answers each of them admits, computed by hand.
///
/// ```text
/// shot  slate    cover → title    keyframes (title)          any    none   all    count>1
///  1    alpha     10   → Autumn    10 Autumn, 11 Meadow       yes     .      .      yes
///  2    bravo     11   → Meadow    12 Zebra                    .     yes     .       .
///  3    delta    NULL  → NULL      (none)                      .     yes    yes      .
///  4    echo      12   → Zebra     13 Autumn                  yes     .     yes      .
///  5    foxtrot  NULL  → NULL      14 Autumn, 15 NULL         yes     .      *      yes
/// ```
///
/// - the FORWARD semi-join over `title = "Autumn"` admits `[1]` — the shots whose COVER matches,
///   which is a different question from the reverse `any` beside it. A missing or null `cover_id`
///   joins against no `_id`, so shots 3 and 5 are excluded by the join rather than by the predicate.
/// - `any` admits `[1, 4, 5]`, `none` admits `[2, 3]`, `count > 1` admits `[1, 5]`.
/// - `all` is the ONE row marked `*`, and it is where the two backends part. SQL admits
///   `[3, 4, 5]`: shot 5's second keyframe has a `NULL` title, `NOT ( title = ? )` is `NULL`, and a
///   `NULL` is not a counterexample. MongoDB admits `[3, 4]`: `$nor` is two-valued over documents, so
///   a keyframe whose `title` is null or missing does not match the predicate, DOES match the `$nor`,
///   and IS a counterexample.
///
/// Neither is a defect — each is its engine's own truth table — and a caller who needs the SQL
/// reading asks `none` of the negated predicate instead. What this test pins is that the two
/// renderings are the ones the reasoning above is about; the sets themselves need a live server,
/// which this repository provisions for no backend.
#[test]
fn corpus() {
  let autumn = || Keyframe::new().with_title("Autumn");

  // The forward question and the reverse one are DIFFERENT pipelines, which is what makes the two
  // answer sets legible as two.
  let cover = at_field("cover_id", &Ref::new(KEYFRAME, autumn()));
  let any = lowered(
    At::new(&SHOT),
    &Derived::new(KEYFRAME, SHOT_ID).with_any(autumn()),
  )
  .unwrap();
  assert_ne!(cover.joins(), any.joins());
  assert_eq!(
    cover.joins()[0]
      .get_document("$lookup")
      .unwrap()
      .get_str("localField")
      .expect("a local field"),
    "cover_id"
  );
  assert_eq!(
    any.joins()[0]
      .get_document("$lookup")
      .unwrap()
      .get_str("localField")
      .expect("a local field"),
    "_id"
  );

  // `all` and `none` differ ONLY in where the negation sits, which is the pair a reader is most
  // likely to conflate — and the pair whose answers differ most on the corpus.
  let all = lowered(
    At::new(&SHOT),
    &Derived::new(KEYFRAME, SHOT_ID).with_all(autumn()),
  )
  .unwrap();
  let none = lowered(
    At::new(&SHOT),
    &Derived::new(KEYFRAME, SHOT_ID).with_none(autumn()),
  )
  .unwrap();
  assert_eq!(
    all.joins()[1],
    none.joins()[1],
    "both require an empty join"
  );
  assert_ne!(all.joins()[0], none.joins()[0], "and negate in one of them");
}