Skip to main content

relate_executor/overlay/
adjacency.rs

1//! The overlay's neighbor-walk family (LABS-801) — the [`ExecGraph`]
2//! mirror of the base layer's `graph/adjacency.rs`: every engine walk
3//! enters through the resolved spellings, which compare interned ids on
4//! the committed side and the filter's names on the write overlay's
5//! string-typed rel copies. The name-keyed spellings left here
6//! ([`ExecGraph::for_each_neighbor`], [`ExecGraph::try_find_neighbor`])
7//! are the plan boundary's adapters for the callers that still hold
8//! written names; each resolves once and delegates.
9
10use std::cell::RefCell;
11
12use relate_core::{NodeId, RelId};
13use relate_ir::{Direction, RelPattern};
14
15use crate::store::RelTypes;
16
17use super::scratch::WriteScratch;
18use super::ExecGraph;
19
20impl ExecGraph<'_> {
21    pub fn neighbors(&self, id: NodeId, dir: Direction) -> Vec<RelId> {
22        let mut out = Vec::new();
23        self.for_each_neighbor(id, dir, &[], |rid| out.push(rid));
24        out
25    }
26
27    /// Overlay-visible neighbors without cloning the base adjacency `Vec`.
28    /// The name-keyed boundary spelling: the pattern's types resolve once
29    /// here, then [`Self::for_each_neighbor_resolved`] compares ids.
30    pub fn for_each_neighbor(
31        &self,
32        id: NodeId,
33        dir: Direction,
34        types: &[String],
35        f: impl FnMut(RelId),
36    ) {
37        let types = self.rel_types(types);
38        self.for_each_neighbor_resolved(id, dir, &types, f);
39    }
40
41    /// [`Self::for_each_neighbor`] over the resolved filter (LABS-801).
42    pub(crate) fn for_each_neighbor_resolved(
43        &self,
44        id: NodeId,
45        dir: Direction,
46        types: &RelTypes,
47        mut f: impl FnMut(RelId),
48    ) {
49        self.try_for_each_neighbor_resolved(id, dir, types, |rid| {
50            f(rid);
51            Ok::<(), std::convert::Infallible>(())
52        })
53        .expect("the closure is infallible");
54    }
55
56    /// Approximate adjacency degree (see [`Graph::adj_len`]) — side
57    /// selection for existence probes (LABS-193). Base delegation only:
58    /// deliberately not snapshot-filtered (reads.rs's prologue contract).
59    pub fn adj_len(&self, id: NodeId, dir: Direction) -> usize {
60        self.base.adj_len(id, dir)
61    }
62
63    /// See [`Graph::typed_adj_len`] — over the resolved filter
64    /// (LABS-801). Base delegation only, like [`Self::adj_len`].
65    pub(crate) fn typed_adj_len_resolved(
66        &self,
67        id: NodeId,
68        dir: Direction,
69        types: &RelTypes,
70    ) -> usize {
71        self.base.typed_adj_len(id, dir, types)
72    }
73
74    /// The first neighbor of `id` (in `dir`, of `types`) for which `f`
75    /// returns `true`, stopping the walk there — the early-exit idiom for
76    /// existence probes (LABS-193). No match: `Ok(None)`. The name-keyed
77    /// boundary spelling: resolves once, then delegates to
78    /// [`Self::try_find_neighbor_resolved`].
79    pub fn try_find_neighbor<E>(
80        &self,
81        id: NodeId,
82        dir: Direction,
83        types: &[String],
84        f: impl FnMut(RelId) -> std::result::Result<bool, E>,
85    ) -> std::result::Result<Option<RelId>, E> {
86        let types = self.rel_types(types);
87        self.try_find_neighbor_resolved(id, dir, &types, f)
88    }
89
90    /// [`Self::try_find_neighbor`] over the resolved filter (LABS-801).
91    pub(crate) fn try_find_neighbor_resolved<E>(
92        &self,
93        id: NodeId,
94        dir: Direction,
95        types: &RelTypes,
96        mut f: impl FnMut(RelId) -> std::result::Result<bool, E>,
97    ) -> std::result::Result<Option<RelId>, E> {
98        enum Stop<E> {
99            Hit(RelId),
100            Err(E),
101        }
102        let walk: std::result::Result<(), Stop<E>> =
103            self.try_for_each_neighbor_resolved(id, dir, types, |rid| match f(rid) {
104                Ok(true) => Err(Stop::Hit(rid)),
105                Ok(false) => Ok(()),
106                Err(e) => Err(Stop::Err(e)),
107            });
108        match walk {
109            Ok(()) => Ok(None),
110            Err(Stop::Hit(rid)) => Ok(Some(rid)),
111            Err(Stop::Err(e)) => Err(e),
112        }
113    }
114
115    /// `names` — a pattern's written type list — resolved to the interned
116    /// domain once (LABS-801), the boundary every engine walk crosses
117    /// before its per-edge loop.
118    pub(crate) fn rel_types<T: AsRef<str>>(&self, names: &[T]) -> RelTypes {
119        self.base.rel_types(names)
120    }
121
122    /// [`Self::rel_types`] for a planned pattern.
123    pub(crate) fn rel_types_of(&self, rel: &RelPattern) -> RelTypes {
124        self.base.rel_types_of(rel)
125    }
126
127    /// Overlay-visible neighbors under the resolved type filter
128    /// (LABS-801) — the rid-only spelling of
129    /// [`Self::try_for_each_hop_resolved`], the same relation the base
130    /// layer states between its two walks.
131    pub(crate) fn try_for_each_neighbor_resolved<E>(
132        &self,
133        id: NodeId,
134        dir: Direction,
135        types: &RelTypes,
136        mut f: impl FnMut(RelId) -> std::result::Result<(), E>,
137    ) -> std::result::Result<(), E> {
138        self.try_for_each_hop_resolved(id, dir, types, |rid, _| f(rid))
139    }
140
141    /// The neighbor walk yielding the reached node with each relationship
142    /// — the hop spelling of the traversal kernels and the shortest-path
143    /// searches. The read-only arm: nothing to dedup against and nothing
144    /// hidden, so the base walk's own visibility check at the pinned ts is
145    /// the complete answer — the write overlay's per-hop existence
146    /// re-check is an overlay cost a read-only traversal must not pay. The
147    /// write arm is [`Self::try_for_each_hop_overlay`].
148    pub(crate) fn try_for_each_hop_resolved<E>(
149        &self,
150        id: NodeId,
151        dir: Direction,
152        types: &RelTypes,
153        f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
154    ) -> std::result::Result<(), E> {
155        match self.scratch {
156            None => self
157                .base
158                .try_for_each_hop_resolved_at(id, dir, self.snapshot_ts(), types, f),
159            Some(cell) => self.try_for_each_hop_overlay(cell, id, dir, types, f),
160        }
161    }
162
163    /// The one write-overlay walk (LABS-801): committed rels ride the
164    /// base's fused hop walk — one version-chain read per hop, the peer
165    /// carried along — gated by the scratch prologue's existence check
166    /// (a rel deleted in the overlay is not a neighbor); the scratch
167    /// extras' rel copies answer type and endpoints from their one record
168    /// (the copies carry type strings, so the filter compares names,
169    /// `RelTypes::matches_name`).
170    fn try_for_each_hop_overlay<E>(
171        &self,
172        scratch: &RefCell<WriteScratch>,
173        id: NodeId,
174        dir: Direction,
175        types: &RelTypes,
176        mut f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
177    ) -> std::result::Result<(), E> {
178        let ts = self.snapshot_ts();
179        let extras = Self::scratch_hops(scratch, id, dir, types);
180        self.base
181            .try_for_each_hop_resolved_at(id, dir, ts, types, |rid, peer| {
182                // rel_exists is the canonical existence check: a rel
183                // deleted in the overlay is not a neighbor.
184                if !self.rel_exists(rid) {
185                    return Ok(());
186                }
187                f(rid, peer)
188            })?;
189        for (rid, peer) in extras {
190            f(rid, peer)?;
191        }
192        Ok(())
193    }
194
195    /// The write scratch's hops out of `id` under `dir` and the type
196    /// filter, with the node each reaches, gathered under the one borrow —
197    /// no `RefCell` borrow is alive while the caller's closure runs. The
198    /// direction picks the scratch lists (out, in, or out then in), the
199    /// peer is the one `hop_other` rule the base walk applies, and a rel
200    /// id already gathered (a self-loop sits in both lists) is skipped —
201    /// the base walk's `Both` rule. Every entry is a key of `batch.rels`
202    /// (absent = created-then-deleted in this batch), so one record read
203    /// answers type, endpoints and peer.
204    fn scratch_hops(
205        scratch: &RefCell<WriteScratch>,
206        id: NodeId,
207        dir: Direction,
208        types: &RelTypes,
209    ) -> Vec<(RelId, NodeId)> {
210        let s = scratch.borrow();
211        let lists = match dir {
212            Direction::Outgoing => [Some(&s.batch.out_adj), None],
213            Direction::Incoming => [Some(&s.batch.in_adj), None],
214            Direction::Both => [Some(&s.batch.out_adj), Some(&s.batch.in_adj)],
215        };
216        let mut seen = crate::UsedSet::default();
217        let mut hops = Vec::new();
218        for list in lists.into_iter().flatten() {
219            for &rid in list.get(&id).into_iter().flatten() {
220                let Some(rel) = s.batch.rels.get(&rid) else {
221                    continue;
222                };
223                if !types.matches_name(&rel.rel_type) {
224                    continue;
225                }
226                // Scratch adjacency is written only by `create_rel` under the
227                // rel's own endpoint (`out_adj[start]`, `in_adj[end]`) and a
228                // scratch rel never re-points, so the peer always resolves.
229                let peer = crate::store::hop_other(id, rel.start, rel.end, dir).expect(
230                    "a scratch adjacency entry lies under the endpoint list that yielded it",
231                );
232                if seen.insert(rid) {
233                    hops.push((rid, peer));
234                }
235            }
236        }
237        hops
238    }
239}