kglite 0.15.13

Pure-Rust embedded Cypher knowledge graph engine with in-memory, mmap, and disk storage, and agent-facing schema introspection
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
//! D1 — column-store ownership: divergence coverage and the ownership pins.
//!
//! # What "divergence" means here
//!
//! Before D1 Phase 3 a columnar type's `ColumnStore` was reachable through
//! **two** `Arc`s on a memory/mapped graph: a `DirGraph`-level master and the
//! handle inside every node's `PropertyStorage::Columnar`. Nothing stopped
//! those drifting apart — `Arc::make_mut` on either side forked — and deleting
//! one of them was the whole point of the programme. The backend is the sole
//! owner now; these tests keep asking the same questions of the surviving
//! route.
//!
//! This module forks them deliberately and then asks every public read surface
//! what it sees. Two classes of assertion live here:
//!
//! 1. **Cross-surface consistency** (`all_public_reads_agree_*`). Whatever a
//!    read resolves to, *every* surface must resolve to the same thing. This
//!    holds today (all of them read the node handle) and must still hold after
//!    Phase 3 (all of them will read the backend's store). It is
//!    phase-independent and is the real gate.
//! 2. **Which replica wins** (`*_today_*`). Pinned as an exact fact with an
//!    inversion instruction, in the style of `handle.rs`'s
//!    `held_reader_forces_a_whole_graph_copy`. Phase 3 flips these; a failure
//!    before then means an unintended ownership change.
//!
//! # Phase 2 — the mutation-proof gate
//!
//! Phase 1 re-routed every caller; Phase 2 makes that irreversible. Two layers:
//!
//! - **Compile-time.** A columnar node's store handle lives behind
//!   `ColumnarRow`, whose `store` field is private to `graph::storage`, and the
//!   `NodeData` property readers Phase 1 emptied are deleted. New code
//!   *cannot* express a direct-route read; it fails to compile. The two named
//!   escapes (`ColumnarRow::node_handle` / `::repoint`) are pinned site-for-site
//!   by `no_code_reaches_a_node_held_column_store_handle`, so the
//!   remaining direct-route set is an enumerated work list rather than a
//!   guess.
//! - **Runtime**, for what the compiler cannot see: a caller that *could* have
//!   used the accessors but reads a `NodeData` it already holds. `poison_*`
//!   makes the node handle and the backend's store disagree — exactly as
//!   Phase 3 will — and one named test per caller class asserts the class
//!   observes the authoritative value. Each was shown red by reverting that
//!   one call site; see the commit body.
//!
//! # Why the divergence tests do not just assert "the master wins"
//!
//! Through Phases 1-2 the node handle *was* the read route on memory/mapped,
//! and a re-point sweep pushed master writes back onto the nodes at
//! end-of-clause; asserting master-authority then would have been a
//! permanently red test, so the pins recorded the current answer instead.
//! Phase 3 removed the handle, and those pins are inverted in place rather
//! than deleted — each one names what it used to assert.

use std::collections::HashMap;
use std::sync::Arc;

use crate::datatypes::{DataFrame, Value};
use crate::graph::dir_graph::DirGraph;
use crate::graph::schema::{InternedKey, PropertyStorage};
use crate::graph::session::{execute_mut, execute_read, ExecuteOptions};
use crate::graph::storage::column_store::ColumnStore;
use crate::graph::storage::GraphRead;
use petgraph::graph::NodeIndex;

const N: i64 = 4;

fn run(graph: &mut DirGraph, query: &str) {
    let params = HashMap::new();
    let opts = ExecuteOptions::eager(&params);
    execute_mut(graph, query, &opts).unwrap_or_else(|e| panic!("setup query failed: {query}: {e}"));
}

fn read_one(graph: &DirGraph, query: &str) -> Value {
    let params = HashMap::new();
    let opts = ExecuteOptions::eager(&params);
    let out = execute_read(graph, query, &opts).unwrap_or_else(|e| panic!("{query}: {e}"));
    out.result
        .rows
        .first()
        .and_then(|r| r.first())
        .cloned()
        .unwrap_or(Value::Null)
}

/// `n` `Item` nodes with two ordinary properties each — **not** yet columnar.
fn sized_rows(n: i64) -> DirGraph {
    let mut g = DirGraph::new();
    let rows: Vec<Vec<Value>> = (1..=n)
        .map(|i| {
            vec![
                Value::Int64(i),
                Value::String(format!("t{i}")),
                Value::String(format!("c0-{i}")),
                Value::Int64(i * 10),
            ]
        })
        .collect();
    let df = DataFrame::from_cypher_rows(
        vec![
            "id".to_string(),
            "title".to_string(),
            "c0".to_string(),
            "c1".to_string(),
        ],
        rows,
    )
    .unwrap();
    crate::graph::mutation::maintain::add_nodes(
        &mut g,
        df,
        "Item".to_string(),
        "id".to_string(),
        Some("title".to_string()),
        None,
    )
    .unwrap();
    g
}

/// A row-storage fixture, for tests that drive `enable_columnar` themselves.
fn docs_fixture() -> DirGraph {
    sized_rows(N)
}

/// `n` `Item` nodes after `enable_columnar()` — the shape every graph takes the
/// moment it is saved.
fn sized_columnar(n: i64) -> DirGraph {
    let mut g = sized_rows(n);
    g.enable_columnar();
    assert!(
        g.is_columnar(),
        "fixture must own a master column store, or every arm below is vacuous"
    );
    assert!(
        node_row_id(&g, node_of(&g, 1)).is_some(),
        "fixture nodes must be columnar rows, or the ownership arms are vacuous"
    );
    g
}

fn seeded_columnar() -> DirGraph {
    sized_columnar(N)
}

fn node_of(graph: &DirGraph, id: i64) -> NodeIndex {
    graph
        .graph
        .node_indices()
        .find(|&i| graph.graph.get_node_id(i) == Some(Value::Int64(id)))
        .unwrap_or_else(|| panic!("no Item with id {id}"))
}

fn node_row_id(graph: &DirGraph, idx: NodeIndex) -> Option<u32> {
    match graph.graph.node_weight(idx).map(|n| &n.properties) {
        Some(PropertyStorage::Columnar(row)) => Some(row.row_id()),
        _ => None,
    }
}

/// Does node `idx` still share the master's `Arc`?
/// Is the type's master store owned by the backend alone?
///
/// The D1 Phase 3 successor to `node_shares_master`: there is no node-held
/// handle to compare against any more, so the question that matters is whether
/// anything at all shares the store — which is what decides whether the next
/// write forks or mutates in place.
fn master_is_uniquely_owned(graph: &DirGraph) -> bool {
    graph
        .column_store("Item")
        .is_some_and(|master| Arc::strong_count(master) == 1)
}

/// Write `value` straight into the type's master store.
///
/// **Named for the pre-Phase-3 world and kept for continuity of the tests that
/// call it, but it no longer diverges anything.** It used to fork the master
/// away from the node-held handles, and `Arc::make_mut` succeeded at that
/// precisely because the nodes held strong handles (D1 §1.2). Phase 3 deleted
/// those handles, so the store is uniquely owned (see
/// `master_is_uniquely_owned`) and `make_mut` now mutates it in place. The
/// callers are consequently asserting "a read returns what the backend's store
/// holds", not "the surfaces agree despite a divergence" — which is the
/// strongest statement still expressible, since the divergence it was built to
/// create is no longer constructible.
///
/// Returns the interned key written.
fn diverge_master(graph: &mut DirGraph, idx: NodeIndex, key: &str, value: Value) -> InternedKey {
    let row_id = node_row_id(graph, idx).expect("columnar node");
    let ikey = graph.interner.get_or_intern(key);
    let master = Arc::make_mut(graph.column_store_mut("Item").expect("master store"));
    assert!(
        master.set(row_id, ikey, &value, None),
        "master write must land"
    );
    ikey
}

/// Pull `c0` for the node with `id: 1` out of a D3-JSON export.
/// `Value::Null` when the key is absent (which is what a REMOVE produces).
fn extract_json_c0(json: &str) -> Value {
    let obj = json
        .split('{')
        .find(|chunk| chunk.contains("\"id\":1,"))
        .unwrap_or("");
    match obj.split("\"c0\":").nth(1) {
        Some(rest) => {
            let raw = rest
                .split([',', '}'])
                .next()
                .unwrap_or("")
                .trim()
                .trim_matches('"');
            Value::String(raw.to_string())
        }
        None => Value::Null,
    }
}

/// The value each public read surface resolves for `Item{id:1}.c0`.
fn all_read_surfaces(
    graph: &mut DirGraph,
    idx: NodeIndex,
    ikey: InternedKey,
) -> Vec<(&'static str, Value)> {
    // `read_indexed` is the funnel every index / constraint build reads
    // through; its `PropertyReader` needs `&mut` only to intern the key.
    let reader = graph.property_reader("Item", "c0");
    let graph = &*graph;
    vec![
        (
            "GraphRead::node_view",
            graph
                .node_view(idx)
                .and_then(|v| v.get_property("c0"))
                .map(|c| c.into_owned())
                .unwrap_or(Value::Null),
        ),
        (
            "GraphRead::get_node_property",
            graph
                .graph
                .get_node_property(idx, ikey)
                .unwrap_or(Value::Null),
        ),
        (
            "GraphRead::node_row_properties",
            graph
                .graph
                .node_row_properties(idx)
                .into_iter()
                .find(|(k, _)| *k == ikey)
                .map(|(_, v)| v)
                .unwrap_or(Value::Null),
        ),
        (
            "DirGraph::read_indexed (index build funnel)",
            graph.read_indexed(&reader, idx).unwrap_or(Value::Null),
        ),
        (
            "Cypher RETURN n.c0",
            read_one(graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0"),
        ),
        (
            "Cypher RETURN n (whole-node projection)",
            match read_one(graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n") {
                Value::Node(nv) => nv.properties.get("c0").cloned().unwrap_or(Value::Null),
                other => panic!("expected a node value, got {other:?}"),
            },
        ),
        (
            "Cypher properties(n)",
            match read_one(graph, "MATCH (n:Item) WHERE n.id = 1 RETURN properties(n)") {
                Value::Map(m) => m.get("c0").cloned().unwrap_or(Value::Null),
                other => panic!("expected a map, got {other:?}"),
            },
        ),
        ("D3-JSON export", {
            let json = crate::graph::io::export::to_d3_json(graph, None).unwrap();
            extract_json_c0(&json)
        }),
    ]
}

// ── 1. Cross-surface consistency — phase-independent ───────────────────────

/// Without divergence, every surface must see the stored value. Without this
/// arm the consistency test below would pass on a build where every surface
/// returned `Null`.
#[test]
fn all_public_reads_agree_without_divergence() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let ikey = InternedKey::from_str("c0");
    let stored = Value::String("c0-1".into());
    for (surface, got) in all_read_surfaces(&mut graph, idx, ikey) {
        assert_eq!(got, stored, "{surface} disagreed with the stored value");
    }
}

/// **The gate.** Under master/node divergence every public read surface must
/// still agree with every other one. Which replica wins is pinned separately;
/// what must never happen is two surfaces answering differently, because that
/// is a user-visible inconsistency no matter which side is authoritative.
#[test]
fn all_public_reads_agree_under_master_node_divergence() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let ikey = diverge_master(&mut graph, idx, "c0", Value::String("MASTER".into()));

    let surfaces = all_read_surfaces(&mut graph, idx, ikey);
    let (first_name, first) = surfaces[0].clone();
    for (surface, got) in &surfaces[1..] {
        assert_eq!(
            got, &first,
            "{surface} resolved {got:?} but {first_name} resolved {first:?} — \
             two public reads of the same property must never disagree"
        );
    }
    // Agreement alone is satisfied by every surface returning `Null`, which is
    // exactly what a storeless columnar node produces — unanimously, and
    // wrongly. Pin the value the store actually holds so this cannot pass by
    // agreeing on nothing.
    assert_eq!(
        first,
        Value::String("MASTER".into()),
        "{first_name} agreed with the others on {first:?}; all surfaces \
         returning Null is agreement without a read"
    );
}

// ── 2. Which replica wins — pinned, inverted by Phase 3 ────────────────────

/// **Inverted by D1 Phase 3** (was `today_the_node_handle_wins_over_the_master`).
///
/// Before Phase 3 a master-only write was invisible: every read resolved
/// through the node's own `Arc`, and this test asserted it read the *stale*
/// value with an instruction to flip when ownership moved. Ownership has moved.
/// The backend's store is now the only store, so a write into it is what every
/// read returns.
#[test]
fn the_backend_store_is_the_only_read_route() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let ikey = diverge_master(&mut graph, idx, "c0", Value::String("MASTER".into()));
    assert_eq!(
        graph.graph.get_node_property(idx, ikey),
        Some(Value::String("MASTER".into())),
        "a write into the backend's store must be what a read returns — there \
         is no second replica left to shadow it"
    );
}

// ── 3. Writes reconverge the two replicas ──────────────────────────────────

/// A columnar `SET` writes through the master and then re-points every node of
/// the type. Post-Phase-3 there are no node handles to re-point: the write goes
/// into the store the backend owns, the journal releases its pre-image at
/// commit, and every surface reads the new value.
#[test]
fn set_leaves_the_master_uniquely_owned() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let ikey = diverge_master(&mut graph, idx, "c0", Value::String("MASTER".into()));

    run(
        &mut graph,
        "MATCH (n:Item) WHERE n.id = 1 SET n.c0 = 'WRITTEN'",
    );

    assert!(
        master_is_uniquely_owned(&graph),
        "a committed columnar SET must leave the master uniquely owned — the \
         journal's pre-image is released at commit"
    );
    let want = Value::String("WRITTEN".into());
    for (surface, got) in all_read_surfaces(&mut graph, idx, ikey) {
        assert_eq!(got, want, "{surface} did not observe the SET");
    }
}

/// The same for `REMOVE`, which takes a different master path
/// (`Arc::make_mut(master).set(.., Null, ..)`).
#[test]
fn remove_leaves_the_master_uniquely_owned() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let ikey = diverge_master(&mut graph, idx, "c0", Value::String("MASTER".into()));

    run(&mut graph, "MATCH (n:Item) WHERE n.id = 1 REMOVE n.c0");

    assert!(
        master_is_uniquely_owned(&graph),
        "a committed columnar REMOVE must leave the master uniquely owned"
    );
    for (surface, got) in all_read_surfaces(&mut graph, idx, ikey) {
        assert_eq!(got, Value::Null, "{surface} still sees a removed property");
    }
}

/// A `MERGE` key read must resolve the same value the read surfaces do —
/// otherwise `MERGE` would create a duplicate for a row that already matches
/// (or match a row that does not).
#[test]
fn merge_key_read_matches_the_public_read() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let _ = diverge_master(&mut graph, idx, "c0", Value::String("MASTER".into()));

    let before = graph.graph.node_count();
    let observed = read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0");
    let observed_str = match &observed {
        Value::String(s) => s.clone(),
        other => panic!("expected a string, got {other:?}"),
    };
    run(
        &mut graph,
        &format!("MERGE (n:Item {{id: 1, c0: '{observed_str}'}})"),
    );
    assert_eq!(
        graph.graph.node_count(),
        before,
        "MERGE on the value the public read reports must match the existing row, not create one"
    );
}

/// A rolled-back statement must leave every surface on the pre-statement value.
/// The columnar SET path emits no `NodeWeight` undo entry — its only signal is
/// `UndoEntry::ColumnarHandles` — so this is the arm that proves the journal
/// covers the master write at all.
#[test]
fn rollback_restores_every_read_surface() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let ikey = InternedKey::from_str("c0");
    let before = graph.graph.get_node_property(idx, ikey);

    // Two patterns: the first commits its SET, the second is rejected, so the
    // whole statement rolls back.
    let params = HashMap::new();
    let opts = ExecuteOptions::eager(&params);
    let err = execute_mut(
        &mut graph,
        "MATCH (n:Item) WHERE n.id = 1 SET n.c0 = 'DOOMED', \
         n.c1 = duration({months: 2147483648})",
        &opts,
    );
    assert!(err.is_err(), "the fixture statement must fail to roll back");

    assert_eq!(
        graph.graph.get_node_property(idx, ikey),
        before,
        "a rolled-back columnar SET must restore the pre-statement value"
    );
    for (surface, got) in all_read_surfaces(&mut graph, idx, ikey) {
        assert_eq!(
            Some(got),
            before.clone(),
            "{surface} kept a rolled-back value"
        );
    }
}

/// Save + reload must round-trip whatever the read surfaces report — a
/// divergence that only the writer can see is a data-loss bug, not a caching
/// one.
#[test]
fn save_and_reload_round_trips_the_observed_value() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let _ = diverge_master(&mut graph, idx, "c0", Value::String("MASTER".into()));
    run(
        &mut graph,
        "MATCH (n:Item) WHERE n.id = 1 SET n.c0 = 'PERSISTED'",
    );

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("g.kgl");
    let mut arc = Arc::new(graph);
    crate::graph::io::file::prepare_save(&mut arc);
    Arc::make_mut(&mut arc).enable_columnar();
    crate::graph::io::file::write_kgl(&arc, path.to_str().unwrap()).unwrap();

    let loaded = crate::graph::io::file::load_file(path.to_str().unwrap()).unwrap();
    assert_eq!(
        read_one(&loaded, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0"),
        Value::String("PERSISTED".into()),
        "the saved file must carry the value the reads reported"
    );
}

// ── 4. Defect 2 — `maybe_spill_columns` reclaims nothing ───────────────────

/// **D1 defect 2 — CLOSED, and inverted here** (was
/// `spill_forks_the_master_and_reclaims_nothing_today`).
///
/// `maybe_spill_columns` calls `Arc::make_mut` on the type's store and then
/// `materialize_to_files`. Before Phase 3 every node held a strong handle, so
/// `make_mut` *forked*: the master became the file-backed copy while all N
/// nodes kept the pre-spill in-heap store alive, and — unlike the SET path —
/// no sweep re-pointed them. Reads stayed correct; the memory the spill exists
/// to reclaim was never reclaimed.
///
/// With the backend the sole owner the store is uniquely owned, `make_mut`
/// mutates in place, and the spilled store *is* the one every read resolves.
/// The two assertions the old test made are inverted verbatim.
#[test]
fn spill_reclaims_the_heap_it_materialises() {
    let mut graph = seeded_columnar();
    let dir = tempfile::tempdir().unwrap();
    graph.spill_dir = Some(dir.path().to_path_buf());
    // Any limit below the store's heap footprint forces a spill.
    graph.memory_limit = Some(0);

    assert!(
        master_is_uniquely_owned(&graph),
        "precondition: nothing but the backend owns the store before the spill"
    );
    let heap_before = graph
        .column_store("Item")
        .expect("master store")
        .heap_bytes();
    assert!(heap_before > 0, "precondition: the store holds heap data");

    graph.maybe_spill_columns();

    let master = graph.column_store("Item").expect("master store");
    assert!(
        master.is_mapped(),
        "the spill must have materialised the master to files, or this test proves nothing"
    );
    // INVERTED (was: the node keeps an unmapped pre-spill copy alive).
    assert!(
        master.heap_bytes() < heap_before,
        "the spill must reclaim heap: got {} bytes, was {heap_before}. Before D1 \
         Phase 3 `make_mut` forked and this number never moved.",
        master.heap_bytes()
    );
    assert!(
        master_is_uniquely_owned(&graph),
        "and the spilled store must still be the uniquely-owned one — a fork \
         here would mean the reclaimed copy is not what reads resolve"
    );

    // The user-visible contract is unchanged: reads still resolve.
    assert_eq!(
        read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0"),
        Value::String("c0-1".into()),
        "a spill must never change what a read returns"
    );
}

// ── 5. Defect 1 — columnar enumeration completeness ────────────────────────

/// `describe()`'s per-type property block and node samples read through the
/// accessors now; before D1 Phase 1 they went through `NodeData::property_iter`
/// and enumerated **nothing** for a saved graph.
#[test]
fn describe_reports_columnar_properties() {
    use crate::graph::introspection::{ConnectionDetail, CypherDetail, FluentDetail};
    let graph = seeded_columnar();
    let xml = crate::graph::introspection::describe::compute_description(
        &graph,
        None,
        &ConnectionDetail::Off,
        &CypherDetail::Off,
        &FluentDetail::Off,
        None,
        None,
        None,
    )
    .unwrap();
    assert!(
        xml.contains("c0"),
        "describe() lost a columnar property: {xml}"
    );
    assert!(
        xml.contains("c0-1"),
        "describe()'s node sample lost a columnar property value: {xml}"
    );
}

/// `compute_property_stats` accumulates from the row, not just from the
/// `type_schemas` pre-seed: a columnar property must report a non-zero
/// non-null count and real sample values.
#[test]
fn property_stats_count_columnar_rows() {
    let graph = seeded_columnar();
    let stats = crate::graph::introspection::schema_overview::compute_property_stats(
        &graph, "Item", 32, None,
    )
    .expect("property stats");
    let c0 = stats
        .iter()
        .find(|p| p.property_name == "c0")
        .expect("c0 must appear in the property stats");
    assert_eq!(
        c0.non_null, N as usize,
        "columnar rows contributed no values to the property stats"
    );
    assert_eq!(
        c0.unique, N as usize,
        "columnar rows contributed no distinct values"
    );
}

/// `property_ndv` — the planner's selectivity input — must see columnar rows.
/// It bypasses `read_indexed` and reads the node directly, so it is one of the
/// callers the inventory flagged as "a reader would assume it is covered".
#[test]
fn property_ndv_counts_columnar_rows() {
    let graph = seeded_columnar();
    assert_eq!(
        graph.property_ndv("Item", "c0"),
        Some(N as usize),
        "property_ndv must see a columnar type's distinct values"
    );
}

// ══════════════════════════════════════════════════════════════════════════
// Phase 2 — the mutation-proof gate
// ══════════════════════════════════════════════════════════════════════════

// ── The poison primitive ──────────────────────────────────────────────────

/// Install a **different** store for `node_type`, with `edit` applied.
///
/// # What this proves after D1 Phase 3
///
/// In Phase 2 the poison had to fabricate a disagreement between two replicas —
/// a stale copy on every node and the truth in the master — because both routes
/// pointed at the same object and a gate that cannot tell them apart is not a
/// gate. Phase 3 deleted the node-held replica outright, so the disagreement is
/// no longer expressible: `column_store(type)` *is* the read route, and the
/// compile-time gate (`ColumnarRow` carries a row id and nothing else) is what
/// now rules out the class the thread-local hook used to catch.
///
/// What survives here is still worth having: a caller that captured an `Arc` of
/// the store earlier — a cache, a snapshot taken across a write — keeps reading
/// the old object, and every named class test below re-reads through the
/// backend after this swap. The mechanism got simpler because the ownership
/// got simpler.
fn poison_row(
    graph: &mut DirGraph,
    node_type: &str,
    edit: impl FnOnce(&mut ColumnStore),
) -> PoisonGuard {
    let mut replacement: ColumnStore = (**graph
        .column_store(node_type)
        .expect("type must be columnar, or the poison is a no-op"))
    .clone();
    edit(&mut replacement);
    graph.install_column_store(node_type, Arc::new(replacement));
    PoisonGuard
}

/// Kept as a unit so the call sites read unchanged across Phase 2 → 3; the
/// swap is permanent for the graph under test, which is built per test.
struct PoisonGuard;

/// Poison one row's property column.
fn poison_property(
    graph: &mut DirGraph,
    node_type: &str,
    row_id: u32,
    key: &str,
    value: Value,
) -> PoisonGuard {
    let ikey = graph.interner.get_or_intern(key);
    poison_row(graph, node_type, move |store| {
        assert!(
            store.set(row_id, ikey, &value, None),
            "poison write must land, or the swap proves nothing"
        );
    })
}

/// Poison one row's `__title__` column.
fn poison_title(graph: &mut DirGraph, node_type: &str, row_id: u32, value: Value) -> PoisonGuard {
    poison_row(graph, node_type, move |store| {
        assert!(
            store.set_title(row_id, &value),
            "poison title write must land, or the swap proves nothing"
        );
    })
}

/// Fixture: a saved graph with row 0 (`id: 1`) poisoned so its authoritative
/// `c0` is `TRUTH` while its node handle still says `c0-1`.
fn poisoned_fixture() -> (DirGraph, NodeIndex, PoisonGuard) {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let row_id = node_row_id(&graph, idx).expect("columnar node");
    let guard = poison_property(
        &mut graph,
        "Item",
        row_id,
        "c0",
        Value::String("TRUTH".into()),
    );
    (graph, idx, guard)
}

/// **Non-vacuity for the class tests below.** The swap must install a genuinely
/// different allocation and the read route must resolve it — otherwise every
/// named test below would pass by accident.
#[test]
fn poison_installs_a_distinct_store_that_reads_resolve() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let before = Arc::as_ptr(graph.column_store("Item").expect("master"));

    let row_id = node_row_id(&graph, idx).unwrap();
    let _guard = poison_property(
        &mut graph,
        "Item",
        row_id,
        "c0",
        Value::String("TRUTH".into()),
    );

    let after = Arc::as_ptr(graph.column_store("Item").expect("master"));
    assert!(
        !std::ptr::eq(before, after),
        "the poison must install a distinct allocation, or a caller holding the \
         old one would be indistinguishable from one reading the new"
    );
    assert_eq!(
        graph.node_view(idx).unwrap().get_property_value("c0"),
        Some(Value::String("TRUTH".into())),
        "and the read route must resolve the newly installed store"
    );
    assert_eq!(
        node_row_id(&graph, idx),
        Some(row_id),
        "the node's row identity must be untouched — the swap is of the store, \
         not of the node"
    );
}

// ── One named test per caller class ───────────────────────────────────────

/// **R1 — pattern matcher filter.** `MATCH (n:Item {c0: …})` resolves the
/// authoritative value, so the inline-property filter finds the poisoned row
/// and not the stale one.
#[test]
fn r1_matcher_property_filter_reads_the_authoritative_store() {
    let (graph, _idx, _guard) = poisoned_fixture();
    assert_eq!(
        read_one(&graph, "MATCH (n:Item {c0: 'TRUTH'}) RETURN n.id"),
        Value::Int64(1),
        "the matcher's property filter must see the authoritative value"
    );
    assert_eq!(
        read_one(&graph, "MATCH (n:Item {c0: 'c0-1'}) RETURN n.id"),
        Value::Null,
        "the matcher must not match the stale replica"
    );
}

/// **R3 — WHERE / expression resolution.**
#[test]
fn r3_where_clause_reads_the_authoritative_store() {
    let (graph, _idx, _guard) = poisoned_fixture();
    assert_eq!(
        read_one(&graph, "MATCH (n:Item) WHERE n.c0 = 'TRUTH' RETURN n.id"),
        Value::Int64(1)
    );
    assert_eq!(
        read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0"),
        Value::String("TRUTH".into())
    );
}

/// **R4 — projection / whole-node materialisation.**
#[test]
fn r4_whole_node_projection_reads_the_authoritative_store() {
    let (graph, _idx, _guard) = poisoned_fixture();
    match read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n") {
        Value::Node(nv) => assert_eq!(
            nv.properties.get("c0"),
            Some(&Value::String("TRUTH".into())),
            "RETURN n must carry the authoritative value"
        ),
        other => panic!("expected a node value, got {other:?}"),
    }
}

/// **R8 — index build funnel (`read_indexed`).** A property index built after
/// the poison buckets the row under its authoritative value.
#[test]
fn r8_property_index_build_reads_the_authoritative_store() {
    let (mut graph, idx, _guard) = poisoned_fixture();
    graph.create_index("Item", "c0");
    let bucket = graph
        .property_indices
        .get(&("Item".to_string(), "c0".to_string()))
        .expect("index must exist");
    assert_eq!(
        bucket.get(&Value::String("TRUTH".into())),
        Some(&vec![idx]),
        "the built index must bucket the row under its authoritative value"
    );
    assert!(
        !bucket.contains_key(&Value::String("c0-1".into())),
        "the built index must not carry the stale replica's value"
    );
}

/// **R9 — incremental index maintenance.** The incremental updater
/// (`update_property_indices_for_add`) reads through `read_indexed` for exactly
/// this reason; it gets its own arm because it is a separate call path from the
/// rebuild above, and the two must file a row identically.
#[test]
fn r9_incremental_index_maintenance_reads_the_authoritative_store() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let row_id = node_row_id(&graph, idx).unwrap();
    // Build the index *before* the poison, from the pre-poison values.
    graph.create_index("Item", "c0");
    let _guard = poison_property(
        &mut graph,
        "Item",
        row_id,
        "c0",
        Value::String("TRUTH".into()),
    );

    graph.update_property_indices_for_add("Item", idx);

    let bucket = graph
        .property_indices
        .get(&("Item".to_string(), "c0".to_string()))
        .expect("index must exist");
    assert!(
        bucket
            .get(&Value::String("TRUTH".into()))
            .is_some_and(|members| members.contains(&idx)),
        "incremental maintenance must file the row under its authoritative \
         value, or it disagrees with a rebuilt index"
    );
}

/// **R11 — constraint gates.** Declaring a unique constraint validates the
/// existing rows through `read_indexed`; with two rows sharing an
/// authoritative `c0`, the declaration must be rejected.
#[test]
fn r11_unique_constraint_gate_reads_the_authoritative_store() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let row_id = node_row_id(&graph, idx).unwrap();
    // Collide row 0 with row 1's value (`c0-2`) in the master only.
    let _guard = poison_property(
        &mut graph,
        "Item",
        row_id,
        "c0",
        Value::String("c0-2".into()),
    );

    let params = HashMap::new();
    let opts = ExecuteOptions::eager(&params);
    let result = execute_mut(
        &mut graph,
        "CREATE CONSTRAINT FOR (i:Item) REQUIRE i.c0 IS UNIQUE",
        &opts,
    );
    assert!(
        result.is_err(),
        "the constraint gate must see the authoritative duplicate and reject; \
         reading the stale node handles would show four distinct values"
    );
}

/// **R12 — planner statistics.** `property_ndv` bypasses `read_indexed`, so it
/// gets its own arm: the collision above must drop the distinct count.
#[test]
fn r12_property_ndv_reads_the_authoritative_store() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let row_id = node_row_id(&graph, idx).unwrap();
    let _guard = poison_property(
        &mut graph,
        "Item",
        row_id,
        "c0",
        Value::String("c0-2".into()),
    );
    assert_eq!(
        graph.property_ndv("Item", "c0"),
        Some(N as usize - 1),
        "property_ndv must count the authoritative values; reading the stale \
         node handles would still report {N} distinct"
    );
}

/// **R13a — export.** The D3-JSON exporter enumerates a node's properties.
#[test]
fn r13_export_reads_the_authoritative_store() {
    let (graph, _idx, _guard) = poisoned_fixture();
    let json = crate::graph::io::export::to_d3_json(&graph, None).unwrap();
    assert_eq!(
        extract_json_c0(&json),
        Value::String("TRUTH".into()),
        "D3-JSON export must carry the authoritative value"
    );
}

/// **R13b — introspection statistics.** Asserted on `compute_property_stats`
/// directly rather than on the rendered `describe()` XML: the XML mentions a
/// value in several places, so a substring check there cannot tell which
/// producer supplied it, and a mutation of the stats accumulator left it green.
#[test]
fn r13_property_stats_read_the_authoritative_store() {
    let (graph, _idx, _guard) = poisoned_fixture();
    let stats = crate::graph::introspection::schema_overview::compute_property_stats(
        &graph, "Item", 32, None,
    )
    .expect("property stats");
    let c0 = stats
        .iter()
        .find(|p| p.property_name == "c0")
        .expect("c0 must appear in the property stats");
    let values = c0.values.as_ref().expect("small-cardinality values");
    assert!(
        values.contains(&Value::String("TRUTH".into())),
        "property stats must observe the authoritative value; got {values:?}"
    );
    assert!(
        !values.contains(&Value::String("c0-1".into())),
        "property stats must not observe the stale replica; got {values:?}"
    );
}

/// **R14 — binding-layer readers.** `session::resolve_noderefs` is public API,
/// runs after the executor returns and holds only a `&GraphBackend`.
#[test]
fn r14_resolve_noderefs_reads_the_authoritative_store() {
    let mut graph = seeded_columnar();
    let idx = node_of(&graph, 1);
    let row_id = node_row_id(&graph, idx).unwrap();
    let _guard = poison_title(
        &mut graph,
        "Item",
        row_id,
        Value::String("TRUE-TITLE".into()),
    );

    let mut rows = vec![vec![Value::NodeRef(idx.index() as u32)]];
    crate::graph::session::resolve_noderefs(&graph.graph, &mut rows);
    assert_eq!(
        rows[0][0],
        Value::String("TRUE-TITLE".into()),
        "resolve_noderefs must resolve the authoritative title"
    );
}

// ── The compile-time gate's enumerated escape list ────────────────────────

/// **D1 Phase 3 landed: the escapes are gone.**
///
/// `ColumnarRow::node_handle` and `::repoint` were the only two ways to reach a
/// node's own `Arc<ColumnStore>` outside `graph::storage`, and Phase 2 pinned
/// their call sites file-by-file as the Phase-3 work list. Phase 3 deleted the
/// field they exposed, so both methods and every one of their 13 call sites are
/// gone — the expected set is empty.
///
/// The test is kept rather than deleted because an empty expectation is the
/// strongest form of the gate: re-introducing either name anywhere in the crate
/// fails it. If a future phase legitimately needs a node-held handle again, it
/// has to say so here.
const NODE_HANDLE_ESCAPE_SITES: &[(&str, usize)] = &[];

#[test]
fn no_code_reaches_a_node_held_column_store_handle() {
    use std::collections::BTreeMap;

    let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    let mut found: BTreeMap<String, usize> = BTreeMap::new();

    // Split so this detector does not match its own source line — otherwise
    // the file's count would include the scanner and drift every time this
    // function is edited.
    let read_escape = concat!(".node_", "handle()");
    let write_escape = concat!(".re", "point(");

    fn walk(
        dir: &std::path::Path,
        root: &std::path::Path,
        needles: (&str, &str),
        found: &mut BTreeMap<String, usize>,
    ) {
        for entry in std::fs::read_dir(dir).expect("readable source dir") {
            let path = entry.expect("dir entry").path();
            if path.is_dir() {
                walk(&path, root, needles, found);
            } else if path.extension().is_some_and(|e| e == "rs") {
                let text = std::fs::read_to_string(&path).expect("readable source file");
                let hits = text.matches(needles.0).count() + text.matches(needles.1).count();
                if hits > 0 {
                    let rel = path
                        .strip_prefix(root)
                        .expect("under src")
                        .to_string_lossy()
                        .replace('\\', "/");
                    *found.entry(rel).or_insert(0) += hits;
                }
            }
        }
    }
    walk(&src, &src, (read_escape, write_escape), &mut found);

    let expected: BTreeMap<String, usize> = NODE_HANDLE_ESCAPE_SITES
        .iter()
        .map(|(f, n)| ((*f).to_string(), *n))
        .collect();

    assert_eq!(
        found, expected,
        "\nA node-held column-store handle is reachable again.\n\
         D1 Phase 3 made the storage backend the sole owner: a node carries a \
         row id, and the store is resolved by `GraphRead::column_store`. Read \
         through `NodeView` / `GraphRead` and write through \
         `GraphWrite::set_node_property` instead of re-introducing a per-node \
         handle.\n"
    );
}

// ── The save fast path (D1 risk 1) ────────────────────────────────────────

/// A second `save()` on an unmodified graph must **not** rebuild the stores.
///
/// `enable_columnar`'s idempotence guard used to detect a node-private fork by
/// `Arc::ptr_eq`; Phase 3 deleted that check because the fork is no longer
/// expressible. The plan flagged the replacement reasoning (inline-title
/// divergence + orphaned rows) as *believed* sufficient — risk 1 — so this
/// counts rebuilds instead of trusting it. Losing the fast path costs a full
/// O(N) rebuild on every save (~257 s at wiki100m).
#[test]
fn a_second_save_of_an_unmodified_graph_skips_the_rebuild() {
    use crate::graph::dir_graph::COLUMNAR_REBUILDS;
    let rebuilds = || COLUMNAR_REBUILDS.with(|c| c.get());

    let mut graph = docs_fixture();

    let before = rebuilds();
    graph.enable_columnar();
    let first = rebuilds();
    assert_eq!(
        first - before,
        1,
        "the first enable_columnar must rebuild, or this test cannot tell a \
         skipped rebuild from a graph that was never columnar"
    );

    graph.enable_columnar();
    assert_eq!(
        rebuilds(),
        first,
        "a second save of an unmodified graph must take the fast path; a \
         rebuild here means the idempotence guard regressed and every save \
         pays O(N)"
    );

    // And the guard must still *fire* when it should — otherwise "no rebuild"
    // would be trivially true and the assertion above would be vacuous.
    run(
        &mut graph,
        "MATCH (n:Item) WHERE n.id = 1 SET n.title = 'moved'",
    );
    graph.enable_columnar();
    assert_eq!(
        rebuilds(),
        first + 1,
        "an inline-title write must still be detected as drift and rebuild"
    );
}

/// A one-row `SET` on a saved type must touch one row, whatever N is.
///
/// The structural half of the perf claim (the timing half waits for Phase 5's
/// release measurement): the deleted sweep was O(N_type) per clause, so the
/// observable is that a graph of 200 nodes and a graph of 20 nodes both leave
/// every *other* row untouched and the master uniquely owned.
#[test]
fn a_one_row_columnar_set_leaves_every_other_row_untouched() {
    for n in [20i64, 200] {
        let mut graph = sized_columnar(n);
        let before: Vec<Option<Value>> = (0..n)
            .map(|i| {
                graph
                    .column_store("Item")
                    .unwrap()
                    .get(i as u32, InternedKey::from_str("c0"))
            })
            .collect();

        run(&mut graph, "MATCH (n:Item) WHERE n.id = 1 SET n.c0 = 'ONE'");

        let after: Vec<Option<Value>> = (0..n)
            .map(|i| {
                graph
                    .column_store("Item")
                    .unwrap()
                    .get(i as u32, InternedKey::from_str("c0"))
            })
            .collect();

        let changed: Vec<usize> = before
            .iter()
            .zip(&after)
            .enumerate()
            .filter(|(_, (b, a))| b != a)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            changed.len(),
            1,
            "N={n}: a one-row SET must change exactly one row, changed {changed:?}"
        );
        assert!(
            master_is_uniquely_owned(&graph),
            "N={n}: and must leave the master uniquely owned, so the next write \
             mutates in place rather than copying the store"
        );
    }
}