relate_planner/order/mod.rs
1//! Cardinality estimates and MATCH pattern order.
2//!
3//! A missing count falls back to a rank sentinel. Measured counts may be
4//! scaled by relationship degree; rank sentinels stay unscaled.
5
6use std::cmp::Reverse;
7use std::collections::HashSet;
8
9use relate_ir::{Expr, NodePattern, PathPattern, PatternElement, RelPattern};
10use relate_names::NamedToken;
11
12use crate::stats::{NoPatternStats, PatternStats};
13
14mod estimate;
15mod junction;
16mod selectivity;
17mod strategy;
18#[cfg(test)]
19mod strategy_tests;
20
21pub use estimate::{
22 best_seek, crossover_scan_rows, endpoint_estimate, range_seek_gated, where_conjuncts_of, Basis,
23 Bound, Estimate, SeekPick,
24};
25use estimate::{endpoint_bound, label_hits, RANK_BARE};
26pub use junction::{
27 can_reverse_varlen_leg, detect_junction_split, junction_legs_have_cross_inline_refs,
28 reverse_varlen_leg, split_junction_legs, JunctionSplitPoint,
29};
30pub(crate) use strategy::plan_match_strategies;
31pub use strategy::{
32 evaluate_cross_clause_cost, CrossClauseCost, CrossClauseSearchEnd, MatchStrategy,
33 HASH_JOIN_MIN_SIDE_ROWS,
34};
35
36/// Named paths, named variable-length relationships, and non-alternating
37/// GPM paths (quantified patterns, path modes/selectors, path-level WHERE)
38/// stay in written order (TCK Match9). Fixed-length patterns that only set
39/// `needs_gpm()` due to inline node/relationship `WHERE` predicates keep
40/// `nodes`/`rels` and `elements` in 1-to-1 correspondence and are eligible
41/// for reversal (`reversal_safe` guards cross-variable inline predicates,
42/// and `reverse_path` flips both views).
43fn orientation_locked(path: &PathPattern) -> bool {
44 path.has_path_name()
45 || !path.has_compact_alternating_elements()
46 || path.nodes.len() < 2
47 || path
48 .rels
49 .iter()
50 .any(|rel| rel.var_length && rel.variable.is_some())
51}
52
53/// True when `path` may be reversed without changing query semantics or
54/// element-predicate evaluation order under `bound`.
55pub fn can_reverse_path(path: &PathPattern, bound: Bound<'_>) -> bool {
56 !orientation_locked(path) && reversal_safe(path, bound)
57}
58
59/// The reversal's evaluation-order gate — the planner-side twin of the
60/// executor's `pattern_self_contained` (ADR-0350): the forward walk binds a
61/// pattern's elements left to right, so an element's predicate may legally
62/// reference another element's variable and see it bound. Reversing the
63/// path evaluates those predicates in the opposite order, so the reference
64/// would see an unbound variable — the strict evaluator rejects that
65/// (ADR-0335) instead of fabricating null. A path whose element predicates
66/// reference a peer pattern variable therefore keeps its written
67/// orientation; a variable the surrounding scope already binds is safe in
68/// every order.
69fn reversal_safe(path: &PathPattern, bound: Bound<'_>) -> bool {
70 let own = |var: &str| {
71 path.nodes
72 .iter()
73 .any(|n| n.variable.as_ref().is_some_and(|v| v == var))
74 || path
75 .rels
76 .iter()
77 .any(|r| r.variable.as_ref().is_some_and(|v| v == var))
78 };
79 let mut refs = HashSet::new();
80 for node in &path.nodes {
81 let mut node_refs = HashSet::new();
82 if let Some(e) = &node.properties {
83 relate_ir::expr_vars(e, &mut node_refs);
84 }
85 if let Some(e) = &node.where_clause {
86 relate_ir::expr_vars(e, &mut node_refs);
87 }
88 if let Some(le) = &node.label_expr {
89 relate_ir::label_expr_vars(le, &mut node_refs);
90 }
91 // An inline predicate on `node` naturally names `node`'s own variable,
92 // which is bound when `node` is visited in either direction; only
93 // references to *other* pattern variables depend on walk order.
94 if let Some(self_var) = &node.variable {
95 self_var.with_str(|s| {
96 node_refs.remove(s);
97 });
98 }
99 refs.extend(node_refs);
100 }
101 for rel in &path.rels {
102 let mut rel_refs = HashSet::new();
103 if let Some(e) = &rel.properties {
104 relate_ir::expr_vars(e, &mut rel_refs);
105 }
106 if let Some(e) = &rel.where_clause {
107 relate_ir::expr_vars(e, &mut rel_refs);
108 }
109 if let Some(self_var) = &rel.variable {
110 self_var.with_str(|s| {
111 rel_refs.remove(s);
112 });
113 }
114 refs.extend(rel_refs);
115 }
116 !refs.iter().any(|var| own(var) && !bound(var.as_str()))
117}
118
119/// One orientation's price: the degree-scaled walk cost, the seed's own
120/// row estimate and the basis that estimate carries — the tie-breaks need
121/// the seed side, so it is returned rather than recomputed (stellar
122/// F-2-6).
123#[derive(Clone, Copy)]
124struct DirectionCost {
125 walked: u128,
126 seed: u128,
127 basis: Basis,
128}
129
130/// The price of walking `path` in one direction.
131fn direction_cost(
132 path: &PathPattern,
133 reversed: bool,
134 bound: Bound<'_>,
135 where_conjuncts: &[&Expr],
136 stats: &dyn PatternStats,
137) -> DirectionCost {
138 if path.nodes.is_empty() {
139 return DirectionCost {
140 walked: RANK_BARE,
141 seed: RANK_BARE,
142 basis: Basis::Rank,
143 };
144 }
145 // The walk cost and the tie-break seed both read the one shared
146 // spellings — [`walk_cost`] and [`seed_rows`] — the same arithmetic
147 // the executor's estimate runs (LABS-671). The oriented view is two
148 // iterator directions, never the collected `Vec` pair this used to
149 // build per call: the seed endpoint is the walk's first node in the
150 // walked direction, the hop chain zips nodes with rels in it, and
151 // the orientation fact is derived beside both.
152 let seed = if reversed {
153 path.nodes.last().expect("nodes is non-empty")
154 } else {
155 path.nodes.first().expect("nodes is non-empty")
156 };
157 let estimate = endpoint_estimate(seed, bound, where_conjuncts.iter().copied(), stats);
158 let walked = if reversed {
159 walk_cost(
160 estimate,
161 path.nodes
162 .iter()
163 .rev()
164 .zip(path.rels.iter().rev())
165 .map(|(node, rel)| (node, rel, seed_on_rel_start(rel, true))),
166 stats,
167 )
168 } else {
169 walk_cost(
170 estimate,
171 path.nodes
172 .iter()
173 .zip(path.rels.iter())
174 .map(|(node, rel)| (node, rel, seed_on_rel_start(rel, false))),
175 stats,
176 )
177 };
178 DirectionCost {
179 walked,
180 seed: seed_rows(estimate),
181 basis: estimate.basis(),
182 }
183}
184
185/// Which side of `rel` a walk's seed node rides (LABS-426): the typed
186/// derivation every walk-orientation consumer shares — a written-outgoing
187/// rel seeded from its start side walked forward, a written-incoming one
188/// seeded from its start side walked reversed, and an UNDIRECTED rel has
189/// no start side in either orientation (the mean stays; the histogram is
190/// keyed by the start side only). [`reverse_path`] flips directions, so a
191/// post-reversal spelling is its own written direction.
192pub fn seed_on_rel_start(rel: &RelPattern, reversed: bool) -> bool {
193 match rel.direction {
194 relate_ir::Direction::Outgoing => !reversed,
195 relate_ir::Direction::Incoming => reversed,
196 relate_ir::Direction::Both => false,
197 }
198}
199
200/// What one hop's input rows are — the fact that decides whether the
201/// degree-sum clamp holds ([`apply_degree`] vs [`apply_path_degree`]).
202#[derive(Clone, Copy, PartialEq, Eq)]
203enum HopRows {
204 /// Distinct seed nodes: their degree sum cannot exceed the rel
205 /// type's total, so the tail estimate clamps at it.
206 Seeds,
207 /// Paths: one node recurs across many rows (every path through it),
208 /// so the distinct-seed sum bound does not hold and the tail
209 /// multiplies unclamped.
210 Paths,
211}
212
213/// One hop's fanout over a distinct seed set — the planner's walk model
214/// and the kernels' cost gates price a hop leaving distinct nodes with
215/// it (see [`HopRows::Seeds`]).
216pub fn apply_degree(
217 rows: u128,
218 start: &NodePattern,
219 rel: &RelPattern,
220 seed_is_start: bool,
221 stats: &dyn PatternStats,
222) -> u128 {
223 scale_degree(rows, start, rel, seed_is_start, stats, HopRows::Seeds)
224}
225
226/// One hop's fanout over a path multiset — [`apply_degree`]'s policy
227/// without its degree-sum clamp ([`HopRows::Paths`]): a chained path
228/// multiplicity (a quantifier's second and later hops) whose rows are
229/// paths, not distinct nodes. `pub` for the frontier family's cost gate,
230/// which prices the DFS's path count against the distinct endpoints.
231pub fn apply_path_degree(
232 rows: u128,
233 start: &NodePattern,
234 rel: &RelPattern,
235 seed_is_start: bool,
236 stats: &dyn PatternStats,
237) -> u128 {
238 scale_degree(rows, start, rel, seed_is_start, stats, HopRows::Paths)
239}
240
241fn scale_degree(
242 rows: u128,
243 start: &NodePattern,
244 rel: &RelPattern,
245 seed_is_start: bool,
246 stats: &dyn PatternStats,
247 hop_rows: HopRows,
248) -> u128 {
249 priced_degree(rows, start, rel, seed_is_start, stats, hop_rows).unwrap_or(rows)
250}
251
252/// How many relationship types a hop names: the one discriminator the
253/// hop-pricing sites share, so the "exactly one type" test cannot drift
254/// between them.
255enum RelTypes<'a> {
256 /// An untyped rel.
257 None,
258 /// Exactly one named type.
259 One(&'a NamedToken),
260 /// An alternation (`[:A|B]`).
261 Many,
262}
263
264impl<'a> RelTypes<'a> {
265 fn of(rel: &'a RelPattern) -> Self {
266 match rel.types.as_slice() {
267 [] => Self::None,
268 [one] => Self::One(one),
269 _ => Self::Many,
270 }
271 }
272}
273
274/// One hop's fanout for a kernel's cost gate (LABS-991): [`apply_degree`]'s
275/// price where the statistics can name one, and — where they cannot (an
276/// untyped rel, or a hop leaving an unlabeled node, which the walk model
277/// leaves at the input row count) — the out-degree tail over every
278/// labeled node ([`PatternStats::any_degree_tail`]), unclamped so the
279/// bound compounds across a chain's hops. A hop leaving the walk's seed on
280/// the rel's start side only: the in-degree and undirected shapes have no
281/// histogram to ride and keep the unpriced row count, as does a stats
282/// source with no histogram. `pub` for the executor kernels' gate, the one
283/// consumer — the planner's own orientation costs keep [`apply_degree`].
284pub fn apply_hop_bound(
285 rows: u128,
286 start: &NodePattern,
287 rel: &RelPattern,
288 seed_is_start: bool,
289 stats: &dyn PatternStats,
290) -> u128 {
291 if let Some(priced) = priced_degree(rows, start, rel, seed_is_start, stats, HopRows::Seeds) {
292 return priced;
293 }
294 if !seed_is_start {
295 return rows;
296 }
297 // One named type rides that type's tail; untyped and alternated
298 // (`[:A|B]`) rels ride the any-type tail, which bounds every type.
299 let rel_type = match RelTypes::of(rel) {
300 RelTypes::One((rel_type, _)) => Some(rel_type),
301 RelTypes::None | RelTypes::Many => None,
302 };
303 stats
304 .any_degree_tail(rel_type)
305 .map_or(rows, |tail| rows.saturating_mul(u128::from(tail)))
306}
307
308/// The walk model's price for one hop, or `None` when the statistics
309/// cannot name one (an untyped or alternated rel, no rel-type count, a
310/// seed with no label count or an empty label) — the callers differ only
311/// in what an unpriced hop costs.
312fn priced_degree(
313 rows: u128,
314 start: &NodePattern,
315 rel: &RelPattern,
316 seed_is_start: bool,
317 stats: &dyn PatternStats,
318 hop_rows: HopRows,
319) -> Option<u128> {
320 let RelTypes::One(rel_type) = RelTypes::of(rel) else {
321 return None;
322 };
323 // LABS-426 (the mean-to-tail flip): when the hop's seed rides the
324 // rel's START side ([`seed_is_start`], the caller's one derived fact),
325 // the fanout rides the (seed-label, rel-type) out-degree TAIL — the
326 // log2-bucket top, the conservative floor of the highest observed
327 // degree — not the mean: a label with a 53-degree mean and one
328 // 50k-degree supernode expands its seed rows by the supernode's
329 // bucket, the one plan-cost fact the mean cannot express. The min
330 // across the seed's labels — every label's tail bounds the
331 // intersection's max degree (the A:B node's fanout is inside both the
332 // (A,type) and the (B,type) histograms), so the tighter conservative
333 // bound is the min, the same discipline [`label_hits`] uses. Any
334 // other hop shape — undirected ([`seed_on_rel_start`] answers false
335 // in both orientations: no start side), or the seed on the rel's end
336 // side — keeps the mean, as does a seed with no histogram (the null
337 // stats, an unlabeled start).
338 if seed_is_start {
339 if let Some(tail) = start
340 .labels
341 .iter()
342 .filter_map(|label| stats.degree_tail(label, rel_type))
343 .min()
344 {
345 // The clamp: the seed subset's degree SUM cannot exceed the
346 // rel type's total — a whole-label scan (rows near the label
347 // population) is priced by that total, the mean's own scale,
348 // not rows x the one supernode's bucket (the sandbox's
349 // 1000 x 32768 = 32.7M priced a 53k-fanout scan and flipped
350 // the seed to the 100k-DbHits side). A small-seed seek rides
351 // the tail alone: one row matched the label's supernode is
352 // the case the mean cannot price.
353 let scaled = rows.saturating_mul(u128::from(tail));
354 return Some(match (hop_rows, stats.rel_type_rows(rel_type)) {
355 (HopRows::Seeds, Some(total)) => scaled.min(u128::from(total)),
356 _ => scaled,
357 });
358 }
359 }
360 let rel_rows = stats.rel_type_rows(rel_type)?;
361 let label_rows = label_hits(start, stats)?;
362 if label_rows == 0 {
363 return None;
364 }
365 let scaled = rows.saturating_mul(u128::from(rel_rows)) / u128::from(label_rows);
366 Some(if rows > 0 && rel_rows > 0 && scaled == 0 {
367 1
368 } else {
369 scaled
370 })
371}
372
373pub fn seed_rows(estimate: Estimate) -> u128 {
374 // The seed's own cost IS the zero-hop walk — one spelling, derived
375 // from [`walk_cost`] (the compound model's own doc). Stats is never
376 // read on an empty chain, so the no-stats placeholder serves.
377 walk_cost(estimate, std::iter::empty::<Hop<'_>>(), &NoPatternStats)
378}
379
380/// One hop of the walk model's input: the node the walk is leaving,
381/// the rel it traverses, and the hop's derived orientation fact
382/// (`seed_is_start`, from the one typed derivation
383/// [`seed_on_rel_start`]) — computed once by the orientation owner,
384/// never re-derived inside the walk.
385pub type Hop<'a> = (&'a NodePattern, &'a RelPattern, bool);
386
387/// The degree-scaled walk over `hops`: one spelling of hop
388/// application, read by every walk cost via [`walk_cost`] (module-
389/// private: its only callers are in this module).
390fn degree_walk<'a>(
391 rows: u128,
392 hops: impl Iterator<Item = Hop<'a>>,
393 stats: &dyn PatternStats,
394) -> u128 {
395 let mut output = rows;
396 for (node, rel, seed_is_start) in hops {
397 output = apply_degree(output, node, rel, seed_is_start, stats);
398 }
399 output
400}
401
402/// The walk cost of an endpoint estimate over `hops` — the ONE model
403/// of which estimate kind gets which walk, read by the planner's
404/// `direction_cost` (the whole pattern's hop chain) and the executor's
405/// `GraphStats::estimate` (the first hop of the same chain), so the
406/// per-row start selection and the plan-time orientation cannot
407/// disagree on the anchor (LABS-671's insurance test ties them at the
408/// executor side). A measured seed walks the degree-scaled chain; a
409/// sampled `CONTAINS` seed compounds (ADR-0474): its walk cost is the
410/// degree-scaled output floored at the whole-label scan — the scan is
411/// paid once, before any hop, so it never rides the degree (GBL SF0.1
412/// q8: the 13,750-row Forum scan floor keeps the 137-row sampled title
413/// seed from undercutting Person's 1,528-row scan whose degree-scaled
414/// walk lands on the same 13,750 rels). A rank sentinel carries no
415/// measured label to scale — its rows travel unscaled.
416pub fn walk_cost<'a>(
417 estimate: Estimate,
418 hops: impl Iterator<Item = Hop<'a>>,
419 stats: &dyn PatternStats,
420) -> u128 {
421 match estimate {
422 Estimate::Measured(rows) => degree_walk(rows, hops, stats),
423 // the compound: the degree-scaled walk floored at the scan
424 Estimate::Scanned { rows, scan, .. } => degree_walk(rows, hops, stats).max(scan),
425 Estimate::Rank(rows) => rows,
426 }
427}
428
429/// `(reversed, cost)`. A strictly cheaper expanded cost wins. When both
430/// directions estimate the same output (a typed hop scaled by its degree),
431/// the smaller seed endpoint wins (ADR-0218): that is the scan, and the
432/// expanded row count hides it. Equal seeds go to the more trustworthy
433/// seed basis; equal bases keep the written direction.
434fn choose_orientation(
435 path: &PathPattern,
436 bound: Bound<'_>,
437 where_conjuncts: &[&Expr],
438 stats: &dyn PatternStats,
439) -> (bool, u128) {
440 // The written orientation is the one the elements' left-to-right
441 // binding order is defined on; a locked or peer-referenced path keeps
442 // it. Beyond that, an orientation is forced exactly when only one
443 // endpoint is bound — seed from the bound end.
444 let forced = match (path.nodes.first(), path.nodes.last()) {
445 (Some(first), Some(last)) if can_reverse_path(path, bound) => {
446 let first_bound = endpoint_bound(first, bound);
447 let last_bound = endpoint_bound(last, bound);
448 if first_bound && !last_bound {
449 Some(false)
450 } else if last_bound && !first_bound {
451 Some(true)
452 } else {
453 None
454 }
455 }
456 _ => Some(false),
457 };
458 if let Some(reversed) = forced {
459 return (
460 reversed,
461 direction_cost(path, reversed, bound, where_conjuncts, stats).walked,
462 );
463 }
464 let written = direction_cost(path, false, bound, where_conjuncts, stats);
465 let flipped = direction_cost(path, true, bound, where_conjuncts, stats);
466 // A strictly cheaper cost wins, then the smaller seed; a tie on both
467 // goes to the seed whose estimate is the more trustworthy (a
468 // statistic over a default table). Basis never overrides a strictly
469 // cheaper price, and equal bases keep the written direction.
470 let flip = (flipped.walked, flipped.seed, Reverse(flipped.basis))
471 < (written.walked, written.seed, Reverse(written.basis));
472 if flip {
473 (true, flipped.walked)
474 } else {
475 (false, written.walked)
476 }
477}
478
479fn pattern_touches(path: &PathPattern, bound: Bound<'_>) -> bool {
480 relate_ir::path_pattern_vars(path).any(|var| var.with_str(|text| bound(text)))
481}
482
483/// Reverse a linear path pattern in place, flipping its node/relationship
484/// sequence and relationship directions.
485pub fn reverse_path(path: &mut PathPattern) {
486 path.nodes.reverse();
487 path.rels.reverse();
488 for rel in &mut path.rels {
489 rel.direction = rel.direction.flip();
490 }
491 if path.elements.len() == path.nodes.len() + path.rels.len() {
492 path.elements.reverse();
493 for element in &mut path.elements {
494 if let PatternElement::Relationship(rel) = element {
495 rel.direction = rel.direction.flip();
496 }
497 }
498 }
499}
500
501/// Greedy seed plus connected expansion: the cheapest pattern seeds, then
502/// each next pattern that shares a variable already bound (LABS-157), or
503/// the cheapest remaining one when none is connected. Orientation and the
504/// bound set advance with every chosen pattern; the grown set stays
505/// internal (connectivity/orientation state — the caller's binding set is
506/// `rewrite.rs`'s `advance_bound` fold, the one spelling of what a clause
507/// binds). Equal costs keep written order.
508pub(crate) fn order_patterns(
509 patterns: &mut Vec<PathPattern>,
510 prebound: &HashSet<String>,
511 where_clause: Option<&Expr>,
512 stats: &dyn PatternStats,
513) {
514 let mut bound = prebound.clone();
515 // The MATCH's conjunct view, derived once for every orientation this
516 // MATCH prices: the where clause is loop-invariant, so each
517 // candidate's `choose_orientation` reads this slice instead of
518 // re-flattening the `AND` tree per call.
519 let where_conjuncts = where_conjuncts_of(where_clause);
520 let mut pending: Vec<(usize, PathPattern)> =
521 std::mem::take(patterns).into_iter().enumerate().collect();
522 let mut chosen = Vec::with_capacity(pending.len());
523 while !pending.is_empty() {
524 // The bound set stays the loop's mutable state; the ladder reads
525 // it through the membership predicate (one view per iteration,
526 // re-created after each chosen pattern extends the set).
527 let bound_view = |name: &str| bound.contains(name);
528 // The greedy candidate rule without the collected index `Vec`s
529 // this used to build per iteration: when a pattern is already
530 // chosen and some pending pattern connects to the bound set, the
531 // connected patterns are the candidates, otherwise every pending
532 // pattern is (the first choice is unmade or nothing connects).
533 let connected_exists = !chosen.is_empty()
534 && pending
535 .iter()
536 .any(|(_, path)| pattern_touches(path, &bound_view));
537 // The first (cost, written) minimum wins — `min_by_key` settles
538 // it over the filtered candidates without collecting them.
539 let (index, (reversed, _)) = pending
540 .iter()
541 .enumerate()
542 .filter(|(_, (_, path))| !connected_exists || pattern_touches(path, &bound_view))
543 .map(|(index, (_, path))| {
544 (
545 index,
546 choose_orientation(path, &bound_view, &where_conjuncts, stats),
547 )
548 })
549 .min_by_key(|&(index, (_, cost))| (cost, pending[index].0))
550 .expect("candidate set is non-empty");
551 let (_, mut path) = pending.remove(index);
552 if reversed {
553 reverse_path(&mut path);
554 }
555 add_pattern_vars(&mut bound, &path);
556 chosen.push(path);
557 }
558 *patterns = chosen;
559}
560
561/// Add one pattern's variables to a binding set — the ordering pass's own
562/// incremental scope, fed pattern by pattern as `order_patterns` commits
563/// each chosen orientation. The canonical IR walk supplies the names for
564/// both pattern representations.
565fn add_pattern_vars(bound: &mut HashSet<String>, p: &PathPattern) {
566 // Map-bridge feeds: the bound sets stay String-keyed; every IR name
567 // renders once, at its push.
568 bound.extend(
569 relate_ir::pattern_anchor_variables(p)
570 .into_iter()
571 .map(|name| name.to_string()),
572 );
573}
574
575#[cfg(test)]
576mod tests;