mushroomdb 0.5.2

Embedded graph database with Cypher queries, rule triggers, and Arrow export
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
/// Integration tests for `Predicate::Any` — OR composition.
///
/// TDD order per brief:
///   1. Two-branch Any (Overlap + NumericWithin) derives correct edges.
///   2. Nested All-of-Any composition.
///   3. Score = max pin: Any score is the maximum over satisfied branches.
///   4. Retraction when the only satisfied branch breaks.
///   5. Any with max_edges (top-k): branch-score changes cause evict/backfill.
///   6. Snapshot V4 round-trip: RuleDef with Any survives snapshot + WAL replay.
///   7. Bincode backward-compat: old (pre-Any) records still decode.
use core_api::{Direction, GraphDb, Predicate, RuleDef, Value};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn tmp(name: &str) -> std::path::PathBuf {
    let d = std::env::temp_dir().join(format!("graphdb-any-{}-{}", name, std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    d
}

fn mk_tags(items: &[&str]) -> Value {
    Value::List(items.iter().map(|s| Value::Str((*s).into())).collect())
}

// ---------------------------------------------------------------------------
// 1. Two-branch Any: Overlap OR NumericWithin
// ---------------------------------------------------------------------------

/// Any([Overlap(tags, 0.3), NumericWithin(year, 5)]) derives an edge when
/// either branch fires — even when the other does not.
#[test]
fn any_two_branch_overlap_or_numeric_derives_edges() {
    let dir = tmp("two-branch");
    let mut db = GraphDb::open(&dir).unwrap();

    // Rule: src/dst label "N", Any(Overlap OR NumericWithin).
    db.create_rule(RuleDef {
        name: "any_test".into(),
        src_label: "N".into(),
        dst_label: "N".into(),
        predicate: Predicate::Any(vec![
            Predicate::Overlap {
                field: "tags".into(),
                min: 0.3,
            },
            Predicate::NumericWithin {
                field: "year".into(),
                tolerance: 5.0,
            },
        ]),
        edge_type: "ANY".into(),
        weight_prop: Some("score".into()),
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    })
    .unwrap();

    // a: tags=["x","y"], year=2000
    // b: tags=["y","z"], year=2010  — shares tag "y" (jaccard 1/3 ≥ 0.3 → Overlap fires)
    // c: tags=["p","q"], year=2003  — no tag overlap; year diff=3 ≤ 5 → NumericWithin fires
    // d: tags=["p","q"], year=2050  — no tag overlap; year diff=50 > 5 → neither fires
    db.insert_node(
        "N",
        "a",
        vec![
            ("tags".into(), mk_tags(&["x", "y"])),
            ("year".into(), Value::Int(2000)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "b",
        vec![
            ("tags".into(), mk_tags(&["y", "z"])),
            ("year".into(), Value::Int(2010)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "c",
        vec![
            ("tags".into(), mk_tags(&["p", "q"])),
            ("year".into(), Value::Int(2003)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "d",
        vec![
            ("tags".into(), mk_tags(&["p", "q"])),
            ("year".into(), Value::Int(2050)),
        ],
    )
    .unwrap();

    let a_out: Vec<String> = db.neighbors("a", "ANY", Direction::Out).unwrap_or_default();

    // a→b: Overlap fires (jaccard 1/3 ≥ 0.3); year diff=10 > 5 so numeric doesn't.
    assert!(
        a_out.contains(&"b".to_string()),
        "a→b must exist (Overlap branch fires); got {a_out:?}"
    );

    // a→c: tags disjoint; year diff=3 ≤ 5 → NumericWithin fires.
    assert!(
        a_out.contains(&"c".to_string()),
        "a→c must exist (NumericWithin branch fires); got {a_out:?}"
    );

    // a→d: neither branch fires.
    assert!(
        !a_out.contains(&"d".to_string()),
        "a→d must not exist (no branch fires); got {a_out:?}"
    );
}

// ---------------------------------------------------------------------------
// 2. Nested All(FieldEqual, Any(Overlap, NumericWithin))
// ---------------------------------------------------------------------------

#[test]
fn any_nested_in_all_derives_edges() {
    let dir = tmp("nested");
    let mut db = GraphDb::open(&dir).unwrap();

    // Rule: All(FieldEqual(ind), Any(Overlap(tags,0.3), NumericWithin(year,5)))
    db.create_rule(RuleDef {
        name: "nested".into(),
        src_label: "N".into(),
        dst_label: "N".into(),
        predicate: Predicate::All(vec![
            Predicate::FieldEqual {
                field: "ind".into(),
            },
            Predicate::Any(vec![
                Predicate::Overlap {
                    field: "tags".into(),
                    min: 0.3,
                },
                Predicate::NumericWithin {
                    field: "year".into(),
                    tolerance: 5.0,
                },
            ]),
        ]),
        edge_type: "NESTED".into(),
        weight_prop: Some("score".into()),
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    })
    .unwrap();

    // a and b: same ind, share tag → FieldEqual fires + Overlap fires.
    // a and c: same ind, year diff=3 ≤ 5 → FieldEqual fires + NumericWithin fires.
    // a and d: different ind → FieldEqual fails → no edge (regardless of Any).
    db.insert_node(
        "N",
        "a",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("tags".into(), mk_tags(&["x", "y"])),
            ("year".into(), Value::Int(2000)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "b",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("tags".into(), mk_tags(&["y", "z"])),
            ("year".into(), Value::Int(2020)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "c",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("tags".into(), mk_tags(&["p", "q"])),
            ("year".into(), Value::Int(2003)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "d",
        vec![
            ("ind".into(), Value::Str("law".into())),
            ("tags".into(), mk_tags(&["y", "z"])),
            ("year".into(), Value::Int(2001)),
        ],
    )
    .unwrap();

    let a_out: Vec<String> = db
        .neighbors("a", "NESTED", Direction::Out)
        .unwrap_or_default();
    assert!(
        a_out.contains(&"b".to_string()),
        "a→b: same ind + tag overlap → must exist; got {a_out:?}"
    );
    assert!(
        a_out.contains(&"c".to_string()),
        "a→c: same ind + year proximity → must exist; got {a_out:?}"
    );
    assert!(
        !a_out.contains(&"d".to_string()),
        "a→d: different ind → must not exist; got {a_out:?}"
    );
}

// ---------------------------------------------------------------------------
// 3. Score = max pin
// ---------------------------------------------------------------------------

/// When both branches satisfy, Any returns the higher score.
#[test]
fn any_score_is_max_over_satisfied_branches() {
    let dir = tmp("maxscore");
    let mut db = GraphDb::open(&dir).unwrap();

    // Rule: Any(FieldEqual(ind) → score 1.0, NumericWithin(year, 3) → variable).
    db.create_rule(RuleDef {
        name: "maxscore".into(),
        src_label: "N".into(),
        dst_label: "N".into(),
        predicate: Predicate::Any(vec![
            Predicate::FieldEqual {
                field: "ind".into(),
            },
            Predicate::NumericWithin {
                field: "year".into(),
                tolerance: 3.0,
            },
        ]),
        edge_type: "MS".into(),
        weight_prop: Some("score".into()),
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    })
    .unwrap();

    // a & b: ind match (score 1.0) AND year diff=1, tol=3 (score 2/3).
    // Any → max(1.0, 2/3) = 1.0.
    db.insert_node(
        "N",
        "a",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2000)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "b",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2001)),
        ],
    )
    .unwrap();

    let explain = db.explain("a", "b").unwrap();
    let entry = explain
        .iter()
        .find(|e| e.rule == "maxscore" && e.src_key == "a" && e.dst_key == "b")
        .expect("a→b must have an explain entry for 'maxscore'");
    let w = entry
        .weight
        .expect("weight must be present (weight_prop set)");
    assert!(
        (w - 1.0).abs() < 1e-9,
        "Any score must be max(1.0, 2/3) = 1.0; got {w}"
    );

    // a & c: only NumericWithin fires (ind differs), year diff=2 → score 1/3.
    db.insert_node(
        "N",
        "c",
        vec![
            ("ind".into(), Value::Str("law".into())),
            ("year".into(), Value::Int(2002)),
        ],
    )
    .unwrap();
    let explain_c = db.explain("a", "c").unwrap();
    let entry_c = explain_c
        .iter()
        .find(|e| e.rule == "maxscore" && e.src_key == "a" && e.dst_key == "c")
        .expect("a→c must have an explain entry");
    let wc = entry_c.weight.expect("weight present");
    assert!(
        (wc - 1.0 / 3.0).abs() < 1e-9,
        "Any score (only numeric branch fires, year diff=2, tol=3) must be 1/3; got {wc}"
    );
}

// ---------------------------------------------------------------------------
// 4. Retraction: sole satisfied branch breaks → edge retracted.
// ---------------------------------------------------------------------------

#[test]
fn any_retraction_when_sole_branch_breaks() {
    let dir = tmp("retract");
    let mut db = GraphDb::open(&dir).unwrap();

    // Rule: Any(FieldEqual(ind), NumericWithin(year, 2))
    db.create_rule(RuleDef {
        name: "ret".into(),
        src_label: "N".into(),
        dst_label: "N".into(),
        predicate: Predicate::Any(vec![
            Predicate::FieldEqual {
                field: "ind".into(),
            },
            Predicate::NumericWithin {
                field: "year".into(),
                tolerance: 2.0,
            },
        ]),
        edge_type: "RET".into(),
        weight_prop: None,
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    })
    .unwrap();

    // a: ind="arch", year=2000; b: ind="law", year=2001 (year diff=1 ≤ 2).
    // Only NumericWithin branch fires for a→b initially.
    db.insert_node(
        "N",
        "a",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2000)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "b",
        vec![
            ("ind".into(), Value::Str("law".into())),
            ("year".into(), Value::Int(2001)),
        ],
    )
    .unwrap();

    let a_out = db.neighbors("a", "RET", Direction::Out).unwrap_or_default();
    assert!(
        a_out.contains(&"b".to_string()),
        "a→b must exist initially (NumericWithin branch fires); got {a_out:?}"
    );

    // Change b's year so diff=5 > 2 — NumericWithin no longer fires.
    // FieldEqual still won't fire (ind still differs). Edge must be retracted.
    db.set_prop("b", "year", Value::Int(2005)).unwrap();

    let a_out2 = db.neighbors("a", "RET", Direction::Out).unwrap_or_default();
    assert!(
        !a_out2.contains(&"b".to_string()),
        "a→b must be retracted after year change breaks the sole matching branch; got {a_out2:?}"
    );

    // Change b's ind to match "arch" → FieldEqual branch now fires; edge re-derives.
    db.set_prop("b", "ind", Value::Str("arch".into())).unwrap();

    let a_out3 = db.neighbors("a", "RET", Direction::Out).unwrap_or_default();
    assert!(
        a_out3.contains(&"b".to_string()),
        "a→b must re-derive when FieldEqual branch fires; got {a_out3:?}"
    );
}

// ---------------------------------------------------------------------------
// 4b. Edge RETAINED when one branch breaks but the other still holds.
// ---------------------------------------------------------------------------

/// When branch A breaks (via set_prop) while branch B still matches:
///   • the edge MUST be retained
///   • the persisted weight must update from max(A,B) to B's score alone
/// Then when branch B breaks too the edge must be retracted.
///
/// This directly exercises the incremental re-evaluation path where a branch
/// flip changes the score without triggering retraction.
#[test]
fn any_edge_retained_when_one_branch_holds() {
    let dir = tmp("retain-one");
    let mut db = GraphDb::open(&dir).unwrap();

    // Rule: Any(FieldEqual(ind) → 1.0, NumericWithin(year, 10) → variable)
    // weight_prop set so we can inspect the score.
    db.create_rule(RuleDef {
        name: "ret2".into(),
        src_label: "N".into(),
        dst_label: "N".into(),
        predicate: Predicate::Any(vec![
            Predicate::FieldEqual {
                field: "ind".into(),
            },
            Predicate::NumericWithin {
                field: "year".into(),
                tolerance: 10.0,
            },
        ]),
        edge_type: "R2".into(),
        weight_prop: Some("score".into()),
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    })
    .unwrap();

    // src: ind="arch", year=2000
    // dst: ind="arch", year=2004
    //   → FieldEqual fires (score 1.0)
    //   → NumericWithin: diff=4, tol=10 → score = 1 − 4/10 = 0.6
    //   → initial weight = max(1.0, 0.6) = 1.0
    db.insert_node(
        "N",
        "src",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2000)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "dst",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2004)),
        ],
    )
    .unwrap();

    // Verify initial edge and weight = 1.0
    let out0 = db
        .neighbors("src", "R2", Direction::Out)
        .unwrap_or_default();
    assert!(
        out0.contains(&"dst".to_string()),
        "src→dst must exist initially; got {out0:?}"
    );
    let explain0 = db.explain("src", "dst").unwrap();
    let e0 = explain0
        .iter()
        .find(|e| e.rule == "ret2")
        .expect("explain entry for ret2");
    let w0 = e0.weight.expect("weight present");
    assert!(
        (w0 - 1.0).abs() < 1e-9,
        "initial weight must be max(1.0, 0.6) = 1.0; got {w0}"
    );

    // Break branch A: change dst.ind so FieldEqual no longer fires.
    // Branch B (NumericWithin) still fires: year diff=4, score=0.6.
    // Edge must be RETAINED with updated weight = 0.6.
    db.set_prop("dst", "ind", Value::Str("law".into())).unwrap();

    let out1 = db
        .neighbors("src", "R2", Direction::Out)
        .unwrap_or_default();
    assert!(
        out1.contains(&"dst".to_string()),
        "src→dst must be RETAINED after FieldEqual branch breaks (NumericWithin still holds); got {out1:?}"
    );
    let explain1 = db.explain("src", "dst").unwrap();
    let e1 = explain1
        .iter()
        .find(|e| e.rule == "ret2")
        .expect("explain entry for ret2 after branch-A break");
    let w1 = e1.weight.expect("weight present after branch-A break");
    assert!(
        (w1 - 0.6).abs() < 1e-9,
        "weight must update to branch-B score (0.6) after branch-A breaks; got {w1}"
    );

    // Break branch B too: change dst.year so NumericWithin no longer fires.
    // Neither branch matches → edge must be retracted.
    db.set_prop("dst", "year", Value::Int(2050)).unwrap();

    let out2 = db
        .neighbors("src", "R2", Direction::Out)
        .unwrap_or_default();
    assert!(
        !out2.contains(&"dst".to_string()),
        "src→dst must be retracted after both branches break; got {out2:?}"
    );
}

// ---------------------------------------------------------------------------
// 5. Any with max_edges (top-k): branch-score change causes evict/backfill.
// ---------------------------------------------------------------------------

/// Verifies that when max_edges=Some(1) and a property change alters which
/// branch of Any fires (and thus the score), the per-source top-1 is
/// correctly re-evaluated: the lower-scoring dst is evicted and the higher-
/// scoring one backfills.
#[test]
fn any_with_max_edges_score_change_causes_evict_backfill() {
    let dir = tmp("topk");
    let mut db = GraphDb::open(&dir).unwrap();

    // Rule: Any(FieldEqual(ind) → score 1.0, NumericWithin(year, 10) → variable),
    // max_edges=Some(1) → top-1 per source.
    db.create_rule(RuleDef {
        name: "topk_any".into(),
        src_label: "N".into(),
        dst_label: "N".into(),
        predicate: Predicate::Any(vec![
            Predicate::FieldEqual {
                field: "ind".into(),
            },
            Predicate::NumericWithin {
                field: "year".into(),
                tolerance: 10.0,
            },
        ]),
        edge_type: "TK".into(),
        weight_prop: Some("score".into()),
        max_edges: Some(1),
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    })
    .unwrap();

    // src: ind="arch", year=2000.
    // d_low: ind="law", year=2009 → only NumericWithin fires, score=1-9/10=0.1.
    // d_high: ind="arch", year=2020 → FieldEqual fires (score 1.0); numeric year diff=20>10 no.
    //
    // Insert d_low first so it claims top-1 provisionally.
    // Insert d_high second → score 1.0 > 0.1 → d_high evicts d_low.
    db.insert_node(
        "N",
        "src",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2000)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "d_low",
        vec![
            ("ind".into(), Value::Str("law".into())),
            ("year".into(), Value::Int(2009)),
        ],
    )
    .unwrap();
    db.insert_node(
        "N",
        "d_high",
        vec![
            ("ind".into(), Value::Str("arch".into())),
            ("year".into(), Value::Int(2020)),
        ],
    )
    .unwrap();

    let top1: Vec<String> = db
        .neighbors("src", "TK", Direction::Out)
        .unwrap_or_default();
    assert_eq!(
        top1,
        vec!["d_high"],
        "top-1 must be d_high (score 1.0 > 0.1); got {top1:?}"
    );

    // Change d_high's ind so FieldEqual no longer fires and year diff=20>10 so
    // NumericWithin also doesn't fire. d_high drops out entirely.
    // d_low (year diff=9 ≤ 10) must backfill as the new top-1.
    db.set_prop("d_high", "ind", Value::Str("law".into()))
        .unwrap();

    let top1_after: Vec<String> = db
        .neighbors("src", "TK", Direction::Out)
        .unwrap_or_default();
    assert_eq!(
        top1_after,
        vec!["d_low"],
        "d_low must backfill after d_high loses its only matching branch; got {top1_after:?}"
    );

    // Restore d_high's ind → d_high evicts d_low again.
    db.set_prop("d_high", "ind", Value::Str("arch".into()))
        .unwrap();
    let top1_restored: Vec<String> = db
        .neighbors("src", "TK", Direction::Out)
        .unwrap_or_default();
    assert_eq!(
        top1_restored,
        vec!["d_high"],
        "d_high must reclaim top-1 after ind restored; got {top1_restored:?}"
    );
}

// ---------------------------------------------------------------------------
// 6. Snapshot V4 round-trip.
// ---------------------------------------------------------------------------

#[test]
fn any_snapshot_v4_roundtrip() {
    let dir = tmp("snap");
    {
        let mut db = GraphDb::open(&dir).unwrap();
        db.create_rule(RuleDef {
            name: "any_snap".into(),
            src_label: "N".into(),
            dst_label: "N".into(),
            predicate: Predicate::Any(vec![
                Predicate::FieldEqual {
                    field: "ind".into(),
                },
                Predicate::NumericWithin {
                    field: "year".into(),
                    tolerance: 3.0,
                },
            ]),
            edge_type: "SNAP".into(),
            weight_prop: Some("score".into()),
            max_edges: None,
            approximate: false,
            via_label: None,
            via_edge: None,
            via_dir: None,
        })
        .unwrap();

        db.insert_node(
            "N",
            "a",
            vec![
                ("ind".into(), Value::Str("arch".into())),
                ("year".into(), Value::Int(2000)),
            ],
        )
        .unwrap();
        db.insert_node(
            "N",
            "b",
            vec![
                ("ind".into(), Value::Str("arch".into())),
                ("year".into(), Value::Int(2001)),
            ],
        )
        .unwrap();

        // Take snapshot while derived edges (a→b, b→a) are live.
        db.snapshot().unwrap();

        // WAL-tail write after snapshot.
        db.insert_node(
            "N",
            "c",
            vec![
                ("ind".into(), Value::Str("law".into())),
                ("year".into(), Value::Int(2002)),
            ],
        )
        .unwrap();
    }

    // Reopen: snapshot + WAL tail must restore the rule and all derived edges.
    let db = GraphDb::open(&dir).unwrap();

    assert_eq!(db.rules().len(), 1, "rule must survive snapshot+WAL replay");
    assert_eq!(db.rules()[0].name, "any_snap");

    // a→b from snapshot (FieldEqual branch fires, both ind="arch").
    let a_out = db
        .neighbors("a", "SNAP", Direction::Out)
        .unwrap_or_default();
    assert!(
        a_out.contains(&"b".to_string()),
        "a→b must survive snapshot round-trip; got {a_out:?}"
    );

    // a→c from WAL tail (NumericWithin branch fires, year diff=2 ≤ 3).
    assert!(
        a_out.contains(&"c".to_string()),
        "a→c must be derived after WAL replay; got {a_out:?}"
    );
}

// ---------------------------------------------------------------------------
// 7. Bincode backward-compat: old (pre-Any) records still decode.
// ---------------------------------------------------------------------------

#[test]
fn any_bincode_roundtrip_and_old_records_still_decode() {
    // Any must survive bincode encode→decode (the V4 snapshot path uses bincode).
    let rule = RuleDef {
        name: "bc".into(),
        src_label: "A".into(),
        dst_label: "B".into(),
        predicate: Predicate::Any(vec![
            Predicate::FieldEqual { field: "f".into() },
            Predicate::Overlap {
                field: "tags".into(),
                min: 0.5,
            },
        ]),
        edge_type: "E".into(),
        weight_prop: None,
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    };
    let bytes = bincode::serialize(&rule).unwrap();
    let decoded: RuleDef = bincode::deserialize(&bytes).unwrap();
    assert_eq!(rule, decoded, "Any RuleDef must round-trip via bincode");

    // Pre-Any records (old variants 0–6) must still decode correctly.
    let old = RuleDef {
        name: "r".into(),
        src_label: "A".into(),
        dst_label: "B".into(),
        predicate: Predicate::VectorSimilar {
            field: "emb".into(),
            min: 0.9,
        },
        edge_type: "E".into(),
        weight_prop: None,
        max_edges: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
    };
    let old_bytes = bincode::serialize(&old).unwrap();
    let old_decoded: RuleDef = bincode::deserialize(&old_bytes).unwrap();
    assert_eq!(
        old, old_decoded,
        "pre-Any VectorSimilar record must still decode"
    );
}