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