Skip to main content

relate_executor/exec/
graph_stats.rs

1//! The one live-graph [`relate_planner::PatternStats`] implementation (LABS-351): the
2//! executor's compound start-element estimate consumes it directly, and
3//! the top-level crate's plan-time stats adapter delegates to it, so
4//! one implementation answers both consumers.
5
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9use relate_core::Value;
10use relate_ir::{BinaryOp, Expr, NodePattern, RelPattern};
11use relate_names::{NamedToken, SmallName, Token, TokenResolver};
12use relate_planner::{
13    endpoint_estimate, seed_on_rel_start, walk_cost, Bound, ContainsCount, DegreeMoments, KeyStats,
14    Provenance, RowEstimate,
15};
16
17use crate::graph::{key_heavy_count, key_value_admitted, Graph};
18
19/// Construction goes through [`GraphStats::new`] (the ADR-0218 one-
20/// construction idiom the sibling plan-time stats impls use), so an
21/// inline build cannot drift from it.
22pub struct GraphStats<'a> {
23    graph: &'a Graph,
24    params: &'a BTreeMap<String, Value>,
25}
26
27impl<'a> GraphStats<'a> {
28    /// The one construction: the connection's graph and the statement's
29    /// parameters.
30    pub fn new(graph: &'a Graph, params: &'a BTreeMap<String, Value>) -> GraphStats<'a> {
31        GraphStats { graph, params }
32    }
33
34    /// One element's compound start estimate (LABS-351): the planner's
35    /// canonical endpoint ladder over this graph's stats, mapped onto
36    /// the one u64 scale the executor compares. The rank sentinels
37    /// share the measured scale (`direction_cost` compares them
38    /// directly); the bare rank — an unlabeled element, an all-node
39    /// scan — stays the whole-graph sentinel. A sampled `CONTAINS` seed
40    /// compounds (ADR-0474): its first hop is the degree-scaled output
41    /// floored at the whole-label scan the unseekable filter pays, the
42    /// same arithmetic the planner's `direction_cost` runs, so the
43    /// per-row start selection and the plan-time orientation agree on
44    /// the anchor (GBL SF0.1 q8: the Forum side's 13,750-row scan floor
45    /// ties Person's degree-scaled walk and the tie-break's seed
46    /// comparison — 1,528 Person rows against the floored 13,750 —
47    /// flips the anchor to Person).
48    pub(crate) fn estimate<'c>(
49        &self,
50        np: &'c NodePattern,
51        bound: Bound<'_>,
52        where_conjuncts: impl Iterator<Item = &'c Expr> + Clone,
53        first_hop: Option<&RelPattern>,
54        reversed: bool,
55    ) -> u64 {
56        let estimate = endpoint_estimate(np, bound, where_conjuncts, self);
57        // Two local facts: the orientation flag is the caller's derived
58        // one (the forward walker passes false, the backward walker's
59        // k > 0 pivots pass true — LABS-426), and the walk prices this
60        // start's first hop only. The model itself — which estimate kind
61        // gets which walk, and the seed-side derivation — is
62        // [`walk_cost`]'s and [`seed_on_rel_start`]'s to state.
63        let rows = walk_cost(
64            estimate,
65            first_hop
66                .into_iter()
67                .map(|rel| (np, rel, seed_on_rel_start(rel, reversed))),
68            self,
69        );
70        rows.min(u64::MAX as u128) as u64
71    }
72}
73
74impl GraphStats<'_> {
75    /// The store id of a name beside its planning token (ADR-0541): `Id`
76    /// answers it, `Absent` answers `None` without a store read, and only
77    /// `Unresolved` interns by name. `None` means no stored entity
78    /// carries the name.
79    fn id_of(&self, name: &SmallName, token: Token) -> Option<u32> {
80        token.id_or_else(|| name.with_str(|text| self.graph.resolve(text).id()))
81    }
82
83    /// The interned `(label, property)` ids of a value-keyed consult; `None`
84    /// when either side was never interned.
85    fn pair_ids(&self, label: &NamedToken, property: &NamedToken) -> Option<(u32, u32)> {
86        Some((
87            self.id_of(&label.0, label.1)?,
88            self.id_of(&property.0, property.1)?,
89        ))
90    }
91
92    /// A declared index's posting length for the equality: its postings
93    /// are a superset of the live values (ADR-0018: superseded versions
94    /// stay until the next prune), so an upper bound.
95    fn index_estimate(&self, lid: u32, kid: u32, value: &Value) -> Option<RowEstimate> {
96        let rows = self.graph.pattern_equality_rows_by_id(lid, kid, value)?;
97        Some(RowEstimate {
98            rows,
99            provenance: Provenance::UpperBound,
100        })
101    }
102
103    /// The key's sketches: a heavy value answers with its own count and any
104    /// other with the admitted values spread over the distinct count. A
105    /// value the type gate declines (a null, a NaN, long text, a list) is
106    /// unmeasured: the sketches never saw such a value.
107    fn sketch_estimate(&self, lid: u32, kid: u32, value: &Value) -> Option<RowEstimate> {
108        if !key_value_admitted(value) {
109            return None;
110        }
111        let stats = self.graph.key_stats(lid, kid)?;
112        let rows = stats.equality_rows(
113            key_heavy_count(&stats, value),
114            self.graph.label_count_by_id(lid),
115        );
116        Some(RowEstimate {
117            rows,
118            provenance: stats.provenance,
119        })
120    }
121
122    /// The one by-name read of a (label, property) pair: the pair as text
123    /// for the name-keyed store path, or `None` for an `Absent` label (a
124    /// plan-time fact: the store never interned it) before any store read.
125    /// The caller picks what an absent label means for its figure.
126    fn with_label_property<R>(
127        &self,
128        (label, label_token): &NamedToken,
129        property: &NamedToken,
130        read: impl FnOnce(&str, &str) -> R,
131    ) -> Option<R> {
132        if *label_token == Token::Absent {
133            return None;
134        }
135        Some(label.with_str(|label_text| {
136            property
137                .0
138                .with_str(|property_text| read(label_text, property_text))
139        }))
140    }
141
142    /// The interned ids of `rel_types`; a name the store never interned
143    /// selects nothing, so it drops out (the moments' "selects nothing"
144    /// contract, not a fabricated id).
145    fn type_ids(&self, rel_types: &[NamedToken]) -> Vec<u32> {
146        rel_types
147            .iter()
148            .filter_map(|(name, token)| self.id_of(name, *token))
149            .collect()
150    }
151
152    /// The one per-label scaffold the degree figures share: resolve the
153    /// type names, price the type selection (`None` when no type is named:
154    /// every type) over each named label — a label the store never
155    /// interned selects nothing, so it prices as `T::default()` — or over
156    /// every label (`None` label id) when no label is named, and keep the
157    /// smallest per-label figure, the tighter bound on a node carrying all
158    /// the labels (the `degree_tail` min discipline).
159    fn min_over_labels<T: Default>(
160        &self,
161        labels: &[NamedToken],
162        rel_types: &[NamedToken],
163        price: impl Fn(Option<u32>, Option<&[u32]>) -> T,
164        size: impl Fn(&T) -> u128,
165    ) -> Option<T> {
166        let type_ids = self.type_ids(rel_types);
167        let types = (!rel_types.is_empty()).then_some(type_ids.as_slice());
168        if labels.is_empty() {
169            return Some(price(None, types));
170        }
171        labels
172            .iter()
173            .map(|(name, token)| {
174                self.id_of(name, *token)
175                    .map_or_else(T::default, |id| price(Some(id), types))
176            })
177            .min_by_key(size)
178    }
179}
180
181impl relate_planner::PatternStats for GraphStats<'_> {
182    fn label_rows(&self, (name, token): &NamedToken) -> Option<u64> {
183        Some(
184            self.id_of(name, *token)
185                .map_or(0, |id| self.graph.label_count_by_id(id)),
186        )
187    }
188
189    fn equality_rows(
190        &self,
191        (label, label_token): &NamedToken,
192        property: &NamedToken,
193        value: &Expr,
194    ) -> Option<u64> {
195        let value = value.seek_value(self.params)?;
196        let lid = self.id_of(label, *label_token)?;
197        let kid = self.id_of(&property.0, property.1)?;
198        self.graph.pattern_equality_rows_by_id(lid, kid, &value)
199    }
200
201    /// ADR-0486: the range window's posting-length count, delegated to
202    /// [`Graph::pattern_range_rows`] — the same `range_seek_cardinality`
203    /// the executor's own seek cardinality reads, so the ladder's price
204    /// and the runtime funnel decline together. The bound resolves the
205    /// `equality_rows` way: literals and parameters only, `None` for
206    /// anything else (a temporal literal's function call included — the
207    /// funnel's `eval`-resolved bound is the runtime's, not the
208    /// plan-time estimate's).
209    fn range_rows(
210        &self,
211        label: &NamedToken,
212        property: &NamedToken,
213        op: BinaryOp,
214        bound: &Expr,
215    ) -> Option<u64> {
216        let bound = bound.seek_value(self.params)?;
217        // The one by-name fallback: the range seek's owned forms are
218        // names, so a resolved label still reads through the name-keyed
219        // store path; an `Absent` label declines before any store read.
220        self.with_label_property(label, property, |label_text, property_text| {
221            self.graph
222                .pattern_range_rows(label_text, property_text, op, &bound)
223        })
224        .flatten()
225    }
226
227    /// LABS-643: the count is always measurable — the TEXT index's exact
228    /// answer, or without one the sampled estimate
229    /// ([`Graph::pattern_contains_rows`]) — so only a non-string needle
230    /// stays unmeasured (`None`, the ladder's fallback). The provenance
231    /// stays typed in [`ContainsCount`]; the planner compounds the
232    /// sampled form's scan floor on its one scale (ADR-0474). The sample
233    /// rides the name-keyed store path like `range_rows`; an `Absent`
234    /// label is the measurable zero the by-name path answers for a label
235    /// never interned.
236    fn contains_rows(
237        &self,
238        label: &NamedToken,
239        property: &NamedToken,
240        needle: &Expr,
241    ) -> Option<ContainsCount> {
242        let needle = needle.seek_value(self.params)?;
243        let Value::String(needle) = needle else {
244            return None;
245        };
246        Some(
247            self.with_label_property(label, property, |label_text, property_text| {
248                self.graph
249                    .pattern_contains_rows(label_text, property_text, &needle)
250            })
251            .unwrap_or(ContainsCount::SampleScan { rows: 0, scan: 0 }),
252        )
253    }
254
255    /// The per-key statistics of the `(label, property)` pair, shared with
256    /// the graph's published entry; `None` while the label's statistics are
257    /// unbuilt (a consult records the build request, the pump serves it).
258    fn key_stats(&self, label: &NamedToken, property: &NamedToken) -> Option<Arc<KeyStats>> {
259        let (lid, kid) = self.pair_ids(label, property)?;
260        self.graph.key_stats(lid, kid)
261    }
262
263    /// An equality's row estimate with provenance, resolved the
264    /// `equality_rows` way (literals and parameters only). The sources
265    /// are ordered here and nowhere else: a declared index's postings
266    /// first, then the key's sketches.
267    fn equality_estimate(
268        &self,
269        label: &NamedToken,
270        property: &NamedToken,
271        value: &Expr,
272    ) -> Option<RowEstimate> {
273        let value = value.seek_value(self.params)?;
274        let (lid, kid) = self.pair_ids(label, property)?;
275        self.index_estimate(lid, kid, &value)
276            .or_else(|| self.sketch_estimate(lid, kid, &value))
277    }
278
279    fn rel_type_rows(&self, (name, token): &NamedToken) -> Option<u64> {
280        Some(
281            self.id_of(name, *token)
282                .map_or(0, |id| self.graph.pattern_rel_type_rows_by_id(id)),
283        )
284    }
285
286    /// LABS-351: the live graph's histogram tail (the executor keeps the
287    /// real one; the null stats default None).
288    fn degree_tail(&self, label: &NamedToken, rel_type: &NamedToken) -> Option<u64> {
289        let label_id = self.id_of(&label.0, label.1)?;
290        let type_id = self.id_of(&rel_type.0, rel_type.1)?;
291        self.graph.pattern_degree_tail_by_id(label_id, type_id)
292    }
293
294    /// LABS-991: the live histograms' any-label tail.
295    fn any_degree_tail(&self, rel_type: Option<&SmallName>) -> Option<u64> {
296        match rel_type {
297            Some(rel_type) => rel_type.with_str(|text| self.graph.pattern_type_degree_tail(text)),
298            None => self.graph.pattern_any_degree_tail(),
299        }
300    }
301
302    /// The live histograms' out-degree moments, bounded per label by
303    /// [`GraphStats::min_over_labels`].
304    fn degree_moments(
305        &self,
306        labels: &[NamedToken],
307        rel_types: &[NamedToken],
308    ) -> Option<DegreeMoments> {
309        self.min_over_labels(
310            labels,
311            rel_types,
312            |label_id, types| self.graph.pattern_degree_moments(label_id, types),
313            |moments| moments.sum,
314        )
315    }
316
317    /// The live pair counts' in-degree sum, bounded the same way as
318    /// [`PatternStats::degree_moments`]: the smallest per-label sum.
319    fn in_degree_sum(&self, labels: &[NamedToken], rel_types: &[NamedToken]) -> Option<u128> {
320        self.min_over_labels(
321            labels,
322            rel_types,
323            |label_id, types| self.graph.pattern_in_degree_sum(label_id, types),
324            |sum| *sum,
325        )
326    }
327}