relate_executor/graph/key_stats/mod.rs
1//! Per-key value statistics (the per-key statistics ADR): for each `(node label, property
2//! key)` the count of admitted values, their minimum, maximum and sum, an
3//! approximate distinct count and a top-16 heavy-hitter summary, built
4//! lazily per label and never persisted.
5//!
6//! **Consult.** [`Graph::key_stats`] is a single map lookup on a built
7//! label: it clones an `Arc`, allocates nothing and holds a shard lock only
8//! for the lookup. A label that is unbuilt, stale or being built answers
9//! `None` at once and never blocks, builds nothing and never waits for a
10//! build in flight; the first miss on an unbuilt label records a build
11//! request (one more map operation, miss path only).
12//!
13//! **Build.** The request is served by [`Graph::build_pending_key_stats`],
14//! the engine's maintenance entry: one chunked scan per requested label,
15//! taking the node store's lock per node and none between chunks, so
16//! writers are never stalled for the scan. The pump is the one place a
17//! build runs, and the read executor never calls it. The executor holds
18//! the graph by reference, so nothing here can spawn its own thread: the
19//! `relate` crate's statement-completion seam (`connection/stats_pump.rs`)
20//! calls it after every successful statement, once the statement's own
21//! snapshot pin is dropped, for at most one label, and stops it at the
22//! next chunk boundary when the statement's cancel token fires (the
23//! label returns to the queue). A statement therefore inherits at most one
24//! label's scan, and the remaining requests wait for later statements.
25//!
26//! **Staleness.** A node write counts against each of its labels
27//! ([`Graph::key_stats_note_write`], hooked at `index_add` and
28//! `suspect_postings`, the two sites every node create, change, label change
29//! and delete already pass). Past a threshold of a built label's rows the
30//! label turns stale: its entries go and the next consult requests a
31//! rebuild. A write during a build counts the same way; a build that saw
32//! more than the threshold still publishes (best-effort statistics) and its
33//! write count restarts, so a label written faster than it can be scanned
34//! is rebuilt once per threshold of writes, never once per read. Below the
35//! threshold the statistics stay, a bounded drift on a best-effort
36//! estimate. The any-label bucket is unsupported: nothing ages it, so a
37//! consult for it is unmeasured and requests nothing.
38//!
39//! **Budget.** The published statistics hold at most [`BUDGET_BYTES`];
40//! structured keys outrank text keys and evict their entries when the
41//! budget is full. A key that was evicted or never admitted answers `None`.
42
43use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
44use std::sync::{Arc, Mutex};
45
46use relate_core::Value;
47
48use super::{CoreMap, Graph};
49
50mod accum;
51mod build;
52mod gate;
53mod ledger;
54mod sketch;
55
56#[cfg(test)]
57mod tests;
58
59use ledger::Ledger;
60
61/// The consult map: every published key's statistics.
62type Published = CoreMap<(u32, u32), Arc<KeyStats>>;
63
64/// The published statistics' byte budget (about 2,000 keys at the typical
65/// entry size). Outside the ADR-0042 logical charge, like the lazy pairs.
66pub(super) const BUDGET_BYTES: usize = 5 << 20;
67
68/// Smallest stale threshold, so a small label does not rebuild on every
69/// few writes.
70const MIN_STALE_WRITES: u64 = 64;
71
72/// A built label turns stale after `rows / STALE_DIVISOR` writes.
73const STALE_DIVISOR: u64 = 32;
74
75pub(crate) use gate::is_admitted;
76use relate_planner::{HeavyValue, KeyStats};
77
78/// The upper-bound count of `value` when it is one of `stats`' heavy
79/// values, by the index's equality identity (an integer and its equal float
80/// are one value). The identity hash is recomputed here, from the stored
81/// representatives, so the published figures carry no parallel hash state.
82pub(crate) fn heavy_count(stats: &KeyStats, value: &Value) -> Option<u64> {
83 let wanted = sketch::identity_hash(value)?;
84 stats
85 .heavy
86 .iter()
87 .find(|h| sketch::identity_hash(&h.value) == Some(wanted))
88 .map(|h| h.count)
89}
90
91/// Heap bytes a stored value holds beyond its inline size. Admitted values
92/// are scalars and strings of at most [`gate::MAX_TEXT_BYTES`]: only a
93/// string owns a payload.
94fn value_payload_bytes(value: &Value) -> usize {
95 match value {
96 Value::String(text) => text.len(),
97 _ => 0,
98 }
99}
100
101/// Estimated heap footprint of one published entry, charged against
102/// [`BUDGET_BYTES`]: the struct, the heavy values, and the payload of every
103/// stored string (minimum, maximum and heavy values).
104fn approx_bytes(stats: &KeyStats) -> usize {
105 let held = stats.min.iter().chain(stats.max.iter());
106 let heavy = stats.heavy.iter().map(|h| &h.value);
107 std::mem::size_of::<KeyStats>()
108 + stats.heavy.len() * std::mem::size_of::<HeavyValue>()
109 + held.chain(heavy).map(value_payload_bytes).sum::<usize>()
110}
111
112/// Where a label stands.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114enum Phase {
115 /// A consult asked for it; the pump has not claimed it.
116 Requested,
117 /// The pump is scanning it.
118 Building,
119 /// Published.
120 Built,
121 /// Built once, then written past the threshold; the next consult
122 /// requests a rebuild.
123 Stale,
124}
125
126#[derive(Debug)]
127struct LabelState {
128 phase: Phase,
129 /// Writes since the build began (or, while built, since it published).
130 writes: u64,
131 /// Writes a built label tolerates before it turns stale.
132 stale_after: u64,
133}
134
135/// All key-statistics state, one bundle in [`super::index::Indexes`].
136#[derive(Debug, Default)]
137pub(super) struct KeyStatsState {
138 published: Published,
139 labels: CoreMap<u32, LabelState>,
140 /// Labels with any state: zero keeps the write-path hook to one load.
141 active: AtomicUsize,
142 /// Labels waiting for the pump: zero keeps the pump, which every read
143 /// statement calls, to one load.
144 requested: AtomicUsize,
145 ledger: Mutex<Ledger>,
146 /// Monotonic count of changes to what a consult can answer: a label's
147 /// statistics published, aged out (a label turning stale) or cleared,
148 /// bumped AFTER the published map changed. A reader that stamps the
149 /// epoch before it consults can therefore never hold a stamp that
150 /// postdates a change it did not see (a plan cached against the
151 /// statistics of epoch `e` is stale once the epoch moves past `e`).
152 epoch: AtomicU64,
153}
154
155impl KeyStatsState {
156 /// The statistics epoch (see the field): one acquire load.
157 pub(super) fn epoch(&self) -> u64 {
158 self.epoch.load(Ordering::Acquire)
159 }
160
161 /// Record that what a consult answers has changed; called after the
162 /// change is visible.
163 fn bump_epoch(&self) {
164 self.epoch.fetch_add(1, Ordering::Release);
165 }
166
167 /// The consult: one lookup on a hit; on a miss, record a request when
168 /// the label has never been asked for, or went stale.
169 fn get(&self, label: u32, key: u32) -> Option<Arc<KeyStats>> {
170 if let Some(found) = self.published.get(&(label, key)) {
171 return Some(Arc::clone(&found));
172 }
173 self.request(label);
174 None
175 }
176
177 /// The published statistics of one key without recording a request:
178 /// the read for a consumer that benefits from statistics when they
179 /// exist but must not make a build happen on their account.
180 fn peek(&self, label: u32, key: u32) -> Option<Arc<KeyStats>> {
181 self.published
182 .get(&(label, key))
183 .map(|found| Arc::clone(&found))
184 }
185
186 fn request(&self, label: u32) {
187 match self.labels.entry(label) {
188 dashmap::mapref::entry::Entry::Vacant(slot) => {
189 // The entry's shard stays locked while the counters move, so
190 // `clear` removes an entry and its counts as one step.
191 let _held = slot.insert(LabelState {
192 phase: Phase::Requested,
193 writes: 0,
194 stale_after: MIN_STALE_WRITES,
195 });
196 self.active.fetch_add(1, Ordering::Relaxed);
197 self.requested.fetch_add(1, Ordering::Relaxed);
198 }
199 dashmap::mapref::entry::Entry::Occupied(mut slot) => {
200 let state = slot.get_mut();
201 if state.phase == Phase::Stale {
202 state.phase = Phase::Requested;
203 self.requested.fetch_add(1, Ordering::Relaxed);
204 }
205 }
206 }
207 }
208
209 /// One node write against `label`.
210 fn note_write(&self, label: u32) {
211 if self.active.load(Ordering::Relaxed) == 0 {
212 return;
213 }
214 let Some(mut state) = self.labels.get_mut(&label) else {
215 return;
216 };
217 match state.phase {
218 Phase::Built => {
219 state.writes += 1;
220 if state.writes > state.stale_after {
221 let dropped = self.evict_label(label);
222 state.phase = Phase::Stale;
223 // Once per transition, not per write, and only when
224 // published statistics actually went away.
225 if dropped {
226 self.bump_epoch();
227 }
228 }
229 }
230 Phase::Building => state.writes += 1,
231 Phase::Requested | Phase::Stale => {}
232 }
233 }
234
235 /// Drop a label's published entries, whether any were published. The
236 /// caller holds the label's state (lock order: labels, then the
237 /// ledger, then published).
238 fn evict_label(&self, label: u32) -> bool {
239 self.ledger
240 .lock()
241 .expect("ledger lock")
242 .evict_label(label, &self.published)
243 }
244
245 /// Whether any label waits for the pump: the one load the pump's fast
246 /// path and the connection's seam both start with.
247 fn has_requests(&self) -> bool {
248 self.requested.load(Ordering::Relaxed) != 0
249 }
250
251 /// Claim one requested label for the pump.
252 fn claim_requested(&self) -> Option<u32> {
253 if !self.has_requests() {
254 return None;
255 }
256 let candidates: Vec<u32> = self
257 .labels
258 .iter()
259 .filter(|e| e.phase == Phase::Requested)
260 .map(|e| *e.key())
261 .collect();
262 candidates.into_iter().find(|label| {
263 self.labels.get_mut(label).is_some_and(|mut s| {
264 let claimed = s.phase == Phase::Requested;
265 if claimed {
266 s.phase = Phase::Building;
267 s.writes = 0;
268 self.requested.fetch_sub(1, Ordering::Relaxed);
269 }
270 claimed
271 })
272 })
273 }
274
275 /// Give a claimed label back to the queue: its scan was abandoned, so
276 /// the next pump serves it again.
277 fn unclaim(&self, label: u32) {
278 let Some(mut state) = self.labels.get_mut(&label) else {
279 return;
280 };
281 if state.phase == Phase::Building {
282 state.phase = Phase::Requested;
283 self.requested.fetch_add(1, Ordering::Relaxed);
284 }
285 }
286
287 /// Forget everything. The counters move with each entry under that
288 /// entry's shard lock (`request`, `claim_requested`), so removing the
289 /// entries here subtracts exactly what they added: a request racing the
290 /// clear is either removed and subtracted, or inserted after and
291 /// counted, never stranded with a zero counter.
292 pub(super) fn clear(&self) {
293 let (mut removed, mut requested) = (0usize, 0usize);
294 self.labels.retain(|_, state| {
295 removed += 1;
296 requested += usize::from(state.phase == Phase::Requested);
297 false
298 });
299 self.active.fetch_sub(removed, Ordering::Relaxed);
300 self.requested.fetch_sub(requested, Ordering::Relaxed);
301 let had_published = !self.published.is_empty();
302 self.published.clear();
303 *self.ledger.lock().expect("ledger lock") = Ledger::default();
304 if had_published {
305 self.bump_epoch();
306 }
307 }
308
309 /// Whether the counters agree with the label table: only meaningful
310 /// while no request, claim or clear is in flight.
311 #[cfg(test)]
312 fn counters_agree(&self) -> bool {
313 let requested = self
314 .labels
315 .iter()
316 .filter(|e| e.phase == Phase::Requested)
317 .count();
318 self.active.load(Ordering::Relaxed) == self.labels.len()
319 && self.requested.load(Ordering::Relaxed) == requested
320 }
321}
322
323/// One published key's statistics beside the decoded names it belongs to.
324pub(crate) struct PublishedKeyStats {
325 pub(crate) label: Arc<str>,
326 pub(crate) property: Arc<str>,
327 pub(crate) stats: Arc<KeyStats>,
328}
329
330impl Graph {
331 /// The statistics epoch: a monotonic count of changes to what
332 /// [`Graph::key_stats`] can answer (a label's statistics published,
333 /// aged out by writes, or cleared), one atomic load. A consumer that
334 /// reads it BEFORE it consults and stores it beside the result can tell
335 /// later that the result is out of date (the plan cache replans a plan
336 /// that consulted the statistics once the epoch moves).
337 pub fn key_stats_epoch(&self) -> u64 {
338 self.indexes.key_stats.epoch()
339 }
340
341 /// The statistics of `property` on `label`'s nodes by interned id, or
342 /// `None` while the label is unbuilt, stale, being built, or the key was
343 /// declined or evicted. A hit is one map lookup; a miss never blocks
344 /// and never waits for a build in flight (a first miss records a build
345 /// request for [`Graph::build_pending_key_stats`]).
346 pub(crate) fn key_stats(&self, label: u32, key: u32) -> Option<Arc<KeyStats>> {
347 // The any-label bucket has no per-label writes to age it, so it is
348 // unsupported: unmeasured, and no build is requested.
349 if label == self.indexes.star_label_id {
350 return None;
351 }
352 self.indexes.key_stats.get(label, key)
353 }
354
355 /// The distinct count the equality pair's build sizes its table from:
356 /// the key's PUBLISHED statistics, read without a request. A pair build
357 /// happens once per process (the pair is lazy and kept), so a request
358 /// made on its behalf would scan the label to benefit a build that has
359 /// already happened; the build uses statistics only when an earlier
360 /// consult had them built, and never waits for or asks for a build.
361 /// `None` while the label is unbuilt, stale, or the key was declined,
362 /// and for the unsupported any-label bucket.
363 pub(super) fn published_distinct(&self, label: u32, key: u32) -> Option<u64> {
364 if label == self.indexes.star_label_id {
365 return None;
366 }
367 self.indexes.key_stats.peek(label, key).map(|s| s.distinct)
368 }
369
370 /// [`Graph::key_stats`] by name; `None` when either name was never
371 /// interned. The tests' spelling; production resolves tokens in
372 /// `GraphStats`.
373 #[cfg(test)]
374 pub(crate) fn key_stats_named(&self, label: &str, property: &str) -> Option<Arc<KeyStats>> {
375 let label = self.interner.get_id(label)?;
376 let key = self.interner.get_id(property)?;
377 self.key_stats(label, key)
378 }
379
380 /// Whether any label's build is requested: one atomic load, so the
381 /// statement-completion seam costs a statement nothing when no consult
382 /// asked for statistics.
383 pub fn has_pending_key_stats(&self) -> bool {
384 self.indexes.key_stats.has_requests()
385 }
386
387 /// The maintenance entry of the statistics: serve at most `max_labels`
388 /// requested labels' builds, the number built. A label is claimed by one
389 /// caller (a concurrent caller finds nothing to claim), and the scan
390 /// stops at the next chunk boundary when `keep_going` answers `false`,
391 /// returning its label to the queue. The engine's statement-completion
392 /// seam calls this with one label, so a statement inherits at most one
393 /// label's scan.
394 pub fn build_pending_key_stats(
395 &self,
396 max_labels: usize,
397 keep_going: impl Fn() -> bool,
398 ) -> usize {
399 let mut built = 0;
400 while built < max_labels && keep_going() {
401 let Some(label) = self.indexes.key_stats.claim_requested() else {
402 break;
403 };
404 if self.build_key_stats_for(label, &keep_going) {
405 built += 1;
406 }
407 }
408 built
409 }
410
411 /// One node write against each of `labels`: the staleness count.
412 pub(super) fn key_stats_note_write(&self, labels: &[u32]) {
413 for &label in labels {
414 self.indexes.key_stats.note_write(label);
415 }
416 }
417
418 /// Every published key's statistics beside its decoded label and
419 /// property names, ordered by `(label, property)`: the read-only
420 /// snapshot a surface lists. It reads the published map alone, so it
421 /// never records a build request and never builds, and only labels
422 /// whose statistics are currently built (not stale, not evicted) appear.
423 pub(crate) fn published_key_statistics(&self) -> Vec<PublishedKeyStats> {
424 let mut all: Vec<PublishedKeyStats> = self
425 .indexes
426 .key_stats
427 .published
428 .iter()
429 .map(|entry| {
430 let (label, key) = *entry.key();
431 PublishedKeyStats {
432 label: self.interner.get(label),
433 property: self.interner.get(key),
434 stats: Arc::clone(entry.value()),
435 }
436 })
437 .collect();
438 all.sort_by(|a, b| (&*a.label, &*a.property).cmp(&(&*b.label, &*b.property)));
439 all
440 }
441
442 /// Published statistics of every key of `label`, for tests and the
443 /// future surface; `None` entries are keys without statistics.
444 #[cfg(test)]
445 pub(super) fn key_stats_published(
446 &self,
447 label: u32,
448 ) -> std::collections::BTreeMap<u32, Arc<KeyStats>> {
449 self.indexes
450 .key_stats
451 .published
452 .iter()
453 .filter(|e| e.key().0 == label)
454 .map(|e| (e.key().1, Arc::clone(e.value())))
455 .collect()
456 }
457}