Skip to main content

relate_planner/order/
estimate.rs

1//! The endpoint pricing ladder: one canonical estimate of the rows an
2//! element produces, from a bound variable down to the unmeasured rank
3//! sentinels, and the seek picks the plan tree narrates from the same
4//! derivation.
5
6use relate_ir::{orient, pattern_prop_key, var_prop_named, BinaryOp, Expr, NodePattern};
7use relate_names::{NamedToken, SmallName};
8
9use super::selectivity;
10use crate::stats::{ContainsCount, PatternStats, Provenance};
11
12/// Synthetic row counts for the rank fallback. A higher rank is cheaper,
13/// and a known row count below the label sentinel beats an unknown label.
14const RANK_EQ: u128 = 1 << 20;
15const RANK_LABEL: u128 = 1 << 48;
16pub(super) const RANK_BARE: u128 = 1 << 62;
17
18/// ADR-0493's small-window floor: a range window of at most this many
19/// ids always seeks — anchored point reads and small `IN` windows stay
20/// on the index regardless of tiny labels, where the absolute cost
21/// difference is noise.
22const RANGE_SEEK_WIN_FLOOR: u64 = 256;
23
24/// ADR-0493's range-seek crossover — the one policy both the ladder's
25/// range level (here) and the executor funnel's `Seek::Range` serve
26/// (pattern_walk/candidates) consult, so pricing and execution can never
27/// disagree. Measured on a 1.8M-relationship social-network graph: the
28/// seek's per-candidate cost
29/// (~1.36 µs, each candidate materializing a full node) is ~5.2× the
30/// label scan's per-node cost (~0.26 µs) — break-even ≈19%, the
31/// crossover sits at 1/4 with margin. `true` = the window still wins
32/// as an index seek; `false` = the label scan with the residual filter
33/// is cheaper. Revisit when the seek becomes id-only (LABS-853) — the
34/// fraction is expected to rise.
35pub(crate) fn range_seek_wins(window: u64, label_rows: u64) -> bool {
36    window <= RANGE_SEEK_WIN_FLOOR || window * 4 < label_rows
37}
38
39/// ADR-0493's crossover population — the scan a range seek replaces is
40/// the pattern's label conjunction, sized by its smallest label. The
41/// one fold both consumers ride (the ladder's `best_range` over the
42/// planner's stats, the executor funnel's `Seek::crossover_declines`
43/// over the graph's counts): `None` when the pattern names no label or
44/// any label is unmeasured (no measurement, no gate — ADR-0486's
45/// default). Allocation-free: the executor's cheapest-start loop runs
46/// it per (pattern, row) (LABS-351).
47pub fn crossover_scan_rows<L>(
48    labels: impl IntoIterator<Item = L>,
49    rows_of: impl Fn(&L) -> Option<u64>,
50) -> Option<u64> {
51    let mut scan_rows: Option<u64> = None;
52    for label in labels {
53        let rows = rows_of(&label)?;
54        scan_rows = Some(scan_rows.map_or(rows, |min| min.min(rows)));
55    }
56    scan_rows
57}
58
59/// ADR-0493's gate over a population: `true` when a measured scan
60/// population makes the window cheaper as the label scan — the one
61/// composition of [`crossover_scan_rows`] and [`range_seek_wins`] both
62/// consumers apply, so pricing and execution decline the same windows.
63pub fn range_seek_gated(window: u64, scan_rows: Option<u64>) -> bool {
64    scan_rows.is_some_and(|scan| !range_seek_wins(window, scan))
65}
66
67/// One canonical endpoint ladder (LABS-351): a bound variable is one
68/// row, then the best measured index signal (equality, the range window,
69/// CONTAINS, then label rows), then the unmeasured rank sentinels.
70/// Measured counts and rank sentinels share one ordered scale (the
71/// constants are ordered, `direction_cost` compares them directly), so
72/// both the planner's pattern ordering and the executor's start-element
73/// choice consume the same estimate. `pub` for the executor's
74/// `cheapest_start`.
75///
76/// A sampled `CONTAINS` measurement carries its own arm (the compound
77/// start estimate, ADR-0474): the seed's output rows and the whole-label
78/// scan the unseekable filter pays are two different costs — the scan is
79/// a one-time floor, the output scales with the hops — so the walk
80/// compounds them as `max(scan, output x degree)` instead of scaling the
81/// seed alone.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum Estimate {
84    Measured(u128),
85    /// A seed whose unseekable filter still pays the whole-label scan: `rows`
86    /// the estimated output, `scan` the label rows the filter reads, and
87    /// `basis` where `rows` came from — a sampled `CONTAINS` count, the
88    /// key statistics, or the default table. The walk compounds the two
89    /// costs as `max(scan, output x degree)` (ADR-0474).
90    Scanned {
91        rows: u128,
92        scan: u128,
93        basis: Basis,
94    },
95    Rank(u128),
96}
97
98/// Where an estimate's rows came from, ordered by trust: a larger variant
99/// is more trustworthy. The ordering gates strategies and breaks ties
100/// between orientations the cost model prices alike; it never overrides a
101/// strictly cheaper cost (a default can win an anchor it genuinely prices
102/// lower).
103#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
104pub enum Basis {
105    /// An unmeasured rank sentinel: no label count at all.
106    Rank,
107    /// The default selectivity table (ADR-0694).
108    Default,
109    /// A sampled count (a `CONTAINS` scan sample).
110    Sampled,
111    /// The per-key statistics, tagged with their own provenance (ADR-0696).
112    Statistic(Provenance),
113    /// A count read off an index or the label's own row count.
114    Measured,
115}
116
117impl Estimate {
118    /// The trust the estimate's rows carry.
119    pub fn basis(self) -> Basis {
120        match self {
121            Estimate::Measured(_) => Basis::Measured,
122            Estimate::Scanned { basis, .. } => basis,
123            Estimate::Rank(_) => Basis::Rank,
124        }
125    }
126}
127
128/// The where clause as its conjunct list — the ladder's CONTAINS level
129/// reads individual conjuncts, the executor passes its residual conjuncts
130/// in this shape natively, and the plan tree's seek narration (ADR-0486)
131/// reads the same view, so no consumer re-flattens the `AND` tree.
132pub fn where_conjuncts_of(where_clause: Option<&Expr>) -> Vec<&Expr> {
133    let mut conjuncts = Vec::new();
134    if let Some(expr) = where_clause {
135        each_conjunct(expr, &mut |expr| conjuncts.push(expr));
136    }
137    conjuncts
138}
139
140fn unmeasured_rows(node: &NodePattern) -> u128 {
141    let equality = matches!(&node.properties, Some(Expr::Map(pairs)) if !pairs.is_empty());
142    if equality {
143        RANK_EQ
144    } else if !node.labels.is_empty() {
145        RANK_LABEL
146    } else {
147        RANK_BARE
148    }
149}
150
151/// The bound check as a membership predicate, not a concrete collection:
152/// the executor's `cheapest_start` runs once per (pattern, row) and must
153/// not clone the row's keys into a `HashSet` per call (LABS-351, stellar
154/// F-3-1).
155pub type Bound<'a> = &'a dyn Fn(&str) -> bool;
156
157pub fn endpoint_estimate<'a>(
158    node: &'a NodePattern,
159    bound: Bound<'_>,
160    where_conjuncts: impl Iterator<Item = &'a Expr> + Clone,
161    stats: &dyn PatternStats,
162) -> Estimate {
163    if endpoint_bound(node, bound) {
164        return Estimate::Measured(1);
165    }
166    // The conjunct view feeds the three where-clause levels (the seek
167    // pick's window arm, CONTAINS, the default selectivity table); it is
168    // cloned for all but the last, never collected — this runs once per (pattern, row) in the
169    // executor's cheapest-start loop, which stays allocation-free
170    // (LABS-351, stellar F-3-1).
171    let measured = |hits: Option<u64>| hits.map(u128::from).map(Estimate::Measured);
172    // The equality-before-window ordering is `best_seek`'s, not this
173    // chain's (stellar round 2): the first measured level prices the
174    // one pick — the same derivation the plan tree's seek narration
175    // matches — then CONTAINS, then label rows.
176    measured(best_seek(node, where_conjuncts.clone(), stats).map(|pick| pick.rows))
177        .or_else(|| contains_hits(node, where_conjuncts.clone(), stats))
178        .or_else(|| label_rung(node, where_conjuncts, stats))
179        .unwrap_or_else(|| Estimate::Rank(unmeasured_rows(node)))
180}
181
182/// The tightest indexed equality on the folded property map (ADR-0024's
183/// fold — the degenerate tightest window on the same index, ADR-0486):
184/// the minimum `equality_rows` over the map's pairs and the node's
185/// labels, returned as the pick — the winning pair carrying the point
186/// read's [`BinaryOp::Eq`] — so `best_seek` consumes the same
187/// derivation the ladder prices, never a second spelling of the min
188/// policy. `None` when the stats cannot speak for any pair.
189fn best_equality<'a>(
190    node: &'a NodePattern,
191    where_conjuncts: impl IntoIterator<Item = &'a Expr>,
192    stats: &dyn PatternStats,
193) -> Option<SeekPick<'a>> {
194    // The argmin kept as references until the winner is known: only the
195    // winning pick's property is classified into an owned name — building
196    // a `SeekPick` (a property name clone) per (pair, label) candidate
197    // allocated for a minimum only one of them wins. Consult order and
198    // the first-wins tie-break are the collected form's.
199    let mut best: Option<(&SmallName, NamedToken, &Expr, u64)> = None;
200    let consider = |best: &mut Option<(&'a SmallName, NamedToken, &'a Expr, u64)>,
201                    key: NamedToken,
202                    value: &'a Expr| {
203        for named in &node.labels {
204            let Some(rows) = stats.equality_rows(named, &key, value) else {
205                continue;
206            };
207            if best
208                .as_ref()
209                .is_none_or(|(_, _, _, best_rows)| rows < *best_rows)
210            {
211                *best = Some((&named.0, key.clone(), value, rows));
212            }
213        }
214    };
215    if let Some(Expr::Map(pairs)) = node.properties.as_ref() {
216        for (key, value) in pairs {
217            // A value-map key enters the name domain here, beside the token
218            // planning resolved for it.
219            let key = pattern_prop_key(&node.prop_keys, key);
220            consider(&mut best, key, value);
221        }
222    }
223    // Only scan unfolded WHERE equalities when `node.properties` did not
224    // already yield an indexed equality (e.g. varlen/GPM patterns where
225    // `fold_where` leaves `WHERE n.p = v` in the clause predicate).
226    if best.is_none() {
227        if let Some(var) = node.variable.as_ref() {
228            for expr in where_conjuncts {
229                if let Some((prop, bound)) = eq_prop(expr, var) {
230                    consider(&mut best, prop, bound);
231                }
232            }
233        }
234    }
235    best.map(|(label, prop, bound, rows)| SeekPick {
236        label,
237        prop: prop.0,
238        op: BinaryOp::Eq,
239        bound,
240        rows,
241    })
242}
243
244fn eq_prop<'a>(expr: &'a Expr, var: &SmallName) -> Option<(NamedToken, &'a Expr)> {
245    let Expr::Binary {
246        op: BinaryOp::Eq,
247        left,
248        right,
249    } = expr
250    else {
251        return None;
252    };
253    orient(|e| key_named(e, var), left, right, BinaryOp::Eq).map(|(prop, bound, _)| (prop, bound))
254}
255
256/// The range window level (ADR-0486) as an argmin over the where
257/// clause's conjuncts: the label, property, op, bound, and count of the
258/// servable comparison conjunct with the minimum count across the start
259/// element's labels — the `best_equality`/`contains_hits` min policy.
260/// The count is the index's posting-length window: an exact, seekable
261/// measurement, so it consumes as [`Estimate::Measured`] paying no scan
262/// floor, and ranks above the sampled `CONTAINS` level (an exact count
263/// outranks an extrapolation carrying a scan floor — the seekable side
264/// must win the anchor) while the equality point read above it stays
265/// the degenerate tightest window on the same index. The plan tree's
266/// seek narration consumes this same derivation through [`best_seek`],
267/// never a second spelling of the policy. Module-private beside its
268/// level sibling `best_equality`: the level derivations are
269/// [`best_seek`]'s to compose, and the ladder and the seek narration
270/// both consume the pick.
271fn best_range<'a>(
272    node: &'a NodePattern,
273    where_conjuncts: impl IntoIterator<Item = &'a Expr>,
274    stats: &dyn PatternStats,
275) -> Option<SeekPick<'a>> {
276    let var = node.variable.as_ref()?;
277    // ADR-0493's crossover population, folded once per pattern — the
278    // one rule the executor funnel's gate applies too.
279    let scan_rows = crossover_scan_rows(node.labels.iter(), |label| stats.label_rows(label));
280    // The argmin kept as references until the winner is known — the same
281    // winner-only discipline as `best_equality` above: one property clone
282    // for the pick that wins, none for the candidates that do not.
283    let mut best: Option<(&SmallName, NamedToken, BinaryOp, &Expr, u64)> = None;
284    for expr in where_conjuncts {
285        let Some((prop, op, bound)) = range_prop(expr, var) else {
286            continue;
287        };
288        for named in &node.labels {
289            let Some(rows) = stats.range_rows(named, &prop, op, bound) else {
290                continue;
291            };
292            // ADR-0493's crossover per candidate, BEFORE the min: a
293            // gated-out smallest window must not hide a passing larger
294            // one on another label or conjunct. A window at or above a
295            // quarter of the scan population (above the small-window
296            // floor) is cheaper as the label scan with the residual
297            // filter — the candidate declines, the ladder falls
298            // through to CONTAINS / label rows.
299            if !range_seek_gated(rows, scan_rows)
300                && best
301                    .as_ref()
302                    .is_none_or(|(_, _, _, _, best_rows)| rows < *best_rows)
303            {
304                best = Some((&named.0, prop.clone(), op, bound, rows));
305            }
306        }
307    }
308    best.map(|(label, prop, op, bound, rows)| SeekPick {
309        label,
310        prop: prop.0,
311        op,
312        bound,
313        rows,
314    })
315}
316
317/// Whether the stats can already price this conjunct on the node: a
318/// plain `var.key = c` the equality level reads, or a comparison the
319/// range level reads (a window the crossover gate declined is still a
320/// measurement). The default selectivity table prices only what this
321/// declines, so servability has one spelling — the recognizers and
322/// probes of the levels above.
323pub(super) fn priced_by_stats(expr: &Expr, node: &NodePattern, stats: &dyn PatternStats) -> bool {
324    let Some(var) = node.variable.as_ref() else {
325        return false;
326    };
327    if let Some((prop, op, bound)) = range_prop(expr, var) {
328        return node
329            .labels
330            .iter()
331            .any(|label| stats.range_rows(label, &prop, op, bound).is_some());
332    }
333    eq_prop(expr, var).is_some_and(|(prop, bound)| {
334        node.labels
335            .iter()
336            .any(|label| stats.equality_rows(label, &prop, bound).is_some())
337    })
338}
339
340/// The comparison-conjunct recognizer (ADR-0486's v1 floor): the var's
341/// own property under one of the four comparison ops, operand-oriented
342/// the way the executor's `range_seek_expr` orients — property on either
343/// side, the op mirrored for a right-side property (`5 > n.x` is
344/// `n.x < 5`) — the planner/executor twin `contains_prop` vs
345/// `string_seek_expr` already is (LABS-351). Module-private beside its
346/// twin: reachable only through [`best_range`], which feeds the
347/// ladder's window level and the seek narration through [`best_seek`],
348/// so the tree-build consumes this one spelling, never a second. `Eq`
349/// declines (the property-map fold and `equality_rows` own the point
350/// read), as do `IN` and `STARTS WITH` (deferred, ADR-0486).
351fn range_prop<'a>(expr: &'a Expr, var: &SmallName) -> Option<(NamedToken, BinaryOp, &'a Expr)> {
352    let Expr::Binary { op, left, right } = expr else {
353        return None;
354    };
355    if !matches!(
356        op,
357        BinaryOp::Lt | BinaryOp::Lte | BinaryOp::Gt | BinaryOp::Gte
358    ) {
359        return None;
360    }
361    orient(|e| key_named(e, var), left, right, *op).map(|(prop, bound, op)| (prop, op, bound))
362}
363
364/// One indexed seek the start element's predicates resolve to
365/// (ADR-0486): the winning `(label, property)` index pair, the op, the
366/// bound, and the count — the equality-before-window pick, the
367/// anchored-equality point read (a point lookup, the degenerate
368/// tightest window on the same index, carrying [`BinaryOp::Eq`])
369/// outranking the comparison window, an ordering spelled once, in
370/// [`best_seek`], never again as separate control flow in a consumer:
371/// the ladder's first measured level ([`endpoint_estimate`]) and the
372/// plan tree's seek narration (`index_seek` in the top-level crate)
373/// both consume this one pick.
374pub struct SeekPick<'a> {
375    /// The label of the winning `(label, property)` index pair.
376    pub label: &'a SmallName,
377    /// The indexed property the seek serves. Owned: the property map's
378    /// value-domain key is classified into the name domain at the pick
379    /// (there is nothing in the node pattern to borrow it from).
380    pub prop: SmallName,
381    /// The seek's op: [`BinaryOp::Eq`] for the folded point read, the
382    /// oriented comparison op for the window.
383    pub op: BinaryOp,
384    /// The winning pair's bound expression — as folded for the point
385    /// read, as recognized for the window.
386    pub bound: &'a Expr,
387    /// The index's count for the seek — the hit count for the point
388    /// read, the posting-length window for the comparison.
389    pub rows: u64,
390}
391
392/// The one equality-before-window derivation (ADR-0486): the pick a
393/// seek-capable start element's predicates resolve to — an indexed
394/// equality on the folded map first (a point lookup is the degenerate
395/// tightest window on the same index, so it outranks), else the
396/// servable comparison conjunct's window. The ladder's measured level
397/// and the plan tree's seek narration consume this derivation, never a
398/// second spelling of the ranking.
399pub fn best_seek<'a>(
400    node: &'a NodePattern,
401    where_conjuncts: impl IntoIterator<Item = &'a Expr, IntoIter: Clone>,
402    stats: &dyn PatternStats,
403) -> Option<SeekPick<'a>> {
404    let conjuncts = where_conjuncts.into_iter();
405    best_equality(node, conjuncts.clone(), stats).or_else(|| best_range(node, conjuncts, stats))
406}
407
408/// The CONTAINS level with its provenance: the minimum count across the
409/// node's labels, kept as the measured [`ContainsCount`] so the ladder can
410/// price the sampled form's scan floor (the compound, ADR-0474) while the
411/// TEXT-indexed form stays a plain measured count.
412fn contains_hits<'a>(
413    node: &NodePattern,
414    where_conjuncts: impl IntoIterator<Item = &'a Expr>,
415    stats: &dyn PatternStats,
416) -> Option<Estimate> {
417    let var = node.variable.as_ref()?;
418    where_conjuncts
419        .into_iter()
420        .filter_map(|expr| contains_prop(expr, var))
421        .flat_map(|(prop, needle)| {
422            node.labels
423                .iter()
424                .map(move |label| (label, prop.clone(), needle))
425        })
426        .filter_map(|(label, prop, needle)| stats.contains_rows(label, &prop, needle))
427        .min_by_key(|count| count.rows())
428        .map(|count| match count {
429            ContainsCount::TextIndex(rows) => Estimate::Measured(u128::from(rows)),
430            ContainsCount::SampleScan { rows, scan } => Estimate::Scanned {
431                rows: u128::from(rows),
432                scan: u128::from(scan),
433                basis: Basis::Sampled,
434            },
435        })
436}
437
438/// The label level: the label's rows, scaled by the selectivity of the
439/// node's predicates that no measured level priced — a
440/// [`Estimate::Scanned`] whose basis is the least trustworthy term's —
441/// else the plain [`Estimate::Measured`] label count. `None` without a
442/// label count.
443fn label_rung<'a>(
444    node: &NodePattern,
445    where_conjuncts: impl Iterator<Item = &'a Expr>,
446    stats: &dyn PatternStats,
447) -> Option<Estimate> {
448    let label_rows = label_hits(node, stats)?;
449    let scan = u128::from(label_rows);
450    // A conjunct the stats price is a measurement the label count already
451    // answers for (a window the crossover gate declined); only the rest
452    // reaches the pricing.
453    let unpriced = where_conjuncts.filter(|expr| !priced_by_stats(expr, node, stats));
454    let ctx = selectivity::Context {
455        node,
456        label_rows,
457        stats,
458    };
459    Some(match selectivity::price(&ctx, unpriced) {
460        Some(priced) => {
461            let rows = selectivity::scale_rows(scan, priced.selectivity);
462            Estimate::Scanned {
463                rows,
464                scan,
465                basis: priced.basis,
466            }
467        }
468        None => Estimate::Measured(scan),
469    })
470}
471
472pub(super) fn label_hits(node: &NodePattern, stats: &dyn PatternStats) -> Option<u64> {
473    node.labels
474        .iter()
475        .filter_map(|label| stats.label_rows(label))
476        .min()
477}
478
479fn each_conjunct<'a>(expr: &'a Expr, visit: &mut impl FnMut(&'a Expr)) {
480    if let Expr::Binary {
481        op: BinaryOp::And,
482        left,
483        right,
484    } = expr
485    {
486        each_conjunct(left, visit);
487        each_conjunct(right, visit);
488    } else {
489        visit(expr);
490    }
491}
492
493/// `key_of` with the key beside its plan-resolved token.
494fn key_named(expr: &Expr, var: &SmallName) -> Option<NamedToken> {
495    var_prop_named(expr)
496        .filter(|(name, _)| *name == var)
497        .map(|(_, key)| key)
498}
499
500fn contains_prop<'a>(expr: &'a Expr, var: &SmallName) -> Option<(NamedToken, &'a Expr)> {
501    let Expr::Binary {
502        op: BinaryOp::Contains,
503        left,
504        right,
505    } = expr
506    else {
507        return None;
508    };
509    // CONTAINS is operand-asymmetric (needle/haystack), so only the left
510    // side is recognized — a right-side property declines like every other
511    // unservable shape, matching string_seek_expr's one-sided policy; the
512    // estimate falls back to the unfiltered count.
513    key_named(left, var).map(|key| (key, right.as_ref()))
514}
515
516pub(super) fn endpoint_bound(node: &NodePattern, bound: Bound<'_>) -> bool {
517    node.variable
518        .as_ref()
519        .is_some_and(|var| var.with_str(|text| bound(text)))
520}