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
92impl relate_planner::PatternStats for GraphStats<'_> {
93    fn label_rows(&self, (name, token): &NamedToken) -> Option<u64> {
94        Some(
95            self.id_of(name, *token)
96                .map_or(0, |id| self.graph.label_count_by_id(id)),
97        )
98    }
99
100    fn equality_rows(
101        &self,
102        (label, label_token): &NamedToken,
103        property: &NamedToken,
104        value: &Expr,
105    ) -> Option<u64> {
106        let value = value.seek_value(self.params)?;
107        let lid = self.id_of(label, *label_token)?;
108        let kid = self.id_of(&property.0, property.1)?;
109        self.graph.pattern_equality_rows_by_id(lid, kid, &value)
110    }
111
112    /// ADR-0486: the range window's posting-length count, delegated to
113    /// [`Graph::pattern_range_rows`] — the same `range_seek_cardinality`
114    /// the executor's own seek cardinality reads, so the ladder's price
115    /// and the runtime funnel decline together. The bound resolves the
116    /// `equality_rows` way: literals and parameters only, `None` for
117    /// anything else (a temporal literal's function call included — the
118    /// funnel's `eval`-resolved bound is the runtime's, not the
119    /// plan-time estimate's).
120    fn range_rows(
121        &self,
122        (label, label_token): &NamedToken,
123        property: &NamedToken,
124        op: BinaryOp,
125        bound: &Expr,
126    ) -> Option<u64> {
127        let bound = bound.seek_value(self.params)?;
128        // The one by-name fallback: the range seek's owned forms are
129        // names, so a resolved label still reads through the name-keyed
130        // store path; an `Absent` label declines before any store read.
131        if *label_token == Token::Absent {
132            return None;
133        }
134        label.with_str(|label_text| {
135            property.0.with_str(|property_text| {
136                self.graph
137                    .pattern_range_rows(label_text, property_text, op, &bound)
138            })
139        })
140    }
141
142    /// LABS-643: the count is always measurable — the TEXT index's exact
143    /// answer, or without one the sampled estimate
144    /// ([`Graph::pattern_contains_rows`]) — so only a non-string needle
145    /// stays unmeasured (`None`, the ladder's fallback). The provenance
146    /// stays typed in [`ContainsCount`]; the planner compounds the
147    /// sampled form's scan floor on its one scale (ADR-0474). The sample
148    /// rides the name-keyed store path like `range_rows`; an `Absent`
149    /// label is the measurable zero the by-name path answers for a label
150    /// never interned.
151    fn contains_rows(
152        &self,
153        (label, label_token): &NamedToken,
154        property: &NamedToken,
155        needle: &Expr,
156    ) -> Option<ContainsCount> {
157        let needle = needle.seek_value(self.params)?;
158        let Value::String(needle) = needle else {
159            return None;
160        };
161        if *label_token == Token::Absent {
162            return Some(ContainsCount::SampleScan { rows: 0, scan: 0 });
163        }
164        label.with_str(|label_text| {
165            property.0.with_str(|property_text| {
166                Some(
167                    self.graph
168                        .pattern_contains_rows(label_text, property_text, &needle),
169                )
170            })
171        })
172    }
173
174    fn rel_type_rows(&self, (name, token): &NamedToken) -> Option<u64> {
175        Some(
176            self.id_of(name, *token)
177                .map_or(0, |id| self.graph.pattern_rel_type_rows_by_id(id)),
178        )
179    }
180
181    /// LABS-351: the live graph's histogram tail (the executor keeps the
182    /// real one; the null stats default None).
183    fn degree_tail(&self, label: &NamedToken, rel_type: &NamedToken) -> Option<u64> {
184        let label_id = self.id_of(&label.0, label.1)?;
185        let type_id = self.id_of(&rel_type.0, rel_type.1)?;
186        self.graph.pattern_degree_tail_by_id(label_id, type_id)
187    }
188
189    /// LABS-991: the live histograms' any-label tail.
190    fn any_degree_tail(&self, rel_type: Option<&SmallName>) -> Option<u64> {
191        match rel_type {
192            Some(rel_type) => {
193                rel_type.with_str(|text| self.graph.pattern_any_degree_tail(Some(text)))
194            }
195            None => self.graph.pattern_any_degree_tail(None),
196        }
197    }
198
199    /// The live histograms' out-degree moments. Several labels name the
200    /// nodes carrying all of them, bounded by each label's own moments:
201    /// the smaller sum is the tighter bound (the `degree_tail` min
202    /// discipline). A name the store never interned selects nothing.
203    fn degree_moments(
204        &self,
205        labels: &[NamedToken],
206        rel_types: &[NamedToken],
207    ) -> Option<DegreeMoments> {
208        let type_ids = self.type_ids(rel_types);
209        let types = (!rel_types.is_empty()).then_some(type_ids.as_slice());
210        if labels.is_empty() {
211            return Some(self.graph.pattern_degree_moments(None, types));
212        }
213        labels
214            .iter()
215            .map(|(name, token)| {
216                self.id_of(name, *token)
217                    .map_or(DegreeMoments::default(), |id| {
218                        self.graph.pattern_degree_moments(Some(id), types)
219                    })
220            })
221            .min_by_key(|moments| moments.sum)
222    }
223
224    /// The live pair counts' in-degree sum, bounded the same way as
225    /// [`PatternStats::degree_moments`]: the smallest per-label sum.
226    fn in_degree_sum(&self, labels: &[NamedToken], rel_types: &[NamedToken]) -> Option<u128> {
227        let type_ids = self.type_ids(rel_types);
228        let types = (!rel_types.is_empty()).then_some(type_ids.as_slice());
229        if labels.is_empty() {
230            return Some(self.graph.pattern_in_degree_sum(None, types));
231        }
232        labels
233            .iter()
234            .map(|(name, token)| {
235                self.id_of(name, *token)
236                    .map_or(0, |id| self.graph.pattern_in_degree_sum(Some(id), types))
237            })
238            .min()
239    }
240}