Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
f4b7fc4
fix(expression): copy values that read the node's own output on the c…
stefan-gorules Nov 22, 2026
1bdb98d
fix(expression): match a date against every text cell naming it
stefan-gorules Nov 22, 2026
b9d6bef
test(engine): cover the fixed version differences on every evaluation…
stefan-gorules Nov 22, 2026
10ecc76
fix(engine): keep the table index and compiled plan off tables whose …
stefan-gorules Nov 22, 2026
930623b
fix(engine): give batch rows the node values and replaced fields a si…
stefan-gorules Nov 22, 2026
bb51bd2
test(engine): cover the batch and table differences on every evaluati…
stefan-gorules Nov 22, 2026
0f15b19
fix(engine): read declared date inputs in the evaluation's time zone
stefan-gorules Nov 22, 2026
b5e487c
fix(engine): keep script dates right beyond 2099, at extreme years an…
stefan-gorules Nov 22, 2026
eb61ab9
fix(engine): name script modules alike on every traced batch row
stefan-gorules Nov 23, 2026
ec7700b
fix(expression): keep typed batch results and errors equal to the row…
stefan-gorules Nov 23, 2026
8791092
fix(engine): keep loop items, traced table fields and batch node valu…
stefan-gorules Nov 23, 2026
143fcdb
fix(engine): record table references in batch traces when a rule has …
stefan-gorules Nov 23, 2026
71eb599
fix(nodejs): convert decision results, policy traces and handler valu…
stefan-gorules Nov 23, 2026
5382a56
fix(nodejs): reject fractional engine versions
stefan-gorules Nov 23, 2026
76d1562
test(engine): cover null leaves in multi-row batches
stefan-gorules Nov 23, 2026
e39d866
fix(engine): keep a null written under a missing or scalar parent in …
stefan-gorules Nov 23, 2026
469883b
fix(engine): merge a parent reached by duplicate edges once in multi-…
stefan-gorules Nov 23, 2026
3f625b3
fix(engine): let a later table output replace an earlier one under it…
stefan-gorules Nov 23, 2026
6a7b5c9
fix(engine): share common ancestry when batch rows merge related parents
stefan-gorules Nov 23, 2026
cf5f29d
fix(engine): keep one materialization per node so batch joins see sha…
stefan-gorules Nov 23, 2026
96d095d
test(engine): cover policy columns for a tested value that fails
stefan-gorules Nov 23, 2026
9754aa6
fix(engine): return column traces in the legacy format when it is req…
stefan-gorules Nov 23, 2026
5f2a583
fix(engine): return an error instead of building a cyclic value when …
stefan-gorules Nov 23, 2026
c5c07b7
test(engine): cover a script returning a cyclic object on version 2
stefan-gorules Nov 23, 2026
5cdd79e
fix(engine): match version 1 in script globals and dates, stop idle o…
stefan-gorules Nov 23, 2026
ba579f8
fix(engine): leave version 1 table indexes as released and give versi…
stefan-gorules Nov 23, 2026
97227a0
fix(engine): show the tested value under its key when a table reads t…
stefan-gorules Nov 23, 2026
796aaf1
fix(engine): copy values read through $ and leave written-back keys a…
stefan-gorules Nov 23, 2026
21c87ce
perf(engine): keep tables whose outputs read the tested value on the …
stefan-gorules Nov 23, 2026
b4409d6
test(engine): record pinned Date results across zones, DST gaps and f…
stefan-gorules Nov 23, 2026
408fd7b
perf(engine): pin Date in Rust instead of a JavaScript shim on version 2
stefan-gorules Nov 23, 2026
7a08770
fix(engine): keep the machine time zone out of parsed script dates
stefan-gorules Nov 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 19 additions & 7 deletions bindings/nodejs/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::ptr;
use napi::bindgen_prelude::ToNapiValue;
use napi::sys;
use napi::sys::{napi_env, napi_value};
use serde_json::Value;
use zen_engine::{DecisionGraphResponse, EvaluationTrace};
use zen_expression::variable::{RcCell, ToVariable};
use zen_expression::Variable;
Expand All @@ -17,7 +16,6 @@ enum PNode {
Str(Box<str>),
Arr(Vec<u32>),
Obj(Vec<(Box<str>, u32)>),
Json(Value),
}

pub struct PortableArena {
Expand Down Expand Up @@ -68,7 +66,7 @@ impl PortableArena {

PNode::Obj(entries)
}
Variable::Dynamic(d) => PNode::Json(d.to_value()),
Variable::Dynamic(d) => return self.add(&Variable::from(d.to_value()), memo),
};

let id = self.nodes.len() as u32;
Expand All @@ -84,7 +82,6 @@ impl PortableArena {
pub enum TraceField {
None,
Arena(u32),
Json(Value),
}

pub struct NodeEvalResponse {
Expand All @@ -107,7 +104,8 @@ impl NodeEvalResponse {
TraceField::Arena(arena.add(&graph.to_variable(), &mut memo))
}
Some(EvaluationTrace::Policy(policy)) => {
TraceField::Json(serde_json::to_value(&policy).unwrap_or_default())
let value = serde_json::to_value(&policy).unwrap_or_default();
TraceField::Arena(arena.add(&Variable::from(value), &mut memo))
}
Some(EvaluationTrace::V1(document)) => {
TraceField::Arena(arena.add(&document.to_variable(), &mut memo))
Expand Down Expand Up @@ -203,7 +201,6 @@ impl<'a> Materializer<'a> {

Ok(obj)
}
PNode::Json(value) => ToNapiValue::to_napi_value(self.env, value.clone()),
}
}
}
Expand Down Expand Up @@ -231,7 +228,6 @@ impl ToNapiValue for NodeEvalResponse {
let trace = match &val.trace {
TraceField::None => None,
TraceField::Arena(root) => Some(materializer.value(*root)?),
TraceField::Json(value) => Some(ToNapiValue::to_napi_value(env, value.clone())?),
};

if let Some(trace) = trace {
Expand All @@ -242,3 +238,19 @@ impl ToNapiValue for NodeEvalResponse {
Ok(obj)
}
}

pub struct JsonValue(pub serde_json::Value);

impl ToNapiValue for JsonValue {
unsafe fn to_napi_value(env: napi_env, val: Self) -> napi::Result<napi_value> {
let mut arena = PortableArena::new();
let root = arena.add(&Variable::from(val.0), &mut HashMap::new());
let mut materializer = Materializer {
env,
nodes: &arena.nodes,
cache: vec![ptr::null_mut(); arena.nodes.len()],
keys: HashMap::new(),
};
materializer.value(root)
}
}
11 changes: 8 additions & 3 deletions bindings/nodejs/src/decision.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::convert::NodeEvalResponse;
use crate::engine::ZenEvaluateOptions;
use crate::mt::spawn_worker;
use crate::safe_result::SafeResult;
Expand Down Expand Up @@ -28,14 +29,18 @@ impl ZenDecision {
&self,
context: Value,
opts: Option<ZenEvaluateOptions>,
) -> napi::Result<Value> {
) -> napi::Result<NodeEvalResponse> {
let decision = self.0.clone();
let options: zen_engine::EvaluationOptions = opts.unwrap_or_default().try_into()?;
let result = spawn_worker(move || async move {
let context = zen_engine::Variable::try_from_value(context).map_err(
|e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }),
)?;
decision.evaluate_serialized(context, options).await
decision
.evaluate_with_opts(context, options)
.await
.map(NodeEvalResponse::build)
.map_err(|e| serde_json::to_value(&*e).unwrap_or_default())
})
.await
.map_err(|_| anyhow!("Hook timed out"))?
Expand All @@ -51,7 +56,7 @@ impl ZenDecision {
&self,
context: Value,
opts: Option<ZenEvaluateOptions>,
) -> SafeResult<Value> {
) -> SafeResult<NodeEvalResponse> {
self.evaluate(context, opts).await.into()
}

Expand Down
10 changes: 6 additions & 4 deletions bindings/nodejs/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ pub struct ZenEngineOptions {
Option<Function<'static, ZenHttpHandlerRequest, Promise<ZenHttpHandlerResponse>>>,

#[napi(ts_type = "1 | 2")]
pub version: Option<u32>,
pub version: Option<f64>,
}

#[napi]
Expand Down Expand Up @@ -260,9 +260,11 @@ impl ZenEngine {

let mut decision_engine = DecisionEngine::new(loader, Arc::new(custom_node));
if let Some(version) = opts.version {
decision_engine = decision_engine.with_version(
zen_engine::EngineVersion::try_from(version).map_err(|e| anyhow!(e))?,
);
let whole = (version.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&version))
.then_some(version as u32)
.ok_or_else(|| anyhow!("unknown engine version {version}, expected 1 or 2"))?;
decision_engine = decision_engine
.with_version(zen_engine::EngineVersion::try_from(whole).map_err(|e| anyhow!(e))?);
}
if let Some(h) = opts.http_handler {
let http_tsfn = h
Expand Down
16 changes: 8 additions & 8 deletions bindings/nodejs/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,13 @@ impl ZenEngineHandlerRequest {
self.node.clone()
}

#[napi(getter)]
pub fn input(&self) -> Value {
self.input.clone()
#[napi(getter, ts_return_type = "any")]
pub fn input(&self) -> crate::convert::JsonValue {
crate::convert::JsonValue(self.input.clone())
}

#[napi(ts_return_type = "unknown")]
pub fn get_field(&self, path: String) -> napi::Result<Value> {
pub fn get_field(&self, path: String) -> napi::Result<crate::convert::JsonValue> {
let node_config = &self.node.config;

let selected_value: Value = node_config
Expand All @@ -117,17 +117,17 @@ impl ZenEngineHandlerRequest {
.flatten()
.context("Failed to find JSON path")?;
let Value::String(template) = selected_value else {
return Ok(selected_value);
return Ok(crate::convert::JsonValue(selected_value));
};

let template_value = zen_tmpl::render(template.as_str(), Variable::from(&self.input))
.map_err(|e| anyhow!(serde_json::to_string(&e).unwrap_or_else(|_| e.to_string())))?;

Ok(template_value.to_value())
Ok(crate::convert::JsonValue(template_value.to_value()))
}

#[napi(ts_return_type = "unknown")]
pub fn get_field_raw(&self, path: String) -> napi::Result<Value> {
pub fn get_field_raw(&self, path: String) -> napi::Result<crate::convert::JsonValue> {
let node_config = &self.node.config;

let selected_value: Value = node_config
Expand All @@ -136,6 +136,6 @@ impl ZenEngineHandlerRequest {
.flatten()
.context("Failed to find JSON path")?;

Ok(selected_value.clone())
Ok(crate::convert::JsonValue(selected_value.clone()))
}
}
1 change: 1 addition & 0 deletions core/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ doctest = false

[dependencies]
chrono = { workspace = true }
chrono-tz = "0.10"
ahash = { workspace = true }
anyhow = { workspace = true }
base64 = "0.22"
Expand Down
7 changes: 4 additions & 3 deletions core/engine/src/compiled/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ impl DerefMut for Content {

impl Content {
pub(crate) fn of(graph: &GraphContent) -> Self {
let mut graph = graph.clone();
graph.dt_indexes = None;
Self {
graph: graph.clone(),
graph,
compiled_plan: None,
schema_failures: None,
}
Expand Down Expand Up @@ -85,8 +87,7 @@ impl Content {
.iter()
.filter_map(|node| match &node.kind {
DecisionNodeKind::DecisionTableNode { content } => {
TableIndex::build(&content.inputs, &content.rules)
.map(|index| (node.id.clone(), index))
TableIndex::graph(content).map(|index| (node.id.clone(), index))
}
_ => None,
})
Expand Down
9 changes: 9 additions & 0 deletions core/engine/src/compiled/exact/graph/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ impl Row<'_> {
results.push((expression.key.clone(), value.clone()));
}

if result.dot_insert_cycles(&expression.key, &value)
|| session.dollar_cycles(&expression.key, &value)
{
if let Some(results) = results {
self.record(|recorder| recorder.expression(results));
}
return Err(self.error(crate::compiled::exact::Failure::cyclic(&expression.key)));
}

session.insert_dollar(&expression.key, value.clone());

result.dot_insert(&expression.key, value);
Expand Down
4 changes: 4 additions & 0 deletions core/engine/src/compiled/exact/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ impl Failure {
format!(r#"{}: "{source}""#, Self::EXPRESSION)
}

pub fn cyclic(key: &str) -> String {
format!("cyclic value at {key}")
}

pub fn input(error: impl std::fmt::Display) -> String {
format!("{}: {error}", Self::EXPRESSION)
}
Expand Down
16 changes: 15 additions & 1 deletion core/engine/src/compiled/exact/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ impl<'t, 's> RowTable<'t, 's> {
}
}

fn peek(&mut self, col: usize) -> Option<Variable> {
if let Some(value) = &self.refs[col] {
return Some(value.shallow_clone());
}
let field = self.field(col)?;
self.session
.locate(Located::field(self.owner, &self.inputs[col].id));
self.session.run_standard(field).ok()
}

fn bind(&mut self, col: usize) -> Result<bool, ExecutionError> {
let Some(value) = self.reference(col)? else {
return Ok(false);
Expand Down Expand Up @@ -280,7 +290,11 @@ impl RowTable<'_, '_> {
let (Some(_), Some(field)) = (rule.get(&input.id), &input.field) else {
continue;
};
if let Ok(Some(reference)) = self.reference(col) {
let reference = match rule.get(&input.id).is_some_and(|cell| cell.is_empty()) {
true => self.peek(col),
false => self.reference(col).ok().flatten(),
};
if let Some(reference) = reference {
refs.push((field.clone(), reference));
}
}
Expand Down
10 changes: 7 additions & 3 deletions core/engine/src/compiled/graph/columnar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,16 @@ impl CompiledGraph {
})
.collect(),
dated: validator
.map(|(_, schema)| Self::dated(&schema, columns))
.map(|(_, schema)| Self::dated(&schema, columns, extensions.context.timezone()))
.unwrap_or_default(),
})
}

fn dated<'a>(schema: &serde_json::Value, columns: &Columns<'_>) -> Vec<(usize, Leaf<'a>)> {
fn dated<'a>(
schema: &serde_json::Value,
columns: &Columns<'_>,
tz: zen_expression::context::Timezone,
) -> Vec<(usize, Leaf<'a>)> {
if !DeclaredDates::mentions(schema) {
return Vec::new();
}
Expand All @@ -264,7 +268,7 @@ impl CompiledGraph {
let values: Rc<[Variable]> = (0..columns.rows)
.map(|row| {
let value = column.variable(row);
DeclaredDates::prepare(&value, Some(schema)).unwrap_or(value)
DeclaredDates::prepare(&value, Some(schema), tz).unwrap_or(value)
})
.collect();
Some((index, Leaf::Any(values)))
Expand Down
Loading
Loading