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::accounting::hop_counts;
8use super::id_vec::IdVec;
9use super::shard;
10use super::*;
11use crate::adjacency::AdjHop;
12
13fn flatten_adj(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> Vec<RelId> {
14 map.get(&node)
15 .map(|adj| adj.flatten(sealed.get(&node).as_deref()))
16 .unwrap_or_default()
17}
18
19pub(super) fn adj_insert(
20 map: &IdVec<TypedAdj>,
21 node: NodeId,
22 type_id: u32,
23 id: RelId,
24 ts: Option<i64>,
25) {
26 map.entry(node).or_default().insert(type_id, id, ts);
27}
28
29/// Which endpoint of a [`RelRow`] one direction's grouping pass keys on.
30#[derive(Clone, Copy)]
31enum Side {
32 Start,
33 End,
34}
35
36impl Side {
37 fn endpoint(&self, row: &RelRow) -> NodeId {
38 match self {
39 Side::Start => row.start,
40 Side::End => row.end,
41 }
42 }
43}
44
45/// One direction's wholesale build: `map` keyed by the row's `side`
46/// endpoint, each (node, type) run handed to [`TypedAdj::from_runs`] —
47/// no per-hop binary search or memmove, and the chunk order and hop order
48/// are the store tier's, the order an id-ordered load's incremental
49/// [`adj_insert`]s leave (the wholesale build's pinned contract).
50///
51/// Sharded on that same endpoint (the partition its caller hands it), so
52/// a shard owns every row of every node it carries and builds those
53/// nodes whole. The install is the only writer, and the per-node result
54/// is shard-independent: `from_runs` derives a node's chunk order from
55/// each run's first rel id and sorts its hops `cmp_ts_desc`, both total
56/// orders over a node's own hops.
57fn build_side(map: &IdVec<TypedAdj>, rows: &[RelRow], side: Side, shards: &[Vec<usize>]) {
58 let parts = shard::run_shards(shards, |shard| build_shard(rows, shard, side));
59 for (node, adj) in parts.into_iter().flatten() {
60 map.insert(node, adj);
61 }
62}
63
64/// One shard's whole build: sort its row indices by `(endpoint, type)`,
65/// then one [`TypedAdj`] per node from that node's runs. The sort works
66/// a local copy of the caller's shard — the partition is shared
67/// read-only across the rebuild's consumers, so this pass never
68/// reorders it.
69fn build_shard(rows: &[RelRow], shard: &[usize], side: Side) -> Vec<(NodeId, TypedAdj)> {
70 let endpoint = |row: &RelRow| side.endpoint(row);
71 let mut order = shard.to_vec();
72 order.sort_unstable_by(|&a, &b| {
73 let (a, b) = (&rows[a], &rows[b]);
74 endpoint(a)
75 .cmp(&endpoint(b))
76 .then(a.type_id.cmp(&b.type_id))
77 });
78 let mut built = Vec::new();
79 for node_run in order.chunk_by(|&a, &b| endpoint(&rows[a]) == endpoint(&rows[b])) {
80 let node = endpoint(&rows[node_run[0]]);
81 // One run per type: its type id and its hops, unsorted and keyless —
82 // `TypedAdj::from_runs` derives the chunk-order key from the hops.
83 let runs = node_run
84 .chunk_by(|&a, &b| rows[a].type_id == rows[b].type_id)
85 .map(|run| {
86 let hops: Vec<AdjHop> = run
87 .iter()
88 .map(|&index| {
89 let row = &rows[index];
90 AdjHop {
91 ts: row.ts,
92 id: row.id,
93 }
94 })
95 .collect();
96 (rows[run[0]].type_id, hops)
97 });
98 built.push((node, TypedAdj::from_runs(runs)));
99 }
100 built
101}
102
103/// Install both adjacency maps wholesale from the live rel rows: `out_map`
104/// keyed by each row's start, `in_map` by its end. Both maps must be empty:
105/// this is the whole build, not a merge. `rows` is read-only — the start
106/// side reads the start-keyed partition `rebuild_adj` computed for every
107/// start-keyed consumer, the end side partitions by its own endpoint here,
108/// and no fold that follows a rebuild depends on the buffer's order.
109///
110/// Memory shape: the shard parts and the maps they fill coexist at
111/// peak, but each node's `TypedAdj` is **moved** from its part into
112/// the map, never copied — the build materializes one adjacency, not
113/// two. Above it sit the rebuild's declared transients: the row buffer
114/// and the index partitions (8 bytes per row per partition).
115pub(super) fn adj_build(
116 out_map: &IdVec<TypedAdj>,
117 in_map: &IdVec<TypedAdj>,
118 rows: &[RelRow],
119 start_shards: &[Vec<usize>],
120) {
121 debug_assert!(
122 out_map.is_empty() && in_map.is_empty(),
123 "adj_build is a wholesale build, not a merge"
124 );
125 build_side(out_map, rows, Side::Start, start_shards);
126 let end_shards = shard::shard_rows(rows, |row| row.end);
127 build_side(in_map, rows, Side::End, &end_shards);
128}
129
130pub(super) fn adj_reposition(
131 map: &IdVec<TypedAdj>,
132 sealed: &IdVec<SealedAdj>,
133 node: NodeId,
134 type_id: u32,
135 id: RelId,
136 ts: Option<i64>,
137 xmax: u64,
138) {
139 let mut adj_entry = map.entry(node);
140 // Only a sealed chunk can hold a position to supersede; a delta-only
141 // hop is removed outright, so recording its tombstone would leave an
142 // empty region — and its slot array — behind for nothing.
143 if sealed
144 .get(&node)
145 .is_some_and(|region| region.chunk(type_id).is_some())
146 {
147 let mut sealed_entry = sealed.entry(node);
148 adj_entry
149 .or_default()
150 .reposition(sealed_entry.or_default(), type_id, id, ts, xmax);
151 } else {
152 let adj = adj_entry.or_default();
153 adj.remove(None, type_id, id);
154 adj.insert(type_id, id, ts);
155 }
156}
157
158/// Remove one hop from `node`'s `type_id` chunk (LABS-1116: the GC prunes
159/// the hops of chains it removed, so adjacency never references a rel the
160/// version map no longer holds). A node left with no chunks leaves no
161/// adjacency entry behind — `remove_if` re-checks emptiness under the
162/// store's write lock, so a racing insert that recreated a chunk wins and
163/// the entry stays. A sealed region the removal emptied drops its side-table
164/// entry too.
165pub(super) fn adj_remove(
166 map: &IdVec<TypedAdj>,
167 sealed: &IdVec<SealedAdj>,
168 node: NodeId,
169 type_id: u32,
170 id: RelId,
171) {
172 if let Some(mut adj) = map.get_mut(&node) {
173 let mut region = sealed.get_mut(&node);
174 adj.remove(region.as_deref_mut(), type_id, id);
175 }
176 map.remove_if(&node, |adj| adj.chunks.is_empty());
177 sealed.remove_if(&node, |region| region.chunks.is_empty());
178}
179
180/// Record the versioned tombstone a delete places on `node`'s hop (ADR-0551).
181/// A hop that only lives in the delta records one too — the write path
182/// never decodes the sealed stream to find out, and the fold resolves it (a
183/// tombstone whose id names no position is dropped; a deleted delta hop
184/// folds in under its delete stamp). The delta entry is not a precondition:
185/// `adj_remove` drops it one `IdVec` lock ahead of the sealed region's, and
186/// the tombstone must land in that window too.
187pub(super) fn adj_tombstone_deleted(
188 sealed: &IdVec<SealedAdj>,
189 node: NodeId,
190 type_id: u32,
191 id: RelId,
192 xmax: u64,
193) {
194 sealed.entry(node).or_default().tombstone_deleted(
195 type_id,
196 id,
197 xmax,
198 crate::adjacency::Supersede::Deleted,
199 );
200}
201
202impl Graph {
203 /// Fold every due adjacency chunk's delta and reclaimed tombstones into
204 /// its sealed stream (ADR-0551). Runs at the checkpoint (through
205 /// [`Graph::gc_versions`]); a chunk below the watermark stays delta. The
206 /// node's sealed side-table entry is taken only when a chunk is due, and
207 /// dropped when its last chunk recedes.
208 pub(super) fn compact_adjacency_at_watermark(&self, horizon: u64) {
209 self.compact_side(&self.out_adj, &self.sealed_out, horizon);
210 self.compact_side(&self.in_adj, &self.sealed_in, horizon);
211 self.sealed_out
212 .retain(|_, region| !region.chunks.is_empty());
213 self.sealed_in.retain(|_, region| !region.chunks.is_empty());
214 }
215
216 fn compact_side(&self, delta: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, horizon: u64) {
217 // Two passes: the map's one write guard must not span other nodes' folds.
218 let mut due_nodes = Vec::new();
219 delta.for_each(|node, adj| {
220 if !adj
221 .due_chunks(sealed.get(&node).as_deref(), horizon)
222 .is_empty()
223 {
224 due_nodes.push(node);
225 }
226 });
227 for node in due_nodes {
228 let Some(mut adj) = delta.get_mut(&node) else {
229 continue;
230 };
231 let due = adj.due_chunks(sealed.get(&node).as_deref(), horizon);
232 if due.is_empty() {
233 continue;
234 }
235 let mut sealed_entry = sealed.entry(node);
236 adj.fold_due(sealed_entry.or_default(), &due, horizon);
237 }
238 }
239
240 pub fn degree_out(&self, id: NodeId) -> Vec<RelId> {
241 flatten_adj(&self.out_adj, &self.sealed_out, id)
242 }
243
244 /// Typed adjacency length without snapshot filtering. An approximate
245 /// frontier for deciding whether a far-node index probe is cheaper than
246 /// checking the reached neighbors. `types` resolved once at the walk's
247 /// construction; the untyped filter ([`RelTypes::ids`] is `None`)
248 /// counts every type.
249 pub(crate) fn typed_adj_len(
250 &self,
251 id: NodeId,
252 dir: relate_ir::Direction,
253 types: &RelTypes,
254 ) -> usize {
255 let Some(ids) = types.ids() else {
256 return self.adj_len(id, dir);
257 };
258 let len = |m: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>| {
259 let Some(adj) = m.get(&id) else {
260 return 0;
261 };
262 let region = sealed.get(&id);
263 ids.clone()
264 .map(|type_id| adj.total_len(region.as_deref(), type_id))
265 .sum()
266 };
267 match dir {
268 relate_ir::Direction::Outgoing => len(&self.out_adj, &self.sealed_out),
269 relate_ir::Direction::Incoming => len(&self.in_adj, &self.sealed_in),
270 relate_ir::Direction::Both => {
271 len(&self.out_adj, &self.sealed_out) + len(&self.in_adj, &self.sealed_in)
272 }
273 }
274 }
275
276 /// One node's out-degree on one rel type (the typed adjacency chunk
277 /// length) — the id-based core `typed_adj_len`'s per-type arm and the
278 /// LABS-351 histogram maintenance both consume. No string re-interning:
279 /// the caller holds the interned type id.
280 pub(crate) fn out_chunk_len(&self, node: NodeId, type_id: u32) -> u64 {
281 // Delta guard first, sealed inside it — the order every other
282 // adjacency accessor takes them in.
283 self.out_adj
284 .get(&node)
285 .map(|adj| adj.total_len(self.sealed_out.get(&node).as_deref(), type_id) as u64)
286 .unwrap_or(0)
287 }
288
289 /// A node's out-adjacency chunks, one `(rel type, out-degree)` pair
290 /// per chunk: the module's one `(type, count)` chunk enumeration
291 /// ([`hop_counts`], which the adjacency-delta estimate already
292 /// consults), widened to the u64 the degree-statistic entries count
293 /// in. The LABS-351 histogram maintenance
294 /// ([`Graph::rebucket_added_labels`] /
295 /// [`Graph::unbucket_removed_labels`]) and the admission estimate's
296 /// histogram term all consult it. `Graph::incident_rels` hand-walks
297 /// the same chunk map at hop granularity — the other sanctioned walk,
298 /// which this accessor deliberately does not replace.
299 pub(super) fn out_chunks(&self, node: NodeId) -> Vec<(u32, u64)> {
300 hop_counts(&self.out_adj, &self.sealed_out, node)
301 .into_iter()
302 .map(|(type_id, len)| (type_id, len as u64))
303 .collect()
304 }
305
306 /// Adjacency length without allocation or type/overlay filtering —
307 /// an approximate degree for choosing which side of an existence
308 /// probe to walk (LABS-193).
309 pub fn adj_len(&self, id: NodeId, dir: relate_ir::Direction) -> usize {
310 let len = |m: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>| {
311 m.get(&id)
312 .map(|a| {
313 a.chunk_lens(sealed.get(&id).as_deref())
314 .map(|(_, delta, sealed)| delta + sealed)
315 .sum()
316 })
317 .unwrap_or(0)
318 };
319 match dir {
320 relate_ir::Direction::Outgoing => len(&self.out_adj, &self.sealed_out),
321 relate_ir::Direction::Incoming => len(&self.in_adj, &self.sealed_in),
322 relate_ir::Direction::Both => {
323 len(&self.out_adj, &self.sealed_out) + len(&self.in_adj, &self.sealed_in)
324 }
325 }
326 }
327
328 pub fn degree_in(&self, id: NodeId) -> Vec<RelId> {
329 flatten_adj(&self.in_adj, &self.sealed_in, id)
330 }
331
332 pub fn neighbors(&self, id: NodeId, dir: relate_ir::Direction) -> Vec<RelId> {
333 self.neighbors_at(id, dir, self.read_ts())
334 }
335
336 /// Snapshot-visible neighbors. `types` is the name-keyed boundary
337 /// spelling: it resolves once, then the walk compares interned ids
338 /// ([`Self::try_for_each_neighbor_resolved_at`]). Hop ids are copied
339 /// out from under the store lock before the callback runs, so a
340 /// variable-length walk can re-enter this same store.
341 pub fn for_each_neighbor_at<T: AsRef<str>>(
342 &self,
343 id: NodeId,
344 dir: relate_ir::Direction,
345 ts: u64,
346 types: &[T],
347 mut f: impl FnMut(RelId),
348 ) {
349 let types = self.rel_types(types);
350 self.try_for_each_neighbor_resolved_at(id, dir, ts, &types, |rid| {
351 f(rid);
352 Ok::<(), std::convert::Infallible>(())
353 })
354 .expect("the closure is infallible");
355 }
356
357 /// The engine's resolved-walk core (LABS-801): every hop is a chunk
358 /// lookup by interned id — no per-node interning, no string
359 /// comparison. The engine's walks resolve once at their construction
360 /// and come through here; the name-keyed [`Self::for_each_neighbor_at`]
361 /// is the boundary's spelling.
362 ///
363 /// The rid-only spelling of the one walk core,
364 /// [`Self::try_for_each_hop_resolved_at`]: it discards the endpoints.
365 pub(crate) fn try_for_each_neighbor_resolved_at<E>(
366 &self,
367 id: NodeId,
368 dir: relate_ir::Direction,
369 ts: u64,
370 types: &RelTypes,
371 mut f: impl FnMut(RelId) -> std::result::Result<(), E>,
372 ) -> std::result::Result<(), E> {
373 self.try_for_each_hop_resolved_at(id, dir, ts, types, |rid, _| f(rid))
374 }
375
376 /// The resolved-walk core's hop spelling: each visible relationship
377 /// with the node it reaches. The peer comes from the one version-chain
378 /// read that also answers visibility — a rel walk plus a `rel_ends_at`
379 /// per relationship reads the same chain twice per hop, which every
380 /// walk-then-`hop` loop (the traversal kernels, the shortest-path
381 /// searches) paid per followed relationship.
382 pub(crate) fn try_for_each_hop_resolved_at<E>(
383 &self,
384 id: NodeId,
385 dir: relate_ir::Direction,
386 ts: u64,
387 types: &RelTypes,
388 mut f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
389 ) -> std::result::Result<(), E> {
390 use relate_ir::Direction;
391 let mut emit = |rid: RelId, start: NodeId, end: NodeId| {
392 match crate::store::hop_other(id, start, end, dir) {
393 Some(peer) => f(rid, peer),
394 // A hop whose resolved endpoints do not answer to `dir`
395 // (a stale hop of a reused rel id) is dropped — the
396 // walk + `hop` spelling this replaces did the same.
397 None => Ok(()),
398 }
399 };
400 match dir {
401 Direction::Outgoing => {
402 self.for_each_typed_ends(
403 &self.out_adj,
404 &self.sealed_out,
405 id,
406 ts,
407 types,
408 &mut emit,
409 )?;
410 }
411 Direction::Incoming => {
412 self.for_each_typed_ends(&self.in_adj, &self.sealed_in, id, ts, types, &mut emit)?;
413 }
414 Direction::Both => {
415 // Dedup by rel id, not endpoints: a self-loop sits in
416 // both of a node's lists, and a reused rel id (WAL redo
417 // replay keeps the old hop in the old end's adjacency)
418 // can repeat within one list. The crate's engine-id set
419 // alias — `UsedSet`, the FxHash/CoreMap rule
420 // (ADR-0355 / LABS-337).
421 let mut seen = crate::UsedSet::default();
422 let mut dedup = |rid: RelId, start: NodeId, end: NodeId| {
423 if seen.insert(rid) {
424 emit(rid, start, end)?;
425 }
426 Ok(())
427 };
428 self.for_each_typed_ends(
429 &self.out_adj,
430 &self.sealed_out,
431 id,
432 ts,
433 types,
434 &mut dedup,
435 )?;
436 self.for_each_typed_ends(&self.in_adj, &self.sealed_in, id, ts, types, &mut dedup)?;
437 }
438 }
439 Ok(())
440 }
441
442 /// The one typed-chunk walk skeleton: chunk selection by the resolved
443 /// type filter, one version-chain read per hop (visibility and both
444 /// endpoints — `rel_ends_at` answering `Some` is the same check
445 /// `rel_visible_at` makes).
446 fn for_each_typed_ends<E>(
447 &self,
448 map: &IdVec<TypedAdj>,
449 sealed: &IdVec<SealedAdj>,
450 id: NodeId,
451 ts: u64,
452 types: &RelTypes,
453 f: &mut impl FnMut(RelId, NodeId, NodeId) -> std::result::Result<(), E>,
454 ) -> std::result::Result<(), E> {
455 // Copy the hop ids, then drop the store guard before visiting.
456 // `IdVec`'s lock is not re-entrant. The variable-length walker
457 // (`pattern_walk::walk_var_length`) and the GPM descent
458 // (`gpm_rel_dfs`) call back into this same map from `f`; holding
459 // the guard across that call deadlocks on the second hop. The walk
460 // is the delta+sealed merge at `ts` (ADR-0551), delta first.
461 let hops = {
462 let Some(by_type) = map.get(&id) else {
463 return Ok(());
464 };
465 let region = sealed.get(&id);
466 let mut hops = Vec::new();
467 match types.ids() {
468 None => by_type.for_each_hop(region.as_deref(), ts, |hop| hops.push(hop.id)),
469 Some(ids) => {
470 for tid in ids {
471 by_type
472 .for_each_hop_of(region.as_deref(), tid, ts, |hop| hops.push(hop.id));
473 }
474 }
475 }
476 hops
477 };
478 for rid in hops {
479 if let Some((start, end)) = self.rel_ends_at(rid, ts) {
480 f(rid, start, end)?;
481 }
482 }
483 Ok(())
484 }
485
486 pub fn neighbors_at(&self, id: NodeId, dir: relate_ir::Direction, ts: u64) -> Vec<RelId> {
487 let mut out = Vec::new();
488 self.for_each_neighbor_at(id, dir, ts, &[] as &[String], |rid| out.push(rid));
489 out
490 }
491}