relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
//! Aggregate folding (ADR-0036): shared scaffolding for aggregate folding —
//! the RETURN gate and [`FoldOutput`], [`Rank`] and the one projection
//! over it, `finish_folded_rows`.

#[cfg(test)]
use std::cell::Cell;
use std::collections::BTreeMap;

use relate_core::{Result, Value};
use relate_ir::{Clause, Expr, OrderItem, Projection};

use crate::eval::is_agg_expr;
use crate::overlay::{ExecGraph, MaterializeCache};
use crate::row::Row;

use super::order::{
    folded_order_names, page, park_values, resolve_page_bounds, sort_rows_by_parked_keys,
    unpark_order_keys, OrderKeys,
};
use super::scope::{has_star_item, projection_collides_with_internal_names, result_column};
use super::QueryResult;

#[cfg(test)]
thread_local! {
    static PATH_FOLD_BINDINGS: Cell<u64> = const { Cell::new(0) };
}

/// Surviving bindings that took the multi-hop aggregate fold since the last take.
#[cfg(test)]
pub(crate) fn take_path_fold_bindings() -> u64 {
    PATH_FOLD_BINDINGS.with(|count| count.replace(0))
}

pub(crate) fn note_path_binding() {
    #[cfg(test)]
    PATH_FOLD_BINDINGS.with(|count| count.set(count.get() + 1));
}

/// Shared RETURN gate: no DISTINCT, no GROUP BY, no `RETURN *`,
/// at least one aggregate, no user alias in the internal `__` namespace
/// (the reservation [`super::scope::projection_collides_with_internal_names`]
/// owns — the contract and its rationale live there), and every `ORDER BY`
/// key answerable from the folded row (the fold keeps no input rows; see
/// [`folded_order_names`]). The gate fills the shared [`FoldOutput`]
/// directly — the run's params ride in, so no second
/// struct transcribes the gated fields beside it.
pub(crate) fn fold_return<'a>(
    suffix: &'a [Clause],
    params: &'a BTreeMap<String, Value>,
) -> Option<FoldOutput<'a>> {
    let Clause::Return {
        distinct,
        group_by,
        items,
        order,
        skip,
        limit,
    } = suffix.first()?
    else {
        return None;
    };
    if *distinct
        || group_by.is_some()
        || has_star_item(items)
        || projection_collides_with_internal_names(items)
    {
        return None;
    }
    if !items.iter().any(|item| is_agg_expr(&item.expr)) {
        return None;
    }
    let order = folded_order_names(order, items)?
        .into_iter()
        .map(|(key, source)| FoldOrderKey { key, source })
        .collect();
    Some(FoldOutput {
        items,
        order,
        skip: skip.as_ref(),
        limit: limit.as_ref(),
        params,
    })
}

/// What the RETURN gate fills and finishes through: the gated
/// projection shape — items, ORDER BY keys and their sources, SKIP and
/// LIMIT — beside the run's params. One struct, no
/// transcription twin.
pub(crate) struct FoldOutput<'a> {
    pub(crate) items: &'a [Projection],
    /// Per `ORDER BY` key: the key and the output column its folded value
    /// was written to (`folded_order_names`), resolved once here — one entry
    /// per key, owned so the output outlives the [`FoldedReturn`] it was
    /// computed for.
    order: Vec<FoldOrderKey<'a>>,
    skip: Option<&'a Expr>,
    limit: Option<&'a Expr>,
    params: &'a BTreeMap<String, Value>,
}

/// One `ORDER BY` key's folded source: the key and the column its folded
/// value was written to.
struct FoldOrderKey<'a> {
    key: &'a OrderItem,
    source: String,
}

pub(crate) fn finish_folded_rows(
    graph: &ExecGraph<'_>,
    output: &FoldOutput<'_>,
    mut out: Vec<Row>,
) -> Result<FoldedReturn> {
    let bounds = resolve_page_bounds(graph, output.params, output.skip, output.limit)?;
    if !output.order.is_empty() {
        // The folded row is the only row the fold kept: each key parks the
        // value of the item `folded_order_names` resolved for it, and the
        // shared sort entry point orders the rows by those parked columns.
        let keys = OrderKeys::parked_only(
            graph,
            output.order.iter().map(|folded| folded.key),
            output.items,
        );
        for row in out.iter_mut() {
            let parked: Vec<Value> = output
                .order
                .iter()
                .map(|folded| result_column(row, &folded.source).clone())
                .collect();
            park_values(&keys, row, parked);
        }
        sort_rows_by_parked_keys(&keys, &mut out, None)?;
        unpark_order_keys(&keys, &mut out);
    }
    Ok(folded_return(graph, page(out, bounds), output.items))
}

/// One projection item's rank within its half: `Key(i)` reads the fold's
/// key half at `i`, `Agg(i)` its aggregate half at `i`.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Rank {
    Key(usize),
    Agg(usize),
}

/// Project one group into its output row.
pub(crate) fn project_ranked_row<F>(
    items: &[Projection],
    ranks: &[Rank],
    key_vals: &[Value],
    finish: F,
) -> Row
where
    F: Fn(usize) -> Value,
{
    debug_assert_eq!(
        items.len(),
        ranks.len(),
        "ranks is the one-per-item classification of items"
    );
    let mut row = Row::new();
    for (i, (item, rank)) in items.iter().zip(ranks.iter()).enumerate() {
        let name = item.output_name(i);
        match rank {
            Rank::Key(key) => {
                row.insert(
                    name,
                    key_vals
                        .get(*key)
                        .expect("every Key rank indexes key_vals")
                        .clone(),
                );
            }
            Rank::Agg(agg) => {
                row.insert(name, finish(*agg));
            }
        }
    }
    row
}

/// A MATCH fold that already built the following RETURN (ADR-0036).
pub(crate) struct FoldedReturn {
    pub rows: Vec<Row>,
    pub result: QueryResult,
    /// Clauses after the current MATCH that the fold consumed, including RETURN.
    pub consumed_after: usize,
}

fn folded_return(graph: &ExecGraph<'_>, rows: Vec<Row>, items: &[Projection]) -> FoldedReturn {
    FoldedReturn {
        result: result_from_projected(graph, rows.clone(), items),
        rows,
        consumed_after: 1,
    }
}

pub(crate) fn result_from_projected(
    graph: &ExecGraph<'_>,
    rows: Vec<Row>,
    items: &[Projection],
) -> QueryResult {
    let columns: Vec<String> = items
        .iter()
        .enumerate()
        .map(|(i, p)| p.output_name(i))
        .collect();
    let mut cache = MaterializeCache::default();
    let data: Vec<Vec<Value>> = rows
        .iter()
        .map(|r| {
            columns
                .iter()
                .map(|c| graph.materialize_cached(result_column(r, c).clone(), &mut cache))
                .collect()
        })
        .collect();
    QueryResult::intermediate(columns, data, graph.stats())
}