use relate_core::{NodeId, RelId, Result, Value};
use relate_ir::var_prop_named;
use relate_names::{NamedToken, SmallName};
use relate_core::Error;
use crate::ctx::ExecCtx;
use crate::overlay::ExecGraph;
use crate::pattern_walk::{bind_node_stub, bind_rel_stub};
use crate::store::RelTypes;
use super::super::chunk::{Chunk, Column};
use super::super::WalkTallies;
use super::matcher::{Hop, HubStar};
use super::program::{Admission, NodePred};
use super::{KernelMode, KernelOutput};
const MAX_SIDE_HOPS: usize = 2;
#[derive(Clone, Copy)]
struct SideRow {
rels: [RelId; MAX_SIDE_HOPS],
nodes: [NodeId; MAX_SIDE_HOPS],
len: usize,
}
impl SideRow {
fn terminal(&self) -> NodeId {
self.nodes[self.len - 1]
}
fn rels_overlap(&self, other: &SideRow) -> bool {
(0..self.len).any(|i| (0..other.len).any(|j| self.rels[i] == other.rels[j]))
}
}
pub(super) fn run(
ctx: ExecCtx<'_>,
star: &HubStar<'_>,
hubs: Vec<NodeId>,
mode: KernelMode<'_>,
) -> Result<KernelOutput> {
let graph = ctx.graph;
let halt = mode.halt();
let mut side_a = Vec::new();
let projection = Projection::new(star);
let counted_read = match &mode {
KernelMode::Rows { .. } => None,
KernelMode::Exists { counted } => (*counted).map(|expr| {
let (var, key) = var_prop_named(expr)
.expect("the engagement proof admits only var.prop counted expressions");
let slot = projection
.node_slot(var)
.expect("the engagement proof checked the counted variable is bound");
(slot, key)
}),
};
let mut bindings = Bindings::new(&projection, halt);
let mut hit = false;
let tallies = WalkTallies::default();
let side_types: [Vec<RelTypes>; 2] = star
.sides
.each_ref()
.map(|hops| hops.iter().map(|hop| graph.rel_types_of(hop.rel)).collect());
'hubs: for hub in hubs {
graph.cancel_tick()?;
if bindings.full() {
break;
}
side_a.clear();
expand_side(ctx, &star.sides[0], &side_types[0], hub, &tallies, |row| {
side_a.push(row);
Ok(true)
})?;
if side_a.is_empty() {
continue;
}
let mut found = false;
expand_side(ctx, &star.sides[1], &side_types[1], hub, &tallies, |b| {
for a in &side_a {
graph.cancel_tick()?;
if (!star.shared_terminal || a.terminal() == b.terminal()) && !a.rels_overlap(&b) {
let binding = Binding {
hub,
sides: [*a, b],
};
match &mode {
KernelMode::Rows { .. } => {
if bindings.full() {
return Ok(false);
}
bindings.push(graph, &binding);
}
KernelMode::Exists { .. } => {
if counted_nonnull(ctx, &binding, &counted_read) {
found = true;
return Ok(false);
}
}
}
}
}
Ok(true)
})?;
if found {
hit = true;
break 'hubs;
}
}
match mode {
KernelMode::Rows { .. } => {
let (names, columns) = bindings.into_columns();
Ok(KernelOutput::Rows(
Chunk::from_columns(&names, columns).to_rows(),
))
}
KernelMode::Exists { .. } => Ok(KernelOutput::Exists(hit)),
}
}
#[derive(Clone, Copy)]
struct SideWalk<'a> {
ctx: ExecCtx<'a>,
hops: &'a [Hop<'a>],
types: &'a [RelTypes],
tallies: &'a WalkTallies,
}
fn expand_side(
ctx: ExecCtx<'_>,
hops: &[Hop<'_>],
types: &[RelTypes],
hub: NodeId,
tallies: &WalkTallies,
mut on_row: impl FnMut(SideRow) -> Result<bool>,
) -> Result<()> {
let (mut rels, mut nodes) = (
[RelId::default(); MAX_SIDE_HOPS],
[NodeId::default(); MAX_SIDE_HOPS],
);
let walk = SideWalk {
ctx,
hops,
types,
tallies,
};
expand_hop_at(&walk, 0, hub, &mut rels, &mut nodes, &mut on_row).map(|_| ())
}
fn expand_hop_at(
walk: &SideWalk<'_>,
index: usize,
from: NodeId,
rels: &mut [RelId; MAX_SIDE_HOPS],
nodes: &mut [NodeId; MAX_SIDE_HOPS],
on_row: &mut dyn FnMut(SideRow) -> Result<bool>,
) -> Result<bool> {
let Some(hop) = walk.hops.get(index) else {
return on_row(SideRow {
rels: *rels,
nodes: *nodes,
len: index,
});
};
step_hop(
walk,
index,
from,
rels,
nodes,
on_row,
Admission::of(&hop.target),
)
}
enum Walk {
Stop,
Err(Error),
}
impl From<Error> for Walk {
fn from(err: Error) -> Self {
Walk::Err(err)
}
}
fn step_hop<P: NodePred>(
walk: &SideWalk<'_>,
index: usize,
from: NodeId,
rels: &mut [RelId; MAX_SIDE_HOPS],
nodes: &mut [NodeId; MAX_SIDE_HOPS],
on_row: &mut dyn FnMut(SideRow) -> Result<bool>,
pred: P,
) -> Result<bool> {
let SideWalk {
ctx,
hops,
types,
tallies,
} = *walk;
let graph = ctx.graph;
let hop = &hops[index];
let types = &types[index];
let mut prepared: Option<P::Prepared> = None;
let stream = graph.try_for_each_hop_resolved(from, hop.traverse, types, |rid, arrival| {
graph.cancel_tick()?;
if rels[..index].contains(&rid) {
return Ok(());
}
if !pred.admits(&mut prepared, ctx, arrival)? {
return Ok(());
}
tallies.walk();
tallies.expansion_hop(index);
rels[index] = rid;
nodes[index] = arrival;
match expand_hop_at(walk, index + 1, arrival, rels, nodes, on_row) {
Ok(true) => Ok(()),
Ok(false) => Err(Walk::Stop),
Err(err) => Err(Walk::Err(err)),
}
});
match stream {
Err(Walk::Stop) => Ok(false),
Err(Walk::Err(err)) => Err(err),
Ok(()) => Ok(true),
}
}
#[derive(Clone, Copy)]
enum At {
Hub,
Rel { side: usize, hop: usize },
Node { side: usize, hop: usize },
}
struct Slot {
var: SmallName,
at: At,
}
struct Projection {
slots: Vec<Slot>,
}
impl Projection {
fn new(star: &HubStar<'_>) -> Self {
let hub = star.hub[0]
.pattern
.variable
.as_ref()
.expect("the hub-star family is defined by one shared variable");
let mut slots = vec![Slot {
var: hub.clone(),
at: At::Hub,
}];
for (side, hops) in star.sides.iter().enumerate() {
for (hop, h) in hops.iter().enumerate() {
if let Some(var) = h.rel.variable.as_ref() {
slots.push(Slot {
var: var.clone(),
at: At::Rel { side, hop },
});
}
if let Some(var) = h.target.pattern.variable.as_ref() {
slots.push(Slot {
var: var.clone(),
at: At::Node { side, hop },
});
}
}
}
Projection { slots }
}
fn names(&self) -> Vec<String> {
self.slots.iter().map(|slot| slot.var.to_string()).collect()
}
fn node_slot(&self, var: &SmallName) -> Option<At> {
self.slots
.iter()
.find(|slot| slot.var == *var && !matches!(slot.at, At::Rel { .. }))
.map(|slot| slot.at)
}
}
#[derive(Clone, Copy)]
struct Binding {
hub: NodeId,
sides: [SideRow; 2],
}
impl Binding {
fn node(&self, side: usize, hop: usize) -> NodeId {
self.sides[side].nodes[hop]
}
fn rel(&self, side: usize, hop: usize) -> RelId {
self.sides[side].rels[hop]
}
fn node_at(&self, at: At) -> Option<NodeId> {
match at {
At::Hub => Some(self.hub),
At::Node { side, hop } => Some(self.node(side, hop)),
At::Rel { .. } => None,
}
}
}
struct Bindings<'p> {
projection: &'p Projection,
columns: Vec<Vec<Value>>,
halt: Option<usize>,
}
impl<'p> Bindings<'p> {
fn new(projection: &'p Projection, halt: Option<usize>) -> Self {
let columns = vec![Vec::new(); projection.slots.len()];
Bindings {
projection,
columns,
halt,
}
}
fn full(&self) -> bool {
self.halt.is_some_and(|halt| self.columns[0].len() >= halt)
}
fn push(&mut self, graph: &ExecGraph<'_>, binding: &Binding) {
for (slot, column) in self.projection.slots.iter().zip(&mut self.columns) {
column.push(match slot.at {
At::Hub => bind_node_stub(graph, binding.hub),
At::Rel { side, hop } => bind_rel_stub(graph, binding.rel(side, hop)),
At::Node { side, hop } => bind_node_stub(graph, binding.node(side, hop)),
});
}
}
fn into_columns(self) -> (Vec<String>, Vec<Column>) {
let names = self.projection.names();
let encoded = self
.columns
.iter()
.map(|column| Column::from_values(column))
.collect();
(names, encoded)
}
}
fn counted_nonnull(
ctx: ExecCtx<'_>,
binding: &Binding,
counted: &Option<(At, NamedToken)>,
) -> bool {
let Some((at, key)) = counted else {
return true;
};
let node = binding
.node_at(*at)
.expect("the engagement proof checked the counted variable is bound to a node");
matches!(
ctx.graph.node_prop_resolved(node, key),
Some(v) if !v.is_null()
)
}