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, through
123 /// [`Self::live_token`]'s rebase policy — the
124 /// [`Self::prop_key_id_resolved`] twin for types: a type the plan
125 /// saw as never interned resolves by name when the statement's own
126 /// `IN TRANSACTIONS` batches interned it mid-statement.
127 pub(crate) fn rel_types_of(&self, rel: &RelPattern) -> RelTypes {
128 self.base.rel_types_of(rel, |name, token| {
129 self.live_token(token)
130 .id_or_else(|| self.base.rel_type_id(name))
131 })
132 }
133
134 /// Overlay-visible neighbors under the resolved type filter
135 /// (LABS-801) — the rid-only spelling of
136 /// [`Self::try_for_each_hop_resolved`], the same relation the base
137 /// layer states between its two walks.
138 pub(crate) fn try_for_each_neighbor_resolved<E>(
139 &self,
140 id: NodeId,
141 dir: Direction,
142 types: &RelTypes,
143 mut f: impl FnMut(RelId) -> std::result::Result<(), E>,
144 ) -> std::result::Result<(), E> {
145 self.try_for_each_hop_resolved(id, dir, types, |rid, _| f(rid))
146 }
147
148 /// The neighbor walk yielding the reached node with each relationship
149 /// — the hop spelling of the traversal kernels and the shortest-path
150 /// searches. The read-only arm: nothing to dedup against and nothing
151 /// hidden, so the base walk's own visibility check at the pinned ts is
152 /// the complete answer — the write overlay's per-hop existence
153 /// re-check is an overlay cost a read-only traversal must not pay. The
154 /// write arm is [`Self::try_for_each_hop_overlay`].
155 pub(crate) fn try_for_each_hop_resolved<E>(
156 &self,
157 id: NodeId,
158 dir: Direction,
159 types: &RelTypes,
160 f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
161 ) -> std::result::Result<(), E> {
162 match self.scratch {
163 None => self
164 .base
165 .try_for_each_hop_resolved_at(id, dir, self.snapshot_ts(), types, f),
166 Some(cell) => self.try_for_each_hop_overlay(cell, id, dir, types, f),
167 }
168 }
169
170 /// The one write-overlay walk (LABS-801): committed rels ride the
171 /// base's fused hop walk — one version-chain read per hop, the peer
172 /// carried along — gated by the scratch prologue's existence check
173 /// (a rel deleted in the overlay is not a neighbor); the scratch
174 /// extras' rel copies answer type and endpoints from their one record
175 /// (the copies carry type strings, so the filter compares names,
176 /// `RelTypes::matches_name`).
177 fn try_for_each_hop_overlay<E>(
178 &self,
179 scratch: &RefCell<WriteScratch>,
180 id: NodeId,
181 dir: Direction,
182 types: &RelTypes,
183 mut f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
184 ) -> std::result::Result<(), E> {
185 let ts = self.snapshot_ts();
186 let extras = Self::scratch_hops(scratch, id, dir, types);
187 self.base
188 .try_for_each_hop_resolved_at(id, dir, ts, types, |rid, peer| {
189 // rel_exists is the canonical existence check: a rel
190 // deleted in the overlay is not a neighbor.
191 if !self.rel_exists(rid) {
192 return Ok(());
193 }
194 f(rid, peer)
195 })?;
196 for (rid, peer) in extras {
197 f(rid, peer)?;
198 }
199 Ok(())
200 }
201
202 /// The write scratch's hops out of `id` under `dir` and the type
203 /// filter, with the node each reaches, gathered under the one borrow —
204 /// no `RefCell` borrow is alive while the caller's closure runs. The
205 /// direction picks the scratch lists (out, in, or out then in), the
206 /// peer is the one `hop_other` rule the base walk applies, and a rel
207 /// id already gathered (a self-loop sits in both lists) is skipped —
208 /// the base walk's `Both` rule. Every entry is a key of `batch.rels`
209 /// (absent = created-then-deleted in this batch), so one record read
210 /// answers type, endpoints and peer.
211 fn scratch_hops(
212 scratch: &RefCell<WriteScratch>,
213 id: NodeId,
214 dir: Direction,
215 types: &RelTypes,
216 ) -> Vec<(RelId, NodeId)> {
217 let s = scratch.borrow();
218 let lists = match dir {
219 Direction::Outgoing => [Some(&s.batch.out_adj), None],
220 Direction::Incoming => [Some(&s.batch.in_adj), None],
221 Direction::Both => [Some(&s.batch.out_adj), Some(&s.batch.in_adj)],
222 };
223 let mut seen = crate::UsedSet::default();
224 let mut hops = Vec::new();
225 for list in lists.into_iter().flatten() {
226 for &rid in list.get(&id).into_iter().flatten() {
227 let Some(rel) = s.batch.rels.get(&rid) else {
228 continue;
229 };
230 if !types.matches_name(&rel.rel_type) {
231 continue;
232 }
233 // Scratch adjacency is written only by `create_rel` under the
234 // rel's own endpoint (`out_adj[start]`, `in_adj[end]`) and a
235 // scratch rel never re-points, so the peer always resolves.
236 let peer = crate::store::hop_other(id, rel.start, rel.end, dir).expect(
237 "a scratch adjacency entry lies under the endpoint list that yielded it",
238 );
239 if seen.insert(rid) {
240 hops.push((rid, peer));
241 }
242 }
243 }
244 hops
245 }
246}