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;
7
8use relate_core::Value;
9use relate_ir::{BinaryOp, Expr, NodePattern, RelPattern};
10use relate_names::{NamedToken, SmallName, Token, TokenResolver};
11use relate_planner::{
12    endpoint_estimate, seed_on_rel_start, walk_cost, Bound, ContainsCount, DegreeMoments,
13};
14
15use crate::graph::Graph;
16
17/// Construction goes through [`GraphStats::new`] (the ADR-0218 one-
18/// construction idiom the sibling plan-time stats impls use), so an
19/// inline build cannot drift from it.
20pub struct GraphStats<'a> {
21    graph: &'a Graph,
22    params: &'a BTreeMap<String, Value>,
23}
24
25impl<'a> GraphStats<'a> {
26    /// The one construction: the connection's graph and the statement's
27    /// parameters.
28    pub fn new(graph: &'a Graph, params: &'a BTreeMap<String, Value>) -> GraphStats<'a> {
29        GraphStats { graph, params }
30    }
31
32    /// One element's compound start estimate (LABS-351): the planner's
33    /// canonical endpoint ladder over this graph's stats, mapped onto
34    /// the one u64 scale the executor compares. The rank sentinels
35    /// share the measured scale (`direction_cost` compares them
36    /// directly); the bare rank — an unlabeled element, an all-node
37    /// scan — stays the whole-graph sentinel. A sampled `CONTAINS` seed
38    /// compounds (ADR-0474): its first hop is the degree-scaled output
39    /// floored at the whole-label scan the unseekable filter pays, the
40    /// same arithmetic the planner's `direction_cost` runs, so the
41    /// per-row start selection and the plan-time orientation agree on
42    /// the anchor (GBL SF0.1 q8: the Forum side's 13,750-row scan floor
43    /// ties Person's degree-scaled walk and the tie-break's seed
44    /// comparison — 1,528 Person rows against the floored 13,750 —
45    /// flips the anchor to Person).
46    pub(crate) fn estimate<'c>(
47        &self,
48        np: &'c NodePattern,
49        bound: Bound<'_>,
50        where_conjuncts: impl Iterator<Item = &'c Expr> + Clone,
51        first_hop: Option<&RelPattern>,
52        reversed: bool,
53    ) -> u64 {
54        let estimate = endpoint_estimate(np, bound, where_conjuncts, self);
55        // Two local facts: the orientation flag is the caller's derived
56        // one (the forward walker passes false, the backward walker's
57        // k > 0 pivots pass true — LABS-426), and the walk prices this
58        // start's first hop only. The model itself — which estimate kind
59        // gets which walk, and the seed-side derivation — is
60        // [`walk_cost`]'s and [`seed_on_rel_start`]'s to state.
61        let rows = walk_cost(
62            estimate,
63            first_hop
64                .into_iter()
65                .map(|rel| (np, rel, seed_on_rel_start(rel, reversed))),
66            self,
67        );
68        rows.min(u64::MAX as u128) as u64
69    }
70}
71
72impl GraphStats<'_> {
73    /// The store id of a name beside its planning token (ADR-0541): `Id`
74    /// answers it, `Absent` answers `None` without a store read, and only
75    /// `Unresolved` interns by name. `None` means no stored entity
76    /// carries the name.
77    fn id_of(&self, name: &SmallName, token: Token) -> Option<u32> {
78        token.id_or_else(|| name.with_str(|text| self.graph.resolve(text).id()))
79    }
80
81    /// The interned ids of `rel_types`; a name the store never interned
82    /// selects nothing, so it drops out (the moments' "selects nothing"
83    /// contract, not a fabricated id).
84    fn type_ids(&self, rel_types: &[NamedToken]) -> Vec<u32> {
85        rel_types
86            .iter()
87            .filter_map(|(name, token)| self.id_of(name, *token))
88            .collect()
89    }
90
91    /// The one per-label scaffold the degree figures share: resolve the
92    /// type names, price the type selection (`None` when no type is named:
93    /// every type) over each named label — a label the store never
94    /// interned selects nothing, so it prices as `T::default()` — or over
95    /// every label (`None` label id) when no label is named, and keep the
96    /// smallest per-label figure, the tighter bound on a node carrying all
97    /// the labels (the `degree_tail` min discipline).
98    fn min_over_labels<T: Default>(
99        &self,
100        labels: &[NamedToken],
101        rel_types: &[NamedToken],
102        price: impl Fn(Option<u32>, Option<&[u32]>) -> T,
103        size: impl Fn(&T) -> u128,
104    ) -> Option<T> {
105        let type_ids = self.type_ids(rel_types);
106        let types = (!rel_types.is_empty()).then_some(type_ids.as_slice());
107        if labels.is_empty() {
108            return Some(price(None, types));
109        }
110        labels
111            .iter()
112            .map(|(name, token)| {
113                self.id_of(name, *token)
114                    .map_or_else(T::default, |id| price(Some(id), types))
115            })
116            .min_by_key(size)
117    }
118}
119
120impl relate_planner::PatternStats for GraphStats<'_> {
121    fn label_rows(&self, (name, token): &NamedToken) -> Option<u64> {
122        Some(
123            self.id_of(name, *token)
124                .map_or(0, |id| self.graph.label_count_by_id(id)),
125        )
126    }
127
128    fn equality_rows(
129        &self,
130        (label, label_token): &NamedToken,
131        property: &NamedToken,
132        value: &Expr,
133    ) -> Option<u64> {
134        let value = value.seek_value(self.params)?;
135        let lid = self.id_of(label, *label_token)?;
136        let kid = self.id_of(&property.0, property.1)?;
137        self.graph.pattern_equality_rows_by_id(lid, kid, &value)
138    }
139
140    /// ADR-0486: the range window's posting-length count, delegated to
141    /// [`Graph::pattern_range_rows`] — the same `range_seek_cardinality`
142    /// the executor's own seek cardinality reads, so the ladder's price
143    /// and the runtime funnel decline together. The bound resolves the
144    /// `equality_rows` way: literals and parameters only, `None` for
145    /// anything else (a temporal literal's function call included — the
146    /// funnel's `eval`-resolved bound is the runtime's, not the
147    /// plan-time estimate's).
148    fn range_rows(
149        &self,
150        (label, label_token): &NamedToken,
151        property: &NamedToken,
152        op: BinaryOp,
153        bound: &Expr,
154    ) -> Option<u64> {
155        let bound = bound.seek_value(self.params)?;
156        // The one by-name fallback: the range seek's owned forms are
157        // names, so a resolved label still reads through the name-keyed
158        // store path; an `Absent` label declines before any store read.
159        if *label_token == Token::Absent {
160            return None;
161        }
162        label.with_str(|label_text| {
163            property.0.with_str(|property_text| {
164                self.graph
165                    .pattern_range_rows(label_text, property_text, op, &bound)
166            })
167        })
168    }
169
170    /// LABS-643: the count is always measurable — the TEXT index's exact
171    /// answer, or without one the sampled estimate
172    /// ([`Graph::pattern_contains_rows`]) — so only a non-string needle
173    /// stays unmeasured (`None`, the ladder's fallback). The provenance
174    /// stays typed in [`ContainsCount`]; the planner compounds the
175    /// sampled form's scan floor on its one scale (ADR-0474). The sample
176    /// rides the name-keyed store path like `range_rows`; an `Absent`
177    /// label is the measurable zero the by-name path answers for a label
178    /// never interned.
179    fn contains_rows(
180        &self,
181        (label, label_token): &NamedToken,
182        property: &NamedToken,
183        needle: &Expr,
184    ) -> Option<ContainsCount> {
185        let needle = needle.seek_value(self.params)?;
186        let Value::String(needle) = needle else {
187            return None;
188        };
189        if *label_token == Token::Absent {
190            return Some(ContainsCount::SampleScan { rows: 0, scan: 0 });
191        }
192        label.with_str(|label_text| {
193            property.0.with_str(|property_text| {
194                Some(
195                    self.graph
196                        .pattern_contains_rows(label_text, property_text, &needle),
197                )
198            })
199        })
200    }
201
202    fn rel_type_rows(&self, (name, token): &NamedToken) -> Option<u64> {
203        Some(
204            self.id_of(name, *token)
205                .map_or(0, |id| self.graph.pattern_rel_type_rows_by_id(id)),
206        )
207    }
208
209    /// LABS-351: the live graph's histogram tail (the executor keeps the
210    /// real one; the null stats default None).
211    fn degree_tail(&self, label: &NamedToken, rel_type: &NamedToken) -> Option<u64> {
212        let label_id = self.id_of(&label.0, label.1)?;
213        let type_id = self.id_of(&rel_type.0, rel_type.1)?;
214        self.graph.pattern_degree_tail_by_id(label_id, type_id)
215    }
216
217    /// LABS-991: the live histograms' any-label tail.
218    fn any_degree_tail(&self, rel_type: Option<&SmallName>) -> Option<u64> {
219        match rel_type {
220            Some(rel_type) => rel_type.with_str(|text| self.graph.pattern_type_degree_tail(text)),
221            None => self.graph.pattern_any_degree_tail(),
222        }
223    }
224
225    /// The live histograms' out-degree moments, bounded per label by
226    /// [`GraphStats::min_over_labels`].
227    fn degree_moments(
228        &self,
229        labels: &[NamedToken],
230        rel_types: &[NamedToken],
231    ) -> Option<DegreeMoments> {
232        self.min_over_labels(
233            labels,
234            rel_types,
235            |label_id, types| self.graph.pattern_degree_moments(label_id, types),
236            |moments| moments.sum,
237        )
238    }
239
240    /// The live pair counts' in-degree sum, bounded the same way as
241    /// [`PatternStats::degree_moments`]: the smallest per-label sum.
242    fn in_degree_sum(&self, labels: &[NamedToken], rel_types: &[NamedToken]) -> Option<u128> {
243        self.min_over_labels(
244            labels,
245            rel_types,
246            |label_id, types| self.graph.pattern_in_degree_sum(label_id, types),
247            |sum| *sum,
248        )
249    }
250}