relate-executor 1.5.0

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

use std::collections::BTreeMap;

use relate_core::Value;

use super::super::Graph;

#[test]
fn for_each_neighbor_matches_neighbors_at() {
    use relate_ir::Direction;
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let c = g.create_node(vec!["C".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    g.create_rel(c, a, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    for dir in [Direction::Outgoing, Direction::Incoming, Direction::Both] {
        let listed = g.neighbors(a, dir);
        let mut walked = Vec::new();
        g.for_each_neighbor_at(a, dir, g.commit_ts(), &[] as &[String], |rid| {
            walked.push(rid)
        });
        assert_eq!(walked, listed, "dir={dir:?}");
    }
}

#[test]
fn typed_adj_walks_newest_ts_first() {
    use relate_ir::Direction;
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let c = g.create_node(vec!["C".into()], BTreeMap::new()).unwrap();
    let d = g.create_node(vec!["D".into()], BTreeMap::new()).unwrap();
    let old = g
        .create_rel(
            a,
            b,
            "T".into(),
            BTreeMap::from([("ts".into(), Value::Int(1))]),
        )
        .unwrap();
    let newest = g
        .create_rel(
            a,
            c,
            "T".into(),
            BTreeMap::from([("ts".into(), Value::Int(30))]),
        )
        .unwrap();
    let mid = g
        .create_rel(
            a,
            d,
            "T".into(),
            BTreeMap::from([("ts".into(), Value::Int(10))]),
        )
        .unwrap();
    g.commit_write();
    let mut walked = Vec::new();
    g.for_each_neighbor_at(
        a,
        Direction::Outgoing,
        g.commit_ts(),
        &["T".to_string()],
        |rid| walked.push(rid),
    );
    assert_eq!(walked, vec![newest, mid, old]);
    g.begin_write().unwrap();
    g.set_property_rel(old, "ts", Value::Int(40));
    g.commit_write();
    walked.clear();
    g.for_each_neighbor_at(
        a,
        Direction::Outgoing,
        g.commit_ts(),
        &["T".to_string()],
        |rid| walked.push(rid),
    );
    assert_eq!(walked, vec![old, newest, mid]);
}

#[test]
fn typed_adj_skips_other_types() {
    use relate_ir::Direction;
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let c = g.create_node(vec!["C".into()], BTreeMap::new()).unwrap();
    let t = g.create_rel(a, b, "T".into(), BTreeMap::new()).unwrap();
    g.create_rel(a, c, "OTHER".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    let mut only_t = Vec::new();
    g.for_each_neighbor_at(
        a,
        Direction::Outgoing,
        g.commit_ts(),
        &["T".to_string()],
        |rid| only_t.push(rid),
    );
    assert_eq!(only_t, vec![t]);
    let mut dup = Vec::new();
    g.for_each_neighbor_at(
        a,
        Direction::Outgoing,
        g.commit_ts(),
        &["T".to_string(), "T".to_string()],
        |rid| dup.push(rid),
    );
    assert_eq!(dup, vec![t]);
}

/// LABS-801: the resolved walk (`try_for_each_neighbor_resolved_at`) is the
/// id-keyed core every engine walk rides; these pin its filter semantics —
/// one type, several types, a name the store never interned, a mixed
/// known/unknown list, and the untyped `Any`.
#[test]
fn resolved_typed_walk_filters_by_interned_id() {
    use relate_ir::Direction;

    use crate::store::RelTypes;

    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let c = g.create_node(vec!["C".into()], BTreeMap::new()).unwrap();
    let d = g.create_node(vec!["D".into()], BTreeMap::new()).unwrap();
    let r = g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    let s = g.create_rel(a, c, "S".into(), BTreeMap::new()).unwrap();
    g.create_rel(a, d, "T".into(), BTreeMap::new()).unwrap();
    g.commit_write();

    let walk = |types: &RelTypes| {
        let mut out = Vec::new();
        g.try_for_each_neighbor_resolved_at(a, Direction::Outgoing, g.commit_ts(), types, |rid| {
            out.push(rid);
            Ok::<(), ()>(())
        })
        .unwrap();
        out
    };

    // One type.
    assert_eq!(walk(&g.rel_types(&["R"])), vec![r]);
    // Several types: one chunk per type, in the filter's order.
    assert_eq!(walk(&g.rel_types(&["S", "R"])), vec![s, r]);
    // A name the store never interned has no id and matches nothing.
    assert!(walk(&g.rel_types(&["GHOST"])).is_empty());
    // A mixed known/unknown list walks the known type's chunk only.
    assert_eq!(walk(&g.rel_types(&["GHOST", "R"])), vec![r]);
    // The untyped filter walks every chunk.
    assert_eq!(walk(&RelTypes::Any).len(), 3);
}

/// A callback that walks the next node re-enters the same adjacency
/// store. `IdVec` is not re-entrant, so this deadlocks if the hop ids
/// are still borrowed from the store lock. Two hops is the identity
/// loadtest's `MEMBER_OF*1..8` shape.
#[test]
fn neighbor_walk_reenters_the_same_store() {
    use relate_ir::Direction;
    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let c = g.create_node(vec!["C".into()], BTreeMap::new()).unwrap();
    g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    let bc = g.create_rel(b, c, "R".into(), BTreeMap::new()).unwrap();
    g.commit_write();

    let mut second_hop = Vec::new();
    g.for_each_neighbor_at(
        a,
        Direction::Outgoing,
        g.commit_ts(),
        &["R".to_string()],
        |rid| {
            let (start, end) = g.rel_ends_at(rid, g.commit_ts()).unwrap();
            let next = if start == a { end } else { start };
            g.for_each_neighbor_at(
                next,
                Direction::Outgoing,
                g.commit_ts(),
                &["R".to_string()],
                |next_rid| second_hop.push(next_rid),
            );
        },
    );
    assert_eq!(second_hop, vec![bc]);
}

/// The hop walk's (rel, peer) pairs for one node — the one collector the
/// two hop-walk tests share.
fn hop_pairs(
    g: &Graph,
    at: relate_core::NodeId,
    dir: relate_ir::Direction,
    ts: u64,
    types: &crate::store::RelTypes,
) -> Vec<(relate_core::RelId, relate_core::NodeId)> {
    let mut out = Vec::new();
    g.try_for_each_hop_resolved_at(at, dir, ts, types, |rid, peer| {
        out.push((rid, peer));
        Ok::<(), ()>(())
    })
    .unwrap();
    out
}

/// The hop spelling's walk pinned against literal expectations: chunk
/// order (ts DESC, newest rel first — ADR-0203), direction filtering,
/// peer resolution, the self-loop's single hop under `Both`, and a rel
/// invisible at the probed ts. Literals, not a differential against the
/// rid-only spelling — that spelling delegates to this walk, so a
/// differential would assert the walk against itself.
#[test]
fn hop_walk_matches_literal_expectations() {
    use crate::store::RelTypes;
    use relate_ir::Direction;

    let g = Graph::default();
    g.begin_write().unwrap();
    let a = g.create_node(vec!["A".into()], BTreeMap::new()).unwrap();
    let b = g.create_node(vec!["B".into()], BTreeMap::new()).unwrap();
    let r_ab = g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    let r_ba = g.create_rel(b, a, "R".into(), BTreeMap::new()).unwrap();
    let r_loop = g.create_rel(a, a, "LOOP".into(), BTreeMap::new()).unwrap();
    let r_ghost = g.create_rel(a, b, "GHOST".into(), BTreeMap::new()).unwrap();
    g.commit_write();
    let ts = g.commit_ts();

    let walk = |dir: Direction, types: &RelTypes| hop_pairs(&g, a, dir, ts, types);

    // Outgoing: a's out-chunks in insertion order (R, LOOP, GHOST).
    assert_eq!(
        walk(Direction::Outgoing, &g.rel_types(&["R"])),
        vec![(r_ab, b)]
    );
    assert_eq!(
        walk(Direction::Outgoing, &g.rel_types(&["LOOP"])),
        vec![(r_loop, a)]
    );
    assert_eq!(
        walk(Direction::Outgoing, &RelTypes::Any),
        vec![(r_ab, b), (r_loop, a), (r_ghost, b)]
    );
    // Incoming: a's in-chunks hold only b→a (R) and the loop.
    assert_eq!(
        walk(Direction::Incoming, &g.rel_types(&["R"])),
        vec![(r_ba, b)]
    );
    assert_eq!(
        walk(Direction::Incoming, &RelTypes::Any),
        vec![(r_ba, b), (r_loop, a)]
    );
    // Both: out pass then in pass; the loop dedups to one hop.
    assert_eq!(
        walk(Direction::Both, &g.rel_types(&["R"])),
        vec![(r_ab, b), (r_ba, b)]
    );
    assert_eq!(
        walk(Direction::Both, &g.rel_types(&["LOOP"])),
        vec![(r_loop, a)],
        "the self-loop is one hop under Both, not two"
    );
    assert_eq!(
        walk(Direction::Both, &RelTypes::Any),
        vec![(r_ab, b), (r_loop, a), (r_ghost, b), (r_ba, b)]
    );

    // A rel deleted after the commit is invisible at the later ts — the
    // same matrix mode as the other cells: the same walk closure at the
    // new commit ts, the literal surviving list.
    g.begin_write().unwrap();
    g.delete_rel(r_loop);
    g.commit_write();
    let ts = g.commit_ts();
    let walk = |dir: Direction, types: &RelTypes| hop_pairs(&g, a, dir, ts, types);
    assert_eq!(
        walk(Direction::Both, &RelTypes::Any),
        vec![(r_ab, b), (r_ghost, b), (r_ba, b)],
        "the deleted rel is not a hop"
    );
}

/// A rel id reused with different endpoints (WAL redo replay keeps the
/// first hops as history — the `pair_counts_skip_a_reused_rel_ids_stale_hop`
/// precedent): rel 6 lives (1→2), dies, and its id is re-created (1→3).
/// Node 1's out-adjacency then carries TWO hops named 6 and node 2's
/// in-adjacency a stale one.
fn reused_rel_id_graph() -> Graph {
    use crate::graph::RedoOp;

    let g = Graph::default();
    g.apply_redo(
        vec![
            RedoOp::create_node(1, vec!["A".to_string()], BTreeMap::new()),
            RedoOp::create_node(2, vec!["B".to_string()], BTreeMap::new()),
            RedoOp::create_node(3, vec!["C".to_string()], BTreeMap::new()),
        ],
        1,
    )
    .unwrap();
    g.apply_redo(
        vec![RedoOp::create_rel(
            6,
            1,
            2,
            "R".to_string(),
            // Distinct ts payloads per life: equal (ts, id) hops compare
            // equal in TypedAdj::insert_hop and the second create's hop
            // would be dropped from the chunk — the double-hop fixture
            // needs both to survive.
            BTreeMap::from([("ts".to_string(), Value::Int(1))]),
        )],
        2,
    )
    .unwrap();
    g.apply_redo(vec![RedoOp::delete_rel(6)], 3).unwrap();
    g.apply_redo(
        vec![RedoOp::create_rel(
            6,
            1,
            3,
            "R".to_string(),
            BTreeMap::from([("ts".to_string(), Value::Int(2))]),
        )],
        4,
    )
    .unwrap();
    g
}

/// The reused-rel-id fixture at the hop spelling: the `Both` walk must key
/// dedup on the rel id — an endpoint check would double-emit — and a stale
/// hop whose resolved endpoints no longer touch the walked node drops via
/// `hop_other`.
#[test]
fn hop_walk_dedups_a_reused_rel_ids_stale_hops() {
    use relate_ir::Direction;

    use crate::store::RelTypes;

    let g = reused_rel_id_graph();

    let walk = |at, dir| hop_pairs(&g, at, dir, g.commit_ts(), &RelTypes::Any);

    // Per-arm contract under the reuse: Both dedups by rel id, so the two
    // surviving out-hops named 6 emit once, with the resolved peer. The
    // directed arms do not collapse a reused id's repeat entries — the
    // walk's policy since before this change (storage-level pruning of
    // stale hops is the deferred invariant, LABS-928).
    assert_eq!(
        walk(1, Direction::Both),
        vec![(6, 3)],
        "Both collapses the two surviving out-hops named 6"
    );
    assert_eq!(
        walk(1, Direction::Outgoing),
        vec![(6, 3), (6, 3)],
        "the directed arms keep both repeat entries (pre-existing policy, LABS-928)"
    );
    assert_eq!(walk(1, Direction::Incoming), vec![]);
    // The stale hop in node 2's in-adjacency resolves to (1→3): node 2 is
    // not an endpoint, so the hop drops.
    assert_eq!(walk(2, Direction::Both), vec![]);
    assert_eq!(walk(3, Direction::Both), vec![(6, 1)]);
}

/// The batched hop read against the per-edge walk on the reused-rel-id
/// fixture. It agrees everywhere but one place: `Both` has no per-node
/// seen set (only a self-loop is recognised, from its endpoints), so node
/// 1's two surviving out-hops named 6 stay two entries, as in the directed
/// arms, where the per-edge `Both` walk collapses them.
#[test]
fn batched_hop_read_matches_the_per_edge_walk_on_a_reused_rel_id() {
    use relate_ir::Direction;

    use crate::graph::HopBuf;
    use crate::store::RelTypes;

    let g = reused_rel_id_graph();
    let ts = g.commit_ts();
    let batched = |at, dir| {
        let mut out = Vec::new();
        let mut batches = 0;
        g.try_for_each_hop_batch_resolved_at(
            at,
            dir,
            ts,
            &RelTypes::Any,
            &mut HopBuf::default(),
            |hops| {
                batches += 1;
                out.extend_from_slice(hops);
                Ok::<(), ()>(())
            },
        )
        .unwrap();
        assert!(batches <= 1, "a two-hop node is one batch");
        out.into_iter()
            .map(|hop| (hop.rid, hop.peer))
            .collect::<Vec<_>>()
    };
    for at in [1, 2, 3] {
        for dir in [Direction::Outgoing, Direction::Incoming, Direction::Both] {
            let mut per_edge = hop_pairs(&g, at, dir, ts, &RelTypes::Any);
            let mut got = batched(at, dir);
            per_edge.sort();
            got.sort();
            if dir == Direction::Both {
                // The one intentional divergence: the per-edge `Both` walk
                // collapses a repeated rel id, the batched one does not.
                got.dedup();
            }
            assert_eq!(got, per_edge, "{dir:?} at {at}");
        }
    }
    assert_eq!(batched(1, Direction::Both), vec![(6, 3), (6, 3)]);
    assert_eq!(batched(1, Direction::Outgoing), vec![(6, 3), (6, 3)]);
    assert_eq!(batched(2, Direction::Both), vec![]);
}

/// The same reused-rel-id fixture at the kernel's other call sites: the
/// rid-only spelling (`try_for_each_neighbor_resolved_at`) and the
/// name-keyed boundary walk (`for_each_neighbor_at`) ride the one hop walk,
/// so they drop the stale hop and dedup the reused id exactly as it does.
#[test]
fn neighbor_walk_drops_a_reused_rel_ids_stale_hops() {
    use relate_ir::Direction;

    use crate::store::RelTypes;

    let g = reused_rel_id_graph();

    // The rid-only kernel spelling: the hop walk projected to rids.
    let rids = |at, dir| {
        let mut out = Vec::new();
        g.try_for_each_neighbor_resolved_at(at, dir, g.commit_ts(), &RelTypes::Any, |rid| {
            out.push(rid);
            Ok::<(), ()>(())
        })
        .unwrap();
        out
    };
    assert_eq!(
        rids(1, Direction::Both),
        vec![6],
        "Both dedups the reused id"
    );
    assert_eq!(
        rids(1, Direction::Outgoing),
        vec![6, 6],
        "the directed arm keeps both repeat entries"
    );
    assert_eq!(
        rids(2, Direction::Both),
        Vec::<relate_core::RelId>::new(),
        "the stale hop drops: node 2 is not an endpoint"
    );
    assert_eq!(rids(3, Direction::Both), vec![6]);

    // The name-keyed boundary walk agrees with the rid-only spelling.
    let named = |at, dir| {
        let mut out = Vec::new();
        g.for_each_neighbor_at(at, dir, g.commit_ts(), &["R".to_string()], |rid| {
            out.push(rid)
        });
        out
    };
    assert_eq!(named(1, Direction::Both), vec![6]);
    assert_eq!(named(1, Direction::Outgoing), vec![6, 6]);
    assert_eq!(named(2, Direction::Both), Vec::<relate_core::RelId>::new());
    assert_eq!(named(3, Direction::Both), vec![6]);
}