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