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