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/// Live or stubbed counts used to estimate how many rows a pattern endpoint
50/// produces. Every method returns `None` when that signal is unavailable,
51/// which is not the same as zero rows. Labels and relationship types
52/// arrive as a name beside its planning-time [`relate_names::Token`]
53/// (ADR-0541): an implementor reads the id when planning resolved one and
54/// falls back to the name only for an unresolved token.
55pub trait PatternStats {
56    /// Nodes carrying `label`.
57    fn label_rows(&self, label: &NamedToken) -> Option<u64>;
58
59    /// Hits of an equality seek on a RANGE index for `(label, property)`.
60    /// `value` is the raw predicate expression. Implementors resolve
61    /// literals and parameters with [`Expr::seek_value`] and return `None`
62    /// for anything else. `None` also means no RANGE index, not zero hits.
63    fn equality_rows(&self, label: &NamedToken, property: &NamedToken, value: &Expr)
64        -> Option<u64>;
65
66    /// Hits of a comparison predicate (`<`, `<=`, `>`, `>=`) on a RANGE
67    /// index for `(label, property)` — the range window (ADR-0486). The
68    /// four comparison ops only: `=` stays [`PatternStats::equality_rows`]'s
69    /// domain, and `IN` and `STARTS WITH` are deferred. `bound` is the raw
70    /// predicate expression; implementors resolve literals and parameters
71    /// with [`Expr::seek_value`] and return `None` for anything else.
72    /// `None` also means no RANGE index on the pair, no order key on the
73    /// bound, or unbounded temporal postings — the executor seek's own
74    /// decline conditions, spelled once by the index layer — never zero
75    /// hits.
76    fn range_rows(
77        &self,
78        label: &NamedToken,
79        property: &NamedToken,
80        op: BinaryOp,
81        bound: &Expr,
82    ) -> Option<u64> {
83        let _ = (label, property, op, bound);
84        None
85    }
86
87    /// Candidates of a `CONTAINS` filter on `(label, property)`, with the
88    /// provenance that says how the count was measured (LABS-643): the
89    /// exact hits a TEXT index answered, or — without one — the sampled
90    /// estimate carrying the whole-label scan rows the unseekable filter
91    /// still pays. `needle` is the raw predicate expression. Implementors
92    /// resolve literals and parameters with [`Expr::seek_value`] and
93    /// return `None` for anything else. `None` means the count is
94    /// unmeasurable (a non-string needle), not zero candidates.
95    fn contains_rows(
96        &self,
97        label: &NamedToken,
98        property: &NamedToken,
99        needle: &Expr,
100    ) -> Option<ContainsCount>;
101
102    /// Relationships of `rel_type`.
103    fn rel_type_rows(&self, rel_type: &NamedToken) -> Option<u64>;
104
105    /// LABS-351: the tail of a (label, rel-type) out-degree distribution —
106    /// the conservative floor of the highest observed degree (a log2-bucket
107    /// histogram's top bucket). `None` when the stats keep no histogram.
108    /// Consumed by `apply_degree` (LABS-426, the mean-to-tail flip): an
109    /// outgoing hop's fanout rides the tail when the histogram has one,
110    /// the mean otherwise — the plan-choice consequence of the flip is
111    /// the measured part of that change.
112    fn degree_tail(&self, label: &NamedToken, rel_type: &NamedToken) -> Option<u64> {
113        let _ = (label, rel_type);
114        None
115    }
116
117    /// LABS-991: the out-degree tail over every labeled node — the
118    /// log2-bucket floor of the highest observed degree of `rel_type`
119    /// (for `None`, of any relationship: the per-type tails summed, the
120    /// same floor scale, not a strict upper bound). The estimate a hop leaving
121    /// an unlabeled node, or crossing an untyped rel, rides when
122    /// [`PatternStats::degree_tail`] has no `(label, type)` pair to name.
123    /// Nodes carrying no label sit in no histogram and are not covered.
124    /// `None` when the stats keep no histogram.
125    fn any_degree_tail(&self, rel_type: Option<&SmallName>) -> Option<u64> {
126        let _ = rel_type;
127        None
128    }
129}
130
131/// No counts. Ordering uses the bound / equality / label / bare ranks.
132#[derive(Debug, Clone, Copy, Default)]
133pub struct NoPatternStats;
134
135impl PatternStats for NoPatternStats {
136    fn label_rows(&self, _label: &NamedToken) -> Option<u64> {
137        None
138    }
139
140    fn equality_rows(
141        &self,
142        _label: &NamedToken,
143        _property: &NamedToken,
144        _value: &Expr,
145    ) -> Option<u64> {
146        None
147    }
148
149    fn contains_rows(
150        &self,
151        _label: &NamedToken,
152        _property: &NamedToken,
153        _needle: &Expr,
154    ) -> Option<ContainsCount> {
155        None
156    }
157
158    fn rel_type_rows(&self, _rel_type: &NamedToken) -> Option<u64> {
159        None
160    }
161}
162
163/// ADR-0508's per-statement memo over the value-keyed consults — one
164/// [`PatternStats`] wrapper, built once by [`crate::plan_with_stats`] for a
165/// whole plan call, answering repeats from a table of the consults already
166/// made.
167mod memo;
168
169pub(crate) use memo::StatsMemo;
170
171#[cfg(test)]
172mod tests;