use std::collections::HashSet;
use relate_core::tokens::WorkspaceCharge;
use relate_core::{Error, NodeId, RelId, Result, Value};
use relate_ir::{var_prop_named, Direction};
use relate_names::NamedToken;
use crate::ctx::ExecCtx;
use crate::eval::bytecode::{PreparedBytecode, SelectionMask, BATCH_ROWS};
use crate::exec::agg_fold::FoldedReturn;
use crate::exec::chunk::{Chunk, Column};
use crate::exec::kernels::count_entry::CountEntry;
use crate::exec::kernels::matcher::Chain;
use crate::exec::kernels::memo::MemoState;
use crate::exec::kernels::program::{InternedLabels, NodeTarget};
use crate::exec::kernels::{chain_stages_fit, count_fold_tail, KernelMode, KernelOutput};
use crate::exec::match_folds::FoldCtx;
use crate::exec::WalkTallies;
use crate::pattern_walk::{bind_node_stub, bind_rel_stub};
use crate::row::Row;
use crate::store::RelTypes;
#[derive(Clone, Debug)]
pub(crate) struct MorselChunk {
pub(crate) nodes: Vec<Vec<NodeId>>,
pub(crate) rels: Vec<Vec<RelId>>,
}
impl MorselChunk {
pub(crate) fn with_hops(k: usize) -> Self {
let mut nodes = Vec::with_capacity(k + 1);
for _ in 0..=k {
nodes.push(Vec::with_capacity(BATCH_ROWS));
}
let mut rels = Vec::with_capacity(k);
for _ in 0..k {
rels.push(Vec::with_capacity(BATCH_ROWS));
}
Self { nodes, rels }
}
#[inline]
pub(crate) fn len(&self) -> usize {
self.nodes[0].len()
}
#[inline]
pub(crate) fn is_full(&self) -> bool {
self.len() >= BATCH_ROWS
}
#[inline]
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(crate) fn clear(&mut self) {
for col in &mut self.nodes {
col.clear();
}
for col in &mut self.rels {
col.clear();
}
}
#[inline]
pub(crate) fn push_step(
&mut self,
input: &MorselChunk,
r: usize,
j: usize,
rid: RelId,
arrival: NodeId,
) {
for slot in 0..=j {
self.nodes[slot].push(input.nodes[slot][r]);
}
self.nodes[j + 1].push(arrival);
for slot in 0..j {
self.rels[slot].push(input.rels[slot][r]);
}
self.rels[j].push(rid);
}
pub(crate) fn compact_with_mask(
&mut self,
mask: &SelectionMask,
active_nodes: usize,
active_rels: usize,
) {
let mut write_idx = 0;
let count = self.len();
for read_idx in 0..count {
if mask.is_set(read_idx) {
if write_idx != read_idx {
for slot in 0..active_nodes {
self.nodes[slot][write_idx] = self.nodes[slot][read_idx];
}
for slot in 0..active_rels {
self.rels[slot][write_idx] = self.rels[slot][read_idx];
}
}
write_idx += 1;
}
}
for slot in 0..active_nodes {
self.nodes[slot].truncate(write_idx);
}
for slot in 0..active_rels {
self.rels[slot].truncate(write_idx);
}
}
}
#[inline]
fn lineage_contains(chunk: &MorselChunk, r: usize, j: usize, rid: RelId) -> bool {
(0..j).any(|slot| chunk.rels[slot][r] == rid)
}
pub(crate) struct PreparedNodeFilter<'a> {
pub(crate) labels: InternedLabels<'a>,
pub(crate) bytecode: Option<PreparedBytecode<'a>>,
pub(crate) memo: Option<MemoState<()>>,
}
impl<'a> PreparedNodeFilter<'a> {
pub(crate) fn prepare(ctx: ExecCtx<'_>, target: &'a NodeTarget<'a>) -> Result<Self> {
let labels = InternedLabels::resolve(ctx, target.pattern);
let bytecode = target
.bytecode
.as_ref()
.map(|code| code.prepare(ctx))
.transpose()?;
let memo = if target.bytecode.is_none() && !target.unfiltered() {
Some(MemoState::new((), ctx.graph))
} else {
None
};
Ok(Self {
labels,
bytecode,
memo,
})
}
#[inline]
pub(crate) fn filter_batch(
&mut self,
ctx: ExecCtx<'_>,
nodes: &[NodeId],
mask: &mut SelectionMask,
) -> Result<()> {
let graph = ctx.graph;
if let Some(memo) = &mut self.memo {
for (i, &node) in nodes.iter().enumerate() {
if mask.is_set(i) {
let admits = memo.answer(graph, node, || {
if !self.labels.admits(graph, node) {
return Ok(false);
}
Ok(true)
})?;
if !admits {
mask.clear(i);
}
}
}
} else {
for (i, &node) in nodes.iter().enumerate() {
if mask.is_set(i) && !self.labels.admits(graph, node) {
mask.clear(i);
}
}
if let Some(bc) = &mut self.bytecode {
if mask.count_ones(nodes.len()) > 0 {
bc.eval_batch(ctx, nodes, mask)?;
}
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Binding {
Start,
Rel(usize),
Node(usize),
}
fn binding_value(ctx: ExecCtx<'_>, chunk: &MorselChunk, r: usize, binding: Binding) -> Value {
let graph = ctx.graph;
match binding {
Binding::Start => bind_node_stub(graph, chunk.nodes[0][r]),
Binding::Rel(j) => bind_rel_stub(graph, chunk.rels[j][r]),
Binding::Node(j) => bind_node_stub(graph, chunk.nodes[j + 1][r]),
}
}
fn named_bindings(chain: &Chain<'_>) -> Vec<(String, Binding)> {
let mut named = Vec::new();
let mut seen = HashSet::new();
if let Some(var) = chain.start.pattern.variable.as_ref() {
let name = var.to_string();
if seen.insert(name.clone()) {
named.push((name, Binding::Start));
}
}
for (j, hop) in chain.hops.iter().enumerate() {
if let Some(var) = hop.rel.variable.as_ref() {
let name = var.to_string();
if seen.insert(name.clone()) {
named.push((name, Binding::Rel(j)));
}
}
if let Some(var) = hop.target.pattern.variable.as_ref() {
let name = var.to_string();
if seen.insert(name.clone()) {
named.push((name, Binding::Node(j)));
}
}
}
named
}
pub(crate) trait MorselSink {
fn halted(&self) -> bool {
false
}
fn remaining_want(&self) -> Option<usize> {
None
}
fn consume(&mut self, ctx: ExecCtx<'_>, chunk: &MorselChunk) -> Result<()>;
}
pub(crate) enum SinkMode {
Count {
tally: u64,
},
Rows {
halt: Option<usize>,
names: Vec<String>,
bindings: Vec<Binding>,
rows: Vec<Row>,
},
Exists {
counted: Option<(usize, NamedToken)>,
hit: bool,
},
}
impl MorselSink for SinkMode {
#[inline]
fn halted(&self) -> bool {
match self {
Self::Count { .. } => false,
Self::Rows { halt, rows, .. } => halt.is_some_and(|want| rows.len() >= want),
Self::Exists { hit, .. } => *hit,
}
}
#[inline]
fn remaining_want(&self) -> Option<usize> {
match self {
Self::Rows {
halt: Some(want),
rows,
..
} => Some(want.saturating_sub(rows.len())),
Self::Exists { hit: false, .. } => Some(1),
_ => None,
}
}
fn consume(&mut self, ctx: ExecCtx<'_>, chunk: &MorselChunk) -> Result<()> {
let chunk_len = chunk.len();
match self {
Self::Count { tally } => {
*tally += chunk_len as u64;
}
Self::Rows {
halt,
names,
bindings,
rows,
} => {
if names.is_empty() {
let to_add = if let Some(want) = *halt {
(want - rows.len()).min(chunk_len)
} else {
chunk_len
};
for _ in 0..to_add {
ctx.graph.cancel_tick()?;
rows.push(Row::new());
}
} else {
let mut chunk_cols: Vec<Vec<Value>> =
vec![Vec::with_capacity(chunk_len); names.len()];
for r in 0..chunk_len {
ctx.graph.cancel_tick()?;
if halt.is_some_and(|want| rows.len() + chunk_cols[0].len() >= want) {
break;
}
for (col_idx, binding) in bindings.iter().enumerate() {
chunk_cols[col_idx].push(binding_value(ctx, chunk, r, *binding));
}
}
if !chunk_cols[0].is_empty() {
let cols: Vec<Column> =
chunk_cols.iter().map(|c| Column::from_values(c)).collect();
let decoded = Chunk::from_columns(names, cols).to_rows();
rows.extend(decoded);
}
}
}
Self::Exists { counted, hit } => {
if let Some((slot, key)) = counted {
for r in 0..chunk_len {
ctx.graph.cancel_tick()?;
let node = chunk.nodes[*slot][r];
if matches!(
ctx.graph.node_prop_resolved(node, key),
Some(v) if !v.is_null()
) {
*hit = true;
break;
}
}
} else if chunk_len > 0 {
*hit = true;
}
}
}
Ok(())
}
}
struct PreparedHop<'a> {
types: RelTypes,
traverse: Direction,
expand_into: Option<usize>,
filter: PreparedNodeFilter<'a>,
}
struct PipelineCore<'a> {
k: usize,
hops: Vec<PreparedHop<'a>>,
tallies: WalkTallies,
}
impl<'a> PipelineCore<'a> {
fn expand_stage(
&mut self,
ctx: ExecCtx<'a>,
chunks: &mut [MorselChunk],
j: usize,
sink: &mut dyn MorselSink,
) -> Result<()> {
if j == self.k {
sink.consume(ctx, &chunks[0])?;
return Ok(());
}
let hop_types = self.hops[j].types.clone();
let hop_dir = self.hops[j].traverse;
let expand_into = self.hops[j].expand_into;
let (curr, rest) = chunks.split_at_mut(1);
let input = &curr[0];
let input_len = input.len();
for r in 0..input_len {
ctx.graph.cancel_tick()?;
if sink.halted() {
break;
}
let from = input.nodes[j][r];
if let Some(target_slot) = expand_into {
let target = input.nodes[target_slot][r];
let from_deg = ctx.graph.typed_adj_len_resolved(from, hop_dir, &hop_types);
let to_deg = ctx
.graph
.typed_adj_len_resolved(target, hop_dir.flip(), &hop_types);
let (anchor, scan_dir, reversed) = if to_deg < from_deg {
(target, hop_dir.flip(), true)
} else {
(from, hop_dir, false)
};
self.tallies.expand_into(reversed);
ctx.graph.try_for_each_neighbor_resolved::<Error>(
anchor,
scan_dir,
&hop_types,
|rid| {
ctx.graph.cancel_tick()?;
if sink.halted() {
return Ok(());
}
if ctx.graph.hop(from, rid, hop_dir) != Some(target) {
return Ok(());
}
if lineage_contains(input, r, j, rid) {
return Ok(());
}
self.tallies.walk();
self.tallies.expansion_hop(j);
rest[0].push_step(input, r, j, rid, target);
if rest[0].is_full()
|| sink.remaining_want().is_some_and(|w| rest[0].len() >= w)
{
self.flush_and_filter_hop(ctx, rest, j, sink)?;
}
Ok(())
},
)?;
} else {
ctx.graph.try_for_each_hop_resolved::<Error>(
from,
hop_dir,
&hop_types,
|rid, arrival| {
ctx.graph.cancel_tick()?;
if sink.halted() {
return Ok(());
}
if lineage_contains(input, r, j, rid) {
return Ok(());
}
self.tallies.walk();
self.tallies.expansion_hop(j);
rest[0].push_step(input, r, j, rid, arrival);
if rest[0].is_full()
|| sink.remaining_want().is_some_and(|w| rest[0].len() >= w)
{
self.flush_and_filter_hop(ctx, rest, j, sink)?;
}
Ok(())
},
)?;
}
if sink.halted() {
break;
}
}
if !rest[0].is_empty() && !sink.halted() {
self.flush_and_filter_hop(ctx, rest, j, sink)?;
}
Ok(())
}
fn flush_and_filter_hop(
&mut self,
ctx: ExecCtx<'a>,
rest: &mut [MorselChunk],
j: usize,
sink: &mut dyn MorselSink,
) -> Result<()> {
let count = rest[0].len();
if count == 0 {
return Ok(());
}
let mut mask = SelectionMask::all_set(count);
let arrivals = rest[0].nodes[j + 1].as_slice();
self.hops[j].filter.filter_batch(ctx, arrivals, &mut mask)?;
let surviving = mask.count_ones(count);
if surviving == 0 {
rest[0].clear();
return Ok(());
}
if surviving < count {
let active_nodes = j + 2;
let active_rels = j + 1;
rest[0].compact_with_mask(&mask, active_nodes, active_rels);
}
self.expand_stage(ctx, rest, j + 1, sink)?;
rest[0].clear();
Ok(())
}
}
pub(crate) struct PipelineRunner<'a> {
ctx: ExecCtx<'a>,
core: PipelineCore<'a>,
stage_chunks: Vec<MorselChunk>,
_charge: WorkspaceCharge,
}
impl<'a> PipelineRunner<'a> {
fn total_stage_bytes(k: usize) -> usize {
let mut total = 0;
for stage in 0..=k {
let node_bytes = (stage + 1) * BATCH_ROWS * std::mem::size_of::<NodeId>();
let rel_bytes = stage * BATCH_ROWS * std::mem::size_of::<RelId>();
let vec_overhead = (2 * stage + 1) * std::mem::size_of::<Vec<u64>>();
total += node_bytes + rel_bytes + vec_overhead;
}
total
}
pub(crate) fn new(ctx: ExecCtx<'a>, chain: &'a Chain<'a>) -> Result<Self> {
let k = chain.hops.len();
if k == 0 || k > crate::exec::kernels::matcher::MAX_UNROLL_HOPS {
return Err(relate_core::Error::semantic(
"morsel pipeline requires 1..=32 hops",
));
}
let total_buffer_bytes = Self::total_stage_bytes(k);
let charge = WorkspaceCharge::retain(total_buffer_bytes as u64)?;
let mut hops = Vec::with_capacity(k);
for hop in &chain.hops {
hops.push(PreparedHop {
types: ctx.graph.rel_types_of(hop.rel),
traverse: hop.traverse,
expand_into: hop.expand_into,
filter: PreparedNodeFilter::prepare(ctx, &hop.target)?,
});
}
let mut stage_chunks = Vec::with_capacity(k + 1);
for stage in 0..=k {
stage_chunks.push(MorselChunk::with_hops(stage));
}
Ok(Self {
ctx,
core: PipelineCore {
k,
hops,
tallies: WalkTallies::default(),
},
stage_chunks,
_charge: charge,
})
}
pub(crate) fn execute(
&mut self,
starts: Vec<NodeId>,
start_target: &'a NodeTarget<'a>,
sink: &mut dyn MorselSink,
) -> Result<()> {
let mut start_filter = PreparedNodeFilter::prepare(self.ctx, start_target)?;
for batch in starts.chunks(BATCH_ROWS) {
self.ctx.graph.cancel_tick()?;
if sink.halted() {
break;
}
let mut mask = SelectionMask::all_set(batch.len());
start_filter.filter_batch(self.ctx, batch, &mut mask)?;
if mask.count_ones(batch.len()) == 0 {
continue;
}
self.stage_chunks[0].clear();
for idx in mask.iter_set(batch.len()) {
self.stage_chunks[0].nodes[0].push(batch[idx]);
}
self.core
.expand_stage(self.ctx, &mut self.stage_chunks, 0, sink)?;
}
Ok(())
}
}
pub(crate) fn try_morsel_match(
ctx: ExecCtx<'_>,
chain: &Chain<'_>,
starts: Vec<NodeId>,
mode: KernelMode<'_>,
) -> Result<KernelOutput> {
let mut runner = PipelineRunner::new(ctx, chain)?;
match mode {
KernelMode::Rows { want } => {
let (names, bindings) = named_bindings(chain).into_iter().unzip();
let mut sink = SinkMode::Rows {
halt: want,
names,
bindings,
rows: Vec::new(),
};
runner.execute(starts, &chain.start, &mut sink)?;
if let SinkMode::Rows { rows, .. } = sink {
Ok(KernelOutput::Rows(rows))
} else {
unreachable!()
}
}
KernelMode::Exists { counted } => {
let counted_slot = match counted {
Some(expr) => {
let (var, key) = var_prop_named(expr)
.ok_or_else(|| Error::semantic("counted expression must be var.prop"))?;
let slot = if chain.start.pattern.variable.as_ref() == Some(var) {
0
} else {
let mut found = None;
for (j, hop) in chain.hops.iter().enumerate() {
if hop.target.pattern.variable.as_ref() == Some(var) {
found = Some(j + 1);
break;
}
}
found
.ok_or_else(|| Error::semantic("counted variable not bound in chain"))?
};
Some((slot, key))
}
None => None,
};
let mut sink = SinkMode::Exists {
counted: counted_slot,
hit: false,
};
runner.execute(starts, &chain.start, &mut sink)?;
if let SinkMode::Exists { hit, .. } = sink {
Ok(KernelOutput::Exists(hit))
} else {
unreachable!()
}
}
}
}
pub(crate) fn morsel_count(
ctx: ExecCtx<'_>,
chain: &Chain<'_>,
starts: Vec<NodeId>,
) -> Result<u64> {
let mut runner = PipelineRunner::new(ctx, chain)?;
let mut sink = SinkMode::Count { tally: 0 };
runner.execute(starts, &chain.start, &mut sink)?;
if let SinkMode::Count { tally } = sink {
Ok(tally)
} else {
unreachable!()
}
}
pub(crate) fn try_fold_morsel_count(ctx: &FoldCtx<'_>) -> Result<Option<FoldedReturn>> {
let Some(entry) = CountEntry::open(ctx) else {
return Ok(None);
};
let Some(contract) = entry.chain() else {
return Ok(None);
};
let (_tallied, landed) = contract.split_last_hop();
if !chain_stages_fit(&entry.stats(), entry.conjuncts(), &contract, landed) {
return Ok(None);
}
let (exec, starts) = entry.scan(&contract)?;
let count = morsel_count(exec, &contract, starts)?;
Ok(count_fold_tail(exec.graph, u128::from(count), entry.item))
}