Skip to main content

relate_executor/graph/
degree_stats.rs

1//! LABS-351 / LABS-370: the graph's degree statistics — the
2//! (label, rel-type) out-degree histograms (the estimate family: the
3//! high-water buckets, their bump/rebucket/unbucket seams, the
4//! retained-structure recount's histogram share, and the wholesale
5//! rebuild that republishes the degree-statistics set). The exact
6//! count state — the bundle the counting operator answers from —
7//! lives in its own sibling `count_state.rs` (LABS-851's structure
8//! round: the family outgrew one file and split the same way
9//! `degree_stats_incident.rs` and `degree_stats_estimate.rs` split
10//! before). The `Graph` struct (graph/mod.rs) keeps the fields; the
11//! seams live in these files as `impl Graph` blocks (the borrowing
12//! stays on `&self`, which owns the adjacency, the rel store probe
13//! and the label reads the family needs).
14
15use std::collections::{HashMap, HashSet};
16use std::sync::atomic::Ordering;
17
18use relate_core::NodeId;
19
20use relate_planner::DegreeMoments;
21
22use super::count_state::{CountDelta, LabelMutation};
23use super::shard;
24use super::{Graph, LabelCache, RelRow};
25
26/// The histogram family's map: per-(label, rel-type) out-degree bucket
27/// counts, [`Graph::DEGREE_BUCKETS`] each. A type rather than a bare
28/// map so the bucket policy lives with the map it applies to — the one
29/// get-or-create ([`Self::slot`], which is where a bump charges its
30/// entry) and the one shard merge ([`Self::merge`]) — instead of being
31/// re-spelled at every bump and fold site.
32#[derive(Debug, Default, Clone, PartialEq)]
33pub(super) struct DegreeHistograms(HashMap<(u32, u32), [u64; Graph::DEGREE_BUCKETS]>);
34
35impl DegreeHistograms {
36    /// One entry's get-or-create. `on_create` runs only when the entry
37    /// is minted — the bump sites charge their `used_bytes` entry there,
38    /// and the rebuild's folds pass a no-op because its charges are
39    /// recomputed wholesale by the caller's `recompute_used`.
40    fn slot(
41        &mut self,
42        key: (u32, u32),
43        on_create: impl FnOnce(),
44    ) -> &mut [u64; Graph::DEGREE_BUCKETS] {
45        match self.0.entry(key) {
46            std::collections::hash_map::Entry::Vacant(vacant) => {
47                on_create();
48                vacant.insert([0; Graph::DEGREE_BUCKETS])
49            }
50            std::collections::hash_map::Entry::Occupied(occupied) => occupied.into_mut(),
51        }
52    }
53
54    /// Sum a shard's part into the whole, element-wise. Bucket sums are
55    /// **saturating** — the histogram family's convention at every
56    /// bucket mutation (`bump_degree_histograms`, the rebucket pair): a
57    /// bucket counts nodes, so saturation is the honest ceiling, where
58    /// the count family's twin sums are checked-and-loud instead.
59    fn merge(&mut self, part: DegreeHistograms) {
60        for (key, buckets) in part.0 {
61            let slot = self.slot(key, || {});
62            for (sum, count) in slot.iter_mut().zip(buckets) {
63                *sum = sum.saturating_add(count);
64            }
65        }
66    }
67
68    /// Decrement one bucket of an entry that exists — the removal
69    /// direction, which **never** mints: a label leaving a node has no
70    /// histogram of its own to create, and minting one here would
71    /// insert an entry without the `HISTOGRAM_ENTRY_BYTES` charge
72    /// `slot` owns. Saturating, like every other bucket mutation.
73    ///
74    /// Every release is paired with the `slot` that minted its entry
75    /// (the label-mutation seams pair 1:1, and the wholesale rebuild
76    /// mints none of them), so a vacant key here is unrepresentable in
77    /// the paired contract — a broken pairing fails at the seam that
78    /// broke it, not as a silently drifting histogram. The count
79    /// family's twin removal (`count_entry`) fails the same way.
80    fn release(&mut self, key: (u32, u32), bucket: usize) {
81        let buckets = self
82            .0
83            .get_mut(&key)
84            .expect("histogram release without its paired bump");
85        buckets[bucket] = buckets[bucket].saturating_sub(1);
86    }
87}
88
89/// Read-through to the map for the estimate family's lookups (`.get`,
90/// `.keys`, `.iter`, `.len`). Immutable on purpose: every *write* has a
91/// named home on the type ([`DegreeHistograms::slot`],
92/// [`DegreeHistograms::merge`], [`DegreeHistograms::release`]), so a
93/// mutable handle to the raw map would let a later site mint an entry
94/// the `HISTOGRAM_ENTRY_BYTES` charge never sees.
95impl std::ops::Deref for DegreeHistograms {
96    type Target = HashMap<(u32, u32), [u64; Graph::DEGREE_BUCKETS]>;
97    fn deref(&self) -> &Self::Target {
98        &self.0
99    }
100}
101
102impl Graph {
103    /// The histogram's bucket count (LABS-311: one constant, consulted at
104    /// every site — the field, the bumps, the rebuild fold, the tail
105    /// scan). 21 buckets cover degrees to 2^20 (one million), the
106    /// realistic supernode ceiling.
107    pub(super) const DEGREE_BUCKETS: usize = 21;
108    /// One histogram entry's charge: the (u32, u32) key, the bucket
109    /// counts, and the map's per-entry overhead (the same floor-estimate
110    /// style as the adjacency terms). Charged to `used_bytes` on every
111    /// entry creation so the incremental capacity accounting tracks the
112    /// recount oracle (security review: an uncharged query-controlled map
113    /// bypasses the memory-limit enforcement).
114    pub(super) const HISTOGRAM_ENTRY_BYTES: u64 = (std::mem::size_of::<(u32, u32)>()
115        + Self::DEGREE_BUCKETS * std::mem::size_of::<u64>()
116        + 48
117        + 64) as u64;
118    /// floor(log2(degree)) for degree >= 1: bucket 0 counts degree-1
119    /// nodes, bucket k counts 2^k..2^(k+1)-1. Clamped into the last
120    /// bucket above 2^20.
121    pub(super) fn degree_bucket(degree: u64) -> usize {
122        (degree.max(1).ilog2() as usize).min(Self::DEGREE_BUCKETS - 1)
123    }
124
125    /// The histogram family's share of the retained-structure recount
126    /// (the `structure_bytes` oracle): the histogram entries are
127    /// retained structure — an uncharged query-controlled map would
128    /// bypass the memory-limit enforcement (the Capacity check compares
129    /// `used_bytes`). One constant, consulted at every site (LABS-311):
130    /// the recount charges the same HISTOGRAM_ENTRY_BYTES the
131    /// incremental bumps do. The count bundle's share composes beside
132    /// this term at the oracle's one site (`structure_bytes`),
133    /// beside the constraint-key term.
134    pub(super) fn degree_stats_structure_bytes(&self) -> u64 {
135        let histograms = self.degree_histograms.lock().unwrap();
136        (histograms.len() as u64).saturating_mul(Self::HISTOGRAM_ENTRY_BYTES)
137    }
138
139    /// The committed degree-histogram map's keys — the estimate's
140    /// seed.
141    pub(super) fn degree_histogram_keys(&self) -> HashSet<(u32, u32)> {
142        self.degree_histograms
143            .lock()
144            .unwrap()
145            .keys()
146            .copied()
147            .collect()
148    }
149
150    /// Move the from-node up the degree buckets for every label it
151    /// carries: called after a create's adjacency insert, with `before`
152    /// the pre-insert out-degree on the rel type (LABS-351). The
153    /// high-water semantics mean a move is the only outcome (never
154    /// down); the create path guarantees `after = before + 1`, so the
155    /// bucket moves at most one step.
156    pub(super) fn bump_degree_histograms(&self, node: NodeId, type_id: u32, before: u64) {
157        // One loop, both cases (stellar std-3): `old` is None for a node's
158        // first edge (nothing to decrement — a degree-0 before would
159        // collide with the degree-1 bucket), Some(bucket) for a move; the
160        // same-bucket move changes nothing.
161        let after = self.out_chunk_len(node, type_id);
162        let new = Self::degree_bucket(after);
163        let old = (before > 0).then(|| Self::degree_bucket(before));
164        if old.is_some_and(|old| old == new) {
165            return;
166        }
167        let labels = self.live_label_ids(node);
168        let mut histograms = self.degree_histograms.lock().unwrap();
169        for label in labels {
170            let entry = self.histogram_entry(&mut histograms, label, type_id);
171            if let Some(old) = old {
172                entry[old] = entry[old].saturating_sub(1);
173            }
174            entry[new] = entry[new].saturating_add(1);
175        }
176    }
177
178    /// The get-or-create of one histogram entry with its `used_bytes`
179    /// entry charge — the one charge policy both histogram bumps share
180    /// (the memory-limit charge discipline lives once, not copied
181    /// verbatim per bump site). The wholesale rebuild is the one
182    /// exception and stays inline in [`Graph::rebuild_degree_stats`]:
183    /// its entry charges are recomputed wholesale by `recompute_used`
184    /// at the caller's tail, so charging there would double-count.
185    fn histogram_entry<'m>(
186        &self,
187        histograms: &'m mut DegreeHistograms,
188        label: u32,
189        type_id: u32,
190    ) -> &'m mut [u64; Self::DEGREE_BUCKETS] {
191        histograms.slot((label, type_id), || {
192            self.used_bytes
193                .fetch_add(Self::HISTOGRAM_ENTRY_BYTES, Ordering::Relaxed);
194        })
195    }
196
197    /// The node's out-degree buckets enter the histograms of every
198    /// newly added label (each per-type out-degree, bucketed, once per
199    /// label). Bounded by the node's typed adjacency chunks.
200    pub(super) fn rebucket_added_labels(&self, node: NodeId, added_ids: &[u32]) {
201        if added_ids.is_empty() {
202            return;
203        }
204        let mut histograms = self.degree_histograms.lock().unwrap();
205        for (type_id, degree) in self.out_chunks(node) {
206            let bucket = Self::degree_bucket(degree);
207            for label in added_ids {
208                let entry = self.histogram_entry(&mut histograms, *label, type_id);
209                entry[bucket] = entry[bucket].saturating_add(1);
210            }
211        }
212    }
213
214    /// The node's out-degree buckets leave the histograms of every
215    /// actually-removed label (saturating: a high-water degree can exceed
216    /// the current live count). The paired helper of
217    /// [`Graph::rebucket_added_labels`]: one input domain (&[u32] ids),
218    /// one guard, one direction each.
219    pub(super) fn unbucket_removed_labels(&self, node: NodeId, removed_ids: &[u32]) {
220        if removed_ids.is_empty() {
221            return;
222        }
223        let mut histograms = self.degree_histograms.lock().unwrap();
224        for (type_id, degree) in self.out_chunks(node) {
225            let bucket = Self::degree_bucket(degree);
226            for label in removed_ids {
227                histograms.release((*label, type_id), bucket);
228            }
229        }
230    }
231
232    /// LABS-351: the tail of a (label, rel-type) out-degree distribution —
233    /// the conservative floor of the highest observed degree
234    /// (2^k for the highest non-empty bucket k), high-water across
235    /// deletes. `None` when nothing of that pair was ever written. This
236    /// is the estimate the mean degree cannot express: one 50k-degree
237    /// supernode in a 55-average label.
238    pub fn pattern_degree_tail(&self, label: &str, rel_type: &str) -> Option<u64> {
239        let label_id = self.interner.get_id(label)?;
240        let type_id = self.interner.get_id(rel_type)?;
241        self.pattern_degree_tail_by_id(label_id, type_id)
242    }
243
244    /// [`Graph::pattern_degree_tail`] for already-resolved token ids.
245    pub fn pattern_degree_tail_by_id(&self, label_id: u32, type_id: u32) -> Option<u64> {
246        let histograms = self.degree_histograms.lock().unwrap();
247        Self::bucket_tail(histograms.get(&(label_id, type_id))?)
248    }
249
250    /// The floor of the highest observed degree in one histogram (2^k
251    /// for the highest non-empty bucket k) — the one bucket-to-degree
252    /// reading both tail lookups share. `None` for an empty histogram.
253    fn bucket_tail(buckets: &[u64; Self::DEGREE_BUCKETS]) -> Option<u64> {
254        buckets
255            .iter()
256            .rposition(|&count| count > 0)
257            .map(|highest| 1u64 << highest)
258    }
259
260    /// LABS-991: the highest tail ([`Graph::pattern_degree_tail`]'s floor)
261    /// over every labeled node's histogram for `rel_type`. Nodes without a
262    /// label sit in no histogram. `None` when no histogram entry matches.
263    pub(crate) fn pattern_type_degree_tail(&self, rel_type: &str) -> Option<u64> {
264        let type_id = self.interner.get_id(rel_type)?;
265        let histograms = self.degree_histograms.lock().unwrap();
266        Self::type_tail(&histograms, type_id)
267    }
268
269    /// LABS-991: the per-type maxima ([`Graph::pattern_type_degree_tail`])
270    /// summed over every distinct type id — each term the same log2-bucket
271    /// floor as [`Graph::pattern_degree_tail`], so the sum is an estimate on
272    /// that scale, not a strict upper bound. `None` when no histogram entry
273    /// has a tail.
274    pub(crate) fn pattern_any_degree_tail(&self) -> Option<u64> {
275        let histograms = self.degree_histograms.lock().unwrap();
276        let mut per_type: HashMap<u32, u64> = HashMap::new();
277        for (&(_, type_id), buckets) in histograms.iter() {
278            if let Some(tail) = Self::bucket_tail(buckets) {
279                let max = per_type.entry(type_id).or_insert(tail);
280                *max = (*max).max(tail);
281            }
282        }
283        per_type.into_values().reduce(u64::saturating_add)
284    }
285
286    /// The highest tail over every label's histogram for one type id.
287    fn type_tail(histograms: &DegreeHistograms, type_id: u32) -> Option<u64> {
288        histograms
289            .iter()
290            .filter(|(&(_, id), _)| id == type_id)
291            .filter_map(|(_, buckets)| Self::bucket_tail(buckets))
292            .max()
293    }
294
295    /// The estimated out-degree moments of one label's (or, for `None`,
296    /// every labeled node's) histograms over `type_ids` (`None`: every
297    /// type). Each bucket is read at the uniform mean of its degree range
298    /// `[2^k, 2^(k+1) - 1]`, so the figures are estimates on the
299    /// histogram's own scale, high-water across deletes like the tails.
300    ///
301    /// The histograms are per (label, type): a node's degree on two
302    /// selected types sits in two buckets, so the plain sum of their
303    /// squares drops the cross term of the node's total degree
304    /// `(a + b)^2 = a^2 + b^2 + 2ab` and under-prices every untyped or
305    /// multi-type hop. The cross term is added per label under the
306    /// independence of a node's degrees across types, from the label's
307    /// per-type sums over its node count; a single selected type has none.
308    pub(crate) fn pattern_degree_moments(
309        &self,
310        label_id: Option<u32>,
311        type_ids: Option<&[u32]>,
312    ) -> DegreeMoments {
313        self.combine_label_moments(self.label_type_sums(label_id, type_ids))
314    }
315
316    /// The histogram scan under the one lock: per label, the per-type
317    /// degree sums and the squares' sum of the selected histograms.
318    fn label_type_sums(
319        &self,
320        label_id: Option<u32>,
321        type_ids: Option<&[u32]>,
322    ) -> HashMap<u32, (Vec<u128>, u128)> {
323        let mut per_label: HashMap<u32, (Vec<u128>, u128)> = HashMap::new();
324        let histograms = self.degree_histograms.lock().unwrap();
325        for (&(label, type_id), buckets) in histograms.iter() {
326            if !Self::selects(label_id, label) || !Self::selects_type(type_ids, type_id) {
327                continue;
328            }
329            let (sums, sum_sq) = per_label.entry(label).or_default();
330            let mut type_sum = 0u128;
331            for (bucket, &nodes) in buckets.iter().enumerate() {
332                let low = 1u128 << bucket;
333                let high = (low << 1) - 1;
334                let nodes = u128::from(nodes);
335                type_sum = type_sum.saturating_add(nodes * ((low + high) / 2));
336                *sum_sq =
337                    sum_sq.saturating_add(nodes * ((low * low + low * high + high * high) / 3));
338            }
339            sums.push(type_sum);
340        }
341        per_label
342    }
343
344    /// The lock-free derivation: fold the per-label sums into the moments,
345    /// adding each label's cross term over its node count.
346    fn combine_label_moments(&self, per_label: HashMap<u32, (Vec<u128>, u128)>) -> DegreeMoments {
347        let mut moments = DegreeMoments::default();
348        for (label, (sums, sum_sq)) in per_label {
349            let sum = sums.iter().fold(0u128, |acc, &s| acc.saturating_add(s));
350            let nodes = u128::from(self.label_count_by_id(label));
351            // `sum^2 - sum(type sums^2)` is the ordered cross pairs of two
352            // different types' degrees; never negative by construction.
353            let cross_pairs = sum.saturating_mul(sum).saturating_sub(
354                sums.iter()
355                    .fold(0u128, |acc, &s| acc.saturating_add(s.saturating_mul(s))),
356            );
357            moments.sum = moments.sum.saturating_add(sum);
358            moments.sum_sq = moments
359                .sum_sq
360                .saturating_add(sum_sq)
361                .saturating_add(if nodes == 0 { 0 } else { cross_pairs / nodes });
362            // (A label with no live node left only has high-water
363            // buckets: nothing is there to cross, so its term is zero.)
364        }
365        moments
366    }
367
368    /// Every per-label statistics change one label-set mutation makes: the
369    /// degree re/unbucket, the incident pair counts, and the exact label
370    /// counts. `delta` selects the direction — the one entry point both
371    /// label seams call.
372    ///
373    /// `before` is the node's label set before the mutation (the callers'
374    /// effect guard already read it); the set after is the node's live
375    /// set, read once the edit is installed (ADR-0589's label-set map
376    /// moves the node between the two).
377    pub(super) fn apply_label_delta_stats(
378        &self,
379        node: NodeId,
380        before: &[u32],
381        labels: &[u32],
382        delta: CountDelta,
383    ) {
384        match delta {
385            CountDelta::Add => self.rebucket_added_labels(node, labels),
386            CountDelta::Remove => self.unbucket_removed_labels(node, labels),
387        }
388        self.apply_incident_pair_counts(node, labels, delta);
389        let after = self.live_label_ids(node);
390        self.bump_label_counts(LabelMutation {
391            before,
392            after: &after,
393            labels,
394            delta,
395        });
396    }
397
398    /// The degree-stats half of the wholesale rebuild — the family seam
399    /// ADR-0387 Decision 1 promises (the maps' read/bump/rebucket paths
400    /// live in this file, the rebuild's folds included — the
401    /// label-mutation incident walk lives in the family's incident
402    /// sibling, `degree_stats_incident.rs`). Called by `rebuild_adj`
403    /// (graph/rebuild.rs) with the rebuild's materialized [`RelRow`]s
404    /// and their start-keyed partition — the same rows
405    /// `adjacency::adj_build` installs, `id` and `ts` included though
406    /// these folds read neither. A pure fold over its input:
407    /// the (label, rel-type) histograms come from the same rows (a
408    /// node's per-type out-degree is the count of its rows of that
409    /// type), not from the adjacency the caller built, so no
410    /// call-ordering precondition rides the seam.
411    ///
412    /// Sharded by the row's start (the partition `rebuild_adj` computes
413    /// once for every start-keyed consumer), which is what keeps it a
414    /// pure per-node fold: a shard carries every row of every node it
415    /// owns, so each node's out-degree there is the node's whole
416    /// out-degree and the shards' bucket counts merge by summing.
417    /// Nothing per-node crosses a shard boundary.
418    ///
419    /// The estimate family's wholesale rebuild: the histograms (the
420    /// count bundle's rel-side and node-side fields publish wholesale
421    /// through the count family's own [`Graph::rebuild_count_stats`] —
422    /// one bundle, one guard, one publish).
423    pub(super) fn rebuild_degree_stats(
424        &self,
425        rows: &[RelRow],
426        labels: &LabelCache,
427        shards: &[Vec<usize>],
428    ) {
429        let parts = shard::run_shards(shards, |shard| {
430            Self::degree_histogram_part(rows, labels, shard)
431        });
432        let mut histograms = DegreeHistograms::default();
433        for part in parts {
434            histograms.merge(part);
435        }
436        // One publish for the histogram map — the estimate family's
437        // own state; every other site takes exactly this one lock, so
438        // no ordering cycle exists and a reader never sees one
439        // rebuild's histograms mixed with the previous rebuild's.
440        *self.degree_histograms.lock().unwrap() = histograms;
441    }
442
443    /// One shard's share of the histograms. LABS-351: the per-(node, type)
444    /// out-degrees counted off the shard's rows — the same number the
445    /// out-adjacency chunk holds once `adj_build` installed it. A
446    /// shard-local map rather than an out_adj read: it keeps this fold a
447    /// pure function of its rows (no call-ordering precondition rides it),
448    /// at the cost of one transient map per shard. Bucket counts are
449    /// order-independent, so the map's iteration order does not matter.
450    /// Recomputed so the high-water mark recalibrates to the honest live
451    /// state after a restore.
452    fn degree_histogram_part(
453        rows: &[RelRow],
454        labels: &LabelCache,
455        shard: &[usize],
456    ) -> DegreeHistograms {
457        let mut out_degrees: HashMap<(NodeId, u32), u64> = HashMap::new();
458        for &index in shard {
459            let row = &rows[index];
460            *out_degrees.entry((row.start, row.type_id)).or_insert(0) += 1;
461        }
462        let mut histograms = DegreeHistograms::default();
463        for ((start, type_id), degree) in &out_degrees {
464            let bucket = Self::degree_bucket(*degree);
465            let node_labels = labels.get(*start);
466            for label in node_labels.iter() {
467                // Uncharged on purpose: the caller's tail runs
468                // `recompute_used`, which retallies the entry charges
469                // wholesale — charging here would double-count.
470                let slot = histograms.slot((*label, *type_id), || {});
471                slot[bucket] = slot[bucket].saturating_add(1);
472            }
473        }
474        histograms
475    }
476}