use std::collections::BTreeMap;
use relate_core::{Error, Result, Value};
use relate_ir::{Expr, QuantifierKind};
use relate_names::SmallName;
use crate::ctx::EvalCtx;
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::{bool_or_null, eval, fold_quantifier, into_items};
fn wraps_accumulator(expression: &Expr, accumulator: &SmallName) -> bool {
matches!(
expression,
Expr::List(elems)
if matches!(elems.as_slice(), [Expr::Variable(name)] if name == accumulator)
)
}
fn wrap_acc_once(acc: Value, acc_depth: &mut u32) -> Result<Value> {
let child_depth = *acc_depth;
*acc_depth = child_depth.saturating_add(1);
Value::checked_list_with_depth(vec![acc], child_depth)
}
fn accumulator_allocation_bytes(value: &Value) -> u64 {
use crate::workspace::buffer_bytes;
match value {
Value::List(xs) | Value::Vector { values: xs, .. } => {
buffer_bytes(xs.len(), std::mem::size_of::<Value>() as u64)
}
Value::Map(entries) => crate::workspace::map_entries_bytes(entries.len()),
Value::String(text) => relate_core::str_logical_bytes(text),
Value::Bytes(bytes) => relate_core::bytes_logical_bytes(bytes),
_ => 0,
}
}
fn charge_growth(graph: &crate::overlay::ExecGraph<'_>, before: u64, next: &Value) -> Result<()> {
let after = accumulator_allocation_bytes(next);
if after > before {
graph.charge_expression(after)?;
}
Ok(())
}
pub(crate) fn eval_quantifier(
ctx: EvalCtx<'_>,
kind: QuantifierKind,
ident: &SmallName,
list: &Expr,
predicate: &Expr,
) -> Result<Value> {
let EvalCtx {
graph,
row,
params,
cypher_version,
} = ctx;
let list_v = eval(graph, row, list, params, cypher_version)?;
let items = match list_v {
Value::List(xs) => xs,
Value::Null => return Ok(Value::Null),
_ => return Err(Error::ty("quantifier needs a list")),
};
fold_quantifier(kind, into_items(items), |item| {
let mut r = row.clone();
r.insert(ident.to_string(), item);
let p = eval(graph, &r, predicate, params, cypher_version)?;
bool_or_null(&p, "quantifier WHERE")
})
}
pub(crate) fn eval_reduce(
ctx: EvalCtx<'_>,
accumulator: &SmallName,
initial: &Expr,
ident: &SmallName,
list: &Expr,
expression: &Expr,
) -> Result<Value> {
let EvalCtx {
graph,
row,
params,
cypher_version,
} = ctx;
let mut acc = eval(graph, row, initial, params, cypher_version)?;
let items = match eval(graph, row, list, params, cypher_version)? {
Value::List(items) => items,
Value::Null => return Ok(Value::Null),
_ => return Err(Error::ty("reduce() requires a list")),
};
let wrap_acc = wraps_accumulator(expression, accumulator);
let mut acc_depth = acc.depth();
let mut inner = row.clone();
for item in into_items(items) {
graph.cancel_tick()?;
let before = accumulator_allocation_bytes(&acc);
inner.insert(accumulator.to_string(), acc.clone());
inner.insert(ident.to_string(), item);
acc = if wrap_acc {
wrap_acc_once(acc, &mut acc_depth)?
} else {
eval(graph, &inner, expression, params, cypher_version)?
};
charge_growth(graph, before, &acc)?;
}
Ok(acc)
}
pub(crate) fn eval_all_reduce(
ctx: EvalCtx<'_>,
accumulator: &SmallName,
initial: &Expr,
ident: &SmallName,
list: &Expr,
expression: &Expr,
predicate: &Expr,
) -> Result<Value> {
let EvalCtx {
graph,
row,
params,
cypher_version,
} = ctx;
let acc = eval(graph, row, initial, params, cypher_version)?;
let items = match eval(graph, row, list, params, cypher_version)? {
Value::List(items) => items,
Value::Null => return Ok(Value::Null),
_ => return Err(Error::ty("allReduce() requires a list")),
};
let acc_name = accumulator.to_string();
let ident_name = ident.to_string();
let mut fold = AllReduceFold::start(acc, expression, accumulator);
let mut saw_null = false;
let mut inner = row.clone();
for item in into_items(items) {
match fold.step(
graph,
&mut inner,
&acc_name,
&ident_name,
&item,
expression,
predicate,
params,
cypher_version,
)? {
AllReduceStep::Failed => return Ok(Value::Bool(false)),
AllReduceStep::Null => saw_null = true,
AllReduceStep::Holds => {}
}
}
Ok(if saw_null {
Value::Null
} else {
Value::Bool(true)
})
}
#[derive(Clone)]
pub(crate) struct AllReduceFold {
acc: Value,
started_as_integer: bool,
acc_depth: u32,
wrap_acc: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum AllReduceStep {
Holds,
Failed,
Null,
}
impl AllReduceFold {
pub(crate) fn start(acc: Value, expression: &Expr, accumulator: &SmallName) -> Self {
Self {
started_as_integer: matches!(acc, Value::Int(_)),
acc_depth: acc.depth(),
wrap_acc: wraps_accumulator(expression, accumulator),
acc,
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn step(
&mut self,
graph: &ExecGraph<'_>,
inner: &mut Row,
accumulator: &str,
ident: &str,
element: &Value,
expression: &Expr,
predicate: &Expr,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<AllReduceStep> {
graph.cancel_tick()?;
let before = accumulator_allocation_bytes(&self.acc);
inner.insert(accumulator.to_string(), self.acc.clone());
inner.insert(ident.to_string(), element.clone());
let next = if self.wrap_acc {
let acc = std::mem::replace(&mut self.acc, Value::Null);
wrap_acc_once(acc, &mut self.acc_depth)?
} else {
eval(graph, inner, expression, params, cypher_version)?
};
charge_growth(graph, before, &next)?;
if self.started_as_integer && matches!(next, Value::Float(_)) {
return Err(Error::ty(
"Invalid input 'FLOAT' for accumulator. Expected to be INTEGER.",
));
}
self.acc = next;
inner.insert(accumulator.to_string(), self.acc.clone());
match eval(graph, inner, predicate, params, cypher_version)? {
Value::Bool(false) => Ok(AllReduceStep::Failed),
Value::Bool(true) => Ok(AllReduceStep::Holds),
Value::Null => Ok(AllReduceStep::Null),
_ => Err(Error::ty("allReduce() predicate must be boolean")),
}
}
}
#[cfg(test)]
mod tests {
use relate_core::Value;
use crate::exec::test_support::exec_cypher;
use crate::graph::Graph;
fn single_value(cypher: &str) -> Value {
let rows = exec_cypher(&Graph::default(), cypher).rows;
assert_eq!(rows.len(), 1, "{cypher}: {rows:?}");
rows[0][0].clone()
}
#[test]
fn quantifiers_stop_at_the_deciding_element() {
for (cypher, expected) in [
(
"WITH [1, 0] AS xs RETURN any(x IN xs WHERE 1 / x = 1)",
true,
),
(
"WITH [1, 0] AS xs RETURN all(x IN xs WHERE 1 / x = 2)",
false,
),
(
"WITH [1, 0] AS xs RETURN none(x IN xs WHERE 1 / x = 1)",
false,
),
(
"WITH [1, 1, 0] AS xs RETURN single(x IN xs WHERE 1 / x = 1)",
false,
),
(
"WITH [1, 0] AS xs \
RETURN allReduce(acc = 0, x IN xs | acc + 1 / x, acc > 5)",
false,
),
] {
assert_eq!(single_value(cypher), Value::Bool(expected), "{cypher}");
}
let rows = exec_cypher(
&Graph::default(),
"WITH [1, 2, 3] AS xs RETURN any(x IN xs WHERE x = 1) AS hit, xs",
)
.rows;
assert_eq!(rows[0][0], Value::Bool(true));
assert_eq!(
rows[0][1],
Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)].into())
);
}
#[test]
fn quantifiers_scan_every_element_without_a_decision() {
for (cypher, expected) in [
(
"WITH [1, null, 3] AS xs RETURN any(x IN xs WHERE x > 5)",
Value::Null,
),
(
"WITH [1, 2, 3] AS xs RETURN all(x IN xs WHERE x > 0)",
Value::Bool(true),
),
(
"WITH [1, 2, 3] AS xs RETURN single(x IN xs WHERE x = 2)",
Value::Bool(true),
),
(
"WITH [1, 2, 3] AS xs \
RETURN allReduce(acc = 0, x IN xs | acc + x, acc < 10)",
Value::Bool(true),
),
] {
assert_eq!(single_value(cypher), expected, "{cypher}");
}
}
#[test]
fn hundred_thousand_row_list_building_reduce_completes() {
assert_eq!(
single_value("RETURN reduce(acc = 0, x IN range(1, 100000) | acc + size([x])) AS v"),
Value::Int(100000)
);
let wrapped = single_value("RETURN reduce(acc = [], x IN range(1, 3) | [acc]) AS v");
assert_eq!(wrapped.depth(), 4);
}
#[test]
fn wrap_fast_path_keeps_the_loop_bindings_for_the_predicate() {
for (cypher, expected) in [
(
"RETURN allReduce(acc = [], x IN [1, 2, 3] | [acc], x > 1) AS v",
Value::Bool(false),
),
(
"RETURN allReduce(acc = [], x IN [1, 2, 3] | [acc] + [], x > 1) AS v",
Value::Bool(false),
),
(
"RETURN allReduce(acc = [], x IN [1, 2, 3] | [acc], x > 0) AS v",
Value::Bool(true),
),
(
"RETURN allReduce(acc = [], x IN [1, 2, 3] | [acc] + [], x > 0) AS v",
Value::Bool(true),
),
(
"RETURN allReduce(acc = [], x IN [1, 2] | [acc], size(acc) = 1) AS v",
Value::Bool(true),
),
(
"RETURN allReduce(acc = [], x IN [1, 2] | [acc] + [], size(acc) = 1) AS v",
Value::Bool(true),
),
] {
assert_eq!(single_value(cypher), expected, "{cypher}");
}
}
#[test]
fn shared_fan_out_reduce_does_not_expand_exponentially() {
let value = single_value(
"RETURN reduce(acc = range(1, 10000), x IN range(1, 40) | [acc, acc]) AS v",
);
assert_eq!(value.depth(), 41);
}
}