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