Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 12 additions & 5 deletions .github/workflows/rust.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,35 @@ concurrency:

jobs:
test:
name: cargo test (${{ matrix.os }})
name: cargo test (${{ matrix.os }}, ${{ matrix.features.name }})
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- macos-latest
- windows-latest
features:
- name: all features
key: all
flags: --all-features
- name: default features
key: default
flags: ''
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Install Rust
run: rustup update stable
- uses: ./.github/actions/setup-rust
with:
shared-key: rust-test-${{ matrix.os }}
shared-key: rust-test-${{ matrix.os }}-${{ matrix.features.key }}
sccache-bucket: ${{ secrets.SCCACHE_S3_BUCKET }}
sccache-region: ${{ secrets.SCCACHE_AWS_REGION }}
sccache-role-arn: ${{ secrets.SCCACHE_AWS_ROLE_ARN }}
- run: cargo test --workspace --all-features --exclude zen-ffi --exclude zen-nodejs --exclude zen-python --locked
- name: Test without arbitrary_precision
run: cargo test --workspace --exclude zen-ffi --exclude zen-nodejs --exclude zen-python --locked
- uses: taiki-e/install-action@nextest
- run: cargo nextest run --workspace ${{ matrix.features.flags }} --exclude zen-ffi --exclude zen-nodejs --exclude zen-python --locked --no-fail-fast
- run: cargo test --doc --workspace ${{ matrix.features.flags }} --exclude zen-ffi --exclude zen-nodejs --exclude zen-python --exclude zen-engine --locked

fmt:
name: Cargo FMT
Expand Down
17 changes: 10 additions & 7 deletions benchmark/rust/src/bin/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::time::Instant;
use zen_engine::columns::{Column, Columns, Values};
use zen_engine::loader::{FilesystemLoader, FilesystemLoaderOptions, MemoryLoader};
use zen_engine::model::DecisionContent;
use zen_engine::{DecisionEngine, EvaluationOptions, ZEN_CONFIG};
use zen_engine::{DecisionEngine, EvaluationOptions};
use zen_expression::Variable;

struct Counting;
Expand Down Expand Up @@ -667,10 +667,10 @@ async fn main() {
let manifest_path = std::env::args()
.nth(1)
.unwrap_or_else(|| "../manifest.json".to_string());
ZEN_CONFIG.compiled.store(
std::env::var("BENCH_ENGINE").map_or(true, |e| e != "interpreted"),
Ordering::Relaxed,
);
let version = match std::env::var("BENCH_ENGINE").is_ok_and(|e| e == "interpreted") {
true => zen_engine::EngineVersion::V1,
false => zen_engine::EngineVersion::V2,
};
let filter = std::env::var("TRACE_BENCH").ok();
let small_iters: usize = std::env::var("SMALL_ITERS")
.ok()
Expand Down Expand Up @@ -709,7 +709,8 @@ async fn main() {
}
DecisionEngine::default().with_loader(memory)
}
};
}
.with_version(version);
let mut scenarios: Vec<Scenario> = manifest
.iter()
.filter(|e| e.file.starts_with("graphs/") || e.file.starts_with("policies/"))
Expand Down Expand Up @@ -737,7 +738,9 @@ async fn main() {
serde_json::from_value::<DecisionContent>(graph).unwrap(),
);
}
let big = DecisionEngine::default().with_loader(loader);
let big = DecisionEngine::default()
.with_loader(loader)
.with_version(version);
scenarios.push(Scenario {
name: "loops, 50 items".to_string(),
engine: big.clone(),
Expand Down
16 changes: 16 additions & 0 deletions bindings/c/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,22 @@ pub extern "C" fn zen_engine_new_with_loader_config(
ZenResult::ok(Box::into_raw(Box::new(engine)) as *mut ZenEngineStruct)
}

/// Selects the engine version of a ZenEngine instance: 1 is the interpreted engine, 2 the
/// compiled engine. Returns false, and leaves the engine as it is, for any other value or a
/// null engine.
#[no_mangle]
pub extern "C" fn zen_engine_set_version(engine: *mut ZenEngineStruct, version: u32) -> bool {
if engine.is_null() {
return false;
}
let Ok(version) = zen_engine::EngineVersion::try_from(version) else {
return false;
};
let zen_engine = unsafe { &mut *(engine as *mut ZenEngine) };
zen_engine.set_version(version);
true
}

/// Frees the ZenEngine instance reference from the memory
#[no_mangle]
pub extern "C" fn zen_engine_free(engine: *mut ZenEngineStruct) {
Expand Down
7 changes: 7 additions & 0 deletions bindings/c/zen_engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ struct ZenEngineStruct *zen_engine_new(void);
struct ZenResult_ZenEngineStruct zen_engine_new_with_loader_config(struct ZenEngineLoaderConfig config,
struct ZenCustomNodeResult (*maybe_custom_node)(const char *request));

/**
* Selects the engine version of a ZenEngine instance: 1 is the interpreted engine, 2 the
* compiled engine. Returns false, and leaves the engine as it is, for any other value or a
* null engine.
*/
bool zen_engine_set_version(struct ZenEngineStruct *engine, uint32_t version);

/**
* Frees the ZenEngine instance reference from the memory
*/
Expand Down
4 changes: 2 additions & 2 deletions bindings/nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@
"build": "napi build --platform --release --dts index.d.ts",
"build:debug": "napi build --platform --js index.js --dts index.d.ts",
"watch": "cargo watch --ignore '{index.js,index.d.ts}' -- npm run build:debug",
"test": "cross-env __ZEN_MOCK_UTC_TIME=2025-08-19T16:55:02.078Z jest",
"test:wasm": "cross-env NAPI_RS_FORCE_WASI=error NAPI_RS_WASI_FLAVOR=wasm32-wasip1 __ZEN_MOCK_UTC_TIME=2025-08-19T16:55:02.078Z jest -c jest.wasm.config.js",
"test": "jest",
"test:wasm": "cross-env NAPI_RS_FORCE_WASI=error NAPI_RS_WASI_FLAVOR=wasm32-wasip1 jest -c jest.wasm.config.js",
"artifacts": "napi artifacts -d ../../artifacts",
"createNpmDirs": "napi create-npm-dirs && node enrich-npm-dirs.mjs",
"prepublishOnly": "node prepublish.mjs --no-gh-release",
Expand Down
8 changes: 8 additions & 0 deletions bindings/nodejs/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ pub struct ZenEngineOptions {
#[napi(ts_type = "(request: ZenHttpHandlerRequest) => Promise<ZenHttpHandlerResponse>")]
pub http_handler:
Option<Function<'static, ZenHttpHandlerRequest, Promise<ZenHttpHandlerResponse>>>,

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

#[napi]
Expand Down Expand Up @@ -256,6 +259,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))?,
);
}
if let Some(h) = opts.http_handler {
let http_tsfn = h
.build_threadsafe_function()
Expand Down
5 changes: 3 additions & 2 deletions bindings/nodejs/test/decision.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ describe('ZenEngine', () => {
const loader = async (key: string) => fs.readFile(path.join(graphsRoot, key));

const engine = new ZenEngine({ loader });
const now = '2025-08-19T16:55:02.078Z';

const entries = await fs.readdir(graphsRoot);
for (const entry of entries) {
Expand All @@ -136,12 +137,12 @@ describe('ZenEngine', () => {
const fileData: Graph = JSON.parse(fileContents.toString('utf8'));

for (const testCase of fileData.tests) {
const engineResponse = await engine.safeEvaluate(entry, testCase.input);
const engineResponse = await engine.safeEvaluate(entry, testCase.input, { now });

const decision = await engine.safeGetDecision(entry);
assert.ok(decision.success, 'Decision must exist');

const decisionResponse = await decision.data.safeEvaluate(testCase.input);
const decisionResponse = await decision.data.safeEvaluate(testCase.input, { now });

assert.ok(engineResponse.success, 'Engine response must be ok');
assert.ok(decisionResponse.success, 'Decision response must be ok');
Expand Down
9 changes: 8 additions & 1 deletion bindings/python/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,17 @@ impl PyZenEngine {
None => Arc::new(PyDecisionLoader::default()),
};

let engine = DecisionEngine::new(
let mut engine = DecisionEngine::new(
loader,
Arc::new(PyCustomNode::new(custom_node, make_locals())),
);
if let Some(version) = options.get_item("version")? {
let version: u32 = version.extract()?;
engine.set_version(
zen_engine::EngineVersion::try_from(version)
.map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?,
);
}
engine.compile();

Ok(Self {
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/test_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import zen

os.environ['__ZEN_MOCK_UTC_TIME'] = '2025-08-19T16:55:02.078Z'
NOW = "2025-08-19T16:55:02.078Z"

async def loader(key):
with open("../../test-data/" + key, "r") as f:
Expand Down Expand Up @@ -90,9 +90,9 @@ async def test_evaluate_graphs(self):
for test_case in json_contents["tests"]:
key = os.path.basename(json_file)

engine_response = await engine.async_evaluate(key, test_case["input"])
engine_response = await engine.async_evaluate(key, test_case["input"], {"now": NOW})
decision = engine.get_decision(key)
decision_response = await decision.async_evaluate(test_case["input"])
decision_response = await decision.async_evaluate(test_case["input"], {"now": NOW})

self.assertEqual(engine_response["result"], test_case["output"])
self.assertEqual(decision_response["result"], test_case["output"])
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import zen

os.environ['__ZEN_MOCK_UTC_TIME'] = '2025-08-19T16:55:02.078Z'
NOW = "2025-08-19T16:55:02.078Z"

def loader(key):
with open("../../test-data/" + key, "r") as f:
Expand Down Expand Up @@ -165,9 +165,9 @@ def test_evaluate_graphs(self):
for test_case in json_contents["tests"]:
key = os.path.basename(json_file)

engine_response = engine.evaluate(key, test_case["input"])
engine_response = engine.evaluate(key, test_case["input"], {"now": NOW})
decision = engine.get_decision(key)
decision_response = decision.evaluate(test_case["input"])
decision_response = decision.evaluate(test_case["input"], {"now": NOW})

self.assertEqual(engine_response["result"], test_case["output"], key)
self.assertEqual(decision_response["result"], test_case["output"], key)
Expand Down
1 change: 1 addition & 0 deletions bindings/python/zen.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ ZenLoaderCallback: TypeAlias = Callable[[str], Union[str, dict, ZenDecisionConte
class ZenEngineOptions(TypedDict, total=False):
loader: Union[ZenLoaderCallback, ZenLoaderConfig]
customHandler: Callable
version: Literal[1, 2]


class EvaluateBatchRequest(TypedDict):
Expand Down
35 changes: 31 additions & 4 deletions bindings/uniffi/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,11 @@ impl From<ZenEvaluateOptions> for EvaluationOptions {
}
}

#[uniffi::export(async_runtime = "tokio")]
impl ZenEngine {
#[uniffi::constructor(default(loader = None, custom_node = None))]
pub fn new(
fn build(
loader: Option<ZenLoader>,
custom_node: Option<Box<dyn ZenCustomNodeCallback>>,
version: Option<u32>,
) -> Result<Self, ZenError> {
let loader: DynamicLoader = match loader {
Some(loader) => loader.into_dynamic_loader()?,
Expand All @@ -71,18 +70,46 @@ impl ZenEngine {
))),
};

let engine = DecisionEngine::new(
let mut engine = DecisionEngine::new(
loader,
Arc::new(ZenCustomNodeCallbackWrapper(
custom_node.unwrap_or_else(|| Box::new(NoopCustomNodeCallback)),
)),
);
if let Some(version) = version {
engine.set_version(
zen_engine::EngineVersion::try_from(version)
.map_err(|e| ZenError::ValidationError(e.to_string()))?,
);
}
engine.compile();

Ok(Self {
engine: Arc::new(engine),
})
}
}

#[uniffi::export(async_runtime = "tokio")]
impl ZenEngine {
#[uniffi::constructor(default(loader = None, custom_node = None))]
pub fn new(
loader: Option<ZenLoader>,
custom_node: Option<Box<dyn ZenCustomNodeCallback>>,
) -> Result<Self, ZenError> {
Self::build(loader, custom_node, None)
}

/// Creates an engine of the given version: 1 is the interpreted engine, 2 the compiled
/// engine.
#[uniffi::constructor(default(loader = None, custom_node = None))]
pub fn with_version(
version: u32,
loader: Option<ZenLoader>,
custom_node: Option<Box<dyn ZenCustomNodeCallback>>,
) -> Result<Self, ZenError> {
Self::build(loader, custom_node, Some(version))
}

pub async fn evaluate(
&self,
Expand Down
Loading
Loading