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