refactor: plan refusals fall back to the row runner

This commit is contained in:
Stefan Miljakovic committed 2026-10-11 13:51:02 +02:00
1 parent 3a86b14876
commit c979f978e5
10 files changed
+38 -269

No files matched your search

+2 -2
View File
@@ -1,5 +1,5 @@
use super::call::{Call, Load};
use super::{CompiledGraph, Host, Nesting, Source, Step};
use super::{CompiledGraph, Host, Nesting, Step};
use crate::loader::LoaderError;
use crate::model::GraphContent;
use crate::nodes::custom::{CustomDecisionNode, CustomNodeRequest};
@@ -128,7 +128,7 @@ impl CompiledGraph {
parents: Some(&parents),
iteration: iteration + 1,
};
let state = Box::pin(compiled.run(Host { content: &content, extensions: &extensions, max_depth }, &Source::Rows(inputs), inputs.len(), false, nesting)).await;
let state = Box::pin(compiled.run(Host { content: &content, extensions: &extensions, max_depth }, inputs, nesting)).await;
state
.errors
.into_iter()
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::compiled::exact::graph::Row;
use super::traced::Traced;
use super::{CompiledGraph, Host, Nesting, Source};
use super::{CompiledGraph, Host, Nesting};
use crate::decision_graph::graph::DecisionGraphResponse;
use crate::loader::LoaderError;
use crate::model::GraphContent;
@@ -77,7 +77,7 @@ impl Call<'_> {
parents: Some(&parents),
iteration: self.iteration + 1,
};
let state = Box::pin(compiled.run(Host { content: &content, extensions: &extensions, max_depth: self.max_depth }, &Source::Rows(&inputs), 1, false, nesting)).await;
let state = Box::pin(compiled.run(Host { content: &content, extensions: &extensions, max_depth: self.max_depth }, &inputs, nesting)).await;
let error = state.errors.into_iter().next().flatten();
let result = state.results.into_iter().next().flatten();
match error {
+7 -180
View File
@@ -1,9 +1,8 @@
use crate::compiled::graph::data::{Data, Layer, Mask, Shape};
use crate::compiled::graph::data::{Data, Layer, Mask};
use crate::compiled::shred::Normalizer;
use crate::compiled::leaf::{ColumnBuilder, Input, Leaf};
use crate::compiled::graph::{CompiledGraph, Host, Source};
use crate::compiled::leaf::Leaf;
use crate::compiled::graph::CompiledGraph;
use crate::decision_graph::cleaner::{VariableCleaner, ZEN_RESERVED_PROPERTIES};
use crate::decision_graph::walker::GraphWalker;
use crate::model::GraphContent;
use crate::nodes::NodeHandlerExtensions;
use crate::EvaluationError;
@@ -107,11 +106,6 @@ impl ColumnarOutput<'_> {
}
}
struct Group<'a> {
rows: Rc<[usize]>,
leaves: Vec<(Arc<str>, Leaf<'a>)>,
}
impl CompiledGraph {
fn input_data<'a>(columns: &Columns<'a>) -> Data<'a> {
let rows = columns.rows;
@@ -170,44 +164,6 @@ impl CompiledGraph {
)
}
fn reserved(path: &str) -> bool {
path.split('.').any(|segment| segment == "$nodes")
}
fn leaves<'a>(datas: &[Data<'a>]) -> Option<Vec<(Arc<str>, Leaf<'a>)>> {
let folded;
let single = match datas {
[single] => single,
[first, ..] if datas.iter().all(Data::patchable) => {
let mut acc = Data::empty(&first.rows);
for data in datas {
acc = acc.layered(data.patch()?);
}
folded = acc;
&folded
}
_ => return None,
};
let Shape::Patched { base: None, leaves, .. } = &single.shape else {
return None;
};
let overlapping = leaves.iter().any(|(a, _)| {
leaves
.iter()
.any(|(b, _)| b.strip_prefix(a.as_ref()).is_some_and(|rest| rest.starts_with('.')))
});
if overlapping {
return None;
}
Some(
leaves
.iter()
.filter(|(path, _)| !Self::reserved(path))
.map(|(path, leaf)| (path.clone(), Self::cleaned(leaf)))
.collect(),
)
}
fn reserved_inside(value: &Variable) -> bool {
match value {
Variable::Object(map) => {
@@ -268,40 +224,6 @@ impl CompiledGraph {
}
}
fn flattened<'a>(rows: &Rc<[usize]>, datas: &[Data<'a>]) -> Group<'a> {
let columns: Vec<_> = datas.iter().map(Data::materialized).collect();
let mut paths: Vec<Arc<str>> = Vec::new();
let mut values: Vec<Vec<Variable>> = Vec::new();
for i in 0..rows.len() {
let result = match columns.as_slice() {
[single] => GraphWalker::merge_ending(std::iter::once(&single[i])),
_ => GraphWalker::merge_ending(columns.iter().map(|c| &c[i])),
};
VariableCleaner::new().clean(&result);
let mut entries = Vec::new();
Self::flatten(&result, "", &mut entries);
for (path, value) in entries {
let at = match paths.iter().position(|p| p.as_ref() == path) {
Some(at) => at,
None => {
paths.push(Arc::from(path));
values.push(vec![Variable::Null; rows.len()]);
values.len() - 1
}
};
values[at][i] = value;
}
}
Group {
rows: rows.clone(),
leaves: paths
.into_iter()
.zip(values)
.map(|(path, column)| (path, Leaf::Any(column.into())))
.collect(),
}
}
pub(crate) async fn evaluate_columns<'a>(
&self,
content: &Arc<GraphContent>,
@@ -309,109 +231,14 @@ impl CompiledGraph {
max_depth: u8,
columns: &'a Columns<'a>,
) -> ColumnarOutput<'a> {
if let (true, Some(plan)) = (max_depth > 0, self.plan()) {
if max_depth > 0 {
if let Some(failures) = self.planned_input(content, extensions, columns).await {
if let Some(output) = plan.evaluate(self, content, extensions, max_depth, columns, failures).await {
if let Some(output) = self.plan().evaluate(self, content, extensions, max_depth, columns, failures).await {
return output;
}
}
}
let count = columns.rows;
let source = Source::Columns(Rc::new(Self::input_data(columns)));
let state = self.run(Host { content, extensions, max_depth }, &source, count, true, crate::compiled::graph::Nesting::default()).await;
let groups: Vec<Group<'a>> = state
.endings
.iter()
.map(|(rows, datas)| match Self::leaves(datas) {
Some(leaves) => Group {
rows: rows.clone(),
leaves,
},
None => Self::flattened(rows, datas),
})
.collect();
let identity = |rows: &[usize]| rows.len() == count && rows.iter().enumerate().all(|(i, r)| i == *r);
let columns = match groups.as_slice() {
[single] if identity(&single.rows) => single
.leaves
.iter()
.map(|(path, leaf)| (path.clone(), OutputColumn(leaf.clone())))
.collect(),
_ => {
let mut owner: Vec<Option<(usize, usize)>> = vec![None; count];
for (g, group) in groups.iter().enumerate() {
for (i, &row) in group.rows.iter().enumerate() {
owner[row] = Some((g, i));
}
}
let mut paths: Vec<Arc<str>> = Vec::new();
for group in &groups {
for (path, _) in &group.leaves {
if !paths.contains(path) {
paths.push(path.clone());
}
}
}
let owned = owner
.iter()
.zip(&state.errors)
.all(|(owner, error)| owner.is_some() || error.is_some());
let mut aligned: Vec<Vec<(*const [usize], bool)>> = vec![Vec::new(); groups.len()];
let mut passes = |g: usize, leaf: &Leaf<'a>| -> Option<Rc<Input<'a>>> {
let (input, positions) = leaf.passed()?;
let rows = &groups[g].rows;
let ok = match positions {
None => rows.len() == input.rows && rows.iter().enumerate().all(|(i, r)| i == *r),
Some(positions) => {
let key = Rc::as_ptr(positions);
match aligned[g].iter().find(|(k, _)| std::ptr::eq(*k, key)) {
Some((_, ok)) => *ok,
None => {
let ok = positions.as_ref() == rows.as_ref();
aligned[g].push((key, ok));
ok
}
}
}
};
ok.then(|| input.clone())
};
paths
.into_iter()
.map(|path| {
let found: Vec<Option<&Leaf<'a>>> = groups
.iter()
.map(|g| g.leaves.iter().find(|(p, _)| *p == path).map(|(_, l)| l))
.collect();
let passed: Option<Vec<Rc<Input<'a>>>> = match owned {
true => found.iter().enumerate().map(|(g, leaf)| leaf.and_then(|leaf| passes(g, leaf))).collect(),
false => None,
};
if let Some(first) = passed.as_ref().and_then(|p| p.first().filter(|first| p.iter().all(|x| Rc::ptr_eq(x, first)))) {
return (path, OutputColumn(Leaf::Input(first.clone())));
}
let sources: Vec<Option<Column>> = groups
.iter()
.map(|g| g.leaves.iter().find(|(p, _)| *p == path).map(|(_, l)| l.column()))
.collect();
let mut builder = ColumnBuilder::with_capacity(count);
for slot in &owner {
match slot.and_then(|(g, i)| sources[g].as_ref().map(|column| (column, i))) {
Some((column, i)) => builder.push_cell(column, i),
None => builder.push_null(),
}
}
(path, OutputColumn(Leaf::typed(builder.finish())))
})
.collect()
}
};
ColumnarOutput {
rows: count,
columns,
errors: state.errors.into_iter().map(|error| error.map(Rc::from)).collect(),
typed: 0,
laned: 0,
}
let inputs = Self::input_data(columns).materialized();
ColumnarOutput::from_results(self.evaluate(content, extensions, max_depth, &inputs).await)
}
}
+7 -20
View File
@@ -25,7 +25,7 @@ use std::time::Instant;
use zen_expression::lane::Columns;
use zen_expression::lane::LaneRunner;
use zen_expression::Variable;
pub(crate) use state::{Nesting, Source, State};
pub(crate) use state::{Nesting, State};
use state::Host;
use state::NodeColumn;
use step::{Body, Condition, Hit, Kind, Step, Transform};
@@ -35,7 +35,7 @@ pub struct CompiledGraph {
steps: Vec<Option<Step>>,
root: Arc<Segment>,
dictionaries: bool,
plan: OnceLock<Option<plan::Plan>>,
plan: OnceLock<plan::Plan>,
}
pub struct CompiledPlan(Result<CompiledGraph, Refusal>);
@@ -114,25 +114,12 @@ impl CompiledGraph {
plan::census::Census::take()
}
fn plan(&self) -> Option<&plan::Plan> {
self.plan
.get_or_init(|| match std::env::var("ZEN_LEGACY") {
Ok(_) => None,
Err(_) => plan::Plan::analyze(self).ok(),
})
.as_ref()
fn plan(&self) -> &plan::Plan {
self.plan.get_or_init(|| plan::Plan::analyze(self))
}
pub(crate) fn plan_verdict(&self, columns: &Columns) -> Result<(), String> {
match self.plan() {
Some(plan) => plan.verdict(self, columns),
None => Err(self
.steps
.iter()
.flatten()
.find_map(|step| plan::Plan::analyze_step(step).err())
.unwrap_or_else(|| "refused".into())),
}
self.plan().verdict(self, columns)
}
pub(crate) async fn evaluate(
@@ -144,7 +131,7 @@ impl CompiledGraph {
) -> Vec<Result<DecisionGraphResponse, Box<EvaluationError>>> {
let start = Instant::now();
let state = self
.run(Host { content, extensions, max_depth }, &Source::Rows(inputs), inputs.len(), false, Nesting::default())
.run(Host { content, extensions, max_depth }, inputs, Nesting::default())
.await;
let performance = format!("{:.1?}", start.elapsed());
state
@@ -172,7 +159,7 @@ impl CompiledGraph {
let start = Instant::now();
let inputs = [input];
let state = self
.run(Host { content, extensions, max_depth }, &Source::Rows(&inputs), 1, false, Nesting::default())
.run(Host { content, extensions, max_depth }, &inputs, Nesting::default())
.await;
if let Some(error) = state.errors.into_iter().next().flatten() {
return Err(error);
+3 -3
View File
@@ -988,10 +988,10 @@ impl SegPlan {
}
impl Plan {
pub fn analyze(_graph: &CompiledGraph) -> Result<Plan, String> {
Ok(Plan {
pub fn analyze(_graph: &CompiledGraph) -> Plan {
Plan {
roots: RwLock::new(Vec::new()),
})
}
}
pub fn analyze_step(step: &Step) -> Result<(), String> {
+11 -18
View File
@@ -11,7 +11,7 @@ use std::rc::Rc;
use zen_expression::lane::LaneRunner;
use zen_expression::Variable;
use zen_types::decision::FunctionNodeContent;
use crate::compiled::graph::{Body, CompiledGraph, Kind, NodeColumn, Source, State, Step, data, plan};
use crate::compiled::graph::{Body, CompiledGraph, Kind, NodeColumn, State, Step, data, plan};
impl CompiledGraph {
#[allow(clippy::too_many_arguments)]
@@ -19,7 +19,7 @@ impl CompiledGraph {
&self,
event: &Execute,
rows: &Rc<[usize]>,
source: &Source<'a>,
inputs: &[Variable],
state: &mut State<'a>,
content: &Arc<GraphContent>,
extensions: &NodeHandlerExtensions,
@@ -30,14 +30,14 @@ impl CompiledGraph {
return;
};
let data = match step.kind {
Kind::Input => source.input(rows),
Kind::Input => Data::plain(rows.clone(), rows.iter().map(|&r| inputs[r].clone()).collect()),
_ => Self::input_of(state, &event.parents, rows),
};
let column_path = match &step.kind {
Kind::Node { body, transform } => {
(transform.input_field.is_none() || transform.base.is_some())
&& !transform.looped
&& (rows.len() > 1 || matches!(source, Source::Columns(_)))
&& rows.len() > 1
&& !(transform.output_path.is_some() && matches!(body, Body::Expression { keys, .. } if keys.is_empty()))
}
_ => false,
@@ -64,10 +64,6 @@ impl CompiledGraph {
let (output, failures): (Data<'a>, Vec<(usize, String)>) = match &step.kind {
Kind::Switch { .. } | Kind::Host => (data, Vec::new()),
Kind::Output if !step.schema => (data, Vec::new()),
Kind::Input if matches!(source, Source::Columns(_)) && Self::columnar_input(step, content, extensions) => {
let failures = self.validate_input(step, &data, &nodes, content, extensions).await;
(data, failures)
}
Kind::Input if !step.schema && Self::unresolved(content, &step.node) => {
let values: Col = data
.materialized()
@@ -80,7 +76,7 @@ impl CompiledGraph {
let (values, failures) = self.bounded(step, &data.materialized(), &nodes, content, extensions).await;
(Data::plain(rows.clone(), values.into()), failures)
}
Kind::Node { .. } => self.node(step, rows, source, &data, &nodes, &extra),
Kind::Node { .. } => self.node(step, rows, &data, &nodes, &extra),
};
for (i, message) in failures {
@@ -180,28 +176,25 @@ impl CompiledGraph {
.collect();
return (Data::plain(rows, values), failures);
}
self.node_with(runner, step, &rows, &Source::Rows(&[]), &data, nodes, &[])
self.node_with(runner, step, &rows, &data, nodes, &[])
}
fn node<'a>(
&self,
step: &Step,
rows: &Rc<[usize]>,
source: &Source<'a>,
data: &Data<'a>,
nodes: &[Option<Variable>],
extra: &[NodeColumn<'a>],
) -> (Data<'a>, Vec<(usize, String)>) {
Self::RUNNER.with_borrow_mut(|runner| self.node_with(runner, step, rows, source, data, nodes, extra))
Self::RUNNER.with_borrow_mut(|runner| self.node_with(runner, step, rows, data, nodes, extra))
}
#[allow(clippy::too_many_arguments)]
fn node_with<'a>(
&self,
runner: &mut LaneRunner,
step: &Step,
rows: &Rc<[usize]>,
source: &Source<'a>,
data: &Data<'a>,
nodes: &[Option<Variable>],
extra: &[NodeColumn<'a>],
@@ -210,7 +203,7 @@ impl CompiledGraph {
return (Data::plain(rows.clone(), Rc::from(Vec::new())), Vec::new());
};
{
let wide = rows.len() > 1 || matches!(source, Source::Columns(_));
let wide = rows.len() > 1;
let rebase = match (&transform.input_field, &transform.base, transform.looped) {
(None, _, false) => Some(None),
(Some(_), Some(base), false) => Some(Some(base.as_ref())),
@@ -284,7 +277,7 @@ impl CompiledGraph {
}
}
pub(in crate::compiled::graph) fn execute_now<'a>(&self, step: &Step, event: &Execute, rows: &Rc<[usize]>, source: &Source<'a>, state: &mut State<'a>, with_nodes: bool) {
pub(in crate::compiled::graph) fn execute_now<'a>(&self, step: &Step, event: &Execute, rows: &Rc<[usize]>, state: &mut State<'a>, with_nodes: bool) {
let data = Self::input_of(state, &event.parents, rows);
let based = match &step.kind {
Kind::Node { transform, .. } if !transform.looped => transform.base.as_deref(),
@@ -317,10 +310,10 @@ impl CompiledGraph {
Kind::Node { body, transform } => {
let column_path = (transform.input_field.is_none() || transform.base.is_some())
&& !transform.looped
&& (rows.len() > 1 || matches!(source, Source::Columns(_)))
&& rows.len() > 1
&& !(transform.output_path.is_some() && matches!(body, Body::Expression { keys, .. } if keys.is_empty()));
let (nodes, extra) = self.node_inputs(step, state, &event.visible, rows, with_nodes, column_path);
self.node(step, rows, source, &data, &nodes, &extra)
self.node(step, rows, &data, &nodes, &extra)
}
_ => (data, Vec::new()),
};
+4 -29
View File
@@ -35,7 +35,6 @@ pub(crate) struct State<'a> {
pub(crate) errors: Vec<Option<Box<EvaluationError>>>,
failed: usize,
pub(in crate::compiled::graph) results: Vec<Option<Variable>>,
pub(crate) endings: Vec<(Rc<[usize]>, Vec<Data<'a>>)>,
nesting: Nesting<'a>,
}
@@ -45,20 +44,6 @@ pub(crate) struct Nesting<'a> {
pub(in crate::compiled::graph) iteration: u8,
}
pub(crate) enum Source<'a> {
Rows(&'a [Variable]),
Columns(Rc<Data<'a>>),
}
impl<'a> Source<'a> {
fn input(&self, rows: &Rc<[usize]>) -> Data<'a> {
match self {
Source::Rows(inputs) => Data::plain(rows.clone(), rows.iter().map(|&r| inputs[r].clone()).collect()),
Source::Columns(data) => Data::gather(std::slice::from_ref(data), rows),
}
}
}
impl CompiledGraph {
pub(in crate::compiled::graph) fn child(&self, segment: &Segment, outcome: Outcome) -> Arc<Segment> {
let End::Switch { children, .. } = &segment.end else {
@@ -186,13 +171,13 @@ impl CompiledGraph {
}
}
pub(in crate::compiled::graph) async fn run<'a>(&self, host: Host<'_>, source: &Source<'a>, count: usize, columnar: bool, nesting: Nesting<'a>) -> State<'a> {
pub(in crate::compiled::graph) async fn run<'a>(&self, host: Host<'_>, inputs: &[Variable], nesting: Nesting<'a>) -> State<'a> {
let Host { content, extensions, max_depth } = host;
let count = inputs.len();
let mut state = State {
nodes: vec![Vec::new(); self.steps.len()],
errors: (0..count).map(|_| None).collect(),
results: vec![None; count],
endings: Vec::new(),
failed: 0,
nesting,
};
@@ -211,9 +196,9 @@ impl CompiledGraph {
break;
}
match self.step_at(event.node).filter(|step| Self::immediate(step)) {
Some(step) => self.execute_now(step, event, &rows, source, &mut state, with_nodes),
Some(step) => self.execute_now(step, event, &rows, &mut state, with_nodes),
None => {
self.execute(event, &rows, source, &mut state, content, extensions, with_nodes, max_depth)
self.execute(event, &rows, inputs, &mut state, content, extensions, with_nodes, max_depth)
.await
}
}
@@ -223,16 +208,6 @@ impl CompiledGraph {
continue;
}
match &segment.end {
End::Finish(ending) if columnar => {
let datas: Vec<Data<'a>> = ending
.iter()
.filter_map(|nid| {
let pieces = state.nodes.get(nid.index())?;
(!pieces.is_empty()).then(|| Data::gather(pieces, &rows))
})
.collect();
state.endings.push((rows.clone(), datas));
}
End::Finish(ending) => {
let columns: Vec<Col> = ending
.iter()
+1 -12
View File
@@ -2,7 +2,7 @@ use std::cell::OnceCell;
use std::rc::Rc;
use zen_expression::lane::{Column, Dictionary, Values};
use zen_expression::Variable;
use super::{Array, Bits, ColumnBuilder, Dict, Input, Items, Literal, Masked, Passed, Picked, Records, Scattered, Stitched, Store, Templated};
use super::{Array, Bits, ColumnBuilder, Dict, Input, Items, Literal, Masked, Picked, Records, Scattered, Stitched, Store, Templated};
#[derive(Clone, Debug)]
pub(crate) enum Leaf<'a> {
@@ -259,17 +259,6 @@ impl<'a> Leaf<'a> {
}))
}
pub fn passed(&self) -> Option<Passed<'_, 'a>> {
match self {
Leaf::Input(input) => Some((input, None)),
Leaf::Picked(picked) => match &picked.source {
Leaf::Input(input) => Some((input, Some(&picked.positions))),
_ => None,
},
_ => None,
}
}
pub fn stitched(sources: Vec<Leaf<'a>>, located: Rc<[(usize, usize)]>) -> Leaf<'a> {
Leaf::Stitched(Rc::new(Stitched {
sources,
+1 -1
View File
@@ -14,4 +14,4 @@ pub(crate) use column::Leaf;
pub(crate) use dict::Dict;
pub(crate) use literal::Literal;
pub(crate) use records::{Field, Items, Records};
pub(crate) use views::{Input, Masked, Passed, Picked, Scattered, Stitched, Templated};
pub(crate) use views::{Input, Masked, Picked, Scattered, Stitched, Templated};
-2
View File
@@ -18,8 +18,6 @@ pub(crate) struct Stitched<'a> {
pub(super) dense: OnceCell<Leaf<'a>>,
}
pub(crate) type Passed<'l, 'a> = (&'l Rc<Input<'a>>, Option<&'l Rc<[usize]>>);
#[derive(Debug)]
pub(crate) struct Input<'a> {
pub column: Column<'a>,