use relate_core::{Error, NodeId, Result, Value};
use crate::ctx::ExecCtx;
use crate::eval::{eval, predicate_value_holds};
use crate::frontier_decline::FrontierRunDecline;
use crate::metrics::FrontierCounters;
use crate::row::Row;
use super::frontier_tables::{
arms, epsilon_index, within_table_budget, Arm, Arrival, Endpoint, FrontierTables, Parent,
Parents, Step, TableCeiling,
};
use super::guard_memo::StateMemos;
use super::nfa::{FrontierNfa, Pool, STATE_CEILING};
use super::rearival::{RearivalRule, RuleBuffers, Verdict};
pub(crate) const FRONTIER_WALK_BUDGET: u64 = 10_000_000;
pub(crate) struct WalkBudget(u64);
impl WalkBudget {
pub(crate) fn standard() -> Self {
Self(FRONTIER_WALK_BUDGET)
}
#[cfg(test)]
pub(crate) fn for_tests(edge_visits: u64) -> Self {
Self(edge_visits)
}
}
fn walk_budget_exceeded() -> Error {
Error::execution(format!(
"WalkBudgetExceeded: frontier walk exceeds {FRONTIER_WALK_BUDGET} edge \
visits per run; a frontier that would blow up fails here instead of \
running to fixpoint (work budget)."
))
}
#[derive(Debug)]
pub(crate) struct FrontierRun {
tables: FrontierTables,
pub(crate) endpoints: Vec<Endpoint>,
pub(crate) per_level: Vec<usize>,
pub(crate) edge_visits: u64,
pub(crate) arms: Vec<Vec<Arm>>,
pub(crate) rule: FrontierCounters,
}
impl FrontierRun {
pub(crate) fn parents(&self) -> Parents<'_> {
self.tables.parents()
}
pub(crate) fn facts(&self) -> FrontierCounters {
FrontierCounters {
edge_visits: self.edge_visits,
levels: self.per_level.len() as u64,
endpoints: self.endpoints.len() as u64,
cells: self.per_level.iter().sum::<usize>() as u64,
..self.rule
}
}
pub(super) fn reclaim(self) -> FrontierTables {
self.tables
}
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub(crate) enum RunOutcome {
Served(FrontierRun),
Declined {
facts: FrontierCounters,
reason: FrontierRunDecline,
},
}
impl RunOutcome {
pub(crate) fn facts(&self) -> FrontierCounters {
match self {
RunOutcome::Served(run) => run.facts(),
RunOutcome::Declined { facts, .. } => *facts,
}
}
#[cfg(test)]
pub(crate) fn unwrap_served(self) -> FrontierRun {
match self {
RunOutcome::Served(run) => run,
RunOutcome::Declined { facts, reason } => {
panic!("the run declined on {reason:?}: {facts:?}")
}
}
}
}
pub(crate) fn run(
ctx: ExecCtx<'_>,
seed: NodeId,
nfa: &FrontierNfa,
budget: WalkBudget,
pool: Pool,
tables: &mut FrontierTables,
bufs: &mut RuleBuffers,
) -> Result<RunOutcome> {
run_with_halt(ctx, seed, nfa, budget, pool, tables, bufs, |_, _| Ok(false))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_with_halt<HALT: FnMut(&Parents<'_>, &[Endpoint]) -> Result<bool>>(
ctx: ExecCtx<'_>,
seed: NodeId,
nfa: &FrontierNfa,
budget: WalkBudget,
pool: Pool,
tables: &mut FrontierTables,
bufs: &mut RuleBuffers,
mut halt: HALT,
) -> Result<RunOutcome> {
let view = ctx.graph;
let states = nfa.states as usize;
assert!(
tables.shaped_for(states),
"the clause's frontier tables are shaped for the run's automaton"
);
tables.begin_seed();
let mut tables = std::mem::take(tables);
let mut endpoints: Vec<Endpoint> = Vec::new();
let arms = arms(view, nfa);
let eps_from = epsilon_index(nfa);
let mut rule = RearivalRule::new(view, nfa, &arms, seed, pool, bufs);
let mut candidates: Vec<Endpoint> = Vec::new();
let guards = RunGuards {
ctx,
nfa,
memos: StateMemos::new(view, states),
};
let mut over_ceiling = false;
if tables.arrive(seed, nfa.start, None).is_err()
|| close_epsilons(seed, nfa.start, &guards, &mut tables, &eps_from)? == Closed::Ceiling
{
over_ceiling = true;
}
if !over_ceiling && nfa.min_hops == 0 {
for state in 0..states as u32 {
if tables.pair_seen(seed, state) && nfa.accepting[state as usize] {
tables.mark_endpoint(seed);
endpoints.push(Endpoint {
node: seed,
state,
hops: 0,
arrival: Arrival::Zero,
});
break;
}
}
}
let max_level = nfa.max_hops.unwrap_or(u32::MAX);
let mut per_level = vec![tables.pair_count()];
let mut edge_visits = 0u64;
let mut hops = 0u32;
let mut halted = halt(&tables.parents(), &endpoints)?;
let mut level_start = 0usize;
let mut level_end = tables.pair_count();
while !halted && !over_ceiling && level_start != level_end {
if hops == max_level {
break;
}
if edge_visits > budget.0 {
return Err(walk_budget_exceeded());
}
if !within_table_budget(tables.heap_bytes() + rule.heap_bytes()) {
over_ceiling = true;
break;
}
view.cancel_tick()?;
hops += 1;
let in_bounds = hops >= nfa.min_hops && hops <= max_level;
for index in level_start..level_end {
let (u, s) = tables.pair_at(index);
for arm in &arms[s as usize] {
let t = &nfa.transitions[arm.transition];
view.try_for_each_hop_resolved::<Error>(u, t.direction, &arm.types, |rid, v| {
edge_visits += 1;
if !guards.state_admits(t.to, v)?
|| !guards.predicate_admits(
arm.transition,
(u, s),
v,
t.to,
&tables.parents(),
)?
{
return Ok(());
}
let arrived = tables.arrive(
v,
t.to,
Some(Parent {
node: u,
state: s,
step: Step::Rel(rid),
}),
);
let arrived = match arrived {
Ok(arrived) => arrived,
Err(TableCeiling) => {
over_ceiling = true;
return Ok(());
}
};
if t.accepts && !arrived.endpoint {
if in_bounds {
let admitted = if pool == Pool::Default {
rule.admits(&tables.parents(), (u, s), v)?
} else {
true
};
if admitted {
tables.mark_endpoint(v);
endpoints.push(Endpoint {
node: v,
state: t.to,
hops,
arrival: Arrival::Rel {
pred: (u, s),
rel: rid,
},
});
}
} else if !tables.candidate_marked(v) {
tables.mark_candidate(v);
candidates.push(Endpoint {
node: v,
state: t.to,
hops,
arrival: Arrival::Rel {
pred: (u, s),
rel: rid,
},
});
}
}
if arrived.new
&& close_epsilons(v, t.to, &guards, &mut tables, &eps_from)?
== Closed::Ceiling
{
over_ceiling = true;
return Ok(());
}
Ok(())
})?;
}
}
per_level.push(tables.pair_count() - level_end);
level_start = level_end;
level_end = tables.pair_count();
halted = halt(&tables.parents(), &endpoints)?;
}
if !halted && !over_ceiling {
for candidate in candidates {
if !tables.endpoint_marked(candidate.node)
&& matches!(rule.pool_witness(candidate.node)?, Verdict::Proven(_))
{
tables.mark_endpoint(candidate.node);
endpoints.push(candidate);
}
}
}
let declined = if over_ceiling {
Some(FrontierRunDecline::TableBudget)
} else if rule.budget_exhausted() {
Some(FrontierRunDecline::RearrivalBudget)
} else {
None
};
let rule_facts = rule.counters();
let run = FrontierRun {
tables,
endpoints,
per_level,
edge_visits,
arms,
rule: rule_facts,
};
Ok(match declined {
Some(reason) => RunOutcome::Declined {
facts: run.facts(),
reason,
},
None => RunOutcome::Served(run),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Closed {
Done,
Ceiling,
}
fn close_epsilons(
node: NodeId,
state: u32,
guards: &RunGuards<'_, '_>,
tables: &mut FrontierTables,
eps_from: &[Vec<u32>],
) -> Result<Closed> {
let mut work = vec![(node, state)];
while let Some((n, s)) = work.pop() {
for &to in &eps_from[s as usize] {
let parent = Parent {
node: n,
state: s,
step: Step::Epsilon,
};
if !guards.state_admits(to, n)? {
continue;
}
match tables.arrive(n, to, Some(parent)) {
Ok(arrived) if arrived.new => work.push((n, to)),
Ok(_) => {}
Err(TableCeiling) => return Ok(Closed::Ceiling),
}
}
}
Ok(Closed::Done)
}
struct RunGuards<'c, 'n> {
ctx: ExecCtx<'c>,
nfa: &'n FrontierNfa,
memos: StateMemos,
}
impl RunGuards<'_, '_> {
fn state_admits(&self, state: u32, node: NodeId) -> Result<bool> {
self.memos
.state_admits(self.ctx.graph, self.nfa, self.ctx.params, state, node)
}
fn predicate_admits(
&self,
transition: usize,
from: (NodeId, u32),
arrival: NodeId,
to: u32,
parents: &Parents<'_>,
) -> Result<bool> {
let Some(predicate) = &self.nfa.predicates[transition] else {
return Ok(true);
};
let mut row = Row::new();
for (name, state) in &predicate.vars {
let node = if *state == to {
arrival
} else if *state == from.1 {
from.0
} else {
last_bound(parents, from, *state)
};
let node = self
.ctx
.graph
.node(node)
.expect("a walked node is live under the view that walked it");
row.insert(name.clone(), Value::from_node(node));
}
predicate_value_holds(&eval(
self.ctx.graph,
&row,
&predicate.expr,
self.ctx.params,
)?)
}
}
fn last_bound(parents: &Parents<'_>, from: (NodeId, u32), state: u32) -> NodeId {
let (mut node, mut at) = from;
for _ in 0..STATE_CEILING {
let parent = parents
.parent_of(node, at)
.expect("the compile proved the referenced position lies on the chain");
if parent.state == state {
return parent.node;
}
node = parent.node;
at = parent.state;
}
unreachable!("the first-arrival chain is shorter than the state ceiling")
}