relate-executor 1.0.2

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use super::*;
use crate::graph::count_state::CountStats;
use crate::graph::degree_stats::DegreeHistograms;
use crate::graph::rebuild::take_adj_builds;
use crate::graph::shard::take_shards_run;
use crate::graph::test_support::endpoints;
use std::sync::Arc;

#[test]
fn direct_restore_rejects_sentinel_before_mutating() {
    let graph = Graph::default();
    assert!(matches!(
        graph.load_checkpoint_node(Node {
            id: i64::MAX,
            labels: Arc::new(vec![]),
            properties: relate_core::PropertyMap::share(BTreeMap::new())
        }),
        Err(relate_core::Error::Storage(_))
    ));
    assert!(matches!(
        graph.load_checkpoint_rel(Relationship {
            id: i64::MAX,
            start: 0,
            end: 0,
            rel_type: "R".into(),
            properties: relate_core::PropertyMap::share(BTreeMap::new())
        }),
        Err(relate_core::Error::Storage(_))
    ));
    assert!(matches!(
        graph.load_checkpoint_rel(Relationship {
            id: 0,
            start: i64::MAX,
            end: 0,
            rel_type: "R".into(),
            properties: relate_core::PropertyMap::share(BTreeMap::new())
        }),
        Err(relate_core::Error::Storage(_))
    ));
    assert_eq!(graph.next_node_id(), 0);
    assert_eq!(graph.next_rel_id(), 0);
    assert_eq!(graph.live_node_count(), 0);
}

fn restored_node(id: NodeId, label: &str, name: &str) -> Node {
    Node {
        id,
        labels: Arc::new(vec![label.into()]),
        properties: relate_core::PropertyMap::share(BTreeMap::from([(
            "name".to_string(),
            Value::String(name.into()),
        )])),
    }
}

fn restored_rel(start: NodeId, end: NodeId, rel_type: &str, ts: i64) -> Relationship {
    Relationship {
        id: 0,
        start,
        end,
        rel_type: rel_type.into(),
        properties: relate_core::PropertyMap::share(BTreeMap::from([(
            "ts".to_string(),
            Value::Int(ts),
        )])),
    }
}

/// Overlapping legacy parts (ADR-0183) can restore an id twice; the later
/// row replaces the earlier one, so a delete leaves no copy visible.
#[test]
fn restoring_a_node_twice_keeps_one_version_of_the_later_row() {
    let g = Graph::default();
    g.load_checkpoint_node(restored_node(3, "Old", "first"))
        .unwrap();
    g.load_checkpoint_node(restored_node(3, "New", "second"))
        .unwrap();
    g.set_commit_ts(1);
    g.finish_restore();
    // The open flow's single post-replay site owns the index rebuild — a
    // bare load (this test's shape) supplies it the same way.
    g.rebuild_indexes();
    assert_eq!(g.nodes.get(&3).unwrap().len(), 1);
    let node = g.node(3).unwrap();
    assert_eq!(node.labels.as_slice(), ["New".to_string()].as_slice());
    assert_eq!(
        node.properties,
        restored_node(3, "New", "second").properties
    );
    let no_props = BTreeMap::new();
    assert_eq!(g.lookup_nodes(&["Old".into()], &no_props), Some(vec![]));
    assert_eq!(g.lookup_nodes(&["New".into()], &no_props), Some(vec![3]));

    g.begin_write().unwrap();
    g.delete_node(3, false).unwrap();
    g.commit_write();
    assert!(g.node(3).is_none());
    assert!(g.all_node_ids().is_empty());
}

#[test]
fn restoring_a_rel_twice_keeps_one_version_and_one_hop_per_endpoint() {
    use relate_ir::Direction;

    let g = Graph::default();
    for id in 0..4 {
        g.load_checkpoint_node(restored_node(id, "N", "n")).unwrap();
    }
    // Same endpoints, but a different `ts` sorts the hop elsewhere.
    g.load_checkpoint_rel(restored_rel(0, 1, "R", 1)).unwrap();
    g.load_checkpoint_rel(restored_rel(0, 1, "R", 2)).unwrap();
    assert_eq!(g.rels.get(&0).unwrap().len(), 1);
    // Restore leaves adjacency to `finish_restore`.
    assert!(g.degree_out(0).is_empty());
    g.set_commit_ts(1);
    g.finish_restore();
    assert_eq!(g.degree_out(0), [0]);
    assert_eq!(g.degree_in(1), [0]);
    // Other endpoints and type: the later row wins entirely.
    g.load_checkpoint_rel(restored_rel(2, 3, "S", 3)).unwrap();
    g.finish_restore();
    assert_eq!(g.rels.get(&0).unwrap().len(), 1);
    let rel = g.rel(0).unwrap();
    assert_eq!((rel.start, rel.end, rel.rel_type.as_str()), (2, 3, "S"));
    assert_eq!(rel.properties, restored_rel(2, 3, "S", 3).properties);
    assert!(g.degree_out(0).is_empty());
    assert!(g.degree_in(1).is_empty());
    assert_eq!(g.degree_out(2), [0]);
    assert_eq!(g.degree_in(3), [0]);
    assert!(g.neighbors(0, Direction::Both).is_empty());
    assert_eq!(g.neighbors(2, Direction::Both), [0]);

    g.begin_write().unwrap();
    g.delete_rel(0);
    g.commit_write();
    assert!(g.rel(0).is_none());
    assert!(g.all_rel_ids().is_empty());
    assert!(g.neighbors(2, Direction::Both).is_empty());
    assert!(g.neighbors(3, Direction::Both).is_empty());
}

/// Rows restored out of id order still give each node the adjacency of an
/// id-ordered load: type chunks in first-id order, hops `ts` DESC.
#[test]
fn restored_adjacency_follows_id_order_not_load_order() {
    let g = Graph::default();
    for id in 0..2 {
        g.load_checkpoint_node(restored_node(id, "N", "n")).unwrap();
    }
    for (id, rel_type, ts) in [(3, "B", 9), (1, "A", 5), (2, "B", 1), (0, "A", 7)] {
        g.load_checkpoint_rel(Relationship {
            id,
            ..restored_rel(0, 1, rel_type, ts)
        })
        .unwrap();
    }
    g.set_commit_ts(1);
    g.finish_restore();
    assert_eq!(g.degree_out(0), [0, 1, 3, 2]);
    assert_eq!(g.degree_in(1), [0, 1, 3, 2]);
}

#[test]
fn restore_during_an_open_write_is_a_storage_error() {
    let g = Graph::default();
    g.load_checkpoint_node(restored_node(0, "N", "n")).unwrap();
    g.set_commit_ts(1);
    g.finish_restore();
    g.begin_write().unwrap();
    let written = g.create_node(vec!["W".into()], BTreeMap::new()).unwrap();

    for result in [
        g.load_checkpoint_node(restored_node(written, "Other", "x")),
        g.load_checkpoint_node(restored_node(7, "Other", "x")),
        g.load_checkpoint_rel(restored_rel(0, written, "R", 1)),
    ] {
        assert!(
            matches!(result, Err(relate_core::Error::Storage(ref message)) if message.contains("write is open")),
            "{result:?}"
        );
    }
    assert_eq!(g.next_node_id(), written + 1);
    assert_eq!(g.next_rel_id(), 0);
    assert!(g.rels.is_empty() && !g.nodes.contains_key(&7));
    assert_eq!(g.nodes.get(&written).unwrap().len(), 1);
    assert_eq!(
        g.node(written).unwrap().labels.as_slice(),
        ["W".to_string()].as_slice()
    );
    g.commit_write();
    assert_eq!(g.all_node_ids(), [0, written]);
}

#[test]
fn restore_over_a_committed_write_is_a_storage_error() {
    let g = Graph::default();
    g.load_checkpoint_node(restored_node(0, "N", "first"))
        .unwrap();
    g.set_commit_ts(1);
    g.finish_restore();
    g.begin_write().unwrap();
    g.set_property_node(0, "name", Value::String("second".into()));
    g.commit_write();
    assert_eq!(g.nodes.get(&0).unwrap().len(), 2);

    assert!(matches!(
        g.load_checkpoint_node(restored_node(0, "N", "third")),
        Err(relate_core::Error::Storage(_))
    ));
    assert_eq!(g.nodes.get(&0).unwrap().len(), 2);
    assert_eq!(
        g.node(0).unwrap().properties,
        restored_node(0, "N", "second").properties
    );
}

/// Every live node's adjacency, raw and as each direction expands it.
type NodeAdjacency = (NodeId, Vec<RelId>, Vec<RelId>, [Vec<RelId>; 3]);

fn adjacency(g: &Graph) -> Vec<NodeAdjacency> {
    use relate_ir::Direction;

    let ts = g.commit_ts();
    g.all_node_ids_at(ts)
        .into_iter()
        .map(|id| {
            let expands = [Direction::Outgoing, Direction::Incoming, Direction::Both]
                .map(|dir| g.neighbors_at(id, dir, ts));
            (id, g.degree_out(id), g.degree_in(id), expands)
        })
        .collect()
}

fn create_rel(id: RelId, start: NodeId, end: NodeId, rel_type: &str) -> RedoOp {
    RedoOp::CreateRel {
        id,
        start,
        end,
        rel_type: rel_type.into(),
        properties: relate_core::PropertyMap::share(BTreeMap::new()),
    }
}

/// The calls a store open makes — restore the checkpoint rows,
/// `finish_restore`, replay the WAL tail, `rebuild_indexes` — build
/// adjacency once, and the opened graph has the writer's adjacency.
#[test]
fn checkpoint_load_and_wal_replay_build_adjacency_once() {
    let checkpointed = vec![
        RedoOp::CreateNode {
            id: 0,
            labels: Arc::new(vec!["N".into()]),
            properties: relate_core::PropertyMap::share(BTreeMap::new()),
        },
        RedoOp::CreateNode {
            id: 1,
            labels: Arc::new(vec!["N".into()]),
            properties: relate_core::PropertyMap::share(BTreeMap::new()),
        },
        RedoOp::CreateNode {
            id: 2,
            labels: Arc::new(vec![]),
            properties: relate_core::PropertyMap::share(BTreeMap::new()),
        },
        create_rel(0, 0, 1, "A"),
        create_rel(1, 0, 2, "B"),
        create_rel(2, 1, 2, "A"),
    ];
    let tail = vec![
        vec![create_rel(3, 0, 2, "A"), RedoOp::DeleteRel { id: 0 }],
        vec![
            create_rel(4, 2, 0, "B"),
            RedoOp::SetRelProp {
                id: 2,
                key: "ts".into(),
                value: Value::Int(5),
            },
        ],
        vec![RedoOp::DeleteRel { id: 4 }],
    ];

    // The writer commits the checkpointed rows, then the tail.
    let writer = Graph::default();
    writer.apply_redo(checkpointed, 1).unwrap();
    let nodes: Vec<Node> = writer
        .all_node_ids_at(1)
        .into_iter()
        .map(|id| writer.node_at(id, 1).unwrap())
        .collect();
    let rels: Vec<Relationship> = writer
        .all_rel_ids_at(1)
        .into_iter()
        .map(|id| writer.rel_at(id, 1).unwrap())
        .collect();
    for (ops, ts) in tail.iter().cloned().zip(2..) {
        writer.apply_redo(ops, ts).unwrap();
    }

    take_adj_builds();
    let opened = Graph::default();
    opened.set_commit_ts(1);
    for node in nodes {
        opened.load_checkpoint_node(node).unwrap();
    }
    for rel in rels {
        opened.load_checkpoint_rel(rel).unwrap();
    }
    opened.finish_restore();
    for (ops, ts) in tail.into_iter().zip(2..) {
        opened.apply_replayed_redo(ops, ts).unwrap();
    }
    opened.rebuild_indexes();
    assert_eq!(take_adj_builds(), 1);

    assert_eq!(opened.commit_ts(), writer.commit_ts());
    assert_eq!(adjacency(&opened), adjacency(&writer));
    // Relationships the tail deleted expand nowhere.
    for (id, _, _, expands) in adjacency(&opened) {
        for rels in expands {
            assert!(!rels.contains(&0) && !rels.contains(&4), "{id}: {rels:?}");
        }
    }
}

/// The checkpoint dumps node and rel rows and folds its adjacency afterwards
/// (ADR-0551): restoring those rows rebuilds adjacency as a fresh delta — no
/// sealed bytes or tombstones are serialized — and a WAL tail replayed onto
/// it leaves the reader's adjacency equal to the writer's. The next
/// checkpoint re-seals the restored delta.
#[test]
fn compaction_restore_roundtrip_rebuilds_a_fresh_delta() {
    use relate_ir::Direction;

    let floor = crate::adjacency::COMPACTION_DELTA_FLOOR;
    let mut checkpointed: Vec<RedoOp> = (0..2)
        .map(|id| RedoOp::CreateNode {
            id,
            labels: Arc::new(vec!["N".into()]),
            properties: relate_core::PropertyMap::share(BTreeMap::new()),
        })
        .collect();
    checkpointed.extend((0..floor as RelId).map(|id| create_rel(id, 0, 1, "T")));

    let writer = Graph::default();
    writer.apply_redo(checkpointed, 1).unwrap();
    let nodes: Vec<Node> = writer
        .all_node_ids_at(1)
        .into_iter()
        .map(|id| writer.node_at(id, 1).unwrap())
        .collect();
    let rels: Vec<Relationship> = writer
        .all_rel_ids_at(1)
        .into_iter()
        .map(|id| writer.rel_at(id, 1).unwrap())
        .collect();
    let serialized = |g: &Graph| -> u64 {
        let nodes: u64 = g
            .all_node_ids_at(1)
            .into_iter()
            .filter_map(|id| g.node_checkpoint_bytes(id, 1).unwrap())
            .sum();
        let rels: u64 = g
            .all_rel_ids_at(1)
            .into_iter()
            .filter_map(|id| g.rel_checkpoint_bytes(id, 1).unwrap())
            .sum();
        nodes + rels
    };
    let dumped = serialized(&writer);

    // The checkpoint's GC pass folds the checkpointed delta; the rows it
    // dumped carry none of it.
    writer.gc_versions();
    let type_id = writer.interner.get_id("T").unwrap();
    assert_eq!(writer.sealed_out.get(&0).unwrap().chunk_len(type_id), floor);
    assert_eq!(
        serialized(&writer),
        dumped,
        "the folded layout adds no checkpoint bytes"
    );

    // The WAL tail: a new type, a delete of a sealed hop, and a ts update of
    // a sealed hop.
    let tail = [
        (
            2,
            vec![
                create_rel(floor as RelId, 0, 1, "U"),
                RedoOp::DeleteRel { id: 5 },
            ],
        ),
        (
            3,
            vec![RedoOp::SetRelProp {
                id: 7,
                key: "ts".into(),
                value: Value::Int(100),
            }],
        ),
    ];
    for (ts, ops) in tail.iter().cloned() {
        writer.apply_redo(ops, ts).unwrap();
    }

    let opened = Graph::default();
    opened.set_commit_ts(1);
    for node in nodes {
        opened.load_checkpoint_node(node).unwrap();
    }
    for rel in rels {
        opened.load_checkpoint_rel(rel).unwrap();
    }
    opened.finish_restore();
    for (ts, ops) in tail {
        opened.apply_replayed_redo(ops, ts).unwrap();
    }
    opened.rebuild_indexes();

    let observable = |g: &Graph| -> Vec<(NodeId, [Vec<RelId>; 3])> {
        let ts = g.commit_ts();
        g.all_node_ids_at(ts)
            .into_iter()
            .map(|id| {
                let expands = [Direction::Outgoing, Direction::Incoming, Direction::Both]
                    .map(|dir| g.neighbors_at(id, dir, ts));
                (id, expands)
            })
            .collect()
    };
    assert_eq!(opened.commit_ts(), writer.commit_ts());
    // Restore rebuilt adjacency from the rows: a fresh delta, no sealed hops
    // (the replayed delete still records its tombstone on a zero-hop region).
    for id in opened.all_node_ids_at(opened.commit_ts()) {
        for map in [&opened.out_adj, &opened.in_adj] {
            if let Some(adj) = map.get(&id) {
                assert!(
                    adj.chunk_lens(None).all(|(_, _, sealed)| sealed == 0),
                    "restored node {id} must be delta-only"
                );
            }
        }
    }
    assert_eq!(observable(&opened), observable(&writer));

    // The dumped rows are the whole durable state: the next checkpoint
    // re-seals the restored delta and the reader's adjacency does not move.
    // The replayed delete's tombstone reclaims at the fold, so the sealed
    // stream loses its hop — the writer still holds it only because its GC
    // ran before the tail.
    opened.gc_versions();
    let type_id = opened.interner.get_id("T").unwrap();
    assert_eq!(
        opened.sealed_out.get(&0).unwrap().chunk_len(type_id),
        floor - 1,
        "the restored delta re-seals, without the deleted hop"
    );
    assert_eq!(observable(&opened), observable(&writer));
}

/// An aborted write drops its relationships from adjacency: `abort_write`
/// still rebuilds it from the live versions.
#[test]
fn abort_write_rebuilds_adjacency() {
    let g = Graph::default();
    let (a, b) = endpoints(&g);
    g.begin_write().unwrap();
    let kept = g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    g.begin_write().unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    take_adj_builds();
    g.abort_write();
    assert_eq!(take_adj_builds(), 1);
    assert_eq!(g.degree_out(a), [kept]);
    assert_eq!(g.degree_in(b), [kept]);
}

/// Everything `rebuild_adj` publishes: both adjacency directions with their
/// hop order, the degree histograms, the count bundle itself, and the
/// `used_bytes` the rebuild's tail recomputes from them. The bundle is held
/// whole, not re-listed field by field — a field added to `CountStats`
/// later is covered by this comparison, not silently escaped by it, and
/// this is the one test that would catch a new fold's sharding bug.
#[derive(Debug, PartialEq)]
struct RebuildState {
    adjacency: Vec<NodeAdjacency>,
    histograms: DegreeHistograms,
    stats: CountStats,
    used_bytes: u64,
}

fn rebuild_state(g: &Graph) -> RebuildState {
    RebuildState {
        adjacency: adjacency(g),
        histograms: g.degree_histograms.lock().unwrap().clone(),
        stats: g.count_stats.lock().unwrap().clone(),
        used_bytes: g.used_bytes.load(std::sync::atomic::Ordering::Relaxed),
    }
}

/// The sharded rebuild is the single-shard one. `shard::shard_rows` keys
/// on a node endpoint, so a shard owns every row of every node it carries
/// and nothing the rebuild publishes depends on where the shard boundaries
/// fall: `from_runs` derives each node's chunk order from its own runs'
/// first rel ids and sorts its hops `cmp_ts_desc`, both total orders over
/// that node's hops, and both folds are order-independent aggregates.
#[test]
fn sharded_rebuild_matches_the_single_shard_one() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let starts: Vec<NodeId> = (0..6)
        .map(|i| {
            g.create_node(vec![format!("S{}", i % 3)], BTreeMap::new())
                .unwrap()
        })
        .collect();
    let ends: Vec<NodeId> = (0..5)
        .map(|i| {
            g.create_node(vec![format!("E{}", i % 2)], BTreeMap::new())
                .unwrap()
        })
        .collect();
    // Every start node carries one rel per type, so its out-adjacency has
    // several chunks to order and hops to sort; the ends take several rels
    // each, the same on the incoming side. The vocabulary is bound once: the
    // loop bound and the name both read it, so neither can drift.
    const TYPES: [&str; 3] = ["T0", "T1", "T2"];
    for (i, &start) in starts.iter().enumerate() {
        for j in 0..TYPES.len() {
            g.create_rel(
                start,
                ends[(i + j) % ends.len()],
                TYPES[(i + j) % TYPES.len()].to_string(),
                BTreeMap::new(),
            )
            .unwrap();
        }
    }
    g.commit_write();

    g.rebuild_adj();
    // One rebuild is four `run_shards` calls — both adjacency sides, the
    // degree fold, the count fold — so the single-shard run accumulates 4
    // and the four-shard run 16. Asserting the sum pins every one of the
    // four, the adjacency build included.
    assert_eq!(take_shards_run(), 4);
    let serial = rebuild_state(&g);
    crate::graph::shard::with_workers(4, || g.rebuild_adj());
    assert_eq!(take_shards_run(), 16);
    assert_eq!(rebuild_state(&g), serial);
}