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`, or — for `None` —
262 /// the per-type maxima summed — each term the same log2-bucket floor
263 /// as [`Graph::pattern_degree_tail`], so the sum is an estimate on that
264 /// scale, not a strict upper bound. Nodes without a label sit in no
265 /// histogram. `None` when no histogram entry matches.
266 pub(crate) fn pattern_any_degree_tail(&self, rel_type: Option<&str>) -> Option<u64> {
267 let wanted = match rel_type {
268 Some(text) => Some(self.interner.get_id(text)?),
269 None => None,
270 };
271 let histograms = self.degree_histograms.lock().unwrap();
272 let mut per_type: HashMap<u32, u64> = HashMap::new();
273 for (&(_, type_id), buckets) in histograms.iter() {
274 if wanted.is_some_and(|w| w != type_id) {
275 continue;
276 }
277 let Some(tail) = Self::bucket_tail(buckets) else {
278 continue;
279 };
280 let slot = per_type.entry(type_id).or_insert(0);
281 *slot = (*slot).max(tail);
282 }
283 if per_type.is_empty() {
284 return None;
285 }
286 Some(
287 per_type
288 .values()
289 .fold(0u64, |sum, tail| sum.saturating_add(*tail)),
290 )
291 }
292
293 /// The estimated out-degree moments of one label's (or, for `None`,
294 /// every labeled node's) histograms over `type_ids` (`None`: every
295 /// type). Each bucket is read at the uniform mean of its degree range
296 /// `[2^k, 2^(k+1) - 1]`, so the figures are estimates on the
297 /// histogram's own scale, high-water across deletes like the tails.
298 ///
299 /// The histograms are per (label, type): a node's degree on two
300 /// selected types sits in two buckets, so the plain sum of their
301 /// squares drops the cross term of the node's total degree
302 /// `(a + b)^2 = a^2 + b^2 + 2ab` and under-prices every untyped or
303 /// multi-type hop. The cross term is added per label under the
304 /// independence of a node's degrees across types, from the label's
305 /// per-type sums over its node count; a single selected type has none.
306 pub(crate) fn pattern_degree_moments(
307 &self,
308 label_id: Option<u32>,
309 type_ids: Option<&[u32]>,
310 ) -> DegreeMoments {
311 // Per label: the per-type degree sums and the squares' sum.
312 let mut per_label: HashMap<u32, (Vec<u128>, u128)> = HashMap::new();
313 {
314 let histograms = self.degree_histograms.lock().unwrap();
315 for (&(label, type_id), buckets) in histograms.iter() {
316 if label_id.is_some_and(|wanted| wanted != label)
317 || type_ids.is_some_and(|wanted| !wanted.contains(&type_id))
318 {
319 continue;
320 }
321 let (sums, sum_sq) = per_label.entry(label).or_default();
322 let mut type_sum = 0u128;
323 for (bucket, &nodes) in buckets.iter().enumerate() {
324 let low = 1u128 << bucket;
325 let high = (low << 1) - 1;
326 let nodes = u128::from(nodes);
327 type_sum = type_sum.saturating_add(nodes * ((low + high) / 2));
328 *sum_sq =
329 sum_sq.saturating_add(nodes * ((low * low + low * high + high * high) / 3));
330 }
331 sums.push(type_sum);
332 }
333 }
334 let mut moments = DegreeMoments::default();
335 for (label, (sums, sum_sq)) in per_label {
336 let sum = sums.iter().fold(0u128, |acc, &s| acc.saturating_add(s));
337 let nodes = u128::from(self.label_count_by_id(label));
338 // `sum^2 - sum(type sums^2)` is the ordered cross pairs of two
339 // different types' degrees; never negative by construction.
340 let cross_pairs = sum.saturating_mul(sum).saturating_sub(
341 sums.iter()
342 .fold(0u128, |acc, &s| acc.saturating_add(s.saturating_mul(s))),
343 );
344 moments.sum = moments.sum.saturating_add(sum);
345 moments.sum_sq = moments
346 .sum_sq
347 .saturating_add(sum_sq)
348 .saturating_add(cross_pairs.checked_div(nodes).unwrap_or(0));
349 // (A label with no live node left only has high-water
350 // buckets: nothing is there to cross, so its term is zero.)
351 }
352 moments
353 }
354
355 /// Every per-label statistics change one label-set mutation makes: the
356 /// degree re/unbucket, the incident pair counts, and the exact label
357 /// counts. `delta` selects the direction — the one entry point both
358 /// label seams call.
359 ///
360 /// `before` is the node's label set before the mutation (the callers'
361 /// effect guard already read it); the set after is the node's live
362 /// set, read once the edit is installed (ADR-0589's label-set map
363 /// moves the node between the two).
364 pub(super) fn apply_label_delta_stats(
365 &self,
366 node: NodeId,
367 before: &[u32],
368 labels: &[u32],
369 delta: CountDelta,
370 ) {
371 match delta {
372 CountDelta::Add => self.rebucket_added_labels(node, labels),
373 CountDelta::Remove => self.unbucket_removed_labels(node, labels),
374 }
375 self.apply_incident_pair_counts(node, labels, delta);
376 let after = self.live_label_ids(node);
377 self.bump_label_counts(LabelMutation {
378 before,
379 after: &after,
380 labels,
381 delta,
382 });
383 }
384
385 /// The degree-stats half of the wholesale rebuild — the family seam
386 /// ADR-0387 Decision 1 promises (the maps' read/bump/rebucket paths
387 /// live in this file, the rebuild's folds included — the
388 /// label-mutation incident walk lives in the family's incident
389 /// sibling, `degree_stats_incident.rs`). Called by `rebuild_adj`
390 /// (graph/rebuild.rs) with the rebuild's materialized [`RelRow`]s
391 /// and their start-keyed partition — the same rows
392 /// `adjacency::adj_build` installs, `id` and `ts` included though
393 /// these folds read neither. A pure fold over its input:
394 /// the (label, rel-type) histograms come from the same rows (a
395 /// node's per-type out-degree is the count of its rows of that
396 /// type), not from the adjacency the caller built, so no
397 /// call-ordering precondition rides the seam.
398 ///
399 /// Sharded by the row's start (the partition `rebuild_adj` computes
400 /// once for every start-keyed consumer), which is what keeps it a
401 /// pure per-node fold: a shard carries every row of every node it
402 /// owns, so each node's out-degree there is the node's whole
403 /// out-degree and the shards' bucket counts merge by summing.
404 /// Nothing per-node crosses a shard boundary.
405 ///
406 /// The estimate family's wholesale rebuild: the histograms (the
407 /// count bundle's rel-side and node-side fields publish wholesale
408 /// through the count family's own [`Graph::rebuild_count_stats`] —
409 /// one bundle, one guard, one publish).
410 pub(super) fn rebuild_degree_stats(
411 &self,
412 rows: &[RelRow],
413 labels: &LabelCache,
414 shards: &[Vec<usize>],
415 ) {
416 let parts = shard::run_shards(shards, |shard| {
417 Self::degree_histogram_part(rows, labels, shard)
418 });
419 let mut histograms = DegreeHistograms::default();
420 for part in parts {
421 histograms.merge(part);
422 }
423 // One publish for the histogram map — the estimate family's
424 // own state; every other site takes exactly this one lock, so
425 // no ordering cycle exists and a reader never sees one
426 // rebuild's histograms mixed with the previous rebuild's.
427 *self.degree_histograms.lock().unwrap() = histograms;
428 }
429
430 /// One shard's share of the histograms. LABS-351: the per-(node, type)
431 /// out-degrees counted off the shard's rows — the same number the
432 /// out-adjacency chunk holds once `adj_build` installed it. A
433 /// shard-local map rather than an out_adj read: it keeps this fold a
434 /// pure function of its rows (no call-ordering precondition rides it),
435 /// at the cost of one transient map per shard. Bucket counts are
436 /// order-independent, so the map's iteration order does not matter.
437 /// Recomputed so the high-water mark recalibrates to the honest live
438 /// state after a restore.
439 fn degree_histogram_part(
440 rows: &[RelRow],
441 labels: &LabelCache,
442 shard: &[usize],
443 ) -> DegreeHistograms {
444 let mut out_degrees: HashMap<(NodeId, u32), u64> = HashMap::new();
445 for &index in shard {
446 let row = &rows[index];
447 *out_degrees.entry((row.start, row.type_id)).or_insert(0) += 1;
448 }
449 let mut histograms = DegreeHistograms::default();
450 for ((start, type_id), degree) in &out_degrees {
451 let bucket = Self::degree_bucket(*degree);
452 let node_labels = labels.get(*start);
453 for label in node_labels.iter() {
454 // Uncharged on purpose: the caller's tail runs
455 // `recompute_used`, which retallies the entry charges
456 // wholesale — charging here would double-count.
457 let slot = histograms.slot((*label, *type_id), || {});
458 slot[bucket] = slot[bucket].saturating_add(1);
459 }
460 }
461 histograms
462 }
463}