Skip to main content

relate_executor/graph/
adjacency.rs

1//! Adjacency access (ADR-0031/ADR-0033 typed chunks): degree, neighbor
2//! iteration, and snapshot-visible traversal — split out of `mod.rs`.
3//!
4//! Not to be confused with [`crate::adjacency`], the store tier these
5//! accessors read and write: the typed hop chunks, the sealed stream, and
6//! the fold between them.
7use super::id_vec::IdVec;
8use super::rebuild::RelRow;
9use super::shard;
10use super::*;
11use crate::adjacency::{Hop, SealedRegion};
12
13/// One adjacency chunk's type and delta + sealed hop count — named, because
14/// the two integers swap silently as a tuple.
15#[derive(Clone, Copy, Debug)]
16pub(super) struct ChunkHops {
17    pub(super) type_id: u32,
18    pub(super) hops: usize,
19}
20
21/// One direction's adjacency pair: the live delta map and the sealed side
22/// table beside it (ADR-0551), borrowed together. The pairing
23/// (`out_adj`/`sealed_out`, `in_adj`/`sealed_in`) is stated once, in
24/// [`Graph::out_side`] and [`Graph::in_side`]; every reader, writer and
25/// estimator takes the side, so an out/in mix-up between the two halves
26/// cannot be written.
27#[derive(Clone, Copy)]
28pub(super) struct AdjSide<'a> {
29    delta: &'a IdVec<TypedAdj>,
30    sealed: &'a SealedArena,
31}
32
33impl<'a> AdjSide<'a> {
34    /// This side's live delta map.
35    pub(super) fn delta(&self) -> &'a IdVec<TypedAdj> {
36        self.delta
37    }
38
39    /// This side's sealed side table.
40    pub(super) fn sealed(&self) -> &'a SealedArena {
41        self.sealed
42    }
43
44    /// `node`'s delta chunks and its sealed region, both read guards taken
45    /// delta first (the order every adjacency accessor takes them in).
46    /// `None` when the node has no delta entry.
47    pub(super) fn with_adj<R>(
48        &self,
49        node: NodeId,
50        f: impl FnOnce(&TypedAdj, Option<SealedRegion<'_>>) -> R,
51    ) -> Option<R> {
52        let adj = self.delta.get(&node)?;
53        let region = self.sealed.region(node);
54        Some(f(&adj, region))
55    }
56
57    /// Drop both of this side's tables — the wholesale build's replacement
58    /// step, so a rebuild clears the pair it installs into in one place.
59    fn clear(&self) {
60        self.delta.clear();
61        self.sealed.clear();
62    }
63
64    /// Every physical hop id of `node` in merged order, no visibility filter.
65    fn flatten(&self, node: NodeId) -> Vec<RelId> {
66        self.with_adj(node, |adj, region| adj.flatten(region))
67            .unwrap_or_default()
68    }
69
70    /// One node's adjacency floor in this direction: the delta hop bytes.
71    /// The sealed tier is a graph-level arena (ADR-0599); the write path
72    /// charges its events per region through `Graph::price_sealed_event`,
73    /// never a whole-tier walk.
74    pub(super) fn floor(&self, node: NodeId) -> u64 {
75        self.delta.get(&node).map_or(0, |adj| adj.floor_bytes())
76    }
77
78    /// One [`ChunkHops`] per chunk of `node`, in first-seen type order.
79    pub(super) fn hop_counts(&self, node: NodeId) -> Vec<ChunkHops> {
80        self.with_adj(node, |adj, region| {
81            adj.chunk_lens(region)
82                .map(|(type_id, delta, sealed)| ChunkHops {
83                    type_id,
84                    hops: delta + sealed,
85                })
86                .collect()
87        })
88        .unwrap_or_default()
89    }
90
91    pub(super) fn insert(&self, node: NodeId, type_id: u32, id: RelId, ts: Option<i64>) {
92        self.delta.entry(node).or_default().insert(type_id, id, ts);
93    }
94
95    pub(super) fn reposition(
96        &self,
97        node: NodeId,
98        type_id: u32,
99        id: RelId,
100        ts: Option<i64>,
101        xmax: u64,
102    ) {
103        let mut adj_entry = self.delta.entry(node);
104        // Only a sealed chunk can hold a position to supersede; a delta-only
105        // hop is removed outright, so recording its tombstone would leave an
106        // empty region — and its slot array — behind for nothing.
107        let region = self
108            .sealed
109            .region(node)
110            .filter(|region| region.has_chunk(type_id));
111        match region {
112            Some(region) => adj_entry
113                .or_default()
114                .reposition(region, type_id, id, ts, xmax),
115            None => {
116                let adj = adj_entry.or_default();
117                adj.remove(None, type_id, id);
118                adj.insert(type_id, id, ts);
119            }
120        }
121    }
122
123    /// Remove one hop from `node`'s `type_id` chunk (LABS-1116: the GC prunes
124    /// the hops of chains it removed, so adjacency never references a rel the
125    /// version map no longer holds). A node left with no chunks leaves no
126    /// adjacency entry behind — `remove_if` re-checks emptiness under the
127    /// store's write lock, so a racing insert that recreated a chunk wins and
128    /// the entry stays. A sealed region the removal emptied drops its arena
129    /// entry too (the fold's `put_chunk` with an empty stream drops it).
130    pub(super) fn remove(&self, node: NodeId, type_id: u32, id: RelId) {
131        if let Some(mut adj) = self.delta.get_mut(&node) {
132            adj.remove(self.sealed.region(node), type_id, id);
133        }
134        self.delta.remove_if(&node, TypedAdj::is_empty);
135    }
136
137    /// Record the versioned tombstone a delete places on `node`'s hop
138    /// (ADR-0551). A hop that only lives in the delta records one too — the
139    /// write path never decodes the sealed stream to find out, and the fold
140    /// resolves it (a tombstone whose id names no position is dropped; a
141    /// deleted delta hop folds in under its delete stamp). The delta entry is
142    /// not a precondition: [`Self::remove`] drops it one `IdVec` lock ahead
143    /// of the sealed region's, and the tombstone must land in that window
144    /// too.
145    pub(super) fn tombstone_deleted(&self, node: NodeId, type_id: u32, id: RelId, xmax: u64) {
146        self.sealed.tombstone_deleted(
147            node,
148            type_id,
149            id,
150            xmax,
151            crate::adjacency::Supersede::Deleted,
152        );
153    }
154
155    /// One fold pass of this side under `gate` (ADR-0551 / ADR-0599). Two
156    /// passes: the map's one write guard must not span other nodes' folds.
157    fn fold(&self, horizon: u64, gate: FoldGate) {
158        // The collection pass computes each due node's chunks once, carrying
159        // the pair into the write pass — the fold's one due computation.
160        let mut due_nodes: Vec<(NodeId, Vec<u32>)> = Vec::new();
161        self.delta.for_each(|node, adj| {
162            let due = gate.due(adj, self.sealed.region(node), horizon);
163            if !due.is_empty() {
164                due_nodes.push((node, due));
165            }
166        });
167        for (node, due) in due_nodes {
168            let Some(mut adj) = self.delta.get_mut(&node) else {
169                continue;
170            };
171            adj.fold_due(
172                self.sealed.region_or_default(node),
173                &due,
174                horizon,
175                gate.floor(),
176            );
177        }
178    }
179
180    /// Adjacency length without allocation or type/overlay filtering.
181    fn len(&self, node: NodeId) -> usize {
182        self.with_adj(node, |adj, region| {
183            adj.chunk_lens(region)
184                .map(|(_, delta, sealed)| delta + sealed)
185                .sum()
186        })
187        .unwrap_or(0)
188    }
189
190    /// Length over the resolved `type_ids`.
191    fn typed_len(&self, node: NodeId, type_ids: impl Iterator<Item = u32>) -> usize {
192        self.with_adj(node, |adj, region| {
193            type_ids.map(|type_id| adj.total_len(region, type_id)).sum()
194        })
195        .unwrap_or(0)
196    }
197}
198
199impl Graph {
200    /// The outgoing adjacency pair — the one place `out_adj` meets
201    /// `sealed_out`.
202    pub(super) fn out_side(&self) -> AdjSide<'_> {
203        AdjSide {
204            delta: &self.out_adj,
205            sealed: &self.sealed_out,
206        }
207    }
208
209    /// The sides a walk in `dir` reads, each with the scan direction it
210    /// answers to: the one expansion of a (possibly `Both`) direction into
211    /// adjacency pairs, outgoing side first.
212    pub(super) fn sides(
213        &self,
214        dir: relate_ir::Direction,
215    ) -> impl Iterator<Item = (AdjSide<'_>, relate_ir::Direction)> {
216        use relate_ir::Direction;
217        [
218            (self.out_side(), Direction::Outgoing),
219            (self.in_side(), Direction::Incoming),
220        ]
221        .into_iter()
222        .filter(move |&(_, scan_dir)| dir == Direction::Both || dir == scan_dir)
223    }
224
225    /// The incoming adjacency pair — the one place `in_adj` meets
226    /// `sealed_in`.
227    pub(super) fn in_side(&self) -> AdjSide<'_> {
228        AdjSide {
229            delta: &self.in_adj,
230            sealed: &self.sealed_in,
231        }
232    }
233}
234
235/// Which endpoint of a [`RelRow`] one direction's grouping pass keys on —
236/// the start side (the out adjacency) or the end side (the in adjacency).
237#[derive(Clone, Copy)]
238pub enum Side {
239    Start,
240    End,
241}
242
243/// Which chunks a fold pass takes, and the never-sealed floor it folds
244/// them at — the typed gate the checkpoint pass and the wholesale build
245/// select their candidates and their floor from, so the two folds are one
246/// pass that differs only here.
247#[derive(Clone, Copy)]
248enum FoldGate {
249    /// The checkpoint's watermark gate (ADR-0551): chunks due at `horizon`
250    /// — a never-sealed chunk at
251    /// [`COMPACTION_DELTA_FLOOR`](crate::adjacency::COMPACTION_DELTA_FLOOR),
252    /// a delta past 25% of the sealed hops, or a reclaimable tombstone.
253    Watermark,
254    /// The wholesale build's gate (ADR-0599 / ADR-0608): every chunk whose
255    /// delta reaches
256    /// [`RESTORE_SEAL_HOPS`](crate::adjacency::RESTORE_SEAL_HOPS) — a
257    /// fresh build is all-delta, so the threshold alone decides, no
258    /// sealed-length ratio or tombstone horizon.
259    BuildSeal,
260}
261
262impl FoldGate {
263    /// The gate's candidate selection: the type ids it folds for `adj`.
264    fn due(&self, adj: &TypedAdj, sealed: Option<SealedRegion<'_>>, horizon: u64) -> Vec<u32> {
265        match self {
266            FoldGate::Watermark => adj.due_chunks(sealed, horizon),
267            FoldGate::BuildSeal => adj.sealable_chunks(),
268        }
269    }
270
271    /// The never-sealed fold floor the gate folds at.
272    fn floor(&self) -> usize {
273        match self {
274            FoldGate::Watermark => crate::adjacency::COMPACTION_DELTA_FLOOR,
275            FoldGate::BuildSeal => crate::adjacency::RESTORE_SEAL_HOPS,
276        }
277    }
278}
279
280impl Side {
281    fn endpoint(&self, row: &RelRow) -> NodeId {
282        match self {
283            Side::Start => row.start,
284            Side::End => row.end,
285        }
286    }
287
288    /// This direction's adjacency pair — the one place the endpoint a
289    /// direction partitions rows by meets the tables it installs into, so
290    /// the two cannot be paired the wrong way round.
291    fn adj(self, graph: &Graph) -> AdjSide<'_> {
292        match self {
293            Side::Start => graph.out_side(),
294            Side::End => graph.in_side(),
295        }
296    }
297}
298
299/// One direction's wholesale build: the direction's delta keyed by its
300/// [`Side`] endpoint, each (node, type) run handed to [`TypedAdj::from_runs`]
301/// — no per-hop binary search or memmove, and the chunk order and hop order
302/// are the store tier's, the order an id-ordered load's incremental
303/// [`AdjSide::insert`]s leave (the wholesale build's pinned contract).
304///
305/// Sharded on that same endpoint (the partition its caller hands it), so
306/// a shard owns every row of every node it carries and builds those
307/// nodes whole. The per-node delta follows `from_runs`'s order (each run's
308/// first rel id, hops `cmp_ts_desc`, both total orders over a node's own
309/// hops), and the sealed chunks land in the arena from the shards' threads
310/// — the build pass's own emission (ADR-0608), not a second walk. The
311/// arena's buffers are fitted to their charged size at the end, with no
312/// dead ranges to compact.
313fn build_side(graph: &Graph, rows: &[RelRow], side: Side, shards: &[Vec<usize>]) {
314    // The replace-wholesale step belongs to the build that replaces: this
315    // side's pair is emptied here, so a rebuild cannot leave a direction's
316    // stale chunks behind.
317    let adjacency = side.adj(graph);
318    adjacency.clear();
319    let parts = shard::run_shards(shards, |shard| {
320        build_shard(rows, shard, side, adjacency.sealed)
321    });
322    for (node, adj) in parts.into_iter().flatten() {
323        adjacency.delta.insert(node, adj);
324    }
325    adjacency.sealed.fit();
326}
327
328/// One shard's whole build: sort its row indices by `(endpoint, type)`,
329/// then one [`TypedAdj`] per node from that node's runs. The sort works
330/// a local copy of the caller's shard — the partition is shared
331/// read-only across the rebuild's consumers, so this pass never
332/// reorders it.
333fn build_shard(
334    rows: &[RelRow],
335    shard: &[usize],
336    side: Side,
337    sealed: &SealedArena,
338) -> Vec<(NodeId, TypedAdj)> {
339    let endpoint = |row: &RelRow| side.endpoint(row);
340    let mut order = shard.to_vec();
341    order.sort_unstable_by(|&a, &b| {
342        let (a, b) = (&rows[a], &rows[b]);
343        endpoint(a)
344            .cmp(&endpoint(b))
345            .then(a.type_id.cmp(&b.type_id))
346    });
347    let mut built = Vec::new();
348    for node_run in order.chunk_by(|&a, &b| endpoint(&rows[a]) == endpoint(&rows[b])) {
349        built.push(build_node(rows, node_run, side, sealed));
350    }
351    built
352}
353
354/// One node's whole build from its `(endpoint, type)`-sorted row indices:
355/// the per-type runs in one [`TypedAdj`], then the durable shape
356/// (ADR-0608).
357///
358/// The durable shape: the build seals through the fold predicate's own
359/// gate-and-fold sequence, the same one the checkpoint's GC pass calls —
360/// one gate, one sort, one chunk order, one code path — so a rebuilt graph
361/// and a checkpoint-folded one cannot land on different layouts. Nothing is
362/// sealed yet and no tombstones exist, so the never-sealed floor arm is the
363/// whole predicate and the horizon is inert. Both wholesale rebuilds (a
364/// restore and an aborted write's) emit it here, in the one pass that
365/// derives adjacency, instead of a second serial walk folding afterwards.
366/// The node is one shard's alone, so the arena's one write lock serializes
367/// the emission's appends but never two folds of the same node.
368fn build_node(
369    rows: &[RelRow],
370    node_run: &[usize],
371    side: Side,
372    sealed: &SealedArena,
373) -> (NodeId, TypedAdj) {
374    let node = side.endpoint(&rows[node_run[0]]);
375    // One run per type: its type id and its hops, unsorted and keyless —
376    // `TypedAdj::from_runs` derives the chunk-order key from the hops.
377    let runs = node_run
378        .chunk_by(|&a, &b| rows[a].type_id == rows[b].type_id)
379        .map(|run| {
380            let hops: Vec<Hop> = run
381                .iter()
382                .map(|&index| {
383                    let row = &rows[index];
384                    Hop {
385                        ts: row.ts,
386                        id: row.id,
387                    }
388                })
389                .collect();
390            (rows[run[0]].type_id, hops)
391        });
392    let mut adj = TypedAdj::from_runs(runs);
393    let gate = FoldGate::BuildSeal;
394    let due = gate.due(&adj, None, 0);
395    adj.fold_due(sealed.region_or_default(node), &due, 0, gate.floor());
396    (node, adj)
397}
398
399/// Replace both adjacency pairs wholesale from the live rel rows: the
400/// start side's delta keyed by each row's start, the end side's by its end,
401/// with each pair's sealed table filled alongside it. Each side's pair is
402/// emptied by [`build_side`] as it is built, so a rebuild cannot leave a
403/// direction's stale chunks behind — this is the whole build, not a merge.
404/// `rows` is read-only — the start side reads the start-keyed partition
405/// `rebuild_adj` computed for every start-keyed consumer, the end side
406/// partitions by its own endpoint here, and no fold that follows a rebuild
407/// depends on the buffer's order.
408///
409/// Memory shape: the shard parts and the tables they fill coexist at
410/// peak, but each node's `TypedAdj` is **moved** from its part into
411/// the map, never copied — the build materializes one adjacency, not
412/// two. Above it sit the rebuild's declared transients: the row buffer
413/// and the index partitions (8 bytes per row per partition).
414pub(super) fn adj_build(graph: &Graph, rows: &[RelRow], start_shards: &[Vec<usize>]) {
415    build_side(graph, rows, Side::Start, start_shards);
416    let end_shards = shard::shard_rows(rows, |row| row.end);
417    build_side(graph, rows, Side::End, &end_shards);
418}
419
420impl Graph {
421    /// Fold every due adjacency chunk's delta and reclaimed tombstones into
422    /// its sealed stream (ADR-0551). Runs at the checkpoint (through
423    /// [`Graph::gc_versions`]); a chunk below the watermark stays delta. A
424    /// whole-graph rebuild does not fold here — it emits the durable shape in
425    /// its own pass (ADR-0608). The node's sealed region is taken only when a
426    /// chunk is due, and dropped when its last chunk recedes. The arena is
427    /// compacted after the fold (ADR-0599): the fold appends the new encodings
428    /// and marks the replaced spans dead, and compaction reclaims them.
429    pub(super) fn compact_adjacency_at_watermark(&self, horizon: u64) {
430        self.fold_adjacency_at_watermark(horizon);
431        self.sealed_out.compact();
432        self.sealed_in.compact();
433    }
434
435    /// The checkpoint pass's fold half, without the trailing compaction —
436    /// the seam the reclaim test reads the dead ranges through before
437    /// compaction reclaims them.
438    pub(super) fn fold_adjacency_at_watermark(&self, horizon: u64) {
439        self.out_side().fold(horizon, FoldGate::Watermark);
440        self.in_side().fold(horizon, FoldGate::Watermark);
441    }
442
443    /// How many sealed chunks `node`'s adjacency holds on `side` — the out
444    /// (`Side::Start`) or in (`Side::End`) direction — the wholesale build's
445    /// emission (ADR-0608), read by the storage open tests across the crate
446    /// boundary. Test seam behind the off-by-default `test-hooks` feature,
447    /// never in a shipped build.
448    #[cfg(feature = "test-hooks")]
449    pub fn sealed_chunk_count(&self, node: NodeId, side: Side) -> usize {
450        let sealed = match side {
451            Side::Start => &self.sealed_out,
452            Side::End => &self.sealed_in,
453        };
454        sealed.region(node).map_or(0, |region| region.chunk_count())
455    }
456
457    pub fn degree_out(&self, id: NodeId) -> Vec<RelId> {
458        self.out_side().flatten(id)
459    }
460
461    /// Typed adjacency length without snapshot filtering. An approximate
462    /// frontier for deciding whether a far-node index probe is cheaper than
463    /// checking the reached neighbors. `types` resolved once at the walk's
464    /// construction; the untyped filter ([`RelTypes::ids`] is `None`)
465    /// counts every type.
466    pub(crate) fn typed_adj_len(
467        &self,
468        id: NodeId,
469        dir: relate_ir::Direction,
470        types: &RelTypes,
471    ) -> usize {
472        let Some(ids) = types.ids() else {
473            return self.adj_len(id, dir);
474        };
475        self.sides(dir)
476            .map(|(side, _)| side.typed_len(id, ids.clone()))
477            .sum()
478    }
479
480    /// One node's out-degree on one rel type (the typed adjacency chunk
481    /// length) — the id-based core `typed_adj_len`'s per-type arm and the
482    /// LABS-351 histogram maintenance both consume. No string re-interning:
483    /// the caller holds the interned type id.
484    pub(crate) fn out_chunk_len(&self, node: NodeId, type_id: u32) -> u64 {
485        self.out_side().typed_len(node, std::iter::once(type_id)) as u64
486    }
487
488    /// A node's out-adjacency chunks, one `(rel type, out-degree)` pair
489    /// per chunk: the module's one `(type, count)` chunk enumeration
490    /// ([`hop_counts`], which the adjacency-delta estimate already
491    /// consults), widened to the u64 the degree-statistic entries count
492    /// in. The LABS-351 histogram maintenance
493    /// ([`Graph::rebucket_added_labels`] /
494    /// [`Graph::unbucket_removed_labels`]) and the admission estimate's
495    /// histogram term all consult it. `Graph::incident_rels` hand-walks
496    /// the same chunk map at hop granularity — the other sanctioned walk,
497    /// which this accessor deliberately does not replace.
498    pub(super) fn out_chunks(&self, node: NodeId) -> Vec<(u32, u64)> {
499        self.out_side()
500            .hop_counts(node)
501            .into_iter()
502            .map(|c| (c.type_id, c.hops as u64))
503            .collect()
504    }
505
506    /// Adjacency length without allocation or type/overlay filtering —
507    /// an approximate degree for choosing which side of an existence
508    /// probe to walk (LABS-193).
509    pub fn adj_len(&self, id: NodeId, dir: relate_ir::Direction) -> usize {
510        self.sides(dir).map(|(side, _)| side.len(id)).sum()
511    }
512
513    pub fn degree_in(&self, id: NodeId) -> Vec<RelId> {
514        self.in_side().flatten(id)
515    }
516
517    pub fn neighbors(&self, id: NodeId, dir: relate_ir::Direction) -> Vec<RelId> {
518        self.neighbors_at(id, dir, self.read_ts())
519    }
520
521    /// Snapshot-visible neighbors. `types` is the name-keyed boundary
522    /// spelling: it resolves once, then the walk compares interned ids
523    /// ([`Self::try_for_each_neighbor_resolved_at`]). Hop ids are copied
524    /// out from under the store lock before the callback runs, so a
525    /// variable-length walk can re-enter this same store.
526    pub fn for_each_neighbor_at<T: AsRef<str>>(
527        &self,
528        id: NodeId,
529        dir: relate_ir::Direction,
530        ts: u64,
531        types: &[T],
532        mut f: impl FnMut(RelId),
533    ) {
534        let types = self.rel_types(types);
535        self.try_for_each_neighbor_resolved_at(id, dir, ts, &types, |rid| {
536            f(rid);
537            Ok::<(), std::convert::Infallible>(())
538        })
539        .expect("the closure is infallible");
540    }
541
542    /// The engine's resolved-walk core (LABS-801): every hop is a chunk
543    /// lookup by interned id — no per-node interning, no string
544    /// comparison. The engine's walks resolve once at their construction
545    /// and come through here; the name-keyed [`Self::for_each_neighbor_at`]
546    /// is the boundary's spelling.
547    ///
548    /// The rid-only spelling of the one walk core,
549    /// [`Self::try_for_each_hop_resolved_at`]: it discards the endpoints.
550    pub(crate) fn try_for_each_neighbor_resolved_at<E>(
551        &self,
552        id: NodeId,
553        dir: relate_ir::Direction,
554        ts: u64,
555        types: &RelTypes,
556        mut f: impl FnMut(RelId) -> std::result::Result<(), E>,
557    ) -> std::result::Result<(), E> {
558        self.try_for_each_hop_resolved_at(id, dir, ts, types, |rid, _| f(rid))
559    }
560
561    /// The resolved-walk core's hop spelling: each visible relationship
562    /// with the node it reaches. The peer comes from the one version-chain
563    /// read that also answers visibility — a rel walk plus a `rel_ends_at`
564    /// per relationship reads the same chain twice per hop, which every
565    /// walk-then-`hop` loop (the traversal kernels, the shortest-path
566    /// searches) paid per followed relationship.
567    pub(crate) fn try_for_each_hop_resolved_at<E>(
568        &self,
569        id: NodeId,
570        dir: relate_ir::Direction,
571        ts: u64,
572        types: &RelTypes,
573        mut f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
574    ) -> std::result::Result<(), E> {
575        use relate_ir::Direction;
576        let mut emit = |rid: RelId, start: NodeId, end: NodeId| {
577            match crate::store::hop_other(id, start, end, dir) {
578                Some(peer) => f(rid, peer),
579                // A hop whose resolved endpoints do not answer to `dir`
580                // (a stale hop of a reused rel id) is dropped — the
581                // walk + `hop` spelling this replaces did the same.
582                None => Ok(()),
583            }
584        };
585        match dir {
586            Direction::Outgoing => {
587                self.for_each_typed_ends(self.out_side(), id, ts, types, &mut emit)?;
588            }
589            Direction::Incoming => {
590                self.for_each_typed_ends(self.in_side(), id, ts, types, &mut emit)?;
591            }
592            Direction::Both => {
593                // Dedup by rel id, not endpoints: a self-loop sits in
594                // both of a node's lists, and a reused rel id (WAL redo
595                // replay keeps the old hop in the old end's adjacency)
596                // can repeat within one list. The crate's engine-id set
597                // alias — `UsedSet`, the FxHash/CoreMap rule
598                // (ADR-0355 / LABS-337).
599                let mut seen = crate::UsedSet::default();
600                let mut dedup = |rid: RelId, start: NodeId, end: NodeId| {
601                    if seen.insert(rid) {
602                        emit(rid, start, end)?;
603                    }
604                    Ok(())
605                };
606                self.for_each_typed_ends(self.out_side(), id, ts, types, &mut dedup)?;
607                self.for_each_typed_ends(self.in_side(), id, ts, types, &mut dedup)?;
608            }
609        }
610        Ok(())
611    }
612
613    /// The one typed-chunk walk skeleton: chunk selection by the resolved
614    /// type filter, one version-chain read per hop (visibility and both
615    /// endpoints — `rel_ends_at` answering `Some` is the same check
616    /// `rel_visible_at` makes).
617    fn for_each_typed_ends<E>(
618        &self,
619        side: AdjSide<'_>,
620        id: NodeId,
621        ts: u64,
622        types: &RelTypes,
623        f: &mut impl FnMut(RelId, NodeId, NodeId) -> std::result::Result<(), E>,
624    ) -> std::result::Result<(), E> {
625        // Copy the hop ids, then drop the store guard before visiting.
626        // `IdVec`'s lock is not re-entrant. The variable-length walker
627        // (`pattern_walk::walk_var_length`) and the GPM descent
628        // (`gpm_rel_dfs`) call back into this same map from `f`; holding
629        // the guard across that call deadlocks on the second hop. The walk
630        // is the delta+sealed merge at `ts` (ADR-0551), delta first.
631        let hops = side
632            .with_adj(id, |by_type, region| {
633                let mut hops = Vec::new();
634                match types.ids() {
635                    None => by_type.for_each_hop(region, ts, |hop| hops.push(hop.id)),
636                    Some(ids) => {
637                        for tid in ids {
638                            by_type.for_each_hop_of(region, tid, ts, |hop| hops.push(hop.id));
639                        }
640                    }
641                }
642                hops
643            })
644            .unwrap_or_default();
645        for rid in hops {
646            if let Some((start, end)) = self.rel_ends_at(rid, ts) {
647                f(rid, start, end)?;
648            }
649        }
650        Ok(())
651    }
652
653    pub fn neighbors_at(&self, id: NodeId, dir: relate_ir::Direction, ts: u64) -> Vec<RelId> {
654        let mut out = Vec::new();
655        self.for_each_neighbor_at(id, dir, ts, &[] as &[String], |rid| out.push(rid));
656        out
657    }
658}