use std::collections::BTreeMap;
use indexmap::map::Entry;
use indexmap::IndexMap;
use relate_core::{Error, NodeId, RelId, Result, Value};
use relate_ir::{Direction, NodePattern, PathPattern, Projection, RelPattern};
use relate_names::NamedToken;
use crate::eval::{binary, eval};
use crate::group_key::GroupKey;
use crate::hash_seed::{seeded_map, FxBuildHasher, IdMap, SeededMap};
use crate::overlay::{ExecGraph, RetainedTotal, SeatShape};
use crate::pattern_walk::{
binding, node_candidates, rel_props_ok, rel_variable_row_bound, Binding, NodeBinding,
};
use crate::row::Row;
use crate::store::RelTypes;
use super::super::candidates::node_ok;
use super::super::match_folds::FoldCtx;
use super::super::WalkTallies;
use super::plan::{compile_path, CountSeat, KeyPlan, PathPlan, PathPred};
use super::{
finish_folded_rows, fold_return, note_path_binding, project_ranked_row, CachedKey,
FoldedReturn, Rank, StreamAgg,
};
type Groups = IndexMap<Vec<GroupKey>, GroupSlot>;
type GroupSlot = (Vec<Value>, Vec<(CountSeat, StreamAgg)>);
type NodeCounts = IndexMap<NodeId, i64, FxBuildHasher>;
type NodeGroups = IndexMap<Vec<GroupKey>, (Vec<Value>, i64)>;
const NODE_COUNT_SLOT_BYTES: u64 = 40;
enum Accum {
PerBinding(Groups),
NodeCounted { slot: usize, counts: NodeCounts },
}
struct HopEnd {
start: NodeId,
end: NodeId,
rel: RelId,
}
struct FoldCaches {
props: IdMap<NodeId, SeededMap<String, Value>>,
keys: IdMap<NodeId, CachedKey>,
}
struct FoldEnv<'a> {
graph: &'a ExecGraph<'a>,
row: &'a Row,
params: &'a BTreeMap<String, Value>,
plan: &'a PathPlan,
caches: &'a mut FoldCaches,
accum: &'a mut Accum,
group_retained: &'a mut RetainedTotal,
preds: IdMap<(usize, NodeId), bool>,
tallies: &'a WalkTallies,
step_types: &'a [RelTypes],
}
struct HopWalk<'a> {
path: &'a PathPattern,
rel_idx: usize,
types: &'a RelTypes,
start_slot: usize,
end_slot: usize,
bound_start: Option<NodeId>,
bound_end: Option<NodeId>,
skip_rel: Option<RelId>,
}
fn path_pred_holds(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
pred: &PathPred,
id: NodeId,
) -> Result<bool> {
match pred {
PathPred::Null { key, is_null } => {
let value = graph.node_prop_resolved(id, key).unwrap_or(Value::Null);
Ok(value.is_null() == *is_null)
}
PathPred::Cmp { key, op, other } => {
let prop = graph.node_prop_resolved(id, key).unwrap_or(Value::Null);
let other = eval(graph, row, other, params)?;
Ok(binary(graph, *op, prop, other)?.truthy() == Some(true))
}
}
}
fn slot_preds_hold(env: &mut FoldEnv<'_>, slot: usize, id: NodeId) -> Result<bool> {
if let Some(&ok) = env.preds.get(&(slot, id)) {
return Ok(ok);
}
let mut ok = true;
for pred in &env.plan.conjuncts[slot].preds {
if !path_pred_holds(env.graph, env.row, env.params, pred, id)? {
ok = false;
break;
}
}
env.preds.insert((slot, id), ok);
Ok(ok)
}
fn accept_slot(
env: &mut FoldEnv<'_>,
node: &NodePattern,
slot: usize,
binding: NodeBinding<'_>,
id: NodeId,
) -> Result<bool> {
if !binding.accepts(&id) {
return Ok(false);
}
if !node_ok(env.graph, id, node, env.row, env.params)? {
return Ok(false);
}
slot_preds_hold(env, slot, id)
}
fn collect_neighbors(
env: &FoldEnv<'_>,
origin: NodeId,
rel: &RelPattern,
types: &RelTypes,
dir: Direction,
skip_rel: Option<RelId>,
out: &mut Vec<(RelId, NodeId)>,
) -> Result<()> {
out.clear();
let graph = env.graph;
graph.try_for_each_hop_resolved(origin, dir, types, |rid, id| {
graph.cancel_tick()?;
if skip_rel == Some(rid) {
return Ok::<(), Error>(());
}
env.tallies.walk();
if !rel_props_ok(graph, rid, rel, env.row, env.params)? {
return Ok::<(), Error>(());
}
out.push((rid, id));
Ok::<(), Error>(())
})?;
Ok(())
}
fn resolve_bound<'a>(over: Option<NodeId>, node: &'a NodePattern, row: &Row) -> NodeBinding<'a> {
match over {
Some(id) => Binding::Bound(id),
None => binding(node, row),
}
}
fn expand_hop(env: &mut FoldEnv<'_>, walk: &HopWalk<'_>) -> Result<Vec<HopEnd>> {
let start_node = &walk.path.nodes[walk.rel_idx];
let end_node = &walk.path.nodes[walk.rel_idx + 1];
let rel = &walk.path.rels[walk.rel_idx];
let start_binding = resolve_bound(walk.bound_start, start_node, env.row);
let end_binding = resolve_bound(walk.bound_end, end_node, env.row);
let start_side = HopSide {
node: start_node,
slot: walk.start_slot,
};
let end_side = HopSide {
node: end_node,
slot: walk.end_slot,
};
let (anchors, orientation) = match (start_binding, end_binding) {
(Binding::Mismatch, _) | (_, Binding::Mismatch) => return Ok(Vec::new()),
(Binding::Bound(start_id), end_binding) => (
vec![start_id],
HopOrientation::Forward {
anchor: start_side,
target: end_side,
bound_target: end_binding.bound_id(),
},
),
(_, Binding::Bound(end_id)) => (
vec![end_id],
HopOrientation::Reversed {
anchor: end_side,
target: start_side,
},
),
(_, _) => (
node_candidates(
env.graph,
start_node,
env.row,
env.params,
&env.plan.conjuncts[walk.start_slot].exprs,
)?,
HopOrientation::Forward {
anchor: start_side,
target: end_side,
bound_target: None,
},
),
};
walk_hop(
env,
HopRel {
pattern: rel,
types: walk.types,
skip: walk.skip_rel,
},
anchors,
orientation,
)
}
struct HopSide<'a> {
node: &'a NodePattern,
slot: usize,
}
struct HopRel<'a> {
pattern: &'a RelPattern,
types: &'a RelTypes,
skip: Option<RelId>,
}
enum HopOrientation<'a> {
Forward {
anchor: HopSide<'a>,
target: HopSide<'a>,
bound_target: Option<NodeId>,
},
Reversed {
anchor: HopSide<'a>,
target: HopSide<'a>,
},
}
impl HopOrientation<'_> {
fn traverse_dir(&self, rel: &RelPattern) -> Direction {
match self {
Self::Forward { .. } => rel.direction,
Self::Reversed { .. } => rel.direction.flip(),
}
}
fn roles(&self, anchor_id: NodeId, other_id: NodeId) -> (NodeId, NodeId) {
match self {
Self::Forward { .. } => (anchor_id, other_id),
Self::Reversed { .. } => (other_id, anchor_id),
}
}
fn bound_target(&self) -> Option<NodeId> {
match self {
Self::Forward { bound_target, .. } => *bound_target,
Self::Reversed { .. } => None,
}
}
}
fn walk_hop(
env: &mut FoldEnv<'_>,
rel: HopRel<'_>,
anchors: impl IntoIterator<Item = NodeId>,
orientation: HopOrientation<'_>,
) -> Result<Vec<HopEnd>> {
let (anchor, target) = match &orientation {
HopOrientation::Forward { anchor, target, .. } => (anchor, target),
HopOrientation::Reversed { anchor, target } => (anchor, target),
};
let self_loop = anchor.slot == target.slot;
let dir = orientation.traverse_dir(rel.pattern);
let mut hops = Vec::new();
let mut found = Vec::new();
let anchor_binding = binding(anchor.node, env.row);
for anchor_id in anchors {
env.graph.cancel_tick()?;
if !accept_slot(env, anchor.node, anchor.slot, anchor_binding, anchor_id)? {
continue;
}
let target_binding = resolve_bound(
orientation
.bound_target()
.or_else(|| self_loop.then_some(anchor_id)),
target.node,
env.row,
);
crate::ctx::phase_walk(|| {
collect_neighbors(
env,
anchor_id,
rel.pattern,
rel.types,
dir,
rel.skip,
&mut found,
)
})?;
for &(rid, other_id) in &found {
if accept_slot(env, target.node, target.slot, target_binding, other_id)? {
let (start, end) = orientation.roles(anchor_id, other_id);
hops.push(HopEnd {
start,
end,
rel: rid,
});
}
}
}
Ok(hops)
}
fn path_prop(
graph: &ExecGraph<'_>,
caches: &mut FoldCaches,
id: NodeId,
key: &NamedToken,
) -> Value {
let props = caches.props.entry(id).or_insert_with(seeded_map);
if let Some(found) = key.0.with_str(|text| props.get(text)) {
return found.clone();
}
let value = graph.node_prop_resolved(id, key).unwrap_or(Value::Null);
props.insert(key.0.to_string(), value.clone());
value
}
fn path_key(
graph: &ExecGraph<'_>,
plan: &PathPlan,
caches: &mut FoldCaches,
ids: &[NodeId],
) -> CachedKey {
key_vals(graph, plan, caches, |slot| ids[slot])
}
fn key_vals(
graph: &ExecGraph<'_>,
plan: &PathPlan,
caches: &mut FoldCaches,
node_of: impl Fn(usize) -> NodeId,
) -> CachedKey {
let vals: Vec<Value> = plan
.keys
.iter()
.map(|(slot, prop)| path_prop(graph, caches, node_of(*slot), prop))
.collect();
CachedKey::from_vals(vals)
}
impl CountSeat {
fn fresh_agg(&self) -> StreamAgg {
match self {
Self::Star => StreamAgg::count_star(),
Self::Prop { distinct, .. } | Self::Whole { distinct, .. } => {
StreamAgg::count_of(*distinct)
}
}
}
fn offer(
&self,
graph: &ExecGraph<'_>,
caches: &mut FoldCaches,
agg: &mut StreamAgg,
ids: &[NodeId],
retained: &mut crate::overlay::RetainedTotal,
) -> Result<()> {
match self {
Self::Star => agg.offer_value(None, graph, retained),
Self::Prop { slot, prop, .. } => agg.offer_value(
Some(&path_prop(graph, caches, ids[*slot], prop)),
graph,
retained,
),
Self::Whole { slot, .. } => {
agg.offer_value(Some(&Value::Int(ids[*slot])), graph, retained)
}
}
}
}
fn fresh_group_aggs(template: &[CountSeat]) -> Vec<(CountSeat, StreamAgg)> {
template
.iter()
.map(|seat| (seat.clone(), seat.fresh_agg()))
.collect()
}
fn offer_aggs(
graph: &ExecGraph<'_>,
caches: &mut FoldCaches,
pairs: &mut [(CountSeat, StreamAgg)],
ids: &[NodeId],
retained: &mut crate::overlay::RetainedTotal,
) -> Result<()> {
for (seat, agg) in pairs {
seat.offer(graph, caches, agg, ids, retained)?;
}
Ok(())
}
fn absorb(env: &mut FoldEnv<'_>, bindings: &[Option<NodeId>]) -> Result<()> {
let groups = match &mut *env.accum {
Accum::NodeCounted { slot, counts } => {
absorb_node_counted(
env.graph,
env.group_retained,
counts,
bound_slot(&bindings[*slot]),
)?;
note_path_binding();
return Ok(());
}
Accum::PerBinding(groups) => groups,
};
let ids: Vec<NodeId> = bindings.iter().map(bound_slot).collect();
let cached = match env.plan.key_plan {
KeyPlan::None => CachedKey::from_vals(Vec::new()),
KeyPlan::One(slot) | KeyPlan::NodeCounted(slot) => {
node_key(env.graph, env.plan, env.caches, ids[slot])
}
KeyPlan::Mixed => path_key(env.graph, env.plan, env.caches, &ids),
};
let entry = group_entry(
groups,
env.group_retained,
env.graph,
&env.plan.seats,
cached,
)?;
offer_aggs(
env.graph,
env.caches,
&mut entry.1,
&ids,
env.group_retained,
)?;
note_path_binding();
Ok(())
}
fn bound_slot(id: &Option<NodeId>) -> NodeId {
id.expect("every slot is bound when the walk completes")
}
fn node_key(
graph: &ExecGraph<'_>,
plan: &PathPlan,
caches: &mut FoldCaches,
id: NodeId,
) -> CachedKey {
if let Some(cached) = caches.keys.get(&id) {
return cached.clone();
}
let cached = key_vals(graph, plan, caches, |_| id);
caches.keys.insert(id, cached.clone());
cached
}
fn group_entry<'g>(
groups: &'g mut Groups,
retained: &mut RetainedTotal,
graph: &ExecGraph<'_>,
seats: &[CountSeat],
cached: CachedKey,
) -> Result<&'g mut GroupSlot> {
let map_slots = groups.len();
Ok(match groups.entry(cached.key) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
retained.add_group_landing(
graph,
map_slots,
entry.key(),
cached.vals.len(),
SeatShape::of::<(CountSeat, StreamAgg)>(seats.len()),
)?;
entry.insert((cached.vals, fresh_group_aggs(seats)))
}
})
}
fn absorb_node_counted(
graph: &ExecGraph<'_>,
retained: &mut RetainedTotal,
counts: &mut NodeCounts,
id: NodeId,
) -> Result<()> {
if let Some(count) = counts.get_mut(&id) {
*count += 1;
return Ok(());
}
if counts.len() == counts.capacity() {
let added = counts.capacity().max(4) as u64 * NODE_COUNT_SLOT_BYTES;
retained.add_bytes(graph, added)?;
}
counts.insert(id, 1);
Ok(())
}
fn collapse_node_counts(
graph: &ExecGraph<'_>,
plan: &PathPlan,
caches: &mut FoldCaches,
retained: &mut RetainedTotal,
counts: NodeCounts,
) -> Result<NodeGroups> {
let mut groups: NodeGroups = IndexMap::new();
for (id, count) in counts {
let cached = node_key(graph, plan, caches, id);
let slots = groups.len();
match groups.entry(cached.key) {
Entry::Occupied(entry) => entry.into_mut().1 += count,
Entry::Vacant(entry) => {
retained.add_group_landing(
graph,
slots,
entry.key(),
cached.vals.len(),
SeatShape::ZERO_SEATS,
)?;
entry.insert((cached.vals, count));
}
}
}
Ok(groups)
}
fn project_path_row(
items: &[Projection],
ranks: &[Rank],
key_vals: &[Value],
aggs: &[(CountSeat, StreamAgg)],
) -> Row {
project_ranked_row(items, ranks, key_vals, |agg| aggs[agg].1.finish())
}
fn fold_steps(
env: &mut FoldEnv<'_>,
patterns: &[PathPattern],
step_idx: usize,
skip_rel: Option<RelId>,
bindings: &mut [Option<NodeId>],
) -> Result<()> {
let Some(step) = env.plan.steps.get(step_idx) else {
return absorb(env, bindings);
};
let hops = expand_hop(
env,
&HopWalk {
path: &patterns[step.pattern],
rel_idx: step.rel,
types: &env.step_types[step_idx],
start_slot: step.start_slot,
end_slot: step.end_slot,
bound_start: bindings[step.start_slot],
bound_end: bindings[step.end_slot],
skip_rel,
},
)?;
for hop in hops {
let saved = (bindings[step.start_slot], bindings[step.end_slot]);
bindings[step.start_slot] = Some(hop.start);
bindings[step.end_slot] = Some(hop.end);
let deeper = fold_steps(env, patterns, step_idx + 1, Some(hop.rel), bindings);
bindings[step.start_slot] = saved.0;
bindings[step.end_slot] = saved.1;
deeper?;
}
Ok(())
}
fn any_rel_variable_row_bound(patterns: &[PathPattern], rows: &[Row]) -> bool {
patterns
.iter()
.flat_map(|path| &path.rels)
.any(|rel| rows.iter().any(|row| rel_variable_row_bound(rel, row)))
}
pub(crate) fn try_fold_path_aggs(ctx: &FoldCtx<'_>) -> Result<Option<FoldedReturn>> {
let (graph, rows, params) = (&ctx.graph, ctx.rows, ctx.params);
let (patterns, where_clause, suffix) = (ctx.patterns, ctx.where_clause, ctx.tail);
let Some(output) = fold_return(suffix, params) else {
return Ok(None);
};
let Some(plan) = compile_path(patterns, where_clause, output.items) else {
return Ok(None);
};
if any_rel_variable_row_bound(patterns, rows) {
return Ok(None);
}
let mut accum = match plan.key_plan {
KeyPlan::NodeCounted(slot) => Accum::NodeCounted {
slot,
counts: IndexMap::default(),
},
_ => Accum::PerBinding(IndexMap::new()),
};
let mut caches = FoldCaches {
props: IdMap::default(),
keys: IdMap::default(),
};
let tallies = WalkTallies::default();
let mut group_retained = graph.retain_bytes(0)?;
let step_types: Vec<RelTypes> = plan
.steps
.iter()
.map(|step| graph.rel_types_of(&patterns[step.pattern].rels[step.rel]))
.collect();
for row in rows {
let mut env = FoldEnv {
graph,
row,
params,
plan: &plan,
caches: &mut caches,
accum: &mut accum,
group_retained: &mut group_retained,
preds: IdMap::default(),
tallies: &tallies,
step_types: &step_types,
};
let mut bindings = vec![None; plan.nslots];
fold_steps(&mut env, patterns, 0, None, &mut bindings)?;
}
let out = match accum {
Accum::NodeCounted { counts, .. } => {
collapse_node_counts(graph, &plan, &mut caches, &mut group_retained, counts)?
.into_values()
.map(|(key_vals, count)| {
project_ranked_row(output.items, &plan.ranks, &key_vals, |_| Value::Int(count))
})
.collect()
}
Accum::PerBinding(mut groups) => {
if groups.is_empty() && matches!(plan.key_plan, KeyPlan::None) {
group_retained.add_group_landing(
graph,
0,
&[],
0,
SeatShape::of::<(CountSeat, StreamAgg)>(plan.seats.len()),
)?;
groups.insert(Vec::new(), (Vec::new(), fresh_group_aggs(&plan.seats)));
}
groups
.into_values()
.map(|(key_vals, aggs)| {
project_path_row(output.items, &plan.ranks, &key_vals, &aggs)
})
.collect()
}
};
Ok(Some(finish_folded_rows(graph, &output, out)?))
}