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 super::count_state::CountDelta;
21use super::{Graph, LabelCache, RelRow};
22
23impl Graph {
24 /// The histogram's bucket count (LABS-311: one constant, consulted at
25 /// every site — the field, the bumps, the rebuild fold, the tail
26 /// scan). 21 buckets cover degrees to 2^20 (one million), the
27 /// realistic supernode ceiling.
28 pub(super) const DEGREE_BUCKETS: usize = 21;
29 /// One histogram entry's charge: the (u32, u32) key, the bucket
30 /// counts, and the map's per-entry overhead (the same floor-estimate
31 /// style as the adjacency terms). Charged to `used_bytes` on every
32 /// entry creation so the incremental capacity accounting tracks the
33 /// recount oracle (security review: an uncharged query-controlled map
34 /// bypasses the memory-limit enforcement).
35 pub(super) const HISTOGRAM_ENTRY_BYTES: u64 = (std::mem::size_of::<(u32, u32)>()
36 + Self::DEGREE_BUCKETS * std::mem::size_of::<u64>()
37 + 48
38 + 64) as u64;
39 /// floor(log2(degree)) for degree >= 1: bucket 0 counts degree-1
40 /// nodes, bucket k counts 2^k..2^(k+1)-1. Clamped into the last
41 /// bucket above 2^20.
42 pub(super) fn degree_bucket(degree: u64) -> usize {
43 (degree.max(1).ilog2() as usize).min(Self::DEGREE_BUCKETS - 1)
44 }
45
46 /// The histogram family's share of the retained-structure recount
47 /// (the `structure_bytes` oracle): the histogram entries are
48 /// retained structure — an uncharged query-controlled map would
49 /// bypass the memory-limit enforcement (the Capacity check compares
50 /// `used_bytes`). One constant, consulted at every site (LABS-311):
51 /// the recount charges the same HISTOGRAM_ENTRY_BYTES the
52 /// incremental bumps do. The count bundle's share composes beside
53 /// this term at the oracle's one site (`structure_bytes`),
54 /// beside the constraint-key term.
55 pub(super) fn degree_stats_structure_bytes(&self) -> u64 {
56 let histograms = self.degree_histograms.lock().unwrap();
57 (histograms.len() as u64).saturating_mul(Self::HISTOGRAM_ENTRY_BYTES)
58 }
59
60 /// The committed degree-histogram map's keys — the estimate's
61 /// seed.
62 pub(super) fn degree_histogram_keys(&self) -> HashSet<(u32, u32)> {
63 self.degree_histograms
64 .lock()
65 .unwrap()
66 .keys()
67 .copied()
68 .collect()
69 }
70
71 /// Move the from-node up the degree buckets for every label it
72 /// carries: called after a create's adjacency insert, with `before`
73 /// the pre-insert out-degree on the rel type (LABS-351). The
74 /// high-water semantics mean a move is the only outcome (never
75 /// down); the create path guarantees `after = before + 1`, so the
76 /// bucket moves at most one step.
77 pub(super) fn bump_degree_histograms(&self, node: NodeId, type_id: u32, before: u64) {
78 // One loop, both cases (stellar std-3): `old` is None for a node's
79 // first edge (nothing to decrement — a degree-0 before would
80 // collide with the degree-1 bucket), Some(bucket) for a move; the
81 // same-bucket move changes nothing.
82 let after = self.out_chunk_len(node, type_id);
83 let new = Self::degree_bucket(after);
84 let old = (before > 0).then(|| Self::degree_bucket(before));
85 if old.is_some_and(|old| old == new) {
86 return;
87 }
88 let labels = self.live_label_ids(node);
89 let mut histograms = self.degree_histograms.lock().unwrap();
90 for label in labels {
91 let entry = self.histogram_entry(&mut histograms, label, type_id);
92 if let Some(old) = old {
93 entry[old] = entry[old].saturating_sub(1);
94 }
95 entry[new] = entry[new].saturating_add(1);
96 }
97 }
98
99 /// The get-or-create of one histogram entry with its `used_bytes`
100 /// entry charge — the one charge policy both histogram bumps share
101 /// (the memory-limit charge discipline lives once, not copied
102 /// verbatim per bump site). The wholesale rebuild is the one
103 /// exception and stays inline in [`Graph::rebuild_degree_stats`]:
104 /// its entry charges are recomputed wholesale by `recompute_used`
105 /// at the caller's tail, so charging there would double-count.
106 fn histogram_entry<'m>(
107 &self,
108 histograms: &'m mut HashMap<(u32, u32), [u64; Self::DEGREE_BUCKETS]>,
109 label: u32,
110 type_id: u32,
111 ) -> &'m mut [u64; Self::DEGREE_BUCKETS] {
112 match histograms.entry((label, type_id)) {
113 std::collections::hash_map::Entry::Vacant(v) => {
114 self.used_bytes
115 .fetch_add(Self::HISTOGRAM_ENTRY_BYTES, Ordering::Relaxed);
116 v.insert([0; Self::DEGREE_BUCKETS])
117 }
118 std::collections::hash_map::Entry::Occupied(o) => o.into_mut(),
119 }
120 }
121
122 /// The node's out-degree buckets enter the histograms of every
123 /// newly added label (each per-type out-degree, bucketed, once per
124 /// label). Bounded by the node's typed adjacency chunks.
125 pub(super) fn rebucket_added_labels(&self, node: NodeId, added_ids: &[u32]) {
126 if added_ids.is_empty() {
127 return;
128 }
129 let mut histograms = self.degree_histograms.lock().unwrap();
130 for (type_id, degree) in self.out_chunks(node) {
131 let bucket = Self::degree_bucket(degree);
132 for label in added_ids {
133 let entry = self.histogram_entry(&mut histograms, *label, type_id);
134 entry[bucket] = entry[bucket].saturating_add(1);
135 }
136 }
137 }
138
139 /// The node's out-degree buckets leave the histograms of every
140 /// actually-removed label (saturating: a high-water degree can exceed
141 /// the current live count). The paired helper of
142 /// [`Graph::rebucket_added_labels`]: one input domain (&[u32] ids),
143 /// one guard, one direction each.
144 pub(super) fn unbucket_removed_labels(&self, node: NodeId, removed_ids: &[u32]) {
145 if removed_ids.is_empty() {
146 return;
147 }
148 let mut histograms = self.degree_histograms.lock().unwrap();
149 for (type_id, degree) in self.out_chunks(node) {
150 let bucket = Self::degree_bucket(degree);
151 for label in removed_ids {
152 if let Some(entry) = histograms.get_mut(&(*label, type_id)) {
153 entry[bucket] = entry[bucket].saturating_sub(1);
154 }
155 }
156 }
157 }
158
159 /// LABS-351: the tail of a (label, rel-type) out-degree distribution —
160 /// the conservative floor of the highest observed degree
161 /// (2^k for the highest non-empty bucket k), high-water across
162 /// deletes. `None` when nothing of that pair was ever written. This
163 /// is the estimate the mean degree cannot express: one 50k-degree
164 /// supernode in a 55-average label.
165 pub fn pattern_degree_tail(&self, label: &str, rel_type: &str) -> Option<u64> {
166 let label_id = self.interner.get_id(label)?;
167 let type_id = self.interner.get_id(rel_type)?;
168 self.pattern_degree_tail_by_id(label_id, type_id)
169 }
170
171 /// [`Graph::pattern_degree_tail`] for already-resolved token ids.
172 pub fn pattern_degree_tail_by_id(&self, label_id: u32, type_id: u32) -> Option<u64> {
173 let histograms = self.degree_histograms.lock().unwrap();
174 Self::bucket_tail(histograms.get(&(label_id, type_id))?)
175 }
176
177 /// The floor of the highest observed degree in one histogram (2^k
178 /// for the highest non-empty bucket k) — the one bucket-to-degree
179 /// reading both tail lookups share. `None` for an empty histogram.
180 fn bucket_tail(buckets: &[u64; Self::DEGREE_BUCKETS]) -> Option<u64> {
181 buckets
182 .iter()
183 .rposition(|&count| count > 0)
184 .map(|highest| 1u64 << highest)
185 }
186
187 /// LABS-991: the highest tail ([`Graph::pattern_degree_tail`]'s floor)
188 /// over every labeled node's histogram for `rel_type`, or — for `None` —
189 /// the per-type maxima summed — each term the same log2-bucket floor
190 /// as [`Graph::pattern_degree_tail`], so the sum is an estimate on that
191 /// scale, not a strict upper bound. Nodes without a label sit in no
192 /// histogram. `None` when no histogram entry matches.
193 pub(crate) fn pattern_any_degree_tail(&self, rel_type: Option<&str>) -> Option<u64> {
194 let wanted = match rel_type {
195 Some(text) => Some(self.interner.get_id(text)?),
196 None => None,
197 };
198 let histograms = self.degree_histograms.lock().unwrap();
199 let mut per_type: HashMap<u32, u64> = HashMap::new();
200 for (&(_, type_id), buckets) in histograms.iter() {
201 if wanted.is_some_and(|w| w != type_id) {
202 continue;
203 }
204 let Some(tail) = Self::bucket_tail(buckets) else {
205 continue;
206 };
207 let slot = per_type.entry(type_id).or_insert(0);
208 *slot = (*slot).max(tail);
209 }
210 if per_type.is_empty() {
211 return None;
212 }
213 Some(
214 per_type
215 .values()
216 .fold(0u64, |sum, tail| sum.saturating_add(*tail)),
217 )
218 }
219
220 /// Every per-label statistics change one label-set mutation makes: the
221 /// degree re/unbucket, the incident pair counts, and the exact label
222 /// counts. `delta` selects the direction — the one entry point both
223 /// label seams call.
224 pub(super) fn apply_label_delta_stats(&self, node: NodeId, labels: &[u32], delta: CountDelta) {
225 match delta {
226 CountDelta::Add => self.rebucket_added_labels(node, labels),
227 CountDelta::Remove => self.unbucket_removed_labels(node, labels),
228 }
229 self.apply_incident_pair_counts(node, labels, delta);
230 self.bump_label_counts(labels, delta);
231 }
232
233 /// The degree-stats half of the wholesale rebuild — the family seam
234 /// ADR-0387 Decision 1 promises (the maps' read/bump/rebucket paths
235 /// live in this file, the rebuild's folds included — the
236 /// label-mutation incident walk lives in the family's incident
237 /// sibling, `degree_stats_incident.rs`). Called by `rebuild_adj`
238 /// (graph/index.rs) with the rebuild's materialized [`RelRow`]s —
239 /// the same rows `adjacency::adj_build` installs, `id` and `ts`
240 /// included though these folds read neither. A pure fold over its
241 /// input:
242 /// the (label, rel-type) histograms come from the same rows (a
243 /// node's per-type out-degree is the count of its rows of that
244 /// type), not from the adjacency the caller built, so no
245 /// call-ordering precondition rides the seam.
246 ///
247 /// The estimate family's wholesale rebuild: the histograms (the
248 /// count bundle's rel-side and node-side fields publish wholesale
249 /// through the count family's own [`Graph::rebuild_count_stats`] —
250 /// one bundle, one guard, one publish).
251 pub(super) fn rebuild_degree_stats<'a>(&self, rows: impl Iterator<Item = &'a RelRow>) {
252 let mut label_cache = LabelCache::default();
253 // LABS-351: the per-(node, type) out-degrees counted off the
254 // rows — the same number the out-adjacency chunk holds once
255 // `adj_build` installed it. A fold-local map rather than an out_adj
256 // read: it keeps this seam a pure function of its rows (no
257 // call-ordering precondition rides it), at the cost of one
258 // transient per-rebuild map. Bucket counts are
259 // order-independent, so the map's iteration order does not
260 // matter. Recomputed so the high-water mark recalibrates to the
261 // honest live state after a restore.
262 let mut out_degrees: HashMap<(NodeId, u32), u64> = HashMap::new();
263 for row in rows {
264 // One label read per distinct node, the family's shared
265 // cache seam.
266 label_cache.ensure(self, row.start);
267 *out_degrees.entry((row.start, row.type_id)).or_insert(0) += 1;
268 }
269 let mut histograms: HashMap<(u32, u32), [u64; Graph::DEGREE_BUCKETS]> = HashMap::new();
270 for ((start, type_id), degree) in &out_degrees {
271 let bucket = Self::degree_bucket(*degree);
272 let labels = label_cache.get(*start);
273 for label in labels.iter() {
274 // Uncharged on purpose: the caller's tail runs
275 // `recompute_used`, which retallies the entry charges
276 // wholesale — charging here would double-count.
277 let slot = histograms
278 .entry((*label, *type_id))
279 .or_insert([0; Graph::DEGREE_BUCKETS]);
280 slot[bucket] += 1;
281 }
282 }
283 // One publish for the histogram map — the estimate family's
284 // own state; every other site takes exactly this one lock, so
285 // no ordering cycle exists and a reader never sees one
286 // rebuild's histograms mixed with the previous rebuild's.
287 *self.degree_histograms.lock().unwrap() = histograms;
288 }
289}