use std::collections::BTreeMap;
use std::sync::Arc;
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};
pub(super) fn list_argument(value: Value, what: &str) -> Result<Option<Arc<Vec<Value>>>> {
match value {
Value::List(items) => Ok(Some(items)),
Value::Null => Ok(None),
_ => Err(Error::ty(what)),
}
}
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 } = ctx;
let Some(items) = list_argument(eval(graph, row, list, params)?, "quantifier needs a list")?
else {
return Ok(Value::Null);
};
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)?;
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 } = ctx;
let acc = eval(graph, row, initial, params)?;
let Some(items) = list_argument(eval(graph, row, list, params)?, "reduce() requires a list")?
else {
return Ok(Value::Null);
};
let mut fold = AllReduceFold::start(acc, accumulator, ident, expression);
let mut inner = row.clone();
for item in into_items(items) {
fold.advance(graph, &mut inner, &item, params)?;
}
Ok(fold.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 } = ctx;
let acc = eval(graph, row, initial, params)?;
let Some(items) = list_argument(
eval(graph, row, list, params)?,
"allReduce() requires a list",
)?
else {
return Ok(Value::Null);
};
let mut fold = AllReduceFold::start(acc, accumulator, ident, expression);
let mut saw_null = false;
let mut inner = row.clone();
for item in into_items(items) {
match fold.step(graph, &mut inner, &item, predicate, params)? {
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<'e> {
acc: Value,
started_as_integer: bool,
acc_depth: u32,
wrap_acc: bool,
acc_name: String,
ident_name: String,
expression: &'e Expr,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum AllReduceStep {
Holds,
Failed,
Null,
}
impl<'e> AllReduceFold<'e> {
pub(crate) fn start(
acc: Value,
accumulator: &SmallName,
ident: &SmallName,
expression: &'e Expr,
) -> Self {
Self {
started_as_integer: matches!(acc, Value::Int(_)),
acc_depth: acc.depth(),
wrap_acc: wraps_accumulator(expression, accumulator),
acc_name: accumulator.to_string(),
ident_name: ident.to_string(),
acc,
expression,
}
}
fn advance(
&mut self,
graph: &ExecGraph<'_>,
inner: &mut Row,
element: &Value,
params: &BTreeMap<String, Value>,
) -> Result<()> {
graph.cancel_tick()?;
let before = accumulator_allocation_bytes(&self.acc);
inner.insert(self.acc_name.clone(), self.acc.clone());
inner.insert(self.ident_name.clone(), 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, self.expression, params)?
};
charge_growth(graph, before, &next)?;
self.acc = next;
inner.insert(self.acc_name.clone(), self.acc.clone());
Ok(())
}
pub(crate) fn step(
&mut self,
graph: &ExecGraph<'_>,
inner: &mut Row,
element: &Value,
predicate: &Expr,
params: &BTreeMap<String, Value>,
) -> Result<AllReduceStep> {
self.advance(graph, inner, element, params)?;
if self.started_as_integer && matches!(self.acc, Value::Float(_)) {
return Err(Error::ty(
"Invalid input 'FLOAT' for accumulator. Expected to be INTEGER.",
));
}
match eval(graph, inner, predicate, params)? {
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);
}
}