use std::collections::BTreeMap;
use indexmap::map::Entry;
use indexmap::IndexMap;
use relate_core::tokens::WorkspaceCharge;
use relate_core::{NodeId, Result, Value};
use relate_ir::{classify_aggregate, AggregateKind, Expr, NodePattern, PathPattern};
use crate::ctx::ExecCtx;
use crate::eval::bytecode::BATCH_ROWS;
use crate::eval::eval;
use crate::group_key::GroupKey;
use crate::hash_seed::IdMap;
use crate::overlay::{ExecGraph, RetainedTotal, SeatShape};
use crate::pattern_walk::{bind_node_stub, bind_rel_stub, rel_variable_row_bound};
use crate::row::Row;
use super::agg_fold::{
finish_folded_rows, fold_return, note_path_binding, project_ranked_row, FoldedReturn, Rank,
};
use super::kernels::matcher::{self, Chain};
use super::kernels::scan_segment;
use super::match_folds::FoldCtx;
use super::morsel_agg_types::{classify_agg, classify_key, AggAccum, AggSpec, KeySpec};
use super::morsel_pipeline::{MorselChunk, MorselSink, PipelineRunner};
use super::pushdown::{flatten_and_owned, match_scope, Residual};
enum SinkStorage {
Ungrouped {
accs: Vec<AggAccum>,
},
SingleNode {
slot: usize,
needs_post_merge: bool,
groups: IdMap<NodeId, Vec<AggAccum>>,
node_order: Vec<NodeId>,
},
General {
groups: IndexMap<Vec<GroupKey>, (Vec<Value>, Vec<AggAccum>)>,
},
}
fn single_node_key_slot(key_specs: &[KeySpec], agg_specs: &[AggSpec]) -> Option<(usize, bool)> {
if key_specs.is_empty() {
return None;
}
let first_slot = match key_specs[0] {
KeySpec::Node(s) | KeySpec::NodeProp(s, _) => s,
KeySpec::Rel(_) => return None,
};
let mut has_node = false;
for key in key_specs {
match key {
KeySpec::Node(s) if *s == first_slot => {
has_node = true;
}
KeySpec::NodeProp(s, _) if *s == first_slot => {}
_ => return None,
}
}
if has_node {
Some((first_slot, false))
} else if agg_specs.iter().all(|agg| !agg.is_distinct()) {
Some((first_slot, true))
} else {
None
}
}
struct AggregateSink<'a> {
graph: &'a ExecGraph<'a>,
chain: &'a Chain<'a>,
params: &'a BTreeMap<String, Value>,
key_specs: Vec<KeySpec>,
agg_specs: Vec<AggSpec>,
storage: SinkStorage,
bound_nodes: Vec<Option<NodeId>>,
scratch_keys: Vec<Vec<Option<Value>>>,
scratch_aggs: Vec<Vec<Option<Value>>>,
_charge: WorkspaceCharge,
group_retained: RetainedTotal,
}
impl<'a> AggregateSink<'a> {
fn new(
graph: &'a ExecGraph<'a>,
chain: &'a Chain<'a>,
params: &'a BTreeMap<String, Value>,
key_specs: Vec<KeySpec>,
agg_specs: Vec<AggSpec>,
nslots: usize,
) -> Result<Self> {
let mut group_retained = graph.retain_bytes(0)?;
let storage = if key_specs.is_empty() {
group_retained.add_group_landing(
graph,
0,
&[],
0,
SeatShape::of::<AggAccum>(agg_specs.len()),
)?;
SinkStorage::Ungrouped {
accs: agg_specs.iter().map(AggAccum::new).collect(),
}
} else if let Some((slot, needs_post_merge)) = single_node_key_slot(&key_specs, &agg_specs)
{
SinkStorage::SingleNode {
slot,
needs_post_merge,
groups: IdMap::default(),
node_order: Vec::new(),
}
} else {
SinkStorage::General {
groups: IndexMap::new(),
}
};
let is_single_node = matches!(storage, SinkStorage::SingleNode { .. });
let mut buf_bytes: u64 = 0;
let mut scratch_keys = Vec::with_capacity(key_specs.len());
for key in &key_specs {
if !is_single_node && matches!(key, KeySpec::NodeProp(_, _)) {
scratch_keys.push(vec![None; BATCH_ROWS]);
buf_bytes += crate::workspace::value_buffer_bytes(BATCH_ROWS);
} else {
scratch_keys.push(Vec::new());
}
}
let mut scratch_aggs = Vec::with_capacity(agg_specs.len());
for agg in &agg_specs {
match agg {
AggSpec::CountNodeProp { .. }
| AggSpec::SumNodeProp { .. }
| AggSpec::AvgNodeProp { .. }
| AggSpec::MinNodeProp { .. }
| AggSpec::MaxNodeProp { .. }
| AggSpec::CollectNodeProp { .. } => {
scratch_aggs.push(vec![None; BATCH_ROWS]);
buf_bytes += crate::workspace::value_buffer_bytes(BATCH_ROWS);
}
_ => {
scratch_aggs.push(Vec::new());
}
}
}
let _charge = WorkspaceCharge::retain(buf_bytes)?;
Ok(Self {
graph,
chain,
params,
key_specs,
agg_specs,
storage,
bound_nodes: vec![None; nslots],
scratch_keys,
scratch_aggs,
_charge,
group_retained,
})
}
fn set_bound_nodes(&mut self, bound: Vec<Option<NodeId>>) {
self.bound_nodes = bound;
}
fn fetch_batches(&mut self, chunk: &MorselChunk) {
let chunk_len = chunk.len();
if !matches!(self.storage, SinkStorage::SingleNode { .. }) {
for (idx, key) in self.key_specs.iter().enumerate() {
if let KeySpec::NodeProp(slot, prop) = key {
self.graph.node_prop_batch(
&chunk.nodes[*slot],
prop,
&mut self.scratch_keys[idx][0..chunk_len],
);
}
}
}
for (idx, agg) in self.agg_specs.iter().enumerate() {
let (slot, prop) = match agg {
AggSpec::CountNodeProp { slot, prop, .. }
| AggSpec::SumNodeProp { slot, prop, .. }
| AggSpec::AvgNodeProp { slot, prop, .. }
| AggSpec::MinNodeProp { slot, prop }
| AggSpec::MaxNodeProp { slot, prop }
| AggSpec::CollectNodeProp { slot, prop, .. } => (*slot, prop),
_ => continue,
};
self.graph.node_prop_batch(
&chunk.nodes[slot],
prop,
&mut self.scratch_aggs[idx][0..chunk_len],
);
}
}
}
struct FeedCtx<'a> {
graph: &'a ExecGraph<'a>,
chain: &'a Chain<'a>,
params: &'a BTreeMap<String, Value>,
agg_specs: &'a [AggSpec],
scratch_aggs: &'a [Vec<Option<Value>>],
}
fn feed_aggs(
ctx: &FeedCtx<'_>,
chunk: &MorselChunk,
r: usize,
aggs: &mut [AggAccum],
group_retained: &mut RetainedTotal,
) -> Result<()> {
for (idx, spec) in ctx.agg_specs.iter().enumerate() {
match spec {
AggSpec::CountStar => {
if let AggAccum::CountStar(n) = &mut aggs[idx] {
*n += 1;
}
}
AggSpec::CountNode { slot, .. } => {
let id = chunk.nodes[*slot][r];
aggs[idx].offer_node(ctx.graph, id, group_retained)?;
}
AggSpec::CountRel { slot, .. } => {
let id = chunk.rels[*slot][r];
aggs[idx].offer_rel(ctx.graph, id, group_retained)?;
}
AggSpec::CollectNode { slot, .. } => {
let id = chunk.nodes[*slot][r];
let stub = bind_node_stub(ctx.graph, id);
aggs[idx].offer_val(ctx.graph, &stub, group_retained)?;
}
AggSpec::CountNodeProp { .. }
| AggSpec::SumNodeProp { .. }
| AggSpec::AvgNodeProp { .. }
| AggSpec::MinNodeProp { .. }
| AggSpec::MaxNodeProp { .. }
| AggSpec::CollectNodeProp { .. } => {
let val = ctx.scratch_aggs[idx][r].as_ref().unwrap_or(&Value::Null);
aggs[idx].offer_val(ctx.graph, val, group_retained)?;
}
AggSpec::CountExpr { expr, .. } => {
let mut scratch_row = Row::new();
if let Some(v) = ctx.chain.start.pattern.variable.as_ref() {
scratch_row.insert(v.to_string(), bind_node_stub(ctx.graph, chunk.nodes[0][r]));
}
for (j, hop) in ctx.chain.hops.iter().enumerate() {
if let Some(v) = hop.rel.variable.as_ref() {
scratch_row
.insert(v.to_string(), bind_rel_stub(ctx.graph, chunk.rels[j][r]));
}
if let Some(v) = hop.target.pattern.variable.as_ref() {
scratch_row.insert(
v.to_string(),
bind_node_stub(ctx.graph, chunk.nodes[j + 1][r]),
);
}
}
let val = eval(ctx.graph, &scratch_row, expr, ctx.params)?;
aggs[idx].offer_val(ctx.graph, &val, group_retained)?;
}
}
}
Ok(())
}
impl MorselSink for AggregateSink<'_> {
fn consume(&mut self, ctx: ExecCtx<'_>, chunk: &MorselChunk) -> Result<()> {
let chunk_len = chunk.len();
if chunk_len == 0 {
return Ok(());
}
self.fetch_batches(chunk);
let feed_ctx = FeedCtx {
graph: self.graph,
chain: self.chain,
params: self.params,
agg_specs: &self.agg_specs,
scratch_aggs: &self.scratch_aggs,
};
for r in 0..chunk_len {
ctx.graph.cancel_tick()?;
let mut skip = false;
for (slot, bound) in self.bound_nodes.iter().enumerate() {
if let Some(target_id) = bound {
if chunk.nodes[slot][r] != *target_id {
skip = true;
break;
}
}
}
if skip {
continue;
}
note_path_binding();
match &mut self.storage {
SinkStorage::Ungrouped { accs } => {
feed_aggs(&feed_ctx, chunk, r, accs, &mut self.group_retained)?;
}
SinkStorage::SingleNode {
slot,
groups,
node_order,
..
} => {
let node = chunk.nodes[*slot][r];
if !groups.contains_key(&node) {
let key = [GroupKey::new(&Value::Int(node))];
self.group_retained.add_group_landing(
self.graph,
groups.len(),
&key,
1,
SeatShape::of::<AggAccum>(self.agg_specs.len()),
)?;
node_order.push(node);
}
let accs = groups
.entry(node)
.or_insert_with(|| self.agg_specs.iter().map(AggAccum::new).collect());
feed_aggs(&feed_ctx, chunk, r, accs, &mut self.group_retained)?;
}
SinkStorage::General { groups } => {
let mut vals = Vec::with_capacity(self.key_specs.len());
for (k_idx, key) in self.key_specs.iter().enumerate() {
let val = match key {
KeySpec::Node(slot) => {
bind_node_stub(self.graph, chunk.nodes[*slot][r])
}
KeySpec::Rel(slot) => bind_rel_stub(self.graph, chunk.rels[*slot][r]),
KeySpec::NodeProp(_, _) => {
self.scratch_keys[k_idx][r].clone().unwrap_or(Value::Null)
}
};
vals.push(val);
}
let group_keys: Vec<GroupKey> = vals.iter().map(GroupKey::new).collect();
if !groups.contains_key(&group_keys) {
let map_slots = groups.len();
self.group_retained.add_group_landing(
self.graph,
map_slots,
&group_keys,
vals.len(),
SeatShape::of::<AggAccum>(self.agg_specs.len()),
)?;
}
let entry = match groups.entry(group_keys) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let fresh: Vec<AggAccum> =
self.agg_specs.iter().map(AggAccum::new).collect();
entry.insert((vals, fresh))
}
};
feed_aggs(&feed_ctx, chunk, r, &mut entry.1, &mut self.group_retained)?;
}
}
}
Ok(())
}
}
fn push_missing<T: PartialEq + Clone>(dst: &mut Vec<T>, src: &[T]) {
for item in src {
if !dst.contains(item) {
dst.push(item.clone());
}
}
}
fn merge_nodes(n0: &NodePattern, n1: &NodePattern) -> Option<NodePattern> {
if n0.where_clause.is_some() || n1.where_clause.is_some() {
return None;
}
let properties = match (&n0.properties, &n1.properties) {
(None, None) => None,
(Some(p), None) => Some(p.clone()),
(None, Some(p)) => Some(p.clone()),
(Some(_), Some(_)) => return None,
};
let mut labels = n0.labels.clone();
push_missing(&mut labels, &n1.labels);
let mut prop_keys = n0.prop_keys.clone();
push_missing(&mut prop_keys, &n1.prop_keys);
let label_expr = match (&n0.label_expr, &n1.label_expr) {
(None, None) => None,
(Some(e), None) => Some(e.clone()),
(None, Some(e)) => Some(e.clone()),
(Some(e0), Some(e1)) if e0 == e1 => Some(e0.clone()),
(Some(e0), Some(e1)) => Some(relate_ir::LabelExpr::And(vec![e0.clone(), e1.clone()])),
};
Some(NodePattern {
variable: n0.variable.clone().or_else(|| n1.variable.clone()),
labels,
label_expr,
properties,
prop_keys,
where_clause: None,
force_scan: n0.force_scan || n1.force_scan,
})
}
fn merge_two_one_hop_patterns(patterns: &[PathPattern]) -> Option<PathPattern> {
if patterns.len() != 2 {
return None;
}
let p0 = &patterns[0];
let p1 = &patterns[1];
if p0.rels.len() != 1 || p1.rels.len() != 1 || p0.nodes.len() != 2 || p1.nodes.len() != 2 {
return None;
}
let n0_0 = p0.nodes[0].variable.as_ref();
let n0_1 = p0.nodes[1].variable.as_ref();
let n1_0 = p1.nodes[0].variable.as_ref();
let n1_1 = p1.nodes[1].variable.as_ref();
let m_00 = n0_0.is_some() && n0_0 == n1_0;
let m_01 = n0_0.is_some() && n0_0 == n1_1;
let m_10 = n0_1.is_some() && n0_1 == n1_0;
let m_11 = n0_1.is_some() && n0_1 == n1_1;
if (m_00 as usize + m_01 as usize + m_10 as usize + m_11 as usize) != 1 {
return None;
}
if m_10 {
let shared = merge_nodes(&p0.nodes[1], &p1.nodes[0])?;
let mut merged = p0.clone();
merged.elements.clear();
merged.nodes[1] = shared;
merged.nodes.push(p1.nodes[1].clone());
merged.rels.push(p1.rels[0].clone());
return Some(merged);
}
if m_11 {
let shared = merge_nodes(&p0.nodes[1], &p1.nodes[1])?;
let mut merged = p0.clone();
merged.elements.clear();
merged.nodes[1] = shared;
merged.nodes.push(p1.nodes[0].clone());
let mut r1 = p1.rels[0].clone();
r1.direction = r1.direction.flip();
merged.rels.push(r1);
return Some(merged);
}
if m_00 {
let shared = merge_nodes(&p0.nodes[0], &p1.nodes[0])?;
let mut merged = PathPattern {
nodes: vec![p0.nodes[1].clone(), shared, p1.nodes[1].clone()],
rels: vec![
{
let mut r0 = p0.rels[0].clone();
r0.direction = r0.direction.flip();
r0
},
p1.rels[0].clone(),
],
..p0.clone()
};
merged.elements.clear();
return Some(merged);
}
if m_01 {
let shared = merge_nodes(&p0.nodes[0], &p1.nodes[1])?;
let mut merged = p1.clone();
merged.elements.clear();
merged.nodes[1] = shared;
merged.nodes.push(p0.nodes[1].clone());
merged.rels.push(p0.rels[0].clone());
return Some(merged);
}
None
}
fn any_rel_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_morsel_agg(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);
if crate::exec::hash_join_cross::cross_clause_hash_join_eligible_and_pays(
graph,
rows,
patterns,
where_clause,
params,
) {
return Ok(None);
}
let Some(output) = fold_return(suffix, params) else {
return Ok(None);
};
if any_rel_bound(patterns, rows) {
return Ok(None);
}
if patterns.iter().any(|p| p.has_path_name()) {
return Ok(None);
}
if patterns.iter().any(|p| p.rels.iter().any(|r| r.var_length)) {
return Ok(None);
}
let (hop_count, is_comma) = match patterns.len() {
1 => (patterns[0].rels.len(), false),
2 => (2, true),
_ => return Ok(None),
};
if hop_count > 2 {
return Ok(None);
}
if hop_count == 2 || is_comma {
if output.items.iter().any(|item| {
if !crate::eval::is_agg_expr(&item.expr) {
return false;
}
match &item.expr {
Expr::CountStar => false,
Expr::Function { name, .. } => {
name.with_str(classify_aggregate) != Some(AggregateKind::Count)
}
_ => true,
}
}) {
return Ok(None);
}
}
let single_pattern: Option<PathPattern> = match patterns.len() {
1 => {
let unrolled = matcher::chain_spelling(patterns);
unrolled.first().cloned()
}
2 => merge_two_one_hop_patterns(patterns),
_ => None,
};
let Some(path) = single_pattern else {
return Ok(None);
};
let conjuncts = where_clause.map(flatten_and_owned).unwrap_or_default();
let Some(chain) = matcher::compile_chain(&path, &conjuncts) else {
return Ok(None);
};
let mut key_specs = Vec::new();
let mut agg_specs = Vec::new();
let mut ranks = Vec::with_capacity(output.items.len());
for item in output.items {
if crate::eval::is_agg_expr(&item.expr) {
let Some(spec) = classify_agg(&chain, &item.expr) else {
return Ok(None);
};
ranks.push(Rank::Agg(agg_specs.len()));
agg_specs.push(spec);
} else {
let Some(spec) = classify_key(&chain, &item.expr) else {
return Ok(None);
};
ranks.push(Rank::Key(key_specs.len()));
key_specs.push(spec);
}
}
let nslots = chain.hops.len() + 1;
let mut sink = AggregateSink::new(graph, &chain, params, key_specs, agg_specs, nslots)?;
if rows.is_empty() {
let out = match sink.storage {
SinkStorage::Ungrouped { accs, .. } => {
let finished: Result<Vec<Value>> = accs.into_iter().map(|a| a.finish()).collect();
let vals = finished?;
vec![project_ranked_row(output.items, &ranks, &[], |a| {
vals[a].clone()
})]
}
SinkStorage::SingleNode { .. } | SinkStorage::General { .. } => Vec::new(),
};
return Ok(Some(finish_folded_rows(graph, &output, out)?));
}
let exec_ctx = ExecCtx::new(graph, params);
let mut runner = PipelineRunner::new(exec_ctx, &chain)?;
for row in rows {
let mut bound_nodes = vec![None; nslots];
let mut row_mismatch = false;
if let Some(var) = chain.start.pattern.variable.as_ref() {
var.with_str(|s| {
if let Some(val) = row.get(s) {
if let Value::Node(n) = val {
bound_nodes[0] = Some(n.id);
} else {
row_mismatch = true;
}
}
});
}
for (j, hop) in chain.hops.iter().enumerate() {
if let Some(var) = hop.target.pattern.variable.as_ref() {
var.with_str(|s| {
if let Some(val) = row.get(s) {
if let Value::Node(n) = val {
bound_nodes[j + 1] = Some(n.id);
} else {
row_mismatch = true;
}
}
});
}
}
if row_mismatch {
continue;
}
let starts = if let Some(start_id) = bound_nodes[0] {
vec![start_id]
} else {
let compiled_slice = std::slice::from_ref(&path);
let residual = Residual {
conjuncts: &conjuncts,
scope: &match_scope(graph, row, compiled_slice),
};
scan_segment(exec_ctx, &chain.start, &residual)?
};
if starts.is_empty() {
continue;
}
sink.set_bound_nodes(bound_nodes);
runner.execute(starts, &chain.start, &mut sink)?;
}
let AggregateSink {
storage,
mut group_retained,
key_specs,
agg_specs,
..
} = sink;
let out: Vec<Row> = match storage {
SinkStorage::Ungrouped { accs } => {
let finished: Result<Vec<Value>> = accs.into_iter().map(|a| a.finish()).collect();
let vals = finished?;
vec![project_ranked_row(output.items, &ranks, &[], |a| {
vals[a].clone()
})]
}
SinkStorage::SingleNode {
needs_post_merge,
groups,
node_order,
..
} => {
let mut rows = Vec::new();
finish_single_node(
graph,
output.items,
&ranks,
&key_specs,
agg_specs.len(),
needs_post_merge,
groups,
node_order,
&mut group_retained,
&mut rows,
)?;
rows
}
SinkStorage::General { groups } => {
let mut rows = Vec::with_capacity(groups.len());
for (key_vals, accs) in groups.into_values() {
let finished: Result<Vec<Value>> = accs.into_iter().map(|a| a.finish()).collect();
let vals = finished?;
rows.push(project_ranked_row(output.items, &ranks, &key_vals, |a| {
vals[a].clone()
}));
}
rows
}
};
Ok(Some(finish_folded_rows(graph, &output, out)?))
}
fn for_each_single_node_group(
graph: &ExecGraph<'_>,
key_specs: &[KeySpec],
node_order: &[NodeId],
mut groups: IdMap<NodeId, Vec<AggAccum>>,
mut yield_group: impl FnMut(Vec<Value>, Vec<AggAccum>) -> Result<()>,
) -> Result<()> {
let mut prop_bufs: Vec<Vec<Option<Value>>> = key_specs
.iter()
.map(|k| {
if matches!(k, KeySpec::NodeProp(_, _)) {
vec![None; BATCH_ROWS]
} else {
Vec::new()
}
})
.collect();
for chunk_ids in node_order.chunks(BATCH_ROWS) {
let chunk_len = chunk_ids.len();
for (k_idx, key) in key_specs.iter().enumerate() {
if let KeySpec::NodeProp(_, prop) = key {
graph.node_prop_batch(chunk_ids, prop, &mut prop_bufs[k_idx][..chunk_len]);
}
}
for (i, node_id) in chunk_ids.iter().enumerate() {
let accs = groups
.remove(node_id)
.expect("node_order only records keys inserted into groups");
let mut key_vals = Vec::with_capacity(key_specs.len());
for (k_idx, key) in key_specs.iter().enumerate() {
let val = match key {
KeySpec::Node(_) => bind_node_stub(graph, *node_id),
KeySpec::NodeProp(_, _) => prop_bufs[k_idx][i].take().unwrap_or(Value::Null),
KeySpec::Rel(_) => unreachable!("Rel key not allowed in SingleNode"),
};
key_vals.push(val);
}
yield_group(key_vals, accs)?;
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn finish_single_node(
graph: &ExecGraph<'_>,
output_items: &[relate_ir::Projection],
ranks: &[Rank],
key_specs: &[KeySpec],
agg_specs_len: usize,
needs_post_merge: bool,
groups: IdMap<NodeId, Vec<AggAccum>>,
node_order: Vec<NodeId>,
retained: &mut RetainedTotal,
rows: &mut Vec<Row>,
) -> Result<()> {
if groups.is_empty() {
return Ok(());
}
if !needs_post_merge {
rows.reserve(node_order.len());
for_each_single_node_group(graph, key_specs, &node_order, groups, |key_vals, accs| {
let finished: Result<Vec<Value>> = accs.into_iter().map(|a| a.finish()).collect();
let vals = finished?;
rows.push(project_ranked_row(output_items, ranks, &key_vals, |a| {
vals[a].clone()
}));
Ok(())
})?;
} else {
let mut merged: IndexMap<Vec<GroupKey>, (Vec<Value>, Vec<AggAccum>)> =
IndexMap::with_capacity(node_order.len());
for_each_single_node_group(graph, key_specs, &node_order, groups, |key_vals, accs| {
let group_keys: Vec<GroupKey> = key_vals.iter().map(GroupKey::new).collect();
if !merged.contains_key(&group_keys) {
let map_slots = merged.len();
retained.add_group_landing(
graph,
map_slots,
&group_keys,
key_vals.len(),
SeatShape::of::<AggAccum>(agg_specs_len),
)?;
}
match merged.entry(group_keys) {
Entry::Occupied(mut entry) => {
let (_, existing_accs) = entry.get_mut();
for (a, b) in existing_accs.iter_mut().zip(accs) {
a.merge_from(b, retained, graph)?;
}
}
Entry::Vacant(entry) => {
entry.insert((key_vals, accs));
}
}
Ok(())
})?;
rows.reserve(merged.len());
for (key_vals, accs) in merged.into_values() {
let finished: Result<Vec<Value>> = accs.into_iter().map(|a| a.finish()).collect();
let vals = finished?;
rows.push(project_ranked_row(output_items, ranks, &key_vals, |a| {
vals[a].clone()
}));
}
}
Ok(())
}