Skip to main content

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