kmp-domain 0.12.2

Domain model of the Kernel Memory Protocol: aggregates, value objects, repositories and projections, with no IO
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
use std::cmp::Ordering;
use std::collections::BTreeMap;

use crate::{TemporalAxis, compare_temporal_instants};

use super::coordinate_relation::{CoordinateRelation, CoordinateRelationKind};
use super::declared_edge::DeclaredEdge;
use super::related_fact::{FactState, RelatedFact};
use super::shared_label::SharedLabel;
use super::tension::Tension;

/// The most coordinate relations one reading returns. Pairs grow with the
/// square of the facts a scope holds; past this many the reading says how
/// many it left out rather than growing without bound.
pub const MAX_COORDINATE_RELATIONS: usize = 500;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Relations {
    pub coordinate: Vec<CoordinateRelation>,
    pub tensions: Vec<Tension>,
    /// Coordinate relations past the cap, counted and not returned.
    pub omitted_coordinate: usize,
    /// The same count by the label that lost them, most omitted first, so
    /// a reader knows which label to narrow.
    pub omitted_by_label: Vec<(SharedLabel, usize)>,
}

/// Reads what facts of different abouts have to do with each other, and
/// which declared contradictions still stand between facts that do.
///
/// Coordinate relations are read inside each label two or more abouts
/// share — the same dimension kind and the same scope — one per pair of
/// facts from different abouts. Labels are read narrowest first, and the
/// cap is shared out among them: each label may take an equal share of
/// what is left, and what a narrow label does not use flows to the wider
/// ones after it. So a label a handful of facts stand in is always read
/// whole, and a label every fact stands in — `release=spring` across two
/// projects — takes the rest rather than all of it. Pairs grow with the
/// square of a label's width, which is why the wide one is the one cut.
/// Within a label the pairs keep their order, so the same store reads the
/// same way every time.
pub fn relate(facts: &[RelatedFact], declared: &[DeclaredEdge], axis: TemporalAxis) -> Relations {
    let mut by_label = BTreeMap::<SharedLabel, Vec<&RelatedFact>>::new();
    for fact in facts {
        for label in fact.labels() {
            by_label.entry(label).or_default().push(fact);
        }
    }
    let mut labels = by_label
        .into_iter()
        .map(|(label, mut placed)| {
            placed.sort_by(|left, right| {
                (left.about(), left.ref_id()).cmp(&(right.about(), right.ref_id()))
            });
            placed.dedup_by(|left, right| left.ref_id() == right.ref_id());
            (label, placed)
        })
        .collect::<Vec<_>>();
    labels.sort_by(|(left_label, left), (right_label, right)| {
        left.len()
            .cmp(&right.len())
            .then_with(|| left_label.cmp(right_label))
    });

    let mut coordinate = Vec::new();
    let mut omitted_coordinate = 0usize;
    let mut omitted_by_label = Vec::new();
    for (position, (label, placed)) in labels.iter().enumerate() {
        let remaining = MAX_COORDINATE_RELATIONS.saturating_sub(coordinate.len());
        let share = remaining / (labels.len() - position);
        let mut taken = 0usize;
        let mut omitted = 0usize;
        for (index, first) in placed.iter().enumerate() {
            for second in &placed[index + 1..] {
                if first.about() == second.about() {
                    continue;
                }
                for relation in pair_relations(first, second, label, axis) {
                    if taken < share {
                        coordinate.push(relation);
                        taken += 1;
                    } else {
                        omitted += 1;
                    }
                }
            }
        }
        if omitted > 0 {
            omitted_coordinate += omitted;
            omitted_by_label.push((label.clone(), omitted));
        }
    }
    omitted_by_label.sort_by(|(left_label, left), (right_label, right)| {
        right.cmp(left).then_with(|| left_label.cmp(right_label))
    });

    let by_ref = facts
        .iter()
        .map(|fact| (fact.ref_id(), fact))
        .collect::<BTreeMap<_, _>>();
    let mut tensions = declared
        .iter()
        .filter(|edge| edge.rel == "contradicts")
        .filter_map(|edge| {
            let first = by_ref.get(edge.from.as_str())?;
            let second = by_ref.get(edge.to.as_str())?;
            if first.state() != FactState::Current || second.state() != FactState::Current {
                return None;
            }
            let shared = first
                .labels()
                .intersection(&second.labels())
                .next()
                .cloned();
            Some(Tension::new(
                edge.from.clone(),
                edge.to.clone(),
                shared,
                edge.why.clone(),
                edge.evidence.clone(),
            ))
        })
        .collect::<Vec<_>>();
    tensions
        .sort_by(|left, right| (left.ref_id(), left.other()).cmp(&(right.ref_id(), right.other())));
    tensions.dedup();

    Relations {
        coordinate,
        tensions,
        omitted_coordinate,
        omitted_by_label,
    }
}

fn pair_relations(
    first: &RelatedFact,
    second: &RelatedFact,
    label: &SharedLabel,
    axis: TemporalAxis,
) -> Vec<CoordinateRelation> {
    let mut relations = Vec::new();
    let temporal = if axis == TemporalAxis::Validity {
        span_relation(first.validity_in(label), second.validity_in(label))
    } else {
        instant_relation(
            first.instant_in(label, axis),
            second.instant_in(label, axis),
        )
    };
    let (from, to, kind) = match temporal {
        Some((kind, swapped)) if swapped => (second, first, kind),
        Some((kind, _)) => (first, second, kind),
        None => (first, second, CoordinateRelationKind::SharesScope),
    };
    relations.push(CoordinateRelation::new(
        from.ref_id(),
        to.ref_id(),
        kind,
        label,
        axis,
    ));
    if let (Some(left), Some(right)) = (first.sequence_in(label), second.sequence_in(label))
        && left == right
    {
        relations.push(CoordinateRelation::new(
            first.ref_id(),
            second.ref_id(),
            CoordinateRelationKind::SameSequence,
            label,
            axis,
        ));
    }
    if let (Some(left), Some(right)) = (first.rank_in(label), second.rank_in(label))
        && left == right
    {
        relations.push(CoordinateRelation::new(
            first.ref_id(),
            second.ref_id(),
            CoordinateRelationKind::SameRank,
            label,
            axis,
        ));
    }
    relations
}

/// The order of two instants, from the first's point of view; `None` when
/// either is missing or unreadable, which is what `SharesScope` says.
fn instant_relation(
    first: Option<&str>,
    second: Option<&str>,
) -> Option<(CoordinateRelationKind, bool)> {
    let ordering = compare_temporal_instants(first?, second?)?;
    Some((
        match ordering {
            Ordering::Less => CoordinateRelationKind::Before,
            Ordering::Greater => CoordinateRelationKind::After,
            Ordering::Equal => CoordinateRelationKind::Concurrent,
        },
        false,
    ))
}

/// How two validity spans stand: nested reads as `During` from the inner
/// one (the second flag says the inner one was the second fact), touching
/// as `Concurrent`, and apart as `Before` or `After`. An open side is
/// unbounded on that side.
fn span_relation(
    first: Option<(Option<&str>, Option<&str>)>,
    second: Option<(Option<&str>, Option<&str>)>,
) -> Option<(CoordinateRelationKind, bool)> {
    let (first_from, first_until) = first?;
    let (second_from, second_until) = second?;
    let starts_not_after = |a: Option<&str>, b: Option<&str>| match (a, b) {
        (None, _) => Some(true),
        (Some(_), None) => Some(false),
        (Some(a), Some(b)) => Some(compare_temporal_instants(a, b)? != Ordering::Greater),
    };
    let ends_not_before = |a: Option<&str>, b: Option<&str>| match (a, b) {
        (None, _) => Some(true),
        (Some(_), None) => Some(false),
        (Some(a), Some(b)) => Some(compare_temporal_instants(a, b)? != Ordering::Less),
    };
    let apart_before = match (first_until, second_from) {
        (Some(until), Some(from)) => compare_temporal_instants(until, from)? != Ordering::Greater,
        _ => false,
    };
    if apart_before {
        return Some((CoordinateRelationKind::Before, false));
    }
    let apart_after = match (second_until, first_from) {
        (Some(until), Some(from)) => compare_temporal_instants(until, from)? != Ordering::Greater,
        _ => false,
    };
    if apart_after {
        return Some((CoordinateRelationKind::After, false));
    }
    let first_inside =
        starts_not_after(second_from, first_from)? && ends_not_before(second_until, first_until)?;
    let second_inside =
        starts_not_after(first_from, second_from)? && ends_not_before(first_until, second_until)?;
    if first_inside && second_inside {
        return Some((CoordinateRelationKind::Concurrent, false));
    }
    if first_inside {
        return Some((CoordinateRelationKind::During, false));
    }
    if second_inside {
        return Some((CoordinateRelationKind::During, true));
    }
    Some((CoordinateRelationKind::Concurrent, false))
}

#[cfg(test)]
mod tests {
    use crate::{RelationExplanation, RelationSemanticClass, TemporalCoordinate};

    use super::*;

    fn coordinate(
        scope: &str,
        occurred_at: Option<&str>,
        validity: (Option<&str>, Option<&str>),
        sequence: Option<u32>,
    ) -> TemporalCoordinate {
        coordinate_of_kind("incident", scope, occurred_at, validity, sequence)
    }

    fn coordinate_of_kind(
        kind: &str,
        scope: &str,
        occurred_at: Option<&str>,
        validity: (Option<&str>, Option<&str>),
        sequence: Option<u32>,
    ) -> TemporalCoordinate {
        let mut explanation = RelationExplanation::new(RelationSemanticClass::Structural)
            .with_dimension(kind)
            .with_scope_id(scope);
        if let Some(at) = occurred_at {
            explanation = explanation.with_occurred_at(at);
        }
        if let Some(from) = validity.0 {
            explanation = explanation.with_valid_from(from);
        }
        if let Some(until) = validity.1 {
            explanation = explanation.with_valid_until(until);
        }
        if let Some(sequence) = sequence {
            explanation = explanation.with_sequence(sequence);
        }
        TemporalCoordinate::from_relation_explanation(&explanation)
            .expect("coordinate")
            .expect("placed")
    }

    fn fact(
        ref_id: &str,
        about: &str,
        coordinates: Vec<TemporalCoordinate>,
        state: FactState,
    ) -> RelatedFact {
        RelatedFact::new(ref_id, about, coordinates, state).expect("fact")
    }

    #[test]
    fn the_same_scope_under_two_kinds_is_two_labels_and_relates_nothing() {
        let facts = vec![
            fact(
                "project:alpha:e1",
                "project:alpha",
                vec![coordinate_of_kind(
                    "owner",
                    "about:project:alpha:dimension:kmp",
                    Some("2026-03-04T01:00:00Z"),
                    (None, None),
                    Some(1),
                )],
                FactState::Current,
            ),
            fact(
                "project:beta:e1",
                "project:beta",
                vec![coordinate_of_kind(
                    "repo",
                    "about:project:beta:dimension:kmp",
                    Some("2026-03-04T01:20:00Z"),
                    (None, None),
                    Some(1),
                )],
                FactState::Current,
            ),
        ];

        let relations = relate(&facts, &[], TemporalAxis::Default);

        assert!(
            relations.coordinate.is_empty(),
            "`owner=kmp` and `repo=kmp` share a value, not a label: {:?}",
            relations.coordinate
        );
    }

    #[test]
    fn a_coordinate_relation_names_the_label_it_was_read_in() {
        let facts = vec![
            fact(
                "project:alpha:e1",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:north",
                    Some("2026-03-04T01:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
            fact(
                "project:beta:e1",
                "project:beta",
                vec![coordinate(
                    "about:project:beta:dimension:north",
                    Some("2026-03-04T01:20:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
        ];

        let relations = relate(&facts, &[], TemporalAxis::Default);

        assert_eq!(relations.coordinate.len(), 1);
        assert_eq!(relations.coordinate[0].dimension(), "incident");
        assert_eq!(relations.coordinate[0].scope_id(), "north");
        assert!(
            relations.coordinate[0]
                .why()
                .starts_with("Both stand in `incident=north`;"),
            "{}",
            relations.coordinate[0].why()
        );
    }

    #[test]
    fn facts_of_different_abouts_in_one_scope_are_ordered_on_the_clock_read() {
        let facts = vec![
            fact(
                "project:alpha:e1",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:incident:north",
                    Some("2026-03-04T01:00:00Z"),
                    (None, None),
                    Some(1),
                )],
                FactState::Current,
            ),
            fact(
                "project:beta:e1",
                "project:beta",
                vec![coordinate(
                    "about:project:beta:dimension:incident:north",
                    Some("2026-03-04T01:20:00Z"),
                    (None, None),
                    Some(1),
                )],
                FactState::Current,
            ),
            fact(
                "project:alpha:e2",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:incident:north",
                    Some("2026-03-04T02:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
            fact(
                "project:gamma:e1",
                "project:gamma",
                vec![coordinate(
                    "about:project:gamma:dimension:work:main",
                    Some("2026-03-04T02:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
        ];
        let relations = relate(&facts, &[], TemporalAxis::Default);
        let kinds = relations
            .coordinate
            .iter()
            .map(|relation| {
                (
                    relation.from().to_string(),
                    relation.to().to_string(),
                    relation.kind(),
                )
            })
            .collect::<Vec<_>>();
        assert_eq!(
            kinds,
            vec![
                (
                    "project:alpha:e1".to_string(),
                    "project:beta:e1".to_string(),
                    CoordinateRelationKind::Before
                ),
                (
                    "project:alpha:e1".to_string(),
                    "project:beta:e1".to_string(),
                    CoordinateRelationKind::SameSequence
                ),
                (
                    "project:alpha:e2".to_string(),
                    "project:beta:e1".to_string(),
                    CoordinateRelationKind::After
                ),
            ],
            "two facts of one about never relate to each other here, and gamma shares no scope"
        );
        assert_eq!(relations.coordinate[0].scope_id(), "incident:north");
        assert!(relations.coordinate[0].why().contains("comes before"));
        assert_eq!(relations.omitted_coordinate, 0);
    }

    #[test]
    fn validity_spans_nest_touch_or_stand_apart() {
        let alpha = |from: &str, until: Option<&str>| {
            fact(
                "project:alpha:rule",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:release:spring",
                    None,
                    (Some(from), until),
                    None,
                )],
                FactState::Current,
            )
        };
        let beta = |from: &str, until: Option<&str>| {
            fact(
                "project:beta:rule",
                "project:beta",
                vec![coordinate(
                    "about:project:beta:dimension:release:spring",
                    None,
                    (Some(from), until),
                    None,
                )],
                FactState::Current,
            )
        };
        let kind = |facts: Vec<RelatedFact>| {
            let relations = relate(&facts, &[], TemporalAxis::Validity);
            (
                relations.coordinate[0].from().to_string(),
                relations.coordinate[0].kind(),
            )
        };
        assert_eq!(
            kind(vec![
                alpha("2026-03-10T00:00:00Z", Some("2026-03-12T00:00:00Z")),
                beta("2026-03-01T00:00:00Z", Some("2026-04-01T00:00:00Z"))
            ]),
            (
                "project:alpha:rule".to_string(),
                CoordinateRelationKind::During
            )
        );
        assert_eq!(
            kind(vec![
                alpha("2026-03-01T00:00:00Z", Some("2026-04-01T00:00:00Z")),
                beta("2026-03-10T00:00:00Z", Some("2026-03-12T00:00:00Z"))
            ]),
            (
                "project:beta:rule".to_string(),
                CoordinateRelationKind::During
            ),
            "the inner span is always the one that holds `during` the other"
        );
        assert_eq!(
            kind(vec![
                alpha("2026-03-01T00:00:00Z", Some("2026-03-15T00:00:00Z")),
                beta("2026-03-10T00:00:00Z", None)
            ])
            .1,
            CoordinateRelationKind::Concurrent
        );
        assert_eq!(
            kind(vec![
                alpha("2026-03-01T00:00:00Z", Some("2026-03-10T00:00:00Z")),
                beta("2026-03-10T00:00:00Z", None)
            ])
            .1,
            CoordinateRelationKind::Before,
            "an exclusive end that meets the next start stands apart"
        );
    }

    #[test]
    fn a_fact_without_the_clock_read_only_shares_the_scope() {
        let facts = vec![
            fact(
                "project:alpha:e1",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:incident:north",
                    Some("2026-03-04T01:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
            fact(
                "project:beta:e1",
                "project:beta",
                vec![coordinate(
                    "about:project:beta:dimension:incident:north",
                    None,
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
        ];
        let relations = relate(&facts, &[], TemporalAxis::Occurred);
        assert_eq!(relations.coordinate.len(), 1);
        assert_eq!(
            relations.coordinate[0].kind(),
            CoordinateRelationKind::SharesScope
        );
        assert!(
            relations.coordinate[0]
                .why()
                .contains("neither carries an instant")
        );
    }

    #[test]
    fn a_declared_contradiction_between_two_standing_facts_is_a_tension() {
        let facts = vec![
            fact(
                "project:alpha:freeze",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:release:spring",
                    Some("2026-03-01T00:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
            fact(
                "project:alpha:ship",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:release:spring",
                    Some("2026-03-05T00:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ),
            fact(
                "project:alpha:old",
                "project:alpha",
                vec![coordinate(
                    "about:project:alpha:dimension:release:spring",
                    Some("2026-02-01T00:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Superseded,
            ),
        ];
        let declared = vec![
            DeclaredEdge {
                from: "project:alpha:ship".into(),
                to: "project:alpha:freeze".into(),
                rel: "contradicts".into(),
                why: "Shipping during a freeze.".into(),
                evidence: "Release calendar.".into(),
            },
            DeclaredEdge {
                from: "project:alpha:ship".into(),
                to: "project:alpha:old".into(),
                rel: "contradicts".into(),
                why: "".into(),
                evidence: "".into(),
            },
            DeclaredEdge {
                from: "project:alpha:ship".into(),
                to: "project:alpha:freeze".into(),
                rel: "follows".into(),
                why: "".into(),
                evidence: "".into(),
            },
        ];
        let relations = relate(&facts, &declared, TemporalAxis::Default);
        assert_eq!(
            relations.tensions.len(),
            1,
            "a replaced fact is no longer in tension, and `follows` is no contradiction"
        );
        let tension = &relations.tensions[0];
        assert_eq!(tension.ref_id(), "project:alpha:ship");
        assert_eq!(tension.other(), "project:alpha:freeze");
        assert_eq!(tension.scope_id(), "release:spring");
        assert_eq!(tension.why(), "Shipping during a freeze.");
        assert!(
            relations.coordinate.is_empty(),
            "one about relates to nothing by coordinate"
        );
    }

    #[test]
    fn the_cap_counts_what_it_leaves_out() {
        let mut facts = Vec::new();
        for index in 0..40 {
            for about in ["project:alpha", "project:beta"] {
                facts.push(fact(
                    &format!("{about}:e{index}"),
                    about,
                    vec![coordinate(
                        &format!("about:{about}:dimension:work:main"),
                        Some("2026-03-04T01:00:00Z"),
                        (None, None),
                        None,
                    )],
                    FactState::Current,
                ));
            }
        }
        let relations = relate(&facts, &[], TemporalAxis::Default);
        assert_eq!(relations.coordinate.len(), MAX_COORDINATE_RELATIONS);
        assert_eq!(
            relations.omitted_coordinate,
            40 * 40 - MAX_COORDINATE_RELATIONS
        );
        assert_eq!(
            relations.omitted_by_label,
            [(
                SharedLabel::new("incident", "work:main"),
                40 * 40 - MAX_COORDINATE_RELATIONS
            )]
        );
    }

    /// Forty facts per about in one wide label, and one fact per about in a
    /// narrow one that sorts after it. Read alphabetically the wide label
    /// would fill the cap and the narrow one would never be seen; read
    /// narrowest first the narrow one is whole and the wide one is what is
    /// cut, and the reading says which.
    #[test]
    fn a_narrow_label_is_read_whole_and_the_wide_one_is_the_one_cut() {
        let mut facts = Vec::new();
        for index in 0..40 {
            for about in ["project:alpha", "project:beta"] {
                facts.push(fact(
                    &format!("{about}:e{index}"),
                    about,
                    vec![coordinate_of_kind(
                        "alpha",
                        &format!("about:{about}:dimension:main"),
                        Some("2026-03-04T01:00:00Z"),
                        (None, None),
                        None,
                    )],
                    FactState::Current,
                ));
            }
        }
        for about in ["project:alpha", "project:beta"] {
            facts.push(fact(
                &format!("{about}:north"),
                about,
                vec![coordinate_of_kind(
                    "zeta",
                    &format!("about:{about}:dimension:north"),
                    Some("2026-03-04T02:00:00Z"),
                    (None, None),
                    None,
                )],
                FactState::Current,
            ));
        }
        let relations = relate(&facts, &[], TemporalAxis::Default);
        assert_eq!(relations.coordinate.len(), MAX_COORDINATE_RELATIONS);
        assert_eq!(
            relations.coordinate[0].scope_id(),
            "north",
            "the narrow label comes first: {:?}",
            relations.coordinate[0]
        );
        assert_eq!(
            relations
                .coordinate
                .iter()
                .filter(|relation| relation.scope_id() == "north")
                .count(),
            1,
            "and it is read whole"
        );
        assert_eq!(
            relations.omitted_by_label,
            [(
                SharedLabel::new("alpha", "main"),
                40 * 40 - (MAX_COORDINATE_RELATIONS - 1)
            )],
            "only the wide label lost anything"
        );
        assert_eq!(
            relations.omitted_coordinate,
            40 * 40 - (MAX_COORDINATE_RELATIONS - 1)
        );
    }

    /// Three labels of one, thirty and sixteen hundred pairs: the narrow
    /// two take what they need and the wide one takes the rest, so the cap
    /// is spent whole and nothing narrow waits behind something wide.
    #[test]
    fn what_a_narrow_label_does_not_use_flows_to_the_wider_ones() {
        let mut facts = Vec::new();
        let mut place = |kind: &str, scope: &str, per_about: usize| {
            for index in 0..per_about {
                for about in ["project:alpha", "project:beta"] {
                    facts.push(fact(
                        &format!("{about}:{kind}:e{index}"),
                        about,
                        vec![coordinate_of_kind(
                            kind,
                            &format!("about:{about}:dimension:{scope}"),
                            Some("2026-03-04T01:00:00Z"),
                            (None, None),
                            None,
                        )],
                        FactState::Current,
                    ));
                }
            }
        };
        place("wide", "main", 40);
        place("medium", "mid", 5);
        place("narrow", "one", 1);
        let relations = relate(&facts, &[], TemporalAxis::Default);
        let count = |scope: &str| {
            relations
                .coordinate
                .iter()
                .filter(|relation| relation.scope_id() == scope)
                .count()
        };
        assert_eq!(count("one"), 1);
        assert_eq!(count("mid"), 25);
        assert_eq!(count("main"), MAX_COORDINATE_RELATIONS - 26);
        assert_eq!(relations.coordinate.len(), MAX_COORDINATE_RELATIONS);
        assert_eq!(
            relations.omitted_by_label,
            [(
                SharedLabel::new("wide", "main"),
                1600 - (MAX_COORDINATE_RELATIONS - 26)
            )]
        );
    }
}