kglite 0.16.8

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
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
//! Column-store ownership: divergence coverage and the ownership pins.
//!
//! What this file pins: **the storage backend is the sole owner of a type's
//! `ColumnStore`.**
//!
//! # What "divergence" means here
//!
//! A columnar type's `ColumnStore` was once reachable through **two** `Arc`s —
//! a `DirGraph`-level master and the handle inside every node's
//! `PropertyStorage::Columnar` — which `Arc::make_mut` on either side forked
//! apart. The node-held handle is gone; these tests keep asking the same
//! questions of the surviving route.
//!
//! 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. It is
//!    independent of who owns the store, and it is the real gate.
//! 2. **Which replica wins.** Pinned as an exact fact; a failure means an
//!    unintended ownership change.
//!
//! # The mutation-proof gate
//!
//! Two layers make single ownership irreversible:
//!
//! - **Compile-time.** A columnar node carries a `ColumnarRow`, which holds a
//!   row id and nothing else, so a direct-route read cannot be expressed and
//!   fails to compile. The names of the two accessors that used to expose one
//!   are pinned against an *empty* expected set by
//!   `no_code_reaches_a_node_held_column_store_handle`, so re-introducing
//!   either anywhere in the crate turns that test red.
//! - **Runtime**, for what the compiler cannot see: a caller reading a
//!   `NodeData` it already holds, or an `Arc` of the store it captured before
//!   a write. `poison_*` installs a *different* store behind the backend, and
//!   one named test per caller class asserts the class observes the
//!   authoritative value. Each was shown red by reverting that one call site.

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, unconsolidated.
/// Construction is columnar on every backend, so the rows already live in a
/// store; what has not run yet is `enable_columnar`'s consolidation pass.
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
}

/// Unconsolidated, 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.column_store_count() > 0,
        "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,
    }
}

/// Is the type's master store owned by the backend alone?
///
/// There is no node-held handle to compare against, 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.
///
/// **The name is a holdover and it no longer diverges anything.** It used to
/// fork the master away from the node-held handles; those are gone, so the
/// store is uniquely owned (see `master_is_uniquely_owned`) and `make_mut`
/// mutates it in place. Callers are therefore asserting "a read returns what
/// the backend's store holds" — the strongest statement still expressible.
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 ───────────────────────────────────────────

/// 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.** After a write straight into the backend's store
/// (`diverge_master`), 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"
        );
    }
    // A storeless columnar node makes every surface answer `Null` — unanimous
    // and wrong — so pin the value the store actually holds.
    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 ─────────────────────────────────────────

/// The backend's store is the only store, so a master-only write is what every
/// read returns — there is no node-held `Arc` left to shadow it with a stale
/// value.
#[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 leave the master uniquely owned ──────────────────────────────

/// No node handles are left 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
/// the per-cell `UndoEntry::ColumnarCell` — 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. `maybe_spill_columns` must reclaim the heap it materialises ─────────

/// `maybe_spill_columns` calls `Arc::make_mut` on the type's store and then
/// `materialize_to_files`. While every node still held a strong handle,
/// `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.
#[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"
    );
    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"
    );

    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. Columnar enumeration completeness ───────────────────────────────────

/// `describe()`'s per-type property block and node samples read through the
/// accessors, not `NodeData::property_iter`, which 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.
#[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"
    );
}

// ══════════════════════════════════════════════════════════════════════════
// The mutation-proof gate
// ══════════════════════════════════════════════════════════════════════════

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

/// Install a **different** store for `node_type`, with `edit` applied.
///
/// `column_store(type)` *is* the read route, so a disagreement between two
/// replicas is no longer expressible. What this still catches is a caller that
/// captured an `Arc` of the store earlier — a cache, a snapshot taken across a
/// write — and keeps reading the old object; every named class test below
/// re-reads through the backend after this swap.
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
}

/// Inert: the swap is permanent for the graph under test, which is built per
/// test.
struct PoisonGuard;

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"
        );
    })
}

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 the replaced store 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`) 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 ────────────────────────

/// **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`; the field they exposed no longer exists, so the expected
/// set is empty. An empty expectation is the strongest form of the gate:
/// re-introducing either name anywhere in the crate fails it, and a change that
/// legitimately needs a node-held handle again 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 ────────────────────────────────────────────────────

/// Saving a freshly built graph must **not** rebuild the stores — and neither
/// must saving it again.
///
/// A graph is built in the shape it is saved in, so the consolidation pass has
/// nothing to consolidate and `save()` does not change the write regime. The
/// second half is the idempotence guard, counted rather than trusted: losing
/// the fast path costs a full O(N) rebuild on every save (~257 s at
/// wiki100m).
#[test]
fn saving_a_freshly_built_graph_skips_the_rebuild() {
    use crate::graph::dir_graph::COLUMNAR_REBUILDS;
    let rebuilds = || COLUMNAR_REBUILDS.with(|c| c.get());

    let mut graph = docs_fixture();
    assert!(
        graph.column_store_count() > 0,
        "construction must already be columnar, or this test measures nothing"
    );

    let before = rebuilds();
    graph.enable_columnar();
    graph.enable_columnar();
    assert_eq!(
        rebuilds(),
        before,
        "a save of an unmodified graph must take the fast path; a rebuild here \
         means construction and the saved shape disagree, or 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. A
    // delete is the drift that survives the flip: it leaves the node's row
    // behind, and consolidation is what keeps that row out of the saved file.
    run(&mut graph, "MATCH (n:Item) WHERE n.id = 1 DELETE n");
    graph.enable_columnar();
    assert_eq!(
        rebuilds(),
        before + 1,
        "an orphaned row must still be detected as drift and rebuild"
    );
}

/// A create that reuses a freed petgraph slot puts the type's rows out of
/// ascending-node-index order, and the consolidation pass must notice.
///
/// Row order is part of the `.kgl` format: the column section is positional and
/// the load path binds row k of a type to that type's k-th node in ascending
/// index order. `rebuild_column_stores` sorts by node index, which is what makes
/// the two orders agree — so the drift check has to be what decides the rebuild
/// happens. Once the fast path became the normal case, a delete-then-create
/// pair started serializing every row against the wrong node
/// (`test_runtime_write_bugs.py::test_recreate_after_delete_is_fresh`, which
/// saw it as edges connecting different nodes after a reload).
#[test]
fn a_row_appended_out_of_index_order_is_detected_as_drift() {
    use crate::graph::dir_graph::COLUMNAR_REBUILDS;
    use crate::graph::schema::PropertyStorage;
    let rebuilds = || COLUMNAR_REBUILDS.with(|c| c.get());

    let mut graph = docs_fixture();
    // Free slot 0, then consolidate so the store is dense and in order again.
    run(&mut graph, "MATCH (n:Item) WHERE n.id = 1 DETACH DELETE n");
    graph.enable_columnar();
    let settled = rebuilds();
    graph.enable_columnar();
    assert_eq!(
        rebuilds(),
        settled,
        "precondition: the graph must be settled"
    );

    // The create takes the freed slot 0 but the appended row is last.
    run(&mut graph, "CREATE (:Item {id: 99, title: 'late'})");
    let out_of_order = graph
        .graph
        .node_indices()
        .filter_map(|idx| graph.graph.node_weight(idx))
        .filter_map(|node| match &node.properties {
            PropertyStorage::Columnar(row) => Some(row.row_id()),
            _ => None,
        })
        .enumerate()
        .any(|(position, row_id)| row_id as usize != position);
    assert!(
        out_of_order,
        "precondition: the create must have produced an out-of-order row, or \
         this test cannot see whether the drift check catches one"
    );

    graph.enable_columnar();
    assert_eq!(
        rebuilds(),
        settled + 1,
        "an out-of-order row must be detected as drift; without the rebuild the \
         save writes every row against the wrong node"
    );
    let ordered = graph
        .graph
        .node_indices()
        .filter_map(|idx| graph.graph.node_weight(idx))
        .filter_map(|node| match &node.properties {
            PropertyStorage::Columnar(row) => Some(row.row_id()),
            _ => None,
        })
        .enumerate()
        .all(|(position, row_id)| row_id as usize == position);
    assert!(ordered, "the rebuild must restore ascending row order");
}

/// 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 belongs to a
/// release-mode benchmark): 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"
        );
    }
}

/// Rewrite `Item {id: 1}` through `add_nodes` replace-mode with a batch that
/// carries `c0` and nothing else — so `c1` is the property the caller expects
/// to be gone afterwards.
fn replace_item_one_with_c0_only(graph: &mut DirGraph) {
    let df = DataFrame::from_cypher_rows(
        vec!["id".to_string(), "c0".to_string()],
        vec![vec![Value::Int64(1), Value::String("replaced".into())]],
    )
    .unwrap();
    crate::graph::mutation::maintain::add_nodes(
        graph,
        df,
        "Item".to_string(),
        "id".to_string(),
        None,
        Some("replace".to_string()),
    )
    .unwrap();
}

/// `replace_node_properties` is replace-**all** on every backend, including the
/// overlay a held result view forks the writer into.
///
/// `add_nodes(conflict_handling="replace")` promises the row is rewritten, not
/// merged: a property the batch omits is gone afterwards. `ForkedGraph`'s
/// columnar arm wrote the incoming pairs over the row and left every other cell
/// exactly where it was, where both heap backends null the row first
/// (`impl_heap_column_writes!`). So holding a view turned a replace into an
/// update — a wrong read, not a slow one — and only on a saved (columnar)
/// graph.
///
/// The unforked run above the fork is the control: it is the semantics the
/// forked run has to match, and it passed on both sides of the fix, so a
/// failure there means the *reference* moved rather than the overlay.
#[test]
fn a_forked_columnar_replace_drops_the_properties_it_omits() {
    use crate::graph::handle::make_dir_graph_mut;

    const C1: &str = "MATCH (n:Item) WHERE n.id = 1 RETURN n.c1";
    const C0: &str = "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0";

    let mut control = seeded_columnar();
    assert_eq!(
        read_one(&control, C1),
        Value::Int64(10),
        "precondition: the fixture row carries the property the batch will omit"
    );
    replace_item_one_with_c0_only(&mut control);
    assert_eq!(
        read_one(&control, C0),
        Value::String("replaced".into()),
        "control: the batch's own property is written"
    );
    assert_eq!(
        read_one(&control, C1),
        Value::Null,
        "control: replace-mode drops a property the batch omits"
    );

    let mut writer = Arc::new(seeded_columnar());
    let reader = Arc::clone(&writer);
    let graph = make_dir_graph_mut(&mut writer);
    assert!(
        graph.graph.is_forked(),
        "precondition: a held view must fork the writer, or this is a second \
         run of the control"
    );
    replace_item_one_with_c0_only(graph);
    assert!(
        graph.graph.is_forked(),
        "precondition: the replace must land on the overlay, not after a flatten"
    );
    assert_eq!(
        read_one(graph, C0),
        Value::String("replaced".into()),
        "the batch's own property is written on the overlay too"
    );
    assert_eq!(
        read_one(graph, C1),
        Value::Null,
        "a replace on a forked columnar row must drop the properties the batch \
         omits, exactly as the unforked control does"
    );

    assert_eq!(
        read_one(&reader, C1),
        Value::Int64(10),
        "and the held view keeps the row it was forked with"
    );
}

// ── Backend arms: the same invariants on Mapped and on Disk ────────────────
//
// Every fixture above is `DirGraph::new()`, i.e. `Memory`, so a backend that
// resolved a property through some other replica — or that kept a second
// handle on the store across a write — would have gone unnoticed here.
//
// The arms below re-ask the two load-bearing questions on the other two
// backends. They are deliberately the *questions*, not the whole file: the
// caller-class matrix (`r1_` … `r14_`) exercises reader code that sits above
// the backend and cannot differ per backend, whereas "which store does a read
// resolve" and "who holds it after a write" are exactly the backend's business.

/// `n` `Item` nodes on `mode`, consolidated — the mapped/disk counterpart of
/// [`sized_columnar`]. Its two preconditions are asserted, not assumed.
fn sized_columnar_in_mode(
    n: i64,
    mode: crate::graph::storage::mode::StorageMode,
    path: Option<&std::path::Path>,
) -> DirGraph {
    let mut g = crate::graph::storage::mode::new_dir_graph_in_mode(mode, path)
        .expect("fixture backend must be constructible");
    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.enable_columnar();
    assert_eq!(
        crate::graph::storage::mode::live_storage_mode(&g),
        mode,
        "fixture must be on the backend it names, or the arm tests Memory twice"
    );
    assert!(
        g.column_store_count() > 0,
        "fixture must own a master column store, or every arm below is vacuous"
    );
    g
}

fn mapped_columnar() -> DirGraph {
    sized_columnar_in_mode(N, crate::graph::storage::mode::StorageMode::Mapped, None)
}

/// A read must resolve the store the **backend** owns, on `Mapped` too.
///
/// Red-first: writing the poison into a *clone* of the store instead of
/// installing it turns this assertion red on `c0-1`.
#[test]
fn the_backend_store_is_the_only_read_route_on_mapped() {
    let mut graph = mapped_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()),
    );
    assert_eq!(
        graph.node_view(idx).unwrap().get_property_value("c0"),
        Some(Value::String("TRUTH".into())),
        "a mapped graph must read the store its backend owns"
    );
    assert_eq!(
        read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0"),
        Value::String("TRUTH".into()),
        "and the Cypher read route must resolve the same store"
    );
}

/// A `SET` must mutate the mapped master **in place** and leave it uniquely
/// owned, exactly as it does on `Memory`.
///
/// Two assertions, and the pointer one is the load-bearing half.
/// "Uniquely owned afterwards" is satisfied trivially by a store that forked:
/// `Arc::make_mut` installs a *fresh* allocation in the map, so the map's entry
/// has one holder either way and only the old allocation is shared. Pinning the
/// allocation identity across the statement is what distinguishes "mutated one
/// cell" from "deep-copied every column of the type", which is the whole
/// mechanism this file exists to guard.
///
/// Red-first: holding a second `Arc` on the master across the statement — what
/// the old `ColumnarHandles` journal capture did — forces `make_mut` to
/// fork and turns the pointer assertion red. Verified by doing exactly that.
#[test]
fn set_leaves_the_master_uniquely_owned_on_mapped() {
    let mut graph = mapped_columnar();
    let idx = node_of(&graph, 1);
    let ikey = graph.interner.get_or_intern("c0");
    let before = Arc::as_ptr(graph.column_store("Item").expect("master"));

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

    assert!(
        std::ptr::eq(
            before,
            Arc::as_ptr(graph.column_store("Item").expect("master"))
        ),
        "a columnar SET on Mapped must mutate the master in place — a changed \
         allocation means the statement deep-copied the type's columns"
    );
    assert!(
        master_is_uniquely_owned(&graph),
        "a committed columnar SET on Mapped must leave the master uniquely owned"
    );
    for (surface, got) in all_read_surfaces(&mut graph, idx, ikey) {
        assert_eq!(
            got,
            Value::String("WRITTEN".into()),
            "{surface} did not observe the SET on Mapped"
        );
    }
}

/// The same read-route question on `Disk`.
///
/// `DiskGraph` reaches a type's columns through its own arena rather than a
/// heap map, so "the backend owns the store" is a different claim there and is
/// worth asking separately. The write-ownership arm above has no disk
/// counterpart on purpose: a disk graph takes the whole-graph rollback
/// checkpoint (`supports_undo_journal() == false`), so nothing about the
/// journal's handle on a store applies to it.
///
/// Red-first: dropping the `install_column_store` call inside `poison_row`
/// leaves this reading `c0-1`.
#[test]
fn the_backend_store_is_the_only_read_route_on_disk() {
    let dir = tempfile::tempdir().expect("temp dir");
    let mut graph = sized_columnar_in_mode(
        N,
        crate::graph::storage::mode::StorageMode::Disk,
        Some(dir.path()),
    );
    // Every direct node read on a disk graph must sit inside an open query
    // guard (the arena SAFETY protocol in `disk/graph.rs`); the Cypher route
    // opens its own. Hence the scoping — the guard borrows the graph the
    // poison needs mutably.
    let (idx, row_id) = {
        let _query = graph.graph.begin_query();
        let idx = node_of(&graph, 1);
        let row_id = node_row_id(&graph, idx).expect("columnar node");
        (idx, row_id)
    };
    let _guard = poison_property(
        &mut graph,
        "Item",
        row_id,
        "c0",
        Value::String("TRUTH".into()),
    );
    {
        let _query = graph.graph.begin_query();
        assert_eq!(
            graph.node_view(idx).unwrap().get_property_value("c0"),
            Some(Value::String("TRUTH".into())),
            "a disk graph must read the store its backend owns"
        );
    }
    assert_eq!(
        read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.c0"),
        Value::String("TRUTH".into()),
        "and the Cypher read route must resolve the same store"
    );
}

// ── 4b. The spill pass converges, and still fires when it must ─────────────

/// The spill trigger must reach a fixed point.
///
/// `heap_bytes` counts what a spill cannot move — the tombstone `Vec<bool>`,
/// the `Str` `relocated` overlay, `Mixed` columns, the overflow bag — so
/// comparing *it* against the limit left `StorageMode::Mapped`
/// (`memory_limit = Some(0)`) permanently over: the pass re-ran its whole
/// per-type loop (Vec + sort + a `create_dir_all` syscall per type) after every
/// mutating statement and spilled nothing each time. 245 us per single-row
/// `SET` at 100 types.
///
/// The convergence property is the pair of readings below: after one spill the
/// *spillable* total is zero while the total is not.
#[test]
fn the_spill_trigger_converges_on_the_unspillable_floor() {
    let mut graph = seeded_columnar();
    let dir = tempfile::tempdir().unwrap();
    graph.spill_dir = Some(dir.path().to_path_buf());
    graph.memory_limit = Some(0);

    graph.maybe_spill_columns();

    let master = graph.column_store("Item").expect("master store");
    assert!(
        master.is_mapped(),
        "precondition: the store must actually have spilled"
    );
    assert_eq!(
        master.spillable_heap_bytes(),
        0,
        "everything a spill can move is file-backed, so the trigger must now \
         read zero against its zero limit"
    );
    assert!(
        master.heap_bytes() > 0,
        "precondition: the unspillable floor is still there — without it this \
         test cannot distinguish convergence from an empty store"
    );
    assert!(
        !master.may_have_grown_spillable_heap(),
        "and a completed spill must clear the growth flag, or every later \
         statement re-walks every type to rediscover the floor"
    );
}

/// ...and the flag that buys that skip must not swallow a real spill.
///
/// A `SET` of a property the type has never carried appends a whole column of
/// heap behind the limit. That is the one write shape the growth flag has to
/// catch: break `append_column_typed`'s flag and this goes red (the fresh
/// column stays on the heap because nothing re-runs the pass), while
/// `the_spill_trigger_converges_on_the_unspillable_floor` above stays green.
#[test]
fn a_statement_that_grows_spillable_heap_still_triggers_the_spill() {
    let mut graph = seeded_columnar();
    let dir = tempfile::tempdir().unwrap();
    graph.spill_dir = Some(dir.path().to_path_buf());
    graph.memory_limit = Some(0);
    graph.maybe_spill_columns();
    assert_eq!(
        graph
            .column_store("Item")
            .expect("master store")
            .spillable_heap_bytes(),
        0,
        "precondition: the fixture starts converged"
    );

    run(&mut graph, "MATCH (n:Item) SET n.fresh = 7");

    let master = graph.column_store("Item").expect("master store");
    assert_eq!(
        master.spillable_heap_bytes(),
        0,
        "the appended `fresh` column is spillable heap over a zero limit; the \
         statement that created it must have re-run the spill pass"
    );
    assert_eq!(
        read_one(&graph, "MATCH (n:Item) WHERE n.id = 1 RETURN n.fresh"),
        Value::Int64(7),
        "and the value must survive the spill it triggered"
    );
}