relate-executor 1.4.0

In-memory graph and Cypher physical executor
Documentation
//! The route's one guard: the patterns ADR-0186's Decision sends to BFS.

use crate::UsedSet;
use std::collections::{BTreeMap, HashSet};

use relate_core::Value;
use relate_ir::{
    MatchMode, NodePattern, PathMode, PathPattern, PathSelector, PatternElement, RelPattern,
};

use crate::eval::expr_vars;
use crate::row::Row;
use crate::shortest::followable;

use super::super::selector::resolve_gpm_count;
use super::super::{ElementFilter, GpmFilters};
use crate::pattern_walk::RelFilter;
use crate::shortest::CommonEndNodes;

/// Which shortest-path spelling a routed pattern is: the one fact the
/// element decode cannot read off the lowered pattern. The function and
/// expression forms reject a same-node pair, the keyword selectors keep
/// their closed trails (51N23), and only the expression form stops a fan
/// at its first productive layer.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Spelling {
    KeywordSelector,
    Function,
    Expression,
}

impl Spelling {
    /// The `MATCH`-clause spelling: the function forms carry the flag, a
    /// keyword selector does not. The expression form is stamped by its
    /// own entry ([`super::fold_shortest_route`]), which hands
    /// [`Spelling::Expression`] to the one driver.
    pub(super) fn of(path: &PathPattern) -> Self {
        if path.is_shortest_path_function {
            Spelling::Function
        } else {
            Spelling::KeywordSelector
        }
    }

    /// 51N23's runtime policy.
    pub(super) fn common_end_nodes(self) -> CommonEndNodes {
        match self {
            Spelling::KeywordSelector => CommonEndNodes::Allowed,
            Spelling::Function | Spelling::Expression => CommonEndNodes::Forbidden,
        }
    }

    /// The expression form keeps only the global shortest: an origin's
    /// deeper layers are longer than its own shortest, so they cannot win.
    pub(super) fn first_layer_only(self) -> bool {
        self == Spelling::Expression
    }

    /// Whether a clause-level `WHERE` conjunct that reads the path filters
    /// the *search* (the function and expression forms, as live
    /// `shortestPath()` plans it) or only the selected paths afterwards (a
    /// keyword selector).
    pub(super) fn filters_search_by_clause_where(self) -> bool {
        self != Spelling::KeywordSelector
    }

    /// The hop ceiling an unbounded relationship takes: only the expression
    /// form carries one (the walk's flat default); the clause spellings keep
    /// the pattern's own bound.
    fn unbounded_ceiling(self) -> Option<u32> {
        (self == Spelling::Expression).then_some(crate::pattern_walk::DEFAULT_MAX_HOPS)
    }
}

/// What a pair partition keeps of its trails when the selector counts more
/// than one (ADR-0607): the `k` shortest trails, or every trail of the `k`
/// shortest distinct lengths. A selector that fits the single-path or
/// all-shortest searches carries none.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Keep {
    Paths(usize),
    Groups(usize),
}

/// What a routed pattern's selector asks of a partition: the one shortest
/// trail, every shortest trail, or a count above one (ADR-0607).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Selection {
    Single,
    AllShortest,
    Count(Keep),
}

impl Selection {
    /// All-path selector (every shortest trail) rather than single-path.
    pub(super) fn all(self) -> bool {
        self == Selection::AllShortest
    }

    /// The count the length-class walk answers, if this is one.
    pub(super) fn counted(self) -> Option<Keep> {
        match self {
            Selection::Count(keep) => Some(keep),
            Selection::Single | Selection::AllShortest => None,
        }
    }
}

/// The three elements of a routed pattern and its selector kind.
pub(super) struct Shape<'p> {
    pub start: &'p NodePattern,
    pub rel: &'p RelPattern,
    /// The rel's resolved type filter (LABS-801) — the pattern-level
    /// table's entry for this exact element, found in the same pass that
    /// decoded the shape, never re-derived or re-sniffed.
    pub filter: &'p RelFilter,
    pub end: &'p NodePattern,
    /// The var-length bounds: the rel's own `*m..n` (legacy element shape)
    /// or the quantifier's `{m,n}` (the quantified element every var-length
    /// spelling lowers to, LABS-661) — the inner rel is a plain one-hop.
    pub min: u32,
    pub max: Option<u32>,
    /// What the selector keeps of a partition.
    pub selection: Selection,
    /// The shortest-path spelling this pattern was written with.
    pub spelling: Spelling,
    /// The match mode the guard admitted — always
    /// [`MatchMode::DifferentRelationships`] (the guard declines every
    /// other), carried so the route's unbounded cap reads the admitted
    /// mode instead of restating the admission.
    pub match_mode: MatchMode,
}

/// The one guard: the selectors, match and path modes, and pattern shape of
/// ADR-0186's Decision, an empty incoming used-relationship set, and row
/// bindings the search can honor. `None` keeps the pattern on GPM.
///
/// A path-level `WHERE` does not send the pattern to GPM: an inline one, and
/// a clause-level one of the function spellings, rides the search (see
/// [`super::filters::PathFilter`]); a keyword selector's clause-level one
/// is a post-filter of the selected paths.
pub(super) fn route_shape<'p>(
    path: &'p PathPattern,
    filters: &'p GpmFilters,
    match_mode: MatchMode,
    used: &UsedSet,
    row: &Row,
    params: &BTreeMap<String, Value>,
    spelling: Spelling,
) -> Option<Shape<'p>> {
    // The route takes the `None`, `WALK` and `TRAIL` path modes only — the
    // vocabulary decoded once, here. An explicit `WALK` (whose longer
    // answers may reuse a relationship) stays on GPM: the length-class
    // walk enumerates trails, so a count selector declines it (ADR-0607).
    let explicit_walk = match path.mode {
        Some(PathMode::Walk) => true,
        None | Some(PathMode::Trail) => false,
        Some(_) => return None,
    };
    if match_mode != MatchMode::DifferentRelationships || !used.is_empty() {
        return None;
    }
    let selection = match path.selector.as_ref()? {
        PathSelector::AnyShortest => Selection::Single,
        PathSelector::AllShortest => Selection::AllShortest,
        // The count may arrive as a parameter: the plan cache's
        // auto-parameterization turns a literal `SHORTEST 1` into one, so
        // it resolves through the canonical count helper. A count that
        // does not resolve (or is zero) stays on GPM, which owns the
        // selector's count errors.
        PathSelector::Shortest {
            count: Some(count),
            group,
        } => {
            let n = resolve_gpm_count(Some(count), 1, params).ok()?;
            counted(n, *group)?
        }
        // `ANY k` keeps the `k` shortest, as `SHORTEST k` does (the
        // selector's own reading); `ANY` alone stays on GPM.
        PathSelector::Any(Some(count)) => {
            let n = resolve_gpm_count(Some(count), 1, params).ok()?;
            counted(n, false)?
        }
        PathSelector::Shortest { .. } | PathSelector::Any(_) | PathSelector::All => return None,
    };
    if explicit_walk && selection.counted().is_some() {
        return None;
    }
    let hop = routed_hop(path, filters, selection, spelling, match_mode)?;
    if hop.min > 1
        || hop.rel.where_clause.is_some()
        || !followable(hop.start, hop.rel, hop.end)
        || hop
            .rel
            .variable
            .as_ref()
            .is_some_and(|v| v.with_str(|text| row.contains_key(text)))
    {
        return None;
    }
    // GPM checks the end node with the relationship variable already bound;
    // an endpoint map that reads it (or the path variable) stays on GPM.
    // Text render: the late-binding list compares against the String
    // variable sets of the filter walk.
    let late: Vec<String> = hop
        .rel
        .variable
        .as_ref()
        .map(|v| v.to_string())
        .into_iter()
        .chain(path.path_names().map(|name| name.to_string()))
        .collect();
    let endpoint_ok = |np: &NodePattern| {
        let mut vars = HashSet::new();
        if let Some(props) = &np.properties {
            expr_vars(props, &mut vars);
        }
        np.variable
            .as_ref()
            .is_none_or(|v| matches!(row.get_name(v), None | Some(Value::Node(_))))
            && !late.iter().any(|v| vars.contains(v.as_str()))
    };
    // The start's inline WHERE keeps GPM: GPM checks it once at the start
    // binding, before the relationship variable exists, and the route binds
    // no start predicate of its own.
    // The end's inline WHERE rides the route's path filter instead
    // ([`super::filters::PathFilter`]): GPM checks it at every arrival with
    // the relationship variable bound but no path name bound yet, and the
    // route answers the same predicate against each bound trail — so a
    // WHERE that names a path variable keeps GPM's spelling of the check.
    // A predicate whose reading cannot complete against a bound trail (a
    // later pattern's variable) declines in `Route::try_new`.
    let end_where_ok = hop.end.where_clause.as_ref().is_none_or(|predicate| {
        let mut vars = HashSet::new();
        expr_vars(predicate, &mut vars);
        path.path_names()
            .all(|name| name.with_str(|text| !vars.contains(text)))
    });
    (endpoint_ok(hop.start)
        && hop.start.where_clause.is_none()
        && endpoint_ok(hop.end)
        && end_where_ok)
        .then_some(hop)
}

/// The routed var-length hop of a three-element pattern decoded into the
/// route's one [`Shape`] (F-1-10): the outer nodes, the traversed rel, its
/// resolved filter (LABS-801), and the effective bounds — one decoded
/// unit, never a positional tuple the caller reassembles field-for-field.
/// The selector's `all` fact arrives decided — the one fact the element
/// decode cannot read off the pattern. Every var-length spelling lowers to
/// the quantified element (LABS-661) — `-[r:T*m..n]-` arrives as
/// `[Node, Quantified([anon, one-hop rel, anon]), Node]` with the bounds on
/// the quantifier — so that shape decodes first (the shared
/// `implicit_var_length_rel` decoder); the plain var-length `Relationship`
/// element (hand-built or planner-IR-diagnostic plans) remains the legacy
/// arm.
fn routed_hop<'p>(
    path: &'p PathPattern,
    filters: &'p GpmFilters,
    selection: Selection,
    spelling: Spelling,
    match_mode: MatchMode,
) -> Option<Shape<'p>> {
    let [PatternElement::Node(start), rel_element, PatternElement::Node(end)] =
        path.elements.as_slice()
    else {
        return None;
    };
    // The rel element's resolved filter sits at its own index in the
    // pattern-level table (LABS-801) — the shape decode and the filter
    // lookup read one position, so they cannot disagree. The two arms
    // differ only in where the rel, its filter and the bounds come from.
    let (rel, filter, min, max) = match (rel_element, &filters.filters[1]) {
        (PatternElement::Quantified(qpp), ElementFilter::Group(inner)) => {
            let rel = qpp.implicit_var_length_rel()?;
            let ElementFilter::Rel(filter) = &inner[1] else {
                return None;
            };
            (rel, filter, qpp.min, qpp.max)
        }
        (PatternElement::Relationship(rel), ElementFilter::Rel(filter)) if rel.var_length => {
            (rel, filter, rel.min_hops, rel.max_hops)
        }
        _ => return None,
    };
    Some(Shape {
        start,
        rel,
        filter,
        end,
        min,
        max: max.or(spelling.unbounded_ceiling()),
        selection,
        spelling,
        match_mode,
    })
}

/// The route's reading of a resolved selector count and `GROUPS` flag. One
/// answer is the single-path search, one group the all-shortest search, and
/// a larger count the length-class walk; zero stays on GPM.
fn counted(n: usize, group: bool) -> Option<Selection> {
    match (n, group) {
        (0, _) => None,
        (1, false) => Some(Selection::Single),
        (1, true) => Some(Selection::AllShortest),
        (n, true) => Some(Selection::Count(Keep::Groups(n))),
        (n, false) => Some(Selection::Count(Keep::Paths(n))),
    }
}