relate_planner/stats/mod.rs
1//! Cardinality hints for MATCH pattern ordering.
2//!
3//! The planner does not own the graph. Callers that can see label sizes,
4//! index hit counts, and relationship-type counts pass them in. A missing
5//! count (`None`) makes ordering fall back to the fixed rank of that
6//! endpoint. The [`PatternStats`] trait and its stub live here; the
7//! per-statement consult memo (ADR-0508) wrapping every implementor lives
8//! in [`memo`].
9
10use std::sync::Arc;
11
12use relate_ir::{BinaryOp, Expr};
13use relate_names::{NamedToken, SmallName};
14
15mod key_stats;
16
17pub use key_stats::{HeavyValue, KeyStats, Provenance, RowEstimate};
18
19/// Provenance of a plan-time `CONTAINS` candidate count (LABS-643): the
20/// TEXT index stays the one exact measurement, and without one the count
21/// comes from a bounded sample scan of the label's nodes — exact when the
22/// label fits inside the sampler's bound, an extrapolation beyond it. The
23/// variant, never a bare number, says which: no consumer can mistake the
24/// extrapolation for the measurement, and the sampled form carries the
25/// whole-label scan rows the unseekable filter still pays — the floor the
26/// compound start estimate (ADR-0474) maxes with the
27/// sampled output.
28///
29/// The sampler lives in the executor; the type lives here because the
30/// [`PatternStats::contains_rows`] contract is the one place both the
31/// planner's pattern ordering and the executor's start selection consume
32/// it, and the executor re-exports it so its own construction sites and
33/// tests keep one canonical path.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum ContainsCount {
36 /// Exact hit count a TEXT index on `(label, property)` answered.
37 TextIndex(u64),
38 /// A bounded sample scan's estimate: `rows` is the output estimate —
39 /// the exact count when the label's index bucket holds at most the
40 /// sample bound, otherwise `matches * bucket_rows / scanned`, floored
41 /// at a divisor of the bucket — and `scan` is the bucket's whole row
42 /// count, the label scan the unindexed filter pays before any match.
43 SampleScan { rows: u64, scan: u64 },
44}
45
46impl ContainsCount {
47 /// The row count both provenances carry on the planner's one scale.
48 pub fn rows(self) -> u64 {
49 match self {
50 ContainsCount::TextIndex(rows) | ContainsCount::SampleScan { rows, .. } => rows,
51 }
52 }
53}
54
55/// The first two moments of an out-degree distribution — what a cost gate
56/// needs to price a chain of hops: the mean fanout is `sum / nodes` and
57/// the size-biased (excess) degree a trail meets after its first hop is
58/// `sum_sq / sum - 1`. Estimates on the histogram's log2-bucket scale
59/// (each bucket read at the uniform mean of its degree range), summed
60/// over the selected labels and rel types; a node's degrees on several
61/// selected types are crossed (independently) in `sum_sq`, so it stands
62/// for the node's total degree.
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
64pub struct DegreeMoments {
65 /// Estimated sum of out-degrees (the relationship count the selected
66 /// nodes start).
67 pub sum: u128,
68 /// Estimated sum of squared out-degrees.
69 pub sum_sq: u128,
70}
71
72/// Live or stubbed counts used to estimate how many rows a pattern endpoint
73/// produces. Every method returns `None` when that signal is unavailable,
74/// which is not the same as zero rows. Labels and relationship types
75/// arrive as a name beside its planning-time [`relate_names::Token`]
76/// (ADR-0541): an implementor reads the id when planning resolved one and
77/// falls back to the name only for an unresolved token.
78pub trait PatternStats {
79 /// Nodes carrying `label`.
80 fn label_rows(&self, label: &NamedToken) -> Option<u64>;
81
82 /// Hits of an equality seek on a RANGE index for `(label, property)`.
83 /// `value` is the raw predicate expression. Implementors resolve
84 /// literals and parameters with [`Expr::seek_value`] and return `None`
85 /// for anything else. `None` also means no RANGE index, not zero hits.
86 fn equality_rows(&self, label: &NamedToken, property: &NamedToken, value: &Expr)
87 -> Option<u64>;
88
89 /// Hits of a comparison predicate (`<`, `<=`, `>`, `>=`) on a RANGE
90 /// index for `(label, property)` — the range window (ADR-0486). The
91 /// four comparison ops only: `=` stays [`PatternStats::equality_rows`]'s
92 /// domain, and `IN` and `STARTS WITH` are deferred. `bound` is the raw
93 /// predicate expression; implementors resolve literals and parameters
94 /// with [`Expr::seek_value`] and return `None` for anything else.
95 /// `None` also means no RANGE index on the pair, no order key on the
96 /// bound, or unbounded temporal postings — the executor seek's own
97 /// decline conditions, spelled once by the index layer — never zero
98 /// hits.
99 fn range_rows(
100 &self,
101 label: &NamedToken,
102 property: &NamedToken,
103 op: BinaryOp,
104 bound: &Expr,
105 ) -> Option<u64> {
106 let _ = (label, property, op, bound);
107 None
108 }
109
110 /// Candidates of a `CONTAINS` filter on `(label, property)`, with the
111 /// provenance that says how the count was measured (LABS-643): the
112 /// exact hits a TEXT index answered, or — without one — the sampled
113 /// estimate carrying the whole-label scan rows the unseekable filter
114 /// still pays. `needle` is the raw predicate expression. Implementors
115 /// resolve literals and parameters with [`Expr::seek_value`] and
116 /// return `None` for anything else. `None` means the count is
117 /// unmeasurable (a non-string needle), not zero candidates.
118 fn contains_rows(
119 &self,
120 label: &NamedToken,
121 property: &NamedToken,
122 needle: &Expr,
123 ) -> Option<ContainsCount>;
124
125 /// Relationships of `rel_type`.
126 fn rel_type_rows(&self, rel_type: &NamedToken) -> Option<u64>;
127
128 /// The value statistics of `property` over `label`'s nodes (the
129 /// per-key statistics ADR): count, distinct, minimum, maximum, sum and
130 /// the heavy values, with their [`Provenance`]. `None` means
131 /// unmeasured: the label's statistics are not built yet, the key was
132 /// declined or evicted, or the pair is unresolved — never zero rows.
133 fn key_stats(&self, _label: &NamedToken, _property: &NamedToken) -> Option<Arc<KeyStats>> {
134 None
135 }
136
137 /// Rows an equality of `property` on `label` against `value` selects,
138 /// from the key's statistics (or an index or built pair that answers
139 /// exactly), with the provenance of the answer. `value` is the raw
140 /// predicate expression; implementors resolve literals and parameters
141 /// with [`Expr::seek_value`] and return `None` for anything else.
142 /// Unlike [`PatternStats::equality_rows`], which needs an index, this
143 /// prices an unindexed key too; `None` means unmeasured.
144 fn equality_estimate(
145 &self,
146 _label: &NamedToken,
147 _property: &NamedToken,
148 _value: &Expr,
149 ) -> Option<RowEstimate> {
150 None
151 }
152
153 /// LABS-351: the tail of a (label, rel-type) out-degree distribution —
154 /// the conservative floor of the highest observed degree (a log2-bucket
155 /// histogram's top bucket). `None` when the stats keep no histogram.
156 /// Consumed by `apply_degree` (LABS-426, the mean-to-tail flip): an
157 /// outgoing hop's fanout rides the tail when the histogram has one,
158 /// the mean otherwise — the plan-choice consequence of the flip is
159 /// the measured part of that change.
160 fn degree_tail(&self, label: &NamedToken, rel_type: &NamedToken) -> Option<u64> {
161 let _ = (label, rel_type);
162 None
163 }
164
165 /// LABS-991: the out-degree tail over every labeled node — the
166 /// log2-bucket floor of the highest observed degree of `rel_type`
167 /// (for `None`, of any relationship: the per-type tails summed, the
168 /// same floor scale, not a strict upper bound). The estimate a hop leaving
169 /// an unlabeled node, or crossing an untyped rel, rides when
170 /// [`PatternStats::degree_tail`] has no `(label, type)` pair to name.
171 /// Nodes carrying no label sit in no histogram and are not covered.
172 /// `None` when the stats keep no histogram.
173 fn any_degree_tail(&self, rel_type: Option<&SmallName>) -> Option<u64> {
174 let _ = rel_type;
175 None
176 }
177
178 /// The out-degree moments ([`DegreeMoments`]) of nodes carrying the
179 /// labels in `labels` (empty: every labeled node; several: a bound,
180 /// the smallest per-label moments) over the rel types
181 /// `rel_types` (empty: every type). A name the store never interned
182 /// selects nothing, so its moments are zero. `None` when the stats
183 /// keep no histogram.
184 fn degree_moments(
185 &self,
186 labels: &[NamedToken],
187 rel_types: &[NamedToken],
188 ) -> Option<DegreeMoments> {
189 let _ = (labels, rel_types);
190 None
191 }
192
193 /// The estimated sum of in-degrees — the relationships arriving at
194 /// nodes carrying the labels in `labels` (empty: every labeled node;
195 /// several: a bound, the smallest per-label sum) over the rel types
196 /// `rel_types` (empty: every type). The incoming side of
197 /// [`PatternStats::degree_moments`]' `sum`, which an undirected or
198 /// incoming first hop needs: a label whose rels all point at it has
199 /// no out-degree. `None` when the stats keep no pair counts.
200 fn in_degree_sum(&self, labels: &[NamedToken], rel_types: &[NamedToken]) -> Option<u128> {
201 let _ = (labels, rel_types);
202 None
203 }
204}
205
206/// No counts. Ordering uses the bound / equality / label / bare ranks.
207#[derive(Debug, Clone, Copy, Default)]
208pub struct NoPatternStats;
209
210impl PatternStats for NoPatternStats {
211 fn label_rows(&self, _label: &NamedToken) -> Option<u64> {
212 None
213 }
214
215 fn equality_rows(
216 &self,
217 _label: &NamedToken,
218 _property: &NamedToken,
219 _value: &Expr,
220 ) -> Option<u64> {
221 None
222 }
223
224 fn contains_rows(
225 &self,
226 _label: &NamedToken,
227 _property: &NamedToken,
228 _needle: &Expr,
229 ) -> Option<ContainsCount> {
230 None
231 }
232
233 fn rel_type_rows(&self, _rel_type: &NamedToken) -> Option<u64> {
234 None
235 }
236}
237
238/// ADR-0508's per-statement memo over the value-keyed consults — one
239/// [`PatternStats`] wrapper, built once by [`crate::plan_with_stats`] for a
240/// whole plan call, answering repeats from a table of the consults already
241/// made.
242mod memo;
243
244pub(crate) use memo::StatsMemo;
245
246#[cfg(test)]
247mod tests;