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