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