relate-executor 1.0.0

In-memory graph and Cypher physical executor
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
use super::*;

#[test]
fn pattern_stats_follow_labels_indexes_and_rel_deletes() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let manila = g
        .create_node(
            vec!["Place".into()],
            BTreeMap::from([("name".into(), Value::String("Manila".into()))]),
        )
        .unwrap();
    let paris = g
        .create_node(
            vec!["Place".into()],
            BTreeMap::from([("name".into(), Value::String("Paris".into()))]),
        )
        .unwrap();
    let person = g
        .create_node(
            vec!["Person".into()],
            BTreeMap::from([("name".into(), Value::String("Ada".into()))]),
        )
        .unwrap();
    let tag = g
        .create_node(
            vec!["Tag".into()],
            BTreeMap::from([("name".into(), Value::String("Copernicus".into()))]),
        )
        .unwrap();
    g.create_rel(person, manila, "LIVES_IN".into(), BTreeMap::new())
        .unwrap();
    g.create_rel(person, paris, "LIVES_IN".into(), BTreeMap::new())
        .unwrap();
    let extra = g
        .create_rel(person, tag, "HAS".into(), BTreeMap::new())
        .unwrap();
    g.commit_write();

    assert_eq!(g.pattern_label_rows("Place"), 2);
    assert_eq!(g.pattern_label_rows("Missing"), 0);
    assert_eq!(g.pattern_rel_type_rows("LIVES_IN"), 2);
    assert_eq!(g.pattern_rel_type_rows("HAS"), 1);
    assert_eq!(g.pattern_rel_type_rows("NOPE"), 0);
    assert_eq!(
        g.pattern_equality_rows("Place", "name", &Value::String("Manila".into())),
        None
    );

    g.materialize_range_index("Place", "name");
    assert_eq!(
        g.pattern_equality_rows("Place", "name", &Value::String("Manila".into())),
        Some(1)
    );
    assert_eq!(
        g.pattern_equality_rows("Place", "name", &Value::String("Nope".into())),
        Some(0)
    );

    g.materialize_text_index("Tag", "name");
    assert_eq!(
        g.pattern_contains_rows("Tag", "name", "pernicus"),
        ContainsCount::TextIndex(1)
    );
    assert_eq!(
        g.pattern_contains_rows("Tag", "name", "zzz"),
        ContainsCount::TextIndex(0)
    );
    // No TEXT index on Place: LABS-643's sampled estimate, exact at this
    // size (both Place nodes sit inside the sample bound), carrying the
    // label bucket's rows as the scan floor (the compound's ADR).
    assert_eq!(
        g.pattern_contains_rows("Place", "name", "Manila"),
        ContainsCount::SampleScan { rows: 1, scan: 2 }
    );

    g.begin_write().unwrap();
    g.delete_rel(extra);
    g.commit_write();
    assert_eq!(g.pattern_rel_type_rows("HAS"), 0);
    assert_eq!(g.pattern_rel_type_rows("LIVES_IN"), 2);

    g.begin_write().unwrap();
    g.create_rel(person, manila, "LIVES_IN".into(), BTreeMap::new())
        .unwrap();
    g.abort_write();
    assert_eq!(g.pattern_rel_type_rows("LIVES_IN"), 2);
}

/// LABS-643: the sampled `CONTAINS` estimate a store without a TEXT index
/// reports — exact while the label fits inside the sample bound,
/// extrapolated beyond it, `SampleScan` provenance either way (the TEXT
/// index above stays the one exact measurement).
#[test]
fn sampled_contains_counts_exactly_inside_the_bound_and_extrapolates_beyond() {
    let g = Graph::default();
    g.begin_write().unwrap();
    for i in 0..3 {
        let name = if i == 0 { "Copernicus" } else { "Kepler" };
        g.create_node(
            vec!["Small".into()],
            BTreeMap::from([("name".into(), Value::String(name.into()))]),
        )
        .unwrap();
    }
    // Two beyond-bound labels: every node of one carries the needle, no
    // node of the other does. The all-match half is extrapolation-exact
    // whichever unordered ids the label bucket hands the scan; the
    // no-match half answers the FLOOR, not zero — an unindexed filter
    // still pays the whole-label scan, so its estimate never drops below
    // 1% of the label (CONTAINS_SAMPLE_FLOOR_DIVISOR).
    let big = 2 * CONTAINS_SAMPLE_BOUND;
    for _ in 0..big {
        g.create_node(
            vec!["AllMatch".into()],
            BTreeMap::from([("name".into(), Value::String("xCopernicusx".into()))]),
        )
        .unwrap();
        g.create_node(
            vec!["NoMatch".into()],
            BTreeMap::from([("name".into(), Value::String("Brahe".into()))]),
        )
        .unwrap();
    }
    g.commit_write();

    assert_eq!(
        g.pattern_contains_rows("Small", "name", "Copernicus"),
        ContainsCount::SampleScan { rows: 1, scan: 3 }
    );
    assert_eq!(
        g.pattern_contains_rows("AllMatch", "name", "Copernicus"),
        ContainsCount::SampleScan {
            rows: big as u64,
            scan: big as u64,
        }
    );
    assert_eq!(
        g.pattern_contains_rows("NoMatch", "name", "Copernicus"),
        ContainsCount::SampleScan {
            rows: big as u64 / 100,
            scan: big as u64,
        }
    );
}

/// The extrapolated fraction (LABS-643): half of a beyond-bound label
/// carries the needle, and the estimate lands near half the label — a
/// band, not an exact count, because the label bucket's iteration order
/// (and so the sample) is not insertion order. The band still pins the
/// magnitude: the pre-LABS-643 fallback was the label's whole row count.
#[test]
fn sampled_contains_extrapolates_the_fraction_within_a_band() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let total = 4 * CONTAINS_SAMPLE_BOUND as u64;
    for i in 0..total {
        let name = if i % 2 == 0 { "Copernicus" } else { "Kepler" };
        g.create_node(
            vec!["Half".into()],
            BTreeMap::from([("name".into(), Value::String(name.into()))]),
        )
        .unwrap();
    }
    g.commit_write();
    let rows = match g.pattern_contains_rows("Half", "name", "Copernicus") {
        ContainsCount::SampleScan { rows, .. } => rows,
        other => panic!("expected the sampled estimate, got {other:?}"),
    };
    // The sample's match share extrapolates to total/2; a bound-sized
    // sample's noise is orders of magnitude inside [total/4, 3*total/4].
    assert!(
        rows * 4 > total && rows * 4 < total * 3,
        "sampled {rows} of {total} rows"
    );
}

/// The sampled estimate follows the committed epoch (LABS-643): the
/// memoized answer of the old epoch must not survive a commit that
/// changes the data — the next read resamples.
#[test]
fn sampled_contains_resamples_after_a_commit_moves_the_epoch() {
    let g = Graph::default();
    g.begin_write().unwrap();
    g.create_node(
        vec!["Tag".into()],
        BTreeMap::from([("name".into(), Value::String("Copernicus".into()))]),
    )
    .unwrap();
    g.create_node(
        vec!["Tag".into()],
        BTreeMap::from([("name".into(), Value::String("Kepler".into()))]),
    )
    .unwrap();
    g.commit_write();
    assert_eq!(
        g.pattern_contains_rows("Tag", "name", "Copernicus"),
        ContainsCount::SampleScan { rows: 1, scan: 2 }
    );
    g.begin_write().unwrap();
    g.create_node(
        vec!["Tag".into()],
        BTreeMap::from([("name".into(), Value::String("Copernicus_2".into()))]),
    )
    .unwrap();
    g.commit_write();
    assert_eq!(
        g.pattern_contains_rows("Tag", "name", "Copernicus"),
        ContainsCount::SampleScan { rows: 2, scan: 3 }
    );
}

/// A label or key the store never interned can match nothing, and a
/// non-string property never contains a string needle: the sampled
/// estimate answers zero — measurable, not `None` (LABS-643).
#[test]
fn sampled_contains_answers_zero_for_uninterned_names_and_non_strings() {
    let g = Graph::default();
    g.begin_write().unwrap();
    g.create_node(
        vec!["Tag".into()],
        BTreeMap::from([("name".into(), Value::String("Copernicus".into()))]),
    )
    .unwrap();
    g.create_node(
        vec!["Num".into()],
        BTreeMap::from([("name".into(), Value::Int(7))]),
    )
    .unwrap();
    g.commit_write();
    assert_eq!(
        g.pattern_contains_rows("NoLabel", "name", "x"),
        ContainsCount::SampleScan { rows: 0, scan: 0 }
    );
    assert_eq!(
        g.pattern_contains_rows("Tag", "nokey", "x"),
        ContainsCount::SampleScan { rows: 0, scan: 1 }
    );
    assert_eq!(
        g.pattern_contains_rows("Num", "name", "7"),
        ContainsCount::SampleScan { rows: 0, scan: 1 }
    );
}

/// LABS-351: the (label, rel-type) degree histogram's tail — the estimate
/// the mean degree cannot express. A label of 6 nodes where one carries
/// 20 outgoing rels has a mean degree of ~3.3 but a tail of 16 (the floor
/// of 20); the gate that must never miss the supernode consults the tail.
#[test]
fn degree_tail_reports_the_supernode_not_the_mean() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let outs: Vec<_> = (0..26)
        .map(|_| g.create_node(vec!["Out".into()], BTreeMap::new()).unwrap())
        .collect();
    // Five degree-1 nodes and one degree-20 supernode, all Source.
    for out in outs.iter().take(5) {
        let src = g
            .create_node(vec!["Source".into()], BTreeMap::new())
            .unwrap();
        g.create_rel(src, *out, "R".into(), BTreeMap::new())
            .unwrap();
    }
    let super_node = g
        .create_node(vec!["Source".into()], BTreeMap::new())
        .unwrap();
    for o in outs.iter().take(20) {
        g.create_rel(super_node, *o, "R".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    // The mean: 25 rels over 6 sources ~ 4.2 — the supernode is invisible.
    let mean = g.pattern_rel_type_rows("R") / g.pattern_label_rows("Source");
    assert!(mean < 5, "mean degree {mean} hides the supernode");
    // The tail: the top non-empty bucket floors the supernode's degree 20
    // at 16 (bucket 4); the degree-1 nodes sit in bucket 0.
    assert_eq!(g.pattern_degree_tail("Source", "R"), Some(16));
    // A pair never written answers None, not zero.
    assert_eq!(g.pattern_degree_tail("Source", "NEVER"), None);
    assert_eq!(g.pattern_degree_tail("NoLabel", "R"), None);
}

/// LABS-351: the high-water semantics — a deleted rel does not move the
/// bucket down (the typed adjacency keeps tombstoned entries; the floor
/// only ever overestimates), and the adjacency rebuild recalibrates the
/// tail to the honest live state.
#[test]
fn degree_tail_is_high_water_until_the_rebuild_recalibrates() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let outs: Vec<_> = (0..10)
        .map(|_| g.create_node(vec!["Out".into()], BTreeMap::new()).unwrap())
        .collect();
    let src = g
        .create_node(vec!["Source".into()], BTreeMap::new())
        .unwrap();
    let rels: Vec<_> = outs
        .iter()
        .map(|o| g.create_rel(src, *o, "R".into(), BTreeMap::new()).unwrap())
        .collect();
    g.commit_write();
    assert_eq!(g.pattern_degree_tail("Source", "R"), Some(8)); // floor(10)=8

    // Delete half: the high-water floor stays (the conservative direction).
    g.begin_write().unwrap();
    for r in rels.iter().take(5) {
        g.delete_rel(*r);
    }
    g.commit_write();
    assert_eq!(g.pattern_degree_tail("Source", "R"), Some(8));

    // The rebuild recomputes from the live rels: degree 5 floors at 4.
    g.rebuild_adj();
    assert_eq!(g.pattern_degree_tail("Source", "R"), Some(4));
}

/// LABS-351's blocker fix, pinned: a label added after the edges exist
/// inherits the node's degree buckets immediately (`SET n:Hub` on an
/// already-connected supernode lands in the (Hub, type) histogram), and a
/// removed label stops owning them. The never-miss invariant holds for
/// labels at any time, not only at node create.
#[test]
fn degree_tail_follows_label_mutation() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let outs: Vec<_> = (0..10)
        .map(|_| g.create_node(vec!["Out".into()], BTreeMap::new()).unwrap())
        .collect();
    // Connected first, labeled after: the reverse of the create order.
    let src = g
        .create_node(vec!["Plain".into()], BTreeMap::new())
        .unwrap();
    for o in &outs {
        g.create_rel(src, *o, "R".into(), BTreeMap::new()).unwrap();
    }
    g.commit_write();
    assert_eq!(g.pattern_degree_tail("Plain", "R"), Some(8)); // floor(10)=8
    assert_eq!(g.pattern_degree_tail("Hub", "R"), None); // never written

    g.begin_write().unwrap();
    g.add_labels(src, &["Hub".into()]);
    g.commit_write();
    // The added label inherits the buckets at once — the invariant.
    assert_eq!(g.pattern_degree_tail("Hub", "R"), Some(8));

    g.begin_write().unwrap();
    g.remove_labels(src, &["Hub".into()]);
    g.commit_write();
    // The removed label no longer owns them.
    assert_eq!(g.pattern_degree_tail("Hub", "R"), None);
}

/// LABS-370: the (start-label, rel-type, end-label) pair counts are
/// exact — creates add, deletes remove, and the counting operator can
/// answer from them byte-identically to a scan.
#[test]
fn pair_counts_follow_creates_and_deletes() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let person = g
        .create_node(vec!["Person".into()], BTreeMap::new())
        .unwrap();
    let city = g
        .create_node(vec!["City".into(), "Place".into()], BTreeMap::new())
        .unwrap();
    let r1 = g
        .create_rel(person, city, "LIVES_IN".into(), BTreeMap::new())
        .unwrap();
    g.create_rel(person, city, "LIVES_IN".into(), BTreeMap::new())
        .unwrap();
    g.commit_write();

    assert_eq!(g.pattern_pair_rows("Person", "LIVES_IN", "City"), Some(2));
    assert_eq!(g.pattern_pair_rows("Person", "LIVES_IN", "Place"), Some(2));
    assert_eq!(g.pattern_pair_rows("City", "LIVES_IN", "Person"), None);
    assert_eq!(g.pattern_pair_rows("Person", "NOPE", "City"), None);

    g.begin_write().unwrap();
    g.delete_rel(r1);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("Person", "LIVES_IN", "City"), Some(1));
    assert_eq!(g.pattern_pair_rows("Person", "LIVES_IN", "Place"), Some(1));
}

/// LABS-370: a label mutation moves the node's rel contributions between
/// the pair counts — both endpoint sides, added and removed labels
/// (the #398 blocker's lesson applied to the pair map from day one).
#[test]
fn pair_counts_follow_label_mutations_both_sides() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let c = g.create_node(vec!["C".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    g.create_rel(c, b, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A", "R", "B"), Some(1));
    assert_eq!(g.pattern_pair_rows("C", "R", "B"), Some(1));

    // Start-side addition: A gains "A2"; its rel counts under A2 too.
    g.begin_write().unwrap();
    g.add_labels(a, &["A2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A", "R", "B"), Some(1));
    assert_eq!(g.pattern_pair_rows("A2", "R", "B"), Some(1));

    // End-side addition: B gains "B2"; every rel into B counts under B2.
    g.begin_write().unwrap();
    g.add_labels(b, &["B2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A", "R", "B2"), Some(1));
    assert_eq!(g.pattern_pair_rows("A2", "R", "B2"), Some(1));
    assert_eq!(g.pattern_pair_rows("C", "R", "B2"), Some(1));

    // Removals: the actually-removed labels lose their contributions.
    g.begin_write().unwrap();
    g.remove_labels(a, &["A2".into()]);
    g.remove_labels(b, &["B2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A2", "R", "B"), None);
    assert_eq!(g.pattern_pair_rows("A", "R", "B2"), None);
    assert_eq!(g.pattern_pair_rows("C", "R", "B2"), None);
    assert_eq!(g.pattern_pair_rows("A", "R", "B"), Some(1));
    assert_eq!(g.pattern_pair_rows("C", "R", "B"), Some(1));
}

/// ADR-0551: the checkpoint's fold moves a chunk's hops into the sealed
/// tier; the label-mutation pair walk reads the merged delta+sealed
/// stream, so the mutation still finds (and charges) every incident rel
/// the chunk holds.
#[test]
fn pair_counts_include_sealed_hops_after_a_fold() {
    let g = Graph::default();
    let (a, _, _, type_id) = crate::graph::test_support::folded_floor_chunk(&g);
    let floor = crate::adjacency::COMPACTION_DELTA_FLOOR;
    assert_eq!(g.sealed_out.get(&a).unwrap().chunk_len(type_id), floor);
    assert_eq!(g.pattern_pair_rows("N", "T", "N"), Some(floor as u64));

    g.begin_write().unwrap();
    g.add_labels(a, &["A2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("N", "T", "N"), Some(floor as u64));
    assert_eq!(g.pattern_pair_rows("A2", "T", "N"), Some(floor as u64));
}

/// LABS-370: the wholesale adjacency rebuild recalibrates the pair
/// counts from the live state (the high-water-free exact map, the
/// histogram's rebuild precedent).
#[test]
fn pair_counts_recalibrate_on_rebuild() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    g.rebuild_adj();
    assert_eq!(g.pattern_pair_rows("A", "R", "B"), Some(1));
}

/// LABS-370 round 3 (F-1-2): the incident pair walk must see rels
/// created earlier in the SAME batch — a ts-probe at `commit_ts` misses
/// them (their xmin > commit_ts inside the write window), so a label
/// added after an in-batch rel lost the rel's pair entries. The live
/// version (xmax == 0) sees them; the pair count stays exact with no
/// commit between the create and the label mutation.
#[test]
fn pair_counts_see_in_batch_rels_on_label_mutation() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    // Same batch, no commit between: the label lands after the rel.
    g.add_labels(a, &["A2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A2", "R", "B"), Some(1));
    // The far side too: the end node's added label inherits the
    // in-batch rel.
    g.begin_write().unwrap();
    g.create_rel(a, b, "R2".into(), BTreeMap::new()).unwrap();
    g.add_labels(b, &["B2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A", "R2", "B2"), Some(1));
    assert_eq!(g.pattern_pair_rows("A2", "R2", "B2"), Some(1));
}

/// The WAL proptest's persisted failure (replay_is_deterministic): a rel
/// id deleted and re-created with different endpoints keeps its old hop
/// in the old end's in-adjacency (older snapshots still traverse it),
/// but the rel's LIVE version ends elsewhere — the incident walk
/// ([`Graph::incident_rels`]) used to debug-assert the walked side and
/// mis-price the stale hop as a live incidence (in release builds,
/// silently). The live version's walked-side end decides: the stale hop
/// is history and is skipped, exactly like a hop with no live version.
#[test]
fn pair_counts_skip_a_reused_rel_ids_stale_hop() {
    let g = Graph::default();
    g.apply_redo(
        vec![
            RedoOp::create_node(1, vec!["A".to_string()], BTreeMap::new()),
            RedoOp::create_node(2, vec!["B".to_string()], BTreeMap::new()),
            RedoOp::create_node(3, vec!["C".to_string()], BTreeMap::new()),
        ],
        1,
    )
    .unwrap();
    // Rel 6 lives (1→2), dies, and its id is re-created (1→3): node 2's
    // in-adjacency keeps the first hop.
    g.apply_redo(
        vec![RedoOp::create_rel(
            6,
            1,
            2,
            "R".to_string(),
            BTreeMap::new(),
        )],
        2,
    )
    .unwrap();
    g.apply_redo(vec![RedoOp::delete_rel(6)], 3).unwrap();
    g.apply_redo(
        vec![
            RedoOp::create_rel(6, 1, 3, "R".to_string(), BTreeMap::new()),
            RedoOp::add_labels(2, vec!["B2".to_string()]),
        ],
        4,
    )
    .unwrap();
    // The re-created rel's live pair entry is (A, R, C) — and node 2's
    // label mutation must not charge the stale hop: no (A, R, B2), no
    // (B2, R, A), the diagonal only if a live rel actually rode node 2.
    assert_eq!(g.pattern_pair_rows("A", "R", "C"), Some(1));
    assert_eq!(g.pattern_pair_rows("A", "R", "B"), None);
    assert_eq!(g.pattern_pair_rows("A", "R", "B2"), None);
    assert_eq!(g.pattern_pair_rows("B2", "R", "A"), None);
    assert_eq!(g.pattern_pair_rows("B2", "R", "B2"), None);
}

/// The stale-hop rule's second axis (stellar boundaries round 1): a rel
/// id deleted and re-created with the SAME endpoints but a DIFFERENT
/// rel type keeps its old hop in the old type's adjacency chunk. The
/// endpoint guard alone lets that hop through — the live-identity match
/// must hold on the type axis too, or the stale hop prices pair-count
/// entries under a rel type the live rel no longer has.
#[test]
fn pair_counts_skip_a_reused_rel_ids_retyped_hop() {
    let g = Graph::default();
    g.apply_redo(
        vec![
            RedoOp::create_node(1, vec!["A".to_string()], BTreeMap::new()),
            RedoOp::create_node(2, vec!["B".to_string()], BTreeMap::new()),
        ],
        1,
    )
    .unwrap();
    // Rel 7 lives (1→2, "R"), dies, and its id comes back (1→2, "S"):
    // node 2's in-adjacency keeps the "R"-chunk hop.
    g.apply_redo(
        vec![RedoOp::create_rel(
            7,
            1,
            2,
            "R".to_string(),
            BTreeMap::new(),
        )],
        2,
    )
    .unwrap();
    g.apply_redo(vec![RedoOp::delete_rel(7)], 3).unwrap();
    g.apply_redo(
        vec![
            RedoOp::create_rel(7, 1, 2, "S".to_string(), BTreeMap::new()),
            RedoOp::add_labels(2, vec!["B2".to_string()]),
        ],
        4,
    )
    .unwrap();
    // The live rel's pair entry is (A, S, B) — the label mutation must
    // not charge the stale "R" hop: no (A, R, B2), no (B2, R, A).
    assert_eq!(g.pattern_pair_rows("A", "S", "B"), Some(1));
    assert_eq!(g.pattern_pair_rows("A", "R", "B"), None);
    assert_eq!(g.pattern_pair_rows("A", "R", "B2"), None);
    assert_eq!(g.pattern_pair_rows("B2", "R", "A"), None);
    assert_eq!(g.pattern_pair_rows("A", "S", "B2"), Some(1));
}

/// LABS-425 (round 5's self-loop fix, pinned on the round-6 pass split):
/// a self-loop rides both adjacency sides of its own node, and the
/// correct far set for the mutated node itself is mutation-aware on both
/// sides — the out side charges `mutated × (live ∪ mutated)`, the in side
/// the complement, so the (mutated, type, mutated) diagonal is charged
/// exactly once, by the out side, and drained exactly once on remove.
/// The far rel to the B node carries label A too, so the (A2, R, A) key
/// is charged by BOTH passes — the far-node pass and the self-loop pass
/// collide on one key, pinning that the split passes sum like the
/// interleaved walk did.
#[test]
fn pair_counts_charge_the_self_loop_diagonal_exactly_once() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    // One self-loop and one far rel whose end carries A — the cross-pass
    // key collision: both realize (A2, R, A) on the add below.
    g.create_rel(a, a, "R".into(), BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A", "R", "A"), Some(2));

    // Add: the diagonal gains exactly one charge (not two — the rel rides
    // both adjacency sides), and the cross-pass key lands at 2.
    g.begin_write().unwrap();
    g.add_labels(a, &["A2".into()]);
    g.commit_write();
    // Far pass: mutated [A2] × far [A] -> (A2, R, A).
    // Self-loop out pass: [A2] × (live ∪ mutated) = [A, A2] ->
    // (A2, R, A) again (the collision) and the diagonal (A2, R, A2).
    // Self-loop in pass: (live ∪ mutated) \ mutated = [A] × [A2] ->
    // (A, R, A2).
    assert_eq!(g.pattern_pair_rows("A", "R", "A"), Some(2));
    assert_eq!(g.pattern_pair_rows("A2", "R", "A"), Some(2));
    assert_eq!(g.pattern_pair_rows("A2", "R", "A2"), Some(1));
    assert_eq!(g.pattern_pair_rows("A", "R", "A2"), Some(1));

    // Remove: the diagonal drains exactly once (the entry leaves the
    // map), the collision key drains through both passes' charges, and
    // the untouched (A, R, A) survives.
    g.begin_write().unwrap();
    g.remove_labels(a, &["A2".into()]);
    g.commit_write();
    assert_eq!(g.pattern_pair_rows("A", "R", "A"), Some(2));
    assert_eq!(g.pattern_pair_rows("A2", "R", "A"), None);
    assert_eq!(g.pattern_pair_rows("A2", "R", "A2"), None);
    assert_eq!(g.pattern_pair_rows("A", "R", "A2"), None);
}

/// LABS-370 round 3 (F-1-6): the AddLabels admission estimate simulates
/// the batch's in-batch rels — apply walks them (the incident walk and
/// the rebucket see the rel the batch created), so the estimate must
/// price their entries too or drift from the applied `used_bytes` on a
/// mixed [CreateRel, AddLabels] batch.
#[test]
fn stats_entry_growth_estimates_mixed_batches() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    g.commit_write();
    let ops = vec![
        RedoOp::create_rel(1, a, b, "R".to_string(), BTreeMap::new()),
        RedoOp::add_labels(a, vec!["A2".to_string()]),
    ];
    // CreateRel: the (A,R) histogram entry + the (A,R,B) pair entry.
    // AddLabels on the start node, same batch: the A2 label count, the
    // (A2,R) histogram entry (the in-batch rel's out-degree), and the
    // (A2,R,B) pair entry (the in-batch rel's incident contribution).
    let expected = (2 * Graph::HISTOGRAM_ENTRY_BYTES
        + 2 * Graph::PAIR_COUNT_ENTRY_BYTES
        + Graph::LABEL_COUNT_ENTRY_BYTES) as i64;
    assert_eq!(g.estimate_stats_entry_growth(&ops), expected);
}

/// LABS-425 (stellar round 1): the estimate's incident walk prices BOTH
/// sides of a committed self-loop — the apply path charges
/// `mutated × (live ∪ mutated)` on the out side and the complement on
/// the in side, so the estimate must price the same three pair entries
/// or an over-cap self-loop AddLabels batch slips past admission (the
/// old `seen_far` early-out keyed (type, far) and skipped the in side).
#[test]
fn stats_entry_growth_prices_a_committed_self_loop_on_both_sides() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, a, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    let ops = vec![RedoOp::add_labels(a, vec!["A2".to_string()])];
    // The A2 label count, the (A2, R) histogram entry (the self-loop's
    // out-degree bucket), and the three pair entries: out side
    // A2 × (A ∪ A2) -> (A2,R,A) and the diagonal (A2,R,A2); in side
    // (A ∪ A2) \ A2 -> (A,R,A2).
    let expected = (Graph::HISTOGRAM_ENTRY_BYTES
        + 3 * Graph::PAIR_COUNT_ENTRY_BYTES
        + Graph::LABEL_COUNT_ENTRY_BYTES) as i64;
    assert_eq!(g.estimate_stats_entry_growth(&ops), expected);
}

/// LABS-425 (stellar round 1): a reciprocal same-type pair — a-[:R]->b
/// AND b-[:R]->a — is the other two-sided incidence the old `seen_far`
/// early-out under-priced: the (t, far) key matched across the two
/// sides, so the in-side keys ((far-label, t, added)) were never priced.
#[test]
fn stats_entry_growth_prices_a_reciprocal_pair_on_both_sides() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    g.create_rel(b, a, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    let ops = vec![RedoOp::add_labels(a, vec!["A2".to_string()])];
    // The A2 label count, the (A2, R) histogram entry, and the two pair
    // entries: the out side's (A2,R,B) and the in side's (B,R,A2).
    let expected = (Graph::HISTOGRAM_ENTRY_BYTES
        + 2 * Graph::PAIR_COUNT_ENTRY_BYTES
        + Graph::LABEL_COUNT_ENTRY_BYTES) as i64;
    assert_eq!(g.estimate_stats_entry_growth(&ops), expected);
}

/// LABS-425 (stellar round 1): an IN-BATCH self-loop is two-sided too —
/// the CreateRel lands before the AddLabels applies, so the apply
/// incident walk sees the rel on both adjacency sides and charges both
/// crosses; the estimate's batch-rel walk prices both crosses for it.
#[test]
fn stats_entry_growth_prices_an_in_batch_self_loop_on_both_sides() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    g.commit_write();
    let ops = vec![
        RedoOp::create_rel(1, a, a, "R".to_string(), BTreeMap::new()),
        RedoOp::add_labels(a, vec!["A2".to_string()]),
    ];
    // CreateRel: the (A, R) histogram entry + the (A,R,A) pair entry.
    // AddLabels on the self-looped node: the A2 label count, the
    // (A2, R) histogram entry, and the three pair entries both sides
    // realize (out A2 × (A ∪ A2), in (A ∪ A2) \ A2 × A2).
    let expected = (2 * Graph::HISTOGRAM_ENTRY_BYTES
        + 4 * Graph::PAIR_COUNT_ENTRY_BYTES
        + Graph::LABEL_COUNT_ENTRY_BYTES) as i64;
    assert_eq!(g.estimate_stats_entry_growth(&ops), expected);
}

/// LABS-991: the any-label tail — the highest per-type tail over every
/// labeled node's histogram, the per-type maxima summed for the any-type
/// form — is the bound a hop with no `(label, type)` pair rides.
#[test]
fn any_degree_tail_is_the_highest_tail_across_labels_and_types() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let leaves: Vec<_> = (0..20)
        .map(|_| g.create_node(vec!["Leaf".into()], BTreeMap::new()).unwrap())
        .collect();
    let small = g
        .create_node(vec!["Small".into()], BTreeMap::new())
        .unwrap();
    let big = g.create_node(vec!["Big".into()], BTreeMap::new()).unwrap();
    g.create_rel(small, leaves[0], "R".into(), BTreeMap::new())
        .unwrap();
    // Big: degree 20 on R (tail 16), degree 3 on S (tail 2).
    for leaf in &leaves {
        g.create_rel(big, *leaf, "R".into(), BTreeMap::new())
            .unwrap();
    }
    for leaf in leaves.iter().take(3) {
        g.create_rel(big, *leaf, "S".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    // Per type: the highest label's tail (Big's 16, not Small's 1).
    assert_eq!(g.pattern_any_degree_tail(Some("R")), Some(16));
    assert_eq!(g.pattern_any_degree_tail(Some("S")), Some(2));
    // Any type: the per-type maxima summed (floors on the same scale).
    assert_eq!(g.pattern_any_degree_tail(None), Some(18));
    // A type never written answers None, not zero.
    assert_eq!(g.pattern_any_degree_tail(Some("NEVER")), None);
    // No histogram at all: None.
    assert_eq!(Graph::default().pattern_any_degree_tail(None), None);
}