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