Skip to main content

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