Skip to main content

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