diff --git a/.github/workflows/rust.yaml b/.github/workflows/rust.yaml index da7c2a6b3..177fefef0 100644 --- a/.github/workflows/rust.yaml +++ b/.github/workflows/rust.yaml @@ -29,7 +29,7 @@ concurrency: jobs: test: - name: cargo test (${{ matrix.os }}) + name: cargo test (${{ matrix.os }}, ${{ matrix.features.name }}) strategy: fail-fast: false matrix: @@ -37,6 +37,13 @@ jobs: - 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 @@ -44,13 +51,13 @@ jobs: 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 diff --git a/benchmark/rust/src/bin/trace.rs b/benchmark/rust/src/bin/trace.rs index 404e17878..0a7ddf5f8 100644 --- a/benchmark/rust/src/bin/trace.rs +++ b/benchmark/rust/src/bin/trace.rs @@ -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; @@ -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() @@ -709,7 +709,8 @@ async fn main() { } DecisionEngine::default().with_loader(memory) } - }; + } + .with_version(version); let mut scenarios: Vec = manifest .iter() .filter(|e| e.file.starts_with("graphs/") || e.file.starts_with("policies/")) @@ -737,7 +738,9 @@ async fn main() { serde_json::from_value::(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(), diff --git a/bindings/c/src/engine.rs b/bindings/c/src/engine.rs index f7c0d8024..957e32653 100644 --- a/bindings/c/src/engine.rs +++ b/bindings/c/src/engine.rs @@ -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) { diff --git a/bindings/c/zen_engine.h b/bindings/c/zen_engine.h index da5355381..d64db4204 100644 --- a/bindings/c/zen_engine.h +++ b/bindings/c/zen_engine.h @@ -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 */ diff --git a/bindings/nodejs/package.json b/bindings/nodejs/package.json index e82384ce0..f707e97ca 100644 --- a/bindings/nodejs/package.json +++ b/bindings/nodejs/package.json @@ -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", diff --git a/bindings/nodejs/src/engine.rs b/bindings/nodejs/src/engine.rs index 603d5b93c..1236cb3b6 100644 --- a/bindings/nodejs/src/engine.rs +++ b/bindings/nodejs/src/engine.rs @@ -183,6 +183,9 @@ pub struct ZenEngineOptions { #[napi(ts_type = "(request: ZenHttpHandlerRequest) => Promise")] pub http_handler: Option>>, + + #[napi(ts_type = "1 | 2")] + pub version: Option, } #[napi] @@ -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() diff --git a/bindings/nodejs/test/decision.spec.ts b/bindings/nodejs/test/decision.spec.ts index d94d0079b..1e4e518d7 100644 --- a/bindings/nodejs/test/decision.spec.ts +++ b/bindings/nodejs/test/decision.spec.ts @@ -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) { @@ -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'); diff --git a/bindings/python/src/engine.rs b/bindings/python/src/engine.rs index a6b347182..9f0297111 100644 --- a/bindings/python/src/engine.rs +++ b/bindings/python/src/engine.rs @@ -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 { diff --git a/bindings/python/test_async.py b/bindings/python/test_async.py index 0efad8e75..eab33a6b2 100644 --- a/bindings/python/test_async.py +++ b/bindings/python/test_async.py @@ -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: @@ -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"]) diff --git a/bindings/python/test_sync.py b/bindings/python/test_sync.py index 4d0acc0c3..2104fa32d 100644 --- a/bindings/python/test_sync.py +++ b/bindings/python/test_sync.py @@ -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: @@ -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) diff --git a/bindings/python/zen.pyi b/bindings/python/zen.pyi index b0f76cdd5..cef7f275c 100644 --- a/bindings/python/zen.pyi +++ b/bindings/python/zen.pyi @@ -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): diff --git a/bindings/uniffi/src/engine.rs b/bindings/uniffi/src/engine.rs index 00a6d58f2..659093119 100644 --- a/bindings/uniffi/src/engine.rs +++ b/bindings/uniffi/src/engine.rs @@ -57,12 +57,11 @@ impl From for EvaluationOptions { } } -#[uniffi::export(async_runtime = "tokio")] impl ZenEngine { - #[uniffi::constructor(default(loader = None, custom_node = None))] - pub fn new( + fn build( loader: Option, custom_node: Option>, + version: Option, ) -> Result { let loader: DynamicLoader = match loader { Some(loader) => loader.into_dynamic_loader()?, @@ -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, + custom_node: Option>, + ) -> Result { + 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, + custom_node: Option>, + ) -> Result { + Self::build(loader, custom_node, Some(version)) + } pub async fn evaluate( &self, diff --git a/core/engine/src/compiled/mod.rs b/core/engine/src/compiled/mod.rs index 0e33dc099..861299ada 100644 --- a/core/engine/src/compiled/mod.rs +++ b/core/engine/src/compiled/mod.rs @@ -23,92 +23,62 @@ pub use graph::ColumnarOutput; pub(crate) use graph::{call, traced, CompiledGraph, CompiledPlan, Invalid}; pub use output::{OutputColumn, RecordsView}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Engine { - Configured, - Interpreted, - Compiled, +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +pub enum EngineVersion { + #[default] + V1, + V2, } -thread_local! { - static INTERPRETING: std::cell::Cell = const { std::cell::Cell::new(false) }; -} +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("unknown engine version {0}, expected 1 or 2")] +pub struct UnknownEngineVersion(pub u32); -impl Engine { - pub(crate) fn compiled(self) -> bool { - match self { - Engine::Configured => { - !INTERPRETING.get() - && crate::ZEN_CONFIG - .compiled - .load(std::sync::atomic::Ordering::Relaxed) - } - Engine::Interpreted => false, - Engine::Compiled => true, - } - } - - pub(crate) fn scopes(self) -> bool { - self == Engine::Interpreted && !INTERPRETING.get() - } +impl TryFrom for EngineVersion { + type Error = UnknownEngineVersion; - pub(crate) fn interpreting(future: F) -> Interpreting { - Interpreting(Box::pin(future)) + fn try_from(value: u32) -> Result { + match value { + 1 => Ok(EngineVersion::V1), + 2 => Ok(EngineVersion::V2), + other => Err(UnknownEngineVersion(other)), + } } } -pub(crate) struct Interpreting(std::pin::Pin>); - -struct Restore(bool); - -impl Drop for Restore { - fn drop(&mut self) { - INTERPRETING.set(self.0); +impl From for u32 { + fn from(value: EngineVersion) -> Self { + match value { + EngineVersion::V1 => 1, + EngineVersion::V2 => 2, + } } } -impl std::future::Future for Interpreting { - type Output = F::Output; - - fn poll( - mut self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll { - let _restore = Restore(INTERPRETING.replace(true)); - self.0.as_mut().poll(cx) +impl From for Engine { + fn from(value: EngineVersion) -> Self { + match value { + EngineVersion::V1 => Engine::Interpreted, + EngineVersion::V2 => Engine::Compiled, + } } } -#[cfg(test)] -mod tests { - use super::Engine; - - fn run(future: F) -> F::Output { - tokio::runtime::Builder::new_current_thread() - .build() - .expect("runtime") - .block_on(future) - } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Engine { + Interpreted, + Compiled, +} - #[test] - fn the_interpreting_scope_overrides_only_the_configured_engine() { - let inside = run(Engine::interpreting(async { - ( - Engine::Configured.compiled(), - Engine::Compiled.compiled(), - Engine::Interpreted.scopes(), - ) - })); - assert_eq!(inside, (false, true, false)); - assert!(Engine::Interpreted.scopes()); +impl Engine { + pub(crate) fn version(self) -> EngineVersion { + match self { + Engine::Compiled => EngineVersion::V2, + Engine::Interpreted => EngineVersion::V1, + } } - #[test] - fn the_interpreting_scope_is_restored_after_a_panic() { - let panicked = std::panic::catch_unwind(|| { - run(Engine::interpreting(async { panic!("inside the scope") })) - }); - assert!(panicked.is_err()); - assert!(Engine::Interpreted.scopes()); + pub(crate) fn compiled(self) -> bool { + self == Engine::Compiled } } diff --git a/core/engine/src/compiled/trace/migrate/api.rs b/core/engine/src/compiled/trace/migrate/api.rs index bcc0a4d8c..2da34c048 100644 --- a/core/engine/src/compiled/trace/migrate/api.rs +++ b/core/engine/src/compiled/trace/migrate/api.rs @@ -293,7 +293,8 @@ pub fn restore_json(args: RestoreArgs) -> Result { pub mod testing { pub use crate::compiled::trace::value::{eq, json_len, parse, Obj, Val}; pub use crate::compiled::trace::{ - batch_writes, columnar_traced, graph_runs, native_misses, policy_pair, reevaluations, + batch_writes, columnar_traced, counters, graph_runs, native_misses, policy_pair, + reevaluations, Counters, }; pub fn repack(doc: &str) -> Option { diff --git a/core/engine/src/compiled/trace/mod.rs b/core/engine/src/compiled/trace/mod.rs index 1f6fa8599..db7c430ed 100644 --- a/core/engine/src/compiled/trace/mod.rs +++ b/core/engine/src/compiled/trace/mod.rs @@ -402,71 +402,83 @@ impl Request { } } -static MISSES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -static COLUMNAR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -static ROWWISE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[doc(hidden)] +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Counters { + pub misses: usize, + pub columnar: usize, + pub rowwise: usize, + pub planned: usize, + pub batched: usize, + pub runs: usize, + pub reevaluated: std::collections::BTreeMap<&'static str, usize>, +} + +impl Counters { + pub fn add(&mut self, other: &Counters) { + self.misses += other.misses; + self.columnar += other.columnar; + self.rowwise += other.rowwise; + self.planned += other.planned; + self.batched += other.batched; + self.runs += other.runs; + for (reason, rows) in &other.reevaluated { + *self.reevaluated.entry(reason).or_default() += rows; + } + } +} thread_local! { - static RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static COUNTERS: std::cell::RefCell = std::cell::RefCell::new(Counters::default()); +} + +fn count(update: impl FnOnce(&mut Counters)) { + COUNTERS.with_borrow_mut(update); +} + +#[doc(hidden)] +pub fn counters() -> Counters { + COUNTERS.with_borrow(Clone::clone) } pub(crate) fn count_run() { - RUNS.set(RUNS.get() + 1); + count(|c| c.runs += 1); } #[doc(hidden)] pub fn graph_runs() -> usize { - RUNS.get() + COUNTERS.with_borrow(|c| c.runs) } -static PLANNED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -static BATCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - pub(crate) fn count_columnar(planned: bool, rows: usize) { - let counter = match planned { - true => &PLANNED, - false => &BATCHED, - }; - counter.fetch_add(rows, std::sync::atomic::Ordering::Relaxed); + count(|c| match planned { + true => c.planned += rows, + false => c.batched += rows, + }); } #[doc(hidden)] pub fn columnar_traced() -> (usize, usize) { - ( - PLANNED.load(std::sync::atomic::Ordering::Relaxed), - BATCHED.load(std::sync::atomic::Ordering::Relaxed), - ) + COUNTERS.with_borrow(|c| (c.planned, c.batched)) } #[doc(hidden)] pub fn batch_writes() -> (usize, usize) { - ( - COLUMNAR.load(std::sync::atomic::Ordering::Relaxed), - ROWWISE.load(std::sync::atomic::Ordering::Relaxed), - ) + COUNTERS.with_borrow(|c| (c.columnar, c.rowwise)) } -static REEVALUATED: std::sync::Mutex> = - std::sync::Mutex::new(std::collections::BTreeMap::new()); - pub(crate) fn reevaluated(reason: &'static str, rows: usize) { - if let Ok(mut counts) = REEVALUATED.lock() { - *counts.entry(reason).or_default() += rows; - } + count(|c| *c.reevaluated.entry(reason).or_default() += rows); } #[doc(hidden)] pub fn reevaluations() -> Vec<(&'static str, usize)> { - REEVALUATED - .lock() - .map(|counts| counts.iter().map(|(k, v)| (*k, *v)).collect()) - .unwrap_or_default() + COUNTERS.with_borrow(|c| c.reevaluated.iter().map(|(k, v)| (*k, *v)).collect()) } #[doc(hidden)] pub fn native_misses() -> usize { - MISSES.load(std::sync::atomic::Ordering::Relaxed) + COUNTERS.with_borrow(|c| c.misses) } pub(crate) fn written_at( @@ -489,7 +501,7 @@ pub(crate) fn written_at( match v1::write::write(args) { Ok(output) => TraceDocument::from_output(output), Err(miss) => { - MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + count(|c| c.misses += 1); if std::env::var("ZEN_TRACE_NATIVE_DEBUG").is_ok_and(|v| v != "0") { eprintln!("native trace fell back: {miss}"); } @@ -696,7 +708,7 @@ impl<'a> TraceBatch<'a> { eprintln!("columnar fallback: {reason}"); } out.truncate(mark); - ROWWISE.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + count(|c| c.rowwise += 1); return false; } if verify() { @@ -717,11 +729,11 @@ impl<'a> TraceBatch<'a> { eprintln!("columnar trace row {row} differs: {}", &out[mark..]); } out.truncate(mark); - ROWWISE.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + count(|c| c.rowwise += 1); return false; } } - COLUMNAR.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + count(|c| c.columnar += 1); true } diff --git a/core/engine/src/config.rs b/core/engine/src/config.rs index 8116d6042..424eefe59 100644 --- a/core/engine/src/config.rs +++ b/core/engine/src/config.rs @@ -6,7 +6,6 @@ pub struct ZenConfig { pub nodes_in_context: AtomicBool, pub function_timeout_millis: AtomicU64, pub http_auth: AtomicBool, - pub compiled: AtomicBool, } impl Default for ZenConfig { @@ -15,7 +14,6 @@ impl Default for ZenConfig { nodes_in_context: AtomicBool::new(true), function_timeout_millis: AtomicU64::new(5_000), http_auth: AtomicBool::new(true), - compiled: AtomicBool::new(false), } } } diff --git a/core/engine/src/decision.rs b/core/engine/src/decision.rs index b7558a6a0..a25392d91 100644 --- a/core/engine/src/decision.rs +++ b/core/engine/src/decision.rs @@ -30,7 +30,7 @@ impl From for Decision { adapter: Arc::new(NoopCustomNode::default()), http_handler: None, compiled: OnceLock::new(), - engine: crate::compiled::Engine::Configured, + engine: crate::compiled::Engine::Interpreted, } } } @@ -43,7 +43,7 @@ impl From> for Decision { adapter: Arc::new(NoopCustomNode::default()), http_handler: None, compiled: OnceLock::new(), - engine: crate::compiled::Engine::Configured, + engine: crate::compiled::Engine::Interpreted, } } } @@ -97,6 +97,7 @@ impl Decision { dt_indexes: self.content.dt_indexes.clone(), stripped_functions: self.content.stripped_functions.clone(), validator_cache: Arc::new(OnceCell::from(self.content.validator_cache.clone())), + now: options.now, ..Default::default() }, })?; @@ -161,6 +162,17 @@ impl Decision { self } + pub fn with_version(&self, version: crate::EngineVersion) -> Self { + Self { + engine: version.into(), + ..self.clone() + } + } + + pub fn version(&self) -> crate::EngineVersion { + self.engine.version() + } + #[doc(hidden)] pub fn interpreted(&self) -> Self { Self { diff --git a/core/engine/src/decision_graph/graph.rs b/core/engine/src/decision_graph/graph.rs index 107e59735..710c1edbf 100644 --- a/core/engine/src/decision_graph/graph.rs +++ b/core/engine/src/decision_graph/graph.rs @@ -171,6 +171,7 @@ impl DecisionGraph { } let mut walker = GraphWalker::new(&self.graph); + walker.now = self.config.extensions.now; let mut tracer = NodeTracer::new(self.config.trace); while let Some(nid) = walker.next(&mut self.graph, tracer.trace_callback()) { diff --git a/core/engine/src/decision_graph/walker.rs b/core/engine/src/decision_graph/walker.rs index b9ff9f891..b3c97d20a 100644 --- a/core/engine/src/decision_graph/walker.rs +++ b/core/engine/src/decision_graph/walker.rs @@ -34,6 +34,7 @@ pub(crate) struct GraphWalker { visited_switch_nodes: Vec, nodes_in_context: bool, + pub(crate) now: Option, } const ITER_MAX: usize = 1_000; @@ -63,6 +64,7 @@ impl GraphWalker { iter: 0, nodes_in_context: ZEN_CONFIG.nodes_in_context.load(Ordering::Relaxed), + now: None, } } @@ -168,7 +170,7 @@ impl GraphWalker { if let DecisionNodeKind::SwitchNode { content } = &decision_node.kind { if !self.visited_switch_nodes.contains(&nid) { let (input, input_trace) = self.incoming_node_data(g, nid); - let mut isolate = Isolate::with_environment(input); + let mut isolate = Isolate::with_environment(input).with_now(self.now); if let Some(nodes) = self.nodes_context() { isolate.set_local(Variable::nodes_key(), nodes); } diff --git a/core/engine/src/engine.rs b/core/engine/src/engine.rs index e88899dd7..c30bf608e 100644 --- a/core/engine/src/engine.rs +++ b/core/engine/src/engine.rs @@ -95,7 +95,7 @@ impl Default for DecisionEngine { http_handler: None, compiled: Arc::new(ArcSwapOption::empty()), caches: Default::default(), - engine: crate::compiled::Engine::Configured, + engine: crate::compiled::Engine::Interpreted, } } } @@ -108,7 +108,7 @@ impl DecisionEngine { http_handler: None, compiled: Arc::new(ArcSwapOption::empty()), caches: Default::default(), - engine: crate::compiled::Engine::Configured, + engine: crate::compiled::Engine::Interpreted, } } @@ -196,17 +196,11 @@ impl DecisionEngine { .evaluate_pinned(&self.parts(), key_str, context, options) .await?; } - if self.engine.scopes() { - return crate::compiled::Engine::interpreting( - self.evaluate_with_opts(key_str, context, options), - ) - .await; - } if let Some(set) = self.compiled.load_full() { if let Some(entry) = set.get(key_str) { return match entry { CompiledEntry::Policy(artifact) => artifact - .evaluate_entry(key_str, context, options.trace.is_on()) + .evaluate_entry(key_str, context, options.trace.is_on(), options.now) .map(DecisionGraphResponse::from) .map_err(|e| Box::new(EvaluationError::Policy(e.into()))), CompiledEntry::Graph(graph) => { @@ -252,19 +246,18 @@ impl DecisionEngine { .evaluate_serialized_pinned(&self.parts(), key_str, context, options) .await; } - if self.engine.scopes() { - return crate::compiled::Engine::interpreting( - self.evaluate_serialized(key_str, context, options), - ) - .await; - } if let Some(set) = self.compiled.load_full() { if let Some(entry) = set.get(key_str) { match entry { CompiledEntry::Policy(artifact) => { return DecisionGraphResponse::serialized( artifact - .evaluate_entry(key_str, context, options.trace.is_on()) + .evaluate_entry( + key_str, + context, + options.trace.is_on(), + options.now, + ) .map(DecisionGraphResponse::from) .map_err(|e| Box::new(EvaluationError::Policy(e.into()))), ); @@ -316,6 +309,19 @@ impl DecisionEngine { .await } + pub fn with_version(mut self, version: crate::EngineVersion) -> Self { + self.engine = version.into(); + self + } + + pub fn set_version(&mut self, version: crate::EngineVersion) { + self.engine = version.into(); + } + + pub fn version(&self) -> crate::EngineVersion { + self.engine.version() + } + #[doc(hidden)] pub fn interpreted(mut self) -> Self { self.engine = crate::compiled::Engine::Interpreted; diff --git a/core/engine/src/lib.rs b/core/engine/src/lib.rs index b69b70646..d24e5b1a5 100644 --- a/core/engine/src/lib.rs +++ b/core/engine/src/lib.rs @@ -151,7 +151,9 @@ pub mod columns { } pub use compiled::trace::api as trace; -pub use compiled::{ColumnarOutput, OutputColumn, RecordsView}; +pub use compiled::{ + ColumnarOutput, EngineVersion, OutputColumn, RecordsView, UnknownEngineVersion, +}; pub use config::ZEN_CONFIG; pub use decision::Decision; pub use decision_graph::{ diff --git a/core/engine/src/nodes/context.rs b/core/engine/src/nodes/context.rs index 3c8041d90..cd70e93f4 100644 --- a/core/engine/src/nodes/context.rs +++ b/core/engine/src/nodes/context.rs @@ -330,8 +330,9 @@ pub(crate) fn make_isolate( nodes: Option<&Variable>, extensions: &NodeHandlerExtensions, ) -> Isolate { - let mut isolate = - Isolate::with_environment(input.clone()).with_cache(extensions.compiled_cache.clone()); + let mut isolate = Isolate::with_environment(input.clone()) + .with_cache(extensions.compiled_cache.clone()) + .with_now(extensions.now); if let Some(nodes) = nodes { isolate.set_local(Variable::nodes_key(), nodes.clone()); } diff --git a/core/engine/src/nodes/extensions.rs b/core/engine/src/nodes/extensions.rs index 4ee463288..e6c2cd912 100644 --- a/core/engine/src/nodes/extensions.rs +++ b/core/engine/src/nodes/extensions.rs @@ -23,6 +23,7 @@ pub struct NodeHandlerExtensions { pub(crate) compiled_cache: Option>, pub(crate) stripped_functions: Option, Arc>>>, pub(crate) dt_indexes: Option, TableIndex>>>, + pub(crate) now: Option, } impl Default for NodeHandlerExtensions { @@ -37,6 +38,7 @@ impl Default for NodeHandlerExtensions { stripped_functions: None, dt_indexes: None, http_handler: None, + now: None, } } } diff --git a/core/engine/src/policy/evaluator.rs b/core/engine/src/policy/evaluator.rs index 5acb78c9c..81412a3ee 100644 --- a/core/engine/src/policy/evaluator.rs +++ b/core/engine/src/policy/evaluator.rs @@ -41,7 +41,11 @@ pub(crate) struct EvalArtifact { } impl Db { - pub fn evaluate(&self, req: &EvaluateRequest) -> Result { + pub fn evaluate_at( + &self, + req: &EvaluateRequest, + now: Option, + ) -> Result { if self.is_graph(&req.policy_path) { return Err(EvaluationError::GraphNotEvaluable(req.policy_path.clone())); } @@ -49,12 +53,14 @@ impl Db { return Err(EvaluationError::PolicyNotFound(req.policy_path.clone())); } self.check_imports_resolved(&req.policy_path)?; - self.eval_artifact(&req.policy_path).evaluate(req, false) + self.eval_artifact(&req.policy_path) + .evaluate(req, false, now) } pub fn enhance_trace( &self, req: &EvaluateRequest, + now: Option, ) -> Result { if self.is_graph(&req.policy_path) { return Err(EvaluationError::GraphNotEvaluable(req.policy_path.clone())); @@ -65,7 +71,8 @@ impl Db { self.check_imports_resolved(&req.policy_path)?; let mut req = req.clone(); req.trace = true; - self.eval_artifact(&req.policy_path).evaluate(&req, true) + self.eval_artifact(&req.policy_path) + .evaluate(&req, true, now) } fn check_imports_resolved(&self, entry: &Arc) -> Result<(), EvaluationError> { @@ -99,6 +106,7 @@ impl EvalArtifact { key: &str, input: Variable, trace: bool, + now: Option, ) -> Result { let request = EvaluateRequest { policy_path: Arc::from(key), @@ -106,13 +114,14 @@ impl EvalArtifact { goals: Vec::new(), trace, }; - self.evaluate(&request, false) + self.evaluate(&request, false, now) } pub(crate) fn evaluate( &self, req: &EvaluateRequest, extras: bool, + now: Option, ) -> Result { let start = Instant::now(); @@ -138,7 +147,7 @@ impl EvalArtifact { } else { req.goals.clone() }; - let mut driver = Driver::new(self, &store, &req.policy_path, req.trace, extras); + let mut driver = Driver::new(self, &store, &req.policy_path, req.trace, extras, now); let outcome = roots.iter().try_for_each(|root| driver.demand(root)); let trace = req.trace.then(|| Trace { @@ -417,10 +426,13 @@ impl<'a> Driver<'a> { entry: &'a Arc, trace: bool, extras: bool, + now: Option, ) -> Self { Self { isolate: Rc::new(RefCell::new( - Isolate::new().with_cache(Some(artifact.opcode_cache.clone())), + Isolate::new() + .with_cache(Some(artifact.opcode_cache.clone())) + .with_now(now), )), artifact, store, diff --git a/core/engine/src/policy/runtime.rs b/core/engine/src/policy/runtime.rs index 6007d3ec5..efe023ee1 100644 --- a/core/engine/src/policy/runtime.rs +++ b/core/engine/src/policy/runtime.rs @@ -54,7 +54,7 @@ pub(crate) async fn evaluate_policy( }; let result = workspace - .evaluate(&request) + .evaluate_pinned(&request, &options) .map_err(|e| Box::new(EvaluationError::Policy(e)))?; Ok(DecisionGraphResponse { diff --git a/core/engine/src/workspace/mod.rs b/core/engine/src/workspace/mod.rs index 6afdfb4b3..752e9326b 100644 --- a/core/engine/src/workspace/mod.rs +++ b/core/engine/src/workspace/mod.rs @@ -49,7 +49,7 @@ impl Workspace { Self { db: Db::new(), compiled: Default::default(), - engine: crate::compiled::Engine::Configured, + engine: crate::compiled::Engine::Interpreted, } } @@ -107,15 +107,23 @@ impl Workspace { &context, ); } - self.evaluate_with_driver(req) + self.evaluate_with_driver(req, options.now) } pub fn enhance_trace( &self, req: &EvaluateRequest, + ) -> Result { + self.enhance_trace_pinned(req, &Default::default()) + } + + pub fn enhance_trace_pinned( + &self, + req: &EvaluateRequest, + options: &crate::EvaluationOptions, ) -> Result { if self.engine.compiled() { - let context = crate::compiled::pinning::single(&Default::default()); + let context = crate::compiled::pinning::single(options); return crate::compiled::policy::artifact::Runtime::enhance_trace( &self.db, &self.compiled, @@ -123,7 +131,7 @@ impl Workspace { &context, ); } - self.enhance_trace_with_driver(req) + self.enhance_trace_with_driver(req, options.now) } pub fn evaluate_batch( @@ -176,9 +184,10 @@ impl Workspace { pub fn evaluate_with_driver( &self, req: &EvaluateRequest, + now: Option, ) -> Result { self.db - .evaluate(&req.legacy()) + .evaluate_at(&req.legacy(), now) .map(Into::into) .map_err(Into::into) } @@ -187,13 +196,27 @@ impl Workspace { pub fn enhance_trace_with_driver( &self, req: &EvaluateRequest, + now: Option, ) -> Result { self.db - .enhance_trace(&req.legacy()) + .enhance_trace(&req.legacy(), now) .map(Into::into) .map_err(Into::into) } + pub fn with_version(mut self, version: crate::EngineVersion) -> Self { + self.engine = version.into(); + self + } + + pub fn set_version(&mut self, version: crate::EngineVersion) { + self.engine = version.into(); + } + + pub fn version(&self) -> crate::EngineVersion { + self.engine.version() + } + #[doc(hidden)] pub fn interpreted(mut self) -> Self { self.engine = crate::compiled::Engine::Interpreted; diff --git a/core/engine/tests/bench_matrix.rs b/core/engine/tests/bench_matrix.rs index 52d9ada35..fcb528715 100644 --- a/core/engine/tests/bench_matrix.rs +++ b/core/engine/tests/bench_matrix.rs @@ -1,9 +1,9 @@ #![allow(dead_code)] -mod compiled_default; mod conformance; #[path = "support/fixture.rs"] mod fixture; +mod latest; #[path = "support/policies.rs"] mod policies; #[path = "support/policy_gen.rs"] @@ -13,6 +13,7 @@ mod support; use conformance::run::{GraphRun, PolicyRun}; use conformance::{Dialect, Spec}; use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND}; +use latest::Latest; use policies::Anchor; use policy_gen::{Gen, Rng}; use serde_json::{json, Value}; @@ -21,7 +22,7 @@ use std::sync::Arc; use std::time::Instant; use support::columns::Built; use zen_engine::policy::{EvaluateRequest, PolicyWorkspace}; -use zen_engine::{Decision, DecisionEngine, EvaluationOptions}; +use zen_engine::{Decision, DecisionEngine}; use zen_expression::Variable; struct Matrix { @@ -138,25 +139,33 @@ impl Matrix { rt.block_on(async { for decision in [&job.walker, &job.compiled] { for input in fresh().into_iter().take(2) { - let _ = decision.evaluate(input).await; + let _ = decision + .evaluate_with_opts(input, crate::support::Clock::options()) + .await; } } let _ = job .compiled - .evaluate_batch(&fresh(), EvaluationOptions::default()) + .evaluate_batch(&fresh(), crate::support::Clock::options()) .await; }); let old = self.best(count, fresh, |inputs| { rt.block_on(async { for input in inputs { - let _ = job.walker.evaluate(input).await; + let _ = job + .walker + .evaluate_with_opts(input, crate::support::Clock::options()) + .await; } }) }); let single = self.best(count, fresh, |inputs| { rt.block_on(async { for input in inputs { - let _ = job.compiled.evaluate(input).await; + let _ = job + .compiled + .evaluate_with_opts(input, crate::support::Clock::options()) + .await; } }) }); @@ -164,7 +173,9 @@ impl Matrix { Some((engine, key)) => self.best(count, fresh, |inputs| { rt.block_on(async { for input in inputs { - let _ = engine.evaluate(key, input).await; + let _ = engine + .evaluate_with_opts(key, input, crate::support::Clock::options()) + .await; } }) }), @@ -174,7 +185,7 @@ impl Matrix { rt.block_on(async { drop( job.compiled - .evaluate_batch(&inputs, EvaluationOptions::default()) + .evaluate_batch(&inputs, crate::support::Clock::options()) .await, ); }) @@ -185,14 +196,14 @@ impl Matrix { rt.block_on(async { drop( job.compiled - .evaluate_columns(columns, EvaluationOptions::default()) + .evaluate_columns(columns, crate::support::Clock::options()) .await, ); for _ in 0..reps { let start = Instant::now(); drop( job.compiled - .evaluate_columns(columns, EvaluationOptions::default()) + .evaluate_columns(columns, crate::support::Clock::options()) .await, ); columnar = columnar.min(start.elapsed().as_nanos() as f64 / count as f64); @@ -207,7 +218,9 @@ impl Matrix { let walker = job.cold.clone().interpreted(); rt.block_on(async { for input in inputs { - let _ = walker.evaluate(input).await; + let _ = walker + .evaluate_with_opts(input, crate::support::Clock::options()) + .await; } }) }, @@ -219,7 +232,9 @@ impl Matrix { let decision = job.cold.clone(); rt.block_on(async { for input in inputs { - let _ = decision.evaluate(input).await; + let _ = decision + .evaluate_with_opts(input, crate::support::Clock::options()) + .await; } }) }, @@ -252,10 +267,10 @@ impl Matrix { }; let ws = job.workspace; for request in requests().iter().take(2) { - let _ = ws.evaluate_with_driver(request); - let _ = ws.evaluate(request); + let _ = ws.evaluate_with_driver(request, crate::support::Clock::now()); + let _ = ws.evaluate_pinned(request, &crate::support::Clock::options()); } - drop(ws.evaluate_batch(&requests())); + drop(ws.evaluate_batch_pinned(&requests(), &crate::support::Clock::options())); let time = |run: &dyn Fn(Vec)| { let mut best = f64::INFINITY; for _ in 0..self.reps { @@ -266,9 +281,19 @@ impl Matrix { } best }; - let old = time(&|batch| batch.iter().for_each(|r| drop(ws.evaluate_with_driver(r)))); - let single = time(&|batch| batch.iter().for_each(|r| drop(ws.evaluate(r)))); - let batch = time(&|batch| drop(ws.evaluate_batch(&batch))); + let old = time(&|batch| { + batch + .iter() + .for_each(|r| drop(ws.evaluate_with_driver(r, crate::support::Clock::now()))) + }); + let single = time(&|batch| { + batch + .iter() + .for_each(|r| drop(ws.evaluate_pinned(r, &crate::support::Clock::options()))) + }); + let batch = time(&|batch| { + drop(ws.evaluate_batch_pinned(&batch, &crate::support::Clock::options())) + }); let engine = match job.engine { Some((engine, key)) => { let rt = &self.runtime; @@ -280,7 +305,9 @@ impl Matrix { self.best(count, fresh, |inputs| { rt.block_on(async { for input in inputs { - let _ = engine.evaluate(key, input).await; + let _ = engine + .evaluate_with_opts(key, input, crate::support::Clock::options()) + .await; } }) }) @@ -290,10 +317,20 @@ impl Matrix { let mut columnar = f64::INFINITY; let reps = self.reps; Self::columns(&rows, |columns| { - drop(ws.evaluate_columns(&job.path, &job.goals, columns)); + drop(ws.evaluate_columns_pinned( + &job.path, + &job.goals, + columns, + &crate::support::Clock::options(), + )); for _ in 0..reps { let start = Instant::now(); - drop(ws.evaluate_columns(&job.path, &job.goals, columns)); + drop(ws.evaluate_columns_pinned( + &job.path, + &job.goals, + columns, + &crate::support::Clock::options(), + )); columnar = columnar.min(start.elapsed().as_nanos() as f64 / count as f64); } }); @@ -308,8 +345,12 @@ impl Matrix { let start = Instant::now(); let ws = build(); match driver { - true => drop(ws.evaluate_with_driver(&request)), - false => drop(ws.evaluate(&request)), + true => drop( + ws.evaluate_with_driver(&request, crate::support::Clock::now()), + ), + false => drop( + ws.evaluate_pinned(&request, &crate::support::Clock::options()), + ), } best = best.min(start.elapsed().as_nanos() as f64); } @@ -372,7 +413,7 @@ fn bench_matrix() { } if wants("fixtures") { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let loader = Arc::new(support::create_fs_loader()); for fixture in Fixture::load_all() { if NETWORK_BOUND.contains(&fixture.name.as_str()) @@ -380,8 +421,9 @@ fn bench_matrix() { { continue; } - let decision = - Decision::from(Arc::new(fixture.content.clone())).with_loader(loader.clone()); + let decision = Decision::from(Arc::new(fixture.content.clone())) + .latest() + .with_loader(loader.clone()); let job = GraphJob { corpus: "fixtures", case: fixture.name.clone(), @@ -439,13 +481,13 @@ fn bench_matrix() { continue; }; let build = || { - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().latest(); if let Ok(parsed) = serde_json::from_value(Gen::document(seed)) { ws.set_policy("generated.json", parsed); } ws }; - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().latest(); ws.set_policy("generated.json", parsed); let mut rng = Rng(seed.wrapping_mul(7919) | 1); let rows: Vec = (0..64).map(|_| Gen::valid_input(&mut rng)).collect(); @@ -505,8 +547,8 @@ fn columnar_reasons() { decision: &Decision, rows: Vec| { Matrix::columns(&rows, |columns| { - let output = - runtime.block_on(decision.evaluate_columns(columns, EvaluationOptions::default())); + let output = runtime + .block_on(decision.evaluate_columns(columns, crate::support::Clock::options())); let verdict = match zen_engine::diagnostics::plan_verdict(decision, columns) { Some(Ok(())) => "planned".to_string(), Some(Err(reason)) => reason, @@ -538,7 +580,7 @@ fn columnar_reasons() { graph(&mut out, "spec-graph", suite.id(), &run.compiled, rows) })); } - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let loader = Arc::new(support::create_fs_loader()); for fixture in Fixture::load_all() { if NETWORK_BOUND.contains(&fixture.name.as_str()) @@ -546,8 +588,9 @@ fn columnar_reasons() { { continue; } - let decision = - Decision::from(Arc::new(fixture.content.clone())).with_loader(loader.clone()); + let decision = Decision::from(Arc::new(fixture.content.clone())) + .latest() + .with_loader(loader.clone()); let rows = cycled(&fixture.variants()); let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { graph(&mut out, "fixtures", fixture.name.clone(), &decision, rows) @@ -561,7 +604,12 @@ fn columnar_reasons() { goals: &[Arc], rows: Vec| { Matrix::columns(&rows, |columns| { - let line = match ws.evaluate_columns(path, goals, columns) { + let line = match ws.evaluate_columns_pinned( + path, + goals, + columns, + &crate::support::Clock::options(), + ) { Ok(output) => { let paths = output.paths(); let errors = output.errors.iter().filter(|e| e.is_some()).count(); @@ -612,7 +660,7 @@ fn columnar_reasons() { let Ok(parsed) = serde_json::from_value(Gen::document(seed)) else { continue; }; - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().latest(); ws.set_policy("generated.json", parsed); let mut rng = Rng(seed.wrapping_mul(7919) | 1); let rows = cycled( diff --git a/core/engine/tests/ceiling_lists.rs b/core/engine/tests/ceiling_lists.rs index df3beafc4..6b01c50cc 100644 --- a/core/engine/tests/ceiling_lists.rs +++ b/core/engine/tests/ceiling_lists.rs @@ -1,6 +1,7 @@ -mod compiled_default; +mod latest; mod support; +use latest::Latest; use rust_decimal::Decimal; use serde_json::{json, Value}; use std::fs; @@ -9,7 +10,7 @@ use std::sync::Arc; use std::time::Instant; use support::test_data_root; use zen_engine::model::DecisionContent; -use zen_engine::{Decision, EvaluationOptions}; +use zen_engine::Decision; use zen_expression::Variable; enum Buf { @@ -651,20 +652,20 @@ impl Fixture { #[tokio::test] #[ignore] async fn ceiling_product_listing_scoring() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let rows: usize = std::env::var("BENCH_ROWS") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(1024); let (content, variants) = Fixture::load(); - let mut compiled = Decision::from(Arc::new(content)); + let mut compiled = Decision::from(Arc::new(content)).latest(); compiled.compile(); assert!(matches!( zen_engine::diagnostics::compiled_verdict(&compiled), Some(Ok(())) )); let walker = compiled.interpreted(); - let options = EvaluationOptions::default(); + let options = crate::support::Clock::options(); let sets: Vec<(&str, Vec)> = vec![ ( "harness", @@ -685,7 +686,10 @@ async fn ceiling_product_listing_scoring() { let engine = compiled.evaluate_columns(&columns, options).await; let mut mismatches = 0; for r in 0..rows { - let want = match walker.evaluate(columns.row(r)).await { + let want = match walker + .evaluate_with_opts(columns.row(r), crate::support::Clock::options()) + .await + { Ok(v) => Some(Built::normalized(v.result.to_value())), Err(_) => None, }; @@ -750,7 +754,9 @@ async fn ceiling_product_listing_scoring() { for _ in 0..9 { let t = Instant::now(); for c in (0..rows.min(256)).map(|r| columns.row(r)) { - let _ = walker.evaluate(c).await; + let _ = walker + .evaluate_with_opts(c, crate::support::Clock::options()) + .await; } best[0] = best[0].min(t.elapsed().as_nanos() as f64 / rows.min(256) as f64); let t = Instant::now(); diff --git a/core/engine/tests/ceiling_switch.rs b/core/engine/tests/ceiling_switch.rs index 92daf84ac..b386b3d98 100644 --- a/core/engine/tests/ceiling_switch.rs +++ b/core/engine/tests/ceiling_switch.rs @@ -1,6 +1,7 @@ -mod compiled_default; +mod latest; mod support; +use latest::Latest; use rust_decimal::Decimal; use serde_json::{json, Value}; use std::hint::black_box; @@ -454,7 +455,7 @@ async fn ceiling_multi_switch() { .ok() .and_then(|v| v.parse().ok()) .unwrap_or(1024); - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); assert!(matches!( zen_engine::diagnostics::compiled_verdict(&compiled), diff --git a/core/engine/tests/ceiling_table.rs b/core/engine/tests/ceiling_table.rs index fa9ea0604..800f778f0 100644 --- a/core/engine/tests/ceiling_table.rs +++ b/core/engine/tests/ceiling_table.rs @@ -811,11 +811,17 @@ impl Scaled { } } +fn clock() -> EvaluationOptions { + EvaluationOptions { + now: zen_engine::context::parse_instant("2025-08-19T16:55:02.078Z"), + ..Default::default() + } +} + struct Ceiling; impl Ceiling { async fn measure(label: &str, inputs_json: &[Value], runs: usize) { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); let fixture = Fixture::load(); let mut compiled = Decision::from(Arc::new(fixture.content.clone())).compiled_engine(); compiled.compile(); @@ -827,7 +833,7 @@ impl Ceiling { let built = Built::new(inputs_json).unwrap(); let rows = built.rows; let columns = built.columns(); - let options = EvaluationOptions::default(); + let options = clock(); let inputs = Inputs::of(&built); let folded = Folded::new(); let mut codes = Vec::with_capacity(rows); @@ -849,7 +855,7 @@ impl Ceiling { for row in 0..rows { let input = columns.row(row); let walked = walker - .evaluate(input.clone()) + .evaluate_with_opts(input.clone(), clock()) .await .map(|r| Built::normalized(r.result.to_value())) .map_err(|e| e.to_string()); @@ -892,7 +898,7 @@ impl Ceiling { for _ in 0..runs { let start = std::time::Instant::now(); for c in (0..rows.min(256)).map(|r| columns.row(r)) { - let _ = walker.evaluate(c).await; + let _ = walker.evaluate_with_opts(c, clock()).await; } best[0] = best[0].min(per(start, rows.min(256))); let start = std::time::Instant::now(); @@ -969,7 +975,6 @@ async fn traffic_ceiling() { #[tokio::test] #[ignore] async fn traffic_profile_engine() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); let fixture = Fixture::load(); let variants = fixture.typed_variants(); let random = std::env::var("BENCH_RANDOM").is_ok(); @@ -994,9 +999,7 @@ async fn traffic_profile_engine() { let until = std::time::Instant::now() + std::time::Duration::from_secs(seconds); let mut calls = 0usize; while std::time::Instant::now() < until { - let _ = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) - .await; + let _ = compiled.evaluate_columns(&columns, clock()).await; calls += 1; } println!("calls {calls}"); diff --git a/core/engine/tests/columnar_schemas.rs b/core/engine/tests/columnar_schemas.rs index 55a579733..704c4d700 100644 --- a/core/engine/tests/columnar_schemas.rs +++ b/core/engine/tests/columnar_schemas.rs @@ -1,12 +1,13 @@ -mod compiled_default; +mod latest; mod support; +use latest::Latest; use serde_json::{json, Value}; use std::sync::Arc; use support::columns::Built; use zen_engine::loader::MemoryLoader; use zen_engine::model::{DecisionContent, GraphContent}; -use zen_engine::{Decision, EvaluationOptions}; +use zen_engine::Decision; use zen_expression::Variable; struct Case; @@ -51,11 +52,14 @@ impl Case { } async fn compare(decision: &Decision, rows: Vec) { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + crate::support::Clock::set("2025-03-20T10:15:30Z"); let mut expected = Vec::new(); for row in &rows { let result = decision - .evaluate(Variable::from(row.clone())) + .evaluate_with_opts( + Variable::from(row.clone()), + crate::support::Clock::options(), + ) .await .map(|r| r.result) .map_err(|e| serde_json::to_string(&e).unwrap_or_default()); @@ -70,7 +74,7 @@ impl Case { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let output = decision - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; representations += 1; assert_eq!(output.paths().hosted, 0, "rows left the columnar plan"); @@ -111,7 +115,8 @@ async fn date_schemas_match_row_evaluation_in_one_columnar_batch() { Case::output(None), ], vec![], - )); + )) + .latest(); let rows = vec![ json!({ "at": "2024-01-31T10:00:00Z", "day": "2024-02-29", "customer": { "born": "1990-05-01", "name": "a" }, "count": 1 }), json!({ "at": "2024-01-31T10:00:00+02:00", "day": null, "customer": { "name": "b" }, "count": 2 }), @@ -141,7 +146,8 @@ async fn dates_inside_lists_and_untouched_dates_match_row_evaluation() { Case::output(None), ], vec![], - )); + )) + .latest(); let rows = vec![ json!({ "visits": ["2024-01-01", "2024-02-01"], "plain": "2024-01-01" }), json!({ "visits": ["2024-03-01"], "plain": "x" }), @@ -172,6 +178,7 @@ async fn dictionary_schemas_match_row_evaluation_in_one_columnar_batch() { ], vec!["dicts"], )) + .latest() .with_loader(loader); let rows = vec![ json!({ "tier": "VIP", "since": "2024-01-01" }), @@ -212,7 +219,7 @@ async fn output_schemas_over_mixed_columns_match_row_evaluation() { Case::output(Some(schema)), ], vec![], - )); + )).latest(); let rows: Vec = ["a", "b", "c", "d", "e", "f", "g", "h", "z", "a", "z"] .iter() .map(|kind| json!({ "kind": kind })) @@ -240,7 +247,8 @@ async fn unmodelled_property_keywords_match_row_evaluation() { Case::output(None), ], vec![], - )); + )) + .latest(); let rows = vec![ json!({ "email": "a@b.co", "code": "DE12", "step": 1.5, "contact": "x", "customer": { "vat": "DE1" } }), json!({ "email": "not-an-email", "code": "DE12", "step": 1.5, "contact": 2, "customer": { "vat": "DE1" } }), @@ -286,7 +294,7 @@ async fn output_schemas_over_constant_columns_match_row_evaluation() { Case::output(Some(schema)), ], vec![], - )); + )).latest(); let rows: Vec = (0..8).map(|i| json!({ "kind": format!("k{i}") })).collect(); Case::compare(&decision, rows).await; } diff --git a/core/engine/tests/compiled.rs b/core/engine/tests/compiled.rs index c5bbee6ca..48fc4b733 100644 --- a/core/engine/tests/compiled.rs +++ b/core/engine/tests/compiled.rs @@ -1,9 +1,10 @@ -mod compiled_default; #[path = "support/fixture.rs"] mod fixture; +mod latest; mod support; use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND}; +use latest::Latest; use serde_json::json; use serde_json::Value; use std::collections::BTreeMap; @@ -129,8 +130,8 @@ async fn compiled_graphs_match_the_walker() { let mut failures: Vec = Vec::new(); let mut compared = 0usize; for fixture in Fixture::load_all() { - let walker = Live::walker(&Decision::from(Arc::new(fixture.content.clone()))); - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let walker = Live::walker(&Decision::from(Arc::new(fixture.content.clone())).latest()); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); let verdict = zen_engine::diagnostics::compiled_verdict(&compiled); let key = match &verdict { @@ -144,18 +145,34 @@ async fn compiled_graphs_match_the_walker() { } let variants = fixture.variants(); let contexts: Vec = variants.iter().map(|v| Variable::from(v.clone())).collect(); - let options = EvaluationOptions::default(); + let options = crate::support::Clock::options(); let batch = compiled.evaluate_batch(&contexts, options).await; for (i, input) in variants.iter().enumerate() { let context = Variable::from(input.clone()); let want = reference .graph( || Canon::key(&fixture.name, &[], &context), - || async { Outcome::of(walker.evaluate(Variable::from(input.clone())).await) }, + || async { + Outcome::of( + walker + .evaluate_with_opts( + Variable::from(input.clone()), + crate::support::Clock::options(), + ) + .await, + ) + }, Outcome::recorded, ) .await; - let single = Outcome::of(compiled.evaluate(Variable::from(input.clone())).await); + let single = Outcome::of( + compiled + .evaluate_with_opts( + Variable::from(input.clone()), + crate::support::Clock::options(), + ) + .await, + ); let batched = batch.get(i).map(|r| match r { Ok(r) => Ok(serde_json::to_string(&r.result).unwrap_or_default()), Err(e) => Err(serde_json::to_value(&**e) @@ -205,7 +222,7 @@ async fn compiled_graphs_match_the_walker() { #[tokio::test] #[ignore] async fn compiled_graph_throughput() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let rows: usize = std::env::var("BENCH_ROWS") .ok() .and_then(|v| v.parse().ok()) @@ -225,7 +242,7 @@ async fn compiled_graph_throughput() { { continue; } - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); if !matches!( zen_engine::diagnostics::compiled_verdict(&compiled), @@ -238,7 +255,7 @@ async fn compiled_graph_throughput() { let contexts: Vec = (0..rows) .map(|i| Variable::from(variants[i % variants.len()].clone())) .collect(); - let options = EvaluationOptions::default(); + let options = crate::support::Clock::options(); if let Ok(seconds) = std::env::var("BENCH_PROFILE") { let until = std::time::Instant::now() + std::time::Duration::from_secs(seconds.parse().unwrap_or(5)); @@ -247,7 +264,9 @@ async fn compiled_graph_throughput() { match single { true => { for c in &contexts { - let _ = compiled.evaluate(c.clone()).await; + let _ = compiled + .evaluate_with_opts(c.clone(), crate::support::Clock::options()) + .await; } } false => { @@ -262,12 +281,16 @@ async fn compiled_graph_throughput() { for _ in 0..5 { let start = std::time::Instant::now(); for c in &contexts { - let _ = walker.evaluate(c.clone()).await; + let _ = walker + .evaluate_with_opts(c.clone(), crate::support::Clock::options()) + .await; } best[0] = best[0].min(time(start.elapsed(), rows)); let start = std::time::Instant::now(); for c in &contexts { - let _ = compiled.evaluate(c.clone()).await; + let _ = compiled + .evaluate_with_opts(c.clone(), crate::support::Clock::options()) + .await; } best[1] = best[1].min(time(start.elapsed(), rows)); let start = std::time::Instant::now(); @@ -315,7 +338,7 @@ async fn columnar_graphs_match_the_walker() { { continue; } - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); if !matches!( zen_engine::diagnostics::compiled_verdict(&compiled), @@ -342,7 +365,7 @@ async fn columnar_graphs_match_the_walker() { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let output = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; for row in 0..built.rows { let input = columns.row(row); @@ -350,7 +373,10 @@ async fn columnar_graphs_match_the_walker() { .graph( || Canon::key(&fixture.name, &[], &input), || async { - match walker.evaluate(input.clone()).await { + match walker + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) + .await + { Ok(r) => Ok(Built::normalized(r.result.to_value())), Err(e) => Err(serde_json::to_value(&*e) .map(|v| v.to_string()) @@ -410,7 +436,7 @@ async fn struct_inputs_match_the_walker() { { continue; } - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); if !matches!( zen_engine::diagnostics::compiled_verdict(&compiled), @@ -499,11 +525,14 @@ async fn struct_inputs_match_the_walker() { ), ); let output = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; for row in 0..rows.len() { let input = columns.row(row); - let want = match walker.evaluate(input.clone()).await { + let want = match walker + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) + .await + { Ok(r) => Ok(Built::normalized(r.result.to_value())), Err(e) => Err(serde_json::to_value(&*e) .map(|v| v.to_string()) @@ -563,7 +592,7 @@ async fn columnar_tables_match_coded_nulls_against_null_cells() { ] })) .expect("graph"); - let mut decision = Decision::from(Arc::new(content)); + let mut decision = Decision::from(Arc::new(content)).latest(); decision.compile(); decision }; @@ -587,7 +616,7 @@ async fn columnar_tables_match_coded_nulls_against_null_cells() { let want = ["other", "null", "other", "null", "other"]; for (label, decision) in [("dispatched", &dispatched), ("generic", &generic)] { let output = decision - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; for (row, want) in want.iter().enumerate() { assert!( @@ -610,14 +639,14 @@ async fn columnar_function_rows_time_out_independently() { .into_iter() .find(|f| f.name == "infinite-function.json") .expect("fixture"); - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); let rows: Vec = (0..3).map(|i| serde_json::json!({ "row": i })).collect(); let built = Built::new(&rows).expect("columns"); let columns = built.columns(); let started = std::time::Instant::now(); let output = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; let elapsed = started.elapsed(); let messages: Vec = output @@ -693,13 +722,16 @@ impl FunctionNode { let columns = built.columns(); let mut failures = Vec::new(); for content in contents { - let mut compiled = Decision::from(FunctionNode::graph(content.clone())); + let mut compiled = Decision::from(FunctionNode::graph(content.clone())).latest(); compiled.compile(); let output = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; for row in 0..rows.len() { - let want = match compiled.evaluate(columns.row(row)).await { + let want = match compiled + .evaluate_with_opts(columns.row(row), crate::support::Clock::options()) + .await + { Ok(r) => Ok(Built::normalized(r.result.to_value())), Err(e) => Err(serde_json::to_value(&*e) .map(|v| v.to_string()) @@ -774,7 +806,7 @@ async fn columnar_function_v1_inputs_match_literals() { #[tokio::test] async fn columnar_function_v1_batches_match_rows() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let rows = FunctionNode::rows(12); let contents: Vec = FunctionNode::V1 .iter() @@ -797,7 +829,7 @@ async fn columnar_function_v1_batches_match_rows() { #[tokio::test] #[ignore] async fn columnar_graph_throughput() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let rows: usize = std::env::var("BENCH_ROWS") .ok() .and_then(|v| v.parse().ok()) @@ -815,7 +847,7 @@ async fn columnar_graph_throughput() { { continue; } - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); if loader { compiled = compiled.with_loader(Arc::new(support::create_fs_loader())); } @@ -851,7 +883,7 @@ async fn columnar_graph_throughput() { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let contexts: Vec = (0..rows).map(|r| columns.row(r)).collect(); - let options = EvaluationOptions::default(); + let options = crate::support::Clock::options(); if let Ok(seconds) = std::env::var("BENCH_PROFILE") { let until = std::time::Instant::now() + std::time::Duration::from_secs(seconds.parse().unwrap_or(5)); @@ -869,7 +901,9 @@ async fn columnar_graph_throughput() { if call < 5 { let start = std::time::Instant::now(); for c in contexts.iter().take(256) { - let _ = walker.evaluate(c.clone()).await; + let _ = walker + .evaluate_with_opts(c.clone(), crate::support::Clock::options()) + .await; } best[0] = best[0].min(start.elapsed().as_nanos() as f64 / rows.min(256) as f64); } @@ -931,7 +965,7 @@ impl Latency { #[tokio::test] #[ignore] async fn single_row_latency() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", Outcome::CLOCK); + crate::support::Clock::set(Outcome::CLOCK); let reps: usize = std::env::var("BENCH_REPS") .ok() .and_then(|v| v.parse().ok()) @@ -940,7 +974,7 @@ async fn single_row_latency() { let traced = EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, max_depth: 10, - ..Default::default() + ..crate::support::Clock::options() }; let mut columns: [Vec; 5] = Default::default(); println!( @@ -957,7 +991,7 @@ async fn single_row_latency() { continue; } let content = Arc::new(fixture.content.clone()); - let mut compiled = Decision::from(content.clone()); + let mut compiled = Decision::from(content.clone()).latest(); compiled.compile(); if !matches!( zen_engine::diagnostics::compiled_verdict(&compiled), @@ -975,12 +1009,25 @@ async fn single_row_latency() { let times = [ Latency::measure(&contexts, reps, |c| { let compiled = &compiled; - async move { drop(compiled.evaluate(c).await) } + async move { + drop( + compiled + .evaluate_with_opts(c, crate::support::Clock::options()) + .await, + ) + } }) .await, Latency::measure(&contexts, reps, |c| { let content = content.clone(); - async move { drop(Decision::from(content).evaluate(c).await) } + async move { + drop( + Decision::from(content) + .latest() + .evaluate_with_opts(c, crate::support::Clock::options()) + .await, + ) + } }) .await, Latency::measure(&contexts, reps, |c| { @@ -990,7 +1037,13 @@ async fn single_row_latency() { .await, Latency::measure(&contexts, reps, |c| { let walker = &walker; - async move { drop(walker.evaluate(c).await) } + async move { + drop( + walker + .evaluate_with_opts(c, crate::support::Clock::options()) + .await, + ) + } }) .await, Latency::measure(&contexts, reps, |c| { @@ -1217,7 +1270,7 @@ impl Wide { #[tokio::test] #[ignore] async fn wide_inputs_match_the_walker() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); let rows: usize = std::env::var("WIDE_ROWS") .ok() .and_then(|v| v.parse().ok()) @@ -1234,7 +1287,7 @@ async fn wide_inputs_match_the_walker() { { continue; } - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); if !matches!( zen_engine::diagnostics::compiled_verdict(&compiled), @@ -1246,12 +1299,19 @@ async fn wide_inputs_match_the_walker() { let inputs = Wide::rows(&fixture, rows, Wide::seed(&fixture.name)); let contexts: Vec = inputs.iter().map(|v| Variable::from(v.clone())).collect(); let batch = compiled - .evaluate_batch(&contexts, EvaluationOptions::default()) + .evaluate_batch(&contexts, crate::support::Clock::options()) .await; let mut wants = Vec::with_capacity(inputs.len()); let mut batched = 0usize; for (i, input) in inputs.iter().enumerate() { - let want = Outcome::of(walker.evaluate(Variable::from(input.clone())).await); + let want = Outcome::of( + walker + .evaluate_with_opts( + Variable::from(input.clone()), + crate::support::Clock::options(), + ) + .await, + ); let got = batch.get(i).map(|r| match r { Ok(r) => Ok(serde_json::to_string(&r.result).unwrap_or_default()), Err(e) => Err(serde_json::to_value(&**e) @@ -1280,11 +1340,14 @@ async fn wide_inputs_match_the_walker() { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let output = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; for row in 0..built.rows { let input = columns.row(row); - let want = match walker.evaluate(input.clone()).await { + let want = match walker + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) + .await + { Ok(r) => Ok(Built::normalized(r.result.to_value())), Err(e) => Err(serde_json::to_value(&*e) .map(|v| v.to_string()) @@ -1364,7 +1427,7 @@ async fn plan_census() { { continue; } - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); let variants = match std::env::var("BENCH_VALID").is_ok() && !fixture.inputs.is_empty() { true => fixture.inputs.clone(), @@ -1388,12 +1451,12 @@ async fn plan_census() { }; let columns = built.columns(); let _ = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; let _ = zen_engine::diagnostics::census(); let start = std::time::Instant::now(); let _ = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; println!( "CENSUS\t{}\ttotal\t1\t{}\t{}", @@ -1494,7 +1557,7 @@ impl Chain { rows: &[Value], failures: &mut Vec, ) -> (usize, usize) { - let mut compiled = Decision::from(Arc::new(content)); + let mut compiled = Decision::from(Arc::new(content)).latest(); compiled.compile(); assert!( matches!( @@ -1508,11 +1571,14 @@ impl Chain { let built = Built::new(rows).expect("columns"); let columns = built.columns(); let output = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; for row in 0..built.rows { let input = columns.row(row); - let want = match walker.evaluate(input.clone()).await { + let want = match walker + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) + .await + { Ok(r) => Ok(Built::normalized(r.result.to_value()).to_string()), Err(e) => Err(serde_json::to_value(&*e) .map(|v| v.to_string()) diff --git a/core/engine/tests/compiled_default/mod.rs b/core/engine/tests/compiled_default/mod.rs deleted file mode 100644 index e8ebb0894..000000000 --- a/core/engine/tests/compiled_default/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[ctor::ctor(unsafe)] -fn compiled_by_default() { - zen_engine::ZEN_CONFIG - .compiled - .store(true, std::sync::atomic::Ordering::Relaxed); -} diff --git a/core/engine/tests/compiled_policy.rs b/core/engine/tests/compiled_policy.rs index e7362564f..869b25d69 100644 --- a/core/engine/tests/compiled_policy.rs +++ b/core/engine/tests/compiled_policy.rs @@ -1,6 +1,6 @@ -mod compiled_default; #[allow(dead_code)] mod conformance; +mod latest; #[allow(dead_code)] #[path = "support/policies.rs"] mod policies; @@ -8,6 +8,7 @@ mod policies; mod policy_gen; mod support; +use latest::Latest; use policies::{Anchor, Batch, Generated, PolicyCase}; use policy_gen::{Gen, Rng}; use serde_json::json; @@ -103,11 +104,14 @@ impl Differential { .enumerate() .map(|(i, input)| Self::with_goals(path, input, &PolicyCase::goals(&computed, i))) .collect(); - let batch = ws.evaluate_batch(&requests); + let batch = ws.evaluate_batch_pinned(&requests, &crate::support::Clock::options()); for (i, (input, batched)) in inputs.iter().zip(&batch).enumerate() { let goals = PolicyCase::goals(&computed, i); let want = self.driver(label, ws, path, input, &goals); - let single = Self::shape(&ws.evaluate(&Self::with_goals(path, input, &goals))); + let single = Self::shape(&ws.evaluate_pinned( + &Self::with_goals(path, input, &goals), + &crate::support::Clock::options(), + )); let batched = Self::shape(batched); self.compared += 1; self.succeeded += usize::from(want.is_ok()); @@ -225,7 +229,12 @@ impl Columnar { columns: &zen_expression::lane::Columns, failures: &mut Vec, ) { - let Ok(output) = ws.evaluate_columns(&Arc::from(Generated::PATH), &[], columns) else { + let Ok(output) = ws.evaluate_columns_pinned( + &Arc::from(Generated::PATH), + &[], + columns, + &crate::support::Clock::options(), + ) else { return; }; for row in 0..columns.rows { @@ -276,7 +285,7 @@ fn compiled_policy_throughput() { let time = |elapsed: std::time::Duration| elapsed.as_nanos() as f64 / rows as f64; let mut ratios: Vec<(f64, f64, f64)> = Vec::new(); for seed in 0..seeds { - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().latest(); let Ok(parsed) = serde_json::from_value(Gen::document(seed)) else { continue; }; @@ -290,7 +299,9 @@ fn compiled_policy_throughput() { + std::time::Duration::from_secs(profile.parse().unwrap_or(1)); while std::time::Instant::now() < until { match std::env::var("BENCH_MODE").as_deref() { - Ok("single") => requests.iter().for_each(|r| drop(ws.evaluate(r))), + Ok("single") => requests.iter().for_each(|r| { + drop(ws.evaluate_pinned(r, &crate::support::Clock::options())) + }), Ok("columns") => { if let Some(columns) = Built::new( &requests @@ -301,10 +312,17 @@ fn compiled_policy_throughput() { .as_ref() .map(Built::columns) { - drop(ws.evaluate_columns(&Arc::from("generated.json"), &[], &columns)); + drop(ws.evaluate_columns_pinned( + &Arc::from("generated.json"), + &[], + &columns, + &crate::support::Clock::options(), + )); } } - _ => drop(ws.evaluate_batch(&requests)), + _ => { + drop(ws.evaluate_batch_pinned(&requests, &crate::support::Clock::options())) + } } } continue; @@ -324,19 +342,28 @@ fn compiled_policy_throughput() { for _ in 0..5 { let batch = fresh(); let start = std::time::Instant::now(); - batch.iter().for_each(|r| drop(ws.evaluate_with_driver(r))); + batch + .iter() + .for_each(|r| drop(ws.evaluate_with_driver(r, crate::support::Clock::now()))); best[0] = best[0].min(time(start.elapsed())); let batch = fresh(); let start = std::time::Instant::now(); - batch.iter().for_each(|r| drop(ws.evaluate(r))); + batch + .iter() + .for_each(|r| drop(ws.evaluate_pinned(r, &crate::support::Clock::options()))); best[1] = best[1].min(time(start.elapsed())); let batch = fresh(); let start = std::time::Instant::now(); - drop(ws.evaluate_batch(&batch)); + drop(ws.evaluate_batch_pinned(&batch, &crate::support::Clock::options())); best[2] = best[2].min(time(start.elapsed())); if let Some(columns) = built.as_ref().map(Built::columns) { let start = std::time::Instant::now(); - drop(ws.evaluate_columns(&Arc::from("generated.json"), &[], &columns)); + drop(ws.evaluate_columns_pinned( + &Arc::from("generated.json"), + &[], + &columns, + &crate::support::Clock::options(), + )); best[3] = best[3].min(time(start.elapsed())); } } @@ -364,7 +391,7 @@ fn compiled_policy_throughput() { async fn engine_batch_matches_single_evaluations() { use zen_engine::loader::MemoryLoader; use zen_engine::model::{DecisionContent, PolicyContent}; - use zen_engine::{DecisionEngine, EvaluationOptions}; + use zen_engine::DecisionEngine; let loader = Arc::new(MemoryLoader::default()); let mut rng = Rng(11); @@ -394,7 +421,7 @@ async fn engine_batch_matches_single_evaluations() { _ => Variable::from(Gen::input(&mut rng)), }) .collect(); - let engine = DecisionEngine::default().with_loader(loader); + let engine = DecisionEngine::default().latest().with_loader(loader); for compiled in [false, true] { if compiled { engine.compile(); @@ -402,12 +429,12 @@ async fn engine_batch_matches_single_evaluations() { for key in ["policy", "graph"] { let fresh: Vec = contexts.iter().map(Variable::deep_clone).collect(); let batch = engine - .evaluate_batch(key, &fresh, EvaluationOptions::default()) + .evaluate_batch(key, &fresh, crate::support::Clock::options()) .await; assert_eq!(batch.len(), contexts.len()); for (context, batched) in contexts.iter().zip(batch) { let single = engine - .evaluate_with_opts(key, context.deep_clone(), EvaluationOptions::default()) + .evaluate_with_opts(key, context.deep_clone(), crate::support::Clock::options()) .await; let shape = |r: Result< zen_engine::DecisionGraphResponse, @@ -586,7 +613,12 @@ impl Anchor { failures: &mut Vec, ) -> (usize, usize, usize) { let output = ws - .evaluate_columns(&Arc::from(Anchor::PATH), &[], columns) + .evaluate_columns_pinned( + &Arc::from(Anchor::PATH), + &[], + columns, + &crate::support::Clock::options(), + ) .expect("columnar"); for row in 0..columns.rows { let input = columns.row(row); @@ -898,7 +930,12 @@ fn policy_columnar_shredded_irregular_lists() { let mut failures = Vec::new(); for columns in [&columns, &nulled] { let output = ws - .evaluate_columns(&Arc::from("anchor"), &[], columns) + .evaluate_columns_pinned( + &Arc::from("anchor"), + &[], + columns, + &crate::support::Clock::options(), + ) .expect("columnar"); for row in 0..columns.rows { let request = EvaluateRequest { @@ -908,7 +945,7 @@ fn policy_columnar_shredded_irregular_lists() { trace: zen_engine::trace::TraceFormat::Off, }; let want = ws - .evaluate_with_driver(&request) + .evaluate_with_driver(&request, crate::support::Clock::now()) .map(|r| Built::normalized(r.output.to_value())) .map_err(|e| format!("{e:?}")); let got = match output.errors[row].as_deref() { @@ -976,7 +1013,12 @@ fn policy_columnar_converts_declared_dates_without_hosting() { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let output = ws - .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .evaluate_columns_pinned( + &Arc::from("anchor"), + &[], + &columns, + &crate::support::Clock::options(), + ) .expect("columnar"); assert_eq!(output.paths().hosted, 0, "dated rows were hosted"); for row in 0..columns.rows { @@ -987,7 +1029,7 @@ fn policy_columnar_converts_declared_dates_without_hosting() { trace: zen_engine::trace::TraceFormat::Off, }; let want = ws - .evaluate_with_driver(&request) + .evaluate_with_driver(&request, crate::support::Clock::now()) .map(|r| Built::normalized(r.output.to_value())) .map_err(|e| format!("{e:?}")); let got = match output.errors[row].as_deref() { @@ -1094,7 +1136,12 @@ fn policy_member_blocks_reading_their_own_list_match_the_driver() { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let output = ws - .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .evaluate_columns_pinned( + &Arc::from("anchor"), + &[], + &columns, + &crate::support::Clock::options(), + ) .expect("columnar"); if columnar { assert_eq!(output.paths().hosted, 0, "sibling reads were hosted"); @@ -1107,7 +1154,7 @@ fn policy_member_blocks_reading_their_own_list_match_the_driver() { trace: zen_engine::trace::TraceFormat::Off, }; let want = ws - .evaluate_with_driver(&request) + .evaluate_with_driver(&request, crate::support::Clock::now()) .map(|r| Built::normalized(r.output.to_value())) .map_err(|e| format!("{e:?}")); let got = match output.errors[row].as_deref() { @@ -1161,7 +1208,12 @@ fn policy_column_order_is_path_independent() { let columns = built.columns(); for call in 0..8 { let output = ws - .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .evaluate_columns_pinned( + &Arc::from("anchor"), + &[], + &columns, + &crate::support::Clock::options(), + ) .expect("columnar"); let got: Vec<&str> = output .columns @@ -1201,7 +1253,12 @@ fn policy_tables_match_coded_nulls_against_null_cells() { let want = ["other", "null", "other", "null", "other"]; for call in 0..4 { let output = ws - .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .evaluate_columns_pinned( + &Arc::from("anchor"), + &[], + &columns, + &crate::support::Clock::options(), + ) .expect("columnar"); for (row, want) in want.iter().enumerate() { assert!( @@ -1461,21 +1518,33 @@ fn single_row_latency() { "evaluate", Anchor::time(count, || { let fresh = Anchor::fresh(&rows); - Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate(r)))) + Anchor::clock(|| { + fresh.iter().for_each(|r| { + drop(ws.evaluate_pinned(r, &crate::support::Clock::options())) + }) + }) }), ), ( "evaluate traced", Anchor::time(count, || { let fresh = traced(&rows); - Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate(r)))) + Anchor::clock(|| { + fresh.iter().for_each(|r| { + drop(ws.evaluate_pinned(r, &crate::support::Clock::options())) + }) + }) }), ), ( "enhance_trace", Anchor::time(count, || { let fresh = Anchor::fresh(&rows); - Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.enhance_trace(r)))) + Anchor::clock(|| { + fresh.iter().for_each(|r| { + drop(ws.enhance_trace_pinned(r, &crate::support::Clock::options())) + }) + }) }), ), ]; @@ -1516,7 +1585,7 @@ fn policy_anchor_throughput() { .iter() .map(|r| { Built::normalized( - ws.evaluate_with_driver(r) + ws.evaluate_with_driver(r, crate::support::Clock::now()) .expect("driver") .output .to_value(), @@ -1531,7 +1600,12 @@ fn policy_anchor_throughput() { let until = std::time::Instant::now() + std::time::Duration::from_secs(seconds.parse().unwrap_or(4)); while std::time::Instant::now() < until { - drop(ws.evaluate_columns(&path, &[], &columns)); + drop(ws.evaluate_columns_pinned( + &path, + &[], + &columns, + &crate::support::Clock::options(), + )); } return; } @@ -1540,20 +1614,26 @@ fn policy_anchor_throughput() { "driver", Anchor::time(count, || { let fresh = Anchor::fresh(&rows); - Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate_with_driver(r)))) + Anchor::clock(|| { + fresh + .iter() + .for_each(|r| drop(ws.evaluate_with_driver(r, crate::support::Clock::now()))) + }) }), )); results.push(( "compiled batch", Anchor::time(count, || { let fresh = Anchor::fresh(&rows); - Anchor::clock(|| drop(ws.evaluate_batch(&fresh))) + Anchor::clock(|| { + drop(ws.evaluate_batch_pinned(&fresh, &crate::support::Clock::options())) + }) }), )); let built = Built::new(&values).expect("flat columns"); let columns = built.columns(); let flat = ws - .evaluate_columns(&path, &[], &columns) + .evaluate_columns_pinned(&path, &[], &columns, &crate::support::Clock::options()) .expect("columnar flat"); let flat_wrong = (0..count) .filter(|&r| { @@ -1565,14 +1645,23 @@ fn policy_anchor_throughput() { results.push(( "columnar flat", Anchor::time(count, || { - Anchor::clock(|| drop(ws.evaluate_columns(&path, &[], &columns))) + Anchor::clock(|| { + drop(ws.evaluate_columns_pinned( + &path, + &[], + &columns, + &crate::support::Clock::options(), + )) + }) }), )); let built = Built::nested(&values).expect("nested columns"); let fields = built.fields(); let structs = built.structs(&fields); let columns = built.columns_with(&structs); - let output = ws.evaluate_columns(&path, &[], &columns).expect("columnar"); + let output = ws + .evaluate_columns_pinned(&path, &[], &columns, &crate::support::Clock::options()) + .expect("columnar"); let wrong = (0..count) .filter(|&r| { output.errors[r].is_some() @@ -1583,14 +1672,26 @@ fn policy_anchor_throughput() { let until = std::time::Instant::now() + std::time::Duration::from_secs(seconds.parse().unwrap_or(4)); while std::time::Instant::now() < until { - drop(ws.evaluate_columns(&path, &[], &columns)); + drop(ws.evaluate_columns_pinned( + &path, + &[], + &columns, + &crate::support::Clock::options(), + )); } return; } results.push(( "columnar struct lists", Anchor::time(count, || { - Anchor::clock(|| drop(ws.evaluate_columns(&path, &[], &columns))) + Anchor::clock(|| { + drop(ws.evaluate_columns_pinned( + &path, + &[], + &columns, + &crate::support::Clock::options(), + )) + }) }), )); if support::switches().census { diff --git a/core/engine/tests/concurrent.rs b/core/engine/tests/concurrent.rs index 2439e170d..e1bdfed79 100644 --- a/core/engine/tests/concurrent.rs +++ b/core/engine/tests/concurrent.rs @@ -79,9 +79,6 @@ fn main_graph() -> Value { } fn engine() -> (DecisionEngine, Arc) { - zen_engine::ZEN_CONFIG - .compiled - .store(true, Ordering::Relaxed); let loader = Arc::new(Yielding::default()); for (key, graph) in [("main", main_graph()), ("child", child())] { loader.memory.add( @@ -90,7 +87,9 @@ fn engine() -> (DecisionEngine, Arc) { ); } ( - DecisionEngine::default().with_loader(loader.clone()), + DecisionEngine::default() + .with_version(zen_engine::EngineVersion::V2) + .with_loader(loader.clone()), loader, ) } diff --git a/core/engine/tests/conformance/mod.rs b/core/engine/tests/conformance/mod.rs index 7c6ca5efd..d0e14129d 100644 --- a/core/engine/tests/conformance/mod.rs +++ b/core/engine/tests/conformance/mod.rs @@ -170,7 +170,7 @@ impl Spec { "TZ", std::env::var("SPEC_TZ").unwrap_or_else(|_| "UTC".to_string()), ); - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + crate::support::Clock::set("2025-03-20T10:15:30Z"); } pub fn files(dialect: Dialect) -> Vec { diff --git a/core/engine/tests/conformance/run.rs b/core/engine/tests/conformance/run.rs index 139fbc1b9..c215ce29e 100644 --- a/core/engine/tests/conformance/run.rs +++ b/core/engine/tests/conformance/run.rs @@ -97,14 +97,17 @@ impl GraphRun { } shared.add(Self::MAIN, content(&suite.content)?); let engine = DecisionEngine::default() + .with_version(zen_engine::EngineVersion::V2) .with_loader(shared) .with_adapter(Arc::new(SpecNodes)); engine.compile(); let uncompiled = Decision::from(graph.clone()) + .with_version(zen_engine::EngineVersion::V2) .with_loader(plain) .with_adapter(Arc::new(SpecNodes)); let walker = Live::walker(&uncompiled); let mut compiled = Decision::from(graph) + .with_version(zen_engine::EngineVersion::V2) .with_loader(built) .with_adapter(Arc::new(SpecNodes)); compiled.compile(); @@ -118,6 +121,12 @@ impl GraphRun { pub const MAIN: &'static str = "spec-main"; + pub fn version(&mut self, version: zen_engine::EngineVersion) { + self.uncompiled = self.uncompiled.with_version(version); + self.compiled = self.compiled.with_version(version); + self.engine.set_version(version); + } + pub fn compiled(content: DecisionContent) -> DecisionContent { match content { DecisionContent::Graph(mut graph) => { @@ -141,7 +150,11 @@ impl GraphRun { } pub async fn walker(&self, case: &Case) -> Result { - Self::outcome(self.walker.evaluate(case.input.depth_clone(64)).await) + Self::outcome( + self.walker + .evaluate_with_opts(case.input.depth_clone(64), crate::support::Clock::options()) + .await, + ) } } @@ -155,8 +168,13 @@ pub struct PolicyRun { impl PolicyRun { pub const MAIN: &'static str = "main"; + pub fn version(&mut self, version: zen_engine::EngineVersion) { + self.workspace.set_version(version); + self.engine.set_version(version); + } + pub fn new(suite: &Suite) -> Result { - let mut workspace = PolicyWorkspace::new(); + let mut workspace = PolicyWorkspace::new().with_version(zen_engine::EngineVersion::V2); let loader = Arc::new(MemoryLoader::default()); let policy = |value: &Value| { serde_json::from_value(value.clone()) @@ -188,7 +206,9 @@ impl PolicyRun { .collect(); blocking.sort(); blocking.dedup(); - let engine = DecisionEngine::default().with_loader(loader); + let engine = DecisionEngine::default() + .with_version(zen_engine::EngineVersion::V2) + .with_loader(loader); let gate = suite.diagnostics.is_none(); Ok(PolicyRun { workspace, @@ -216,11 +236,19 @@ impl PolicyRun { } pub fn compiled(&self, case: &Case) -> Result { - self.gated(&self.workspace.evaluate(&Self::request(case))) + self.gated( + &self + .workspace + .evaluate_pinned(&Self::request(case), &crate::support::Clock::options()), + ) } pub fn engine(&self, case: &Case) -> Result { - let result = Guard::block(self.engine.evaluate(Self::MAIN, case.input.depth_clone(64))); + let result = Guard::block(self.engine.evaluate_with_opts( + Self::MAIN, + case.input.depth_clone(64), + crate::support::Clock::options(), + )); match (&result, self.blocking.is_empty()) { (Err(_), false) => Err(format!("CompilationErrors {:?}", self.blocking)), (Err(error), true) => match &**error { diff --git a/core/engine/tests/draws.rs b/core/engine/tests/draws.rs index 4313c5c30..8fe16d10a 100644 --- a/core/engine/tests/draws.rs +++ b/core/engine/tests/draws.rs @@ -20,12 +20,6 @@ fn block(f: F) -> F::Output { .block_on(f) } -fn compiled() { - zen_engine::ZEN_CONFIG - .compiled - .store(true, std::sync::atomic::Ordering::Relaxed); -} - fn chain(nodes: Vec) -> Value { let ids: Vec = nodes .iter() @@ -64,13 +58,13 @@ fn content(graph: Value) -> Arc { } fn decision(graph: Value, children: &[(&str, Value)]) -> Decision { - compiled(); let loader = Arc::new(MemoryLoader::default()); for (key, child) in children { let child: DecisionContent = serde_json::from_value(child.clone()).unwrap(); loader.add(*key, child); } DecisionEngine::default() + .with_version(zen_engine::EngineVersion::V2) .with_loader(loader) .create_decision(content(graph)) .unwrap() @@ -577,8 +571,7 @@ fn policy_trace(result: &zen_engine::policy::EvaluationResult) -> Value { #[test] fn policy_rows_draw_from_their_streams() { - compiled(); - let mut ws = zen_engine::Workspace::new(); + let mut ws = zen_engine::Workspace::new().with_version(zen_engine::EngineVersion::V2); ws.set_policy("policy", policy_document()); let base = 29; let singles: Vec<(Value, Value)> = (0..ROWS) @@ -634,7 +627,6 @@ fn policy_rows_draw_from_their_streams() { #[test] fn engine_policy_batches_draw_per_row() { - compiled(); let loader = Arc::new(MemoryLoader::default()); loader.add( "policy", @@ -642,7 +634,9 @@ fn engine_policy_batches_draw_per_row() { Arc::new(policy_document()), )), ); - let engine = DecisionEngine::default().with_loader(loader); + let engine = DecisionEngine::default() + .with_version(zen_engine::EngineVersion::V2) + .with_loader(loader); let inputs: Vec = (0..ROWS).map(|x| Variable::from(policy_input(x))).collect(); for trace in [TraceFormat::V1, TraceFormat::Off] { let batch = block(engine.evaluate_batch("policy", &inputs, options(trace, 31))); @@ -997,9 +991,8 @@ fn located_policy(extra: bool) -> zen_engine::policy::PolicyDocument { #[test] fn policies_draw_by_block() { - compiled(); let run = |extra: bool| { - let mut ws = zen_engine::Workspace::new(); + let mut ws = zen_engine::Workspace::new().with_version(zen_engine::EngineVersion::V2); ws.set_policy("policy", located_policy(extra)); let singles: Vec = (0..ROWS) .map(|x| { diff --git a/core/engine/tests/engine.rs b/core/engine/tests/engine.rs index 63ce5e7ec..cb2fe5683 100644 --- a/core/engine/tests/engine.rs +++ b/core/engine/tests/engine.rs @@ -23,14 +23,28 @@ async fn engine_memory_loader() { let engine = DecisionEngine::default().with_loader(memory_loader.clone()); let table = engine - .evaluate("table", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "table", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) .await; let function = engine - .evaluate("function", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "function", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) .await; memory_loader.remove("function"); - let not_found = engine.evaluate("function", json!({}).into()).await; + let not_found = engine + .evaluate_with_opts( + "function", + json!({}).into(), + crate::support::Clock::options(), + ) + .await; assert_eq!(table.unwrap().result, json!({"output": 10}).into()); assert_eq!(function.unwrap().result, json!({"output": 24}).into()); @@ -49,7 +63,11 @@ async fn engine_precompiles_graphs() { memory_loader.remove("table"); let table = engine - .evaluate("table", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "table", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) .await; assert_eq!(table.unwrap().result, json!({"output": 10}).into()); @@ -60,12 +78,26 @@ async fn engine_precompiles_graphs() { async fn engine_filesystem_loader() { let engine = DecisionEngine::default().with_loader(Arc::new(create_fs_loader())); let table = engine - .evaluate("table.json", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "table.json", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) .await; let function = engine - .evaluate("function.json", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "function.json", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) + .await; + let not_found = engine + .evaluate_with_opts( + "invalid_file", + json!({}).into(), + crate::support::Clock::options(), + ) .await; - let not_found = engine.evaluate("invalid_file", json!({}).into()).await; assert_eq!(table.unwrap().result, json!({"output": 10}).into()); assert_eq!(function.unwrap().result, json!({"output": 24}).into()); @@ -84,12 +116,26 @@ async fn engine_closure_loader() { }); let table = engine - .evaluate("table", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "table", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) .await; let function = engine - .evaluate("function", json!({ "input": 12 }).into()) + .evaluate_with_opts( + "function", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + ) + .await; + let not_found = engine + .evaluate_with_opts( + "invalid_file", + json!({}).into(), + crate::support::Clock::options(), + ) .await; - let not_found = engine.evaluate("invalid_file", json!({}).into()).await; assert_eq!(table.unwrap().result, json!({"output": 10}).into()); assert_eq!(function.unwrap().result, json!({"output": 24}).into()); @@ -101,7 +147,11 @@ fn engine_noop_loader() { let rt = Builder::new_current_thread().build().unwrap(); // Default engine is noop let engine = DecisionEngine::default(); - let result = rt.block_on(engine.evaluate("any.json", json!({}).into())); + let result = rt.block_on(engine.evaluate_with_opts( + "any.json", + json!({}).into(), + crate::support::Clock::options(), + )); assert_eq!(result.unwrap_err().to_string(), "Loader error"); } @@ -131,7 +181,11 @@ async fn engine_errors() { let engine = DecisionEngine::default().with_loader(Arc::new(create_fs_loader())); let infinite_fn = engine - .evaluate("infinite-function.json", json!({}).into()) + .evaluate_with_opts( + "infinite-function.json", + json!({}).into(), + crate::support::Clock::options(), + ) .await; match infinite_fn.unwrap_err().deref() { EvaluationError::NodeError { @@ -144,7 +198,11 @@ async fn engine_errors() { } let recursive = engine - .evaluate("recursive-table1.json", json!({}).into()) + .evaluate_with_opts( + "recursive-table1.json", + json!({}).into(), + crate::support::Clock::options(), + ) .await; match recursive.unwrap_err().deref() { EvaluationError::NodeError { source, .. } => { @@ -160,13 +218,17 @@ fn engine_with_trace() { let rt = Builder::new_current_thread().build().unwrap(); let engine = DecisionEngine::default().with_loader(Arc::new(create_fs_loader())); - let table_r = rt.block_on(engine.evaluate("table.json", json!({ "input": 12 }).into())); + let table_r = rt.block_on(engine.evaluate_with_opts( + "table.json", + json!({ "input": 12 }).into(), + crate::support::Clock::options(), + )); let table_opt_r = rt.block_on(engine.evaluate_with_opts( "table.json", json!({ "input": 12 }).into(), EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, - ..Default::default() + ..crate::support::Clock::options() }, )); @@ -218,7 +280,10 @@ async fn engine_function_imports() { let decision = DecisionEngine::default() .create_decision(Arc::new(function_content.into())) .unwrap(); - let response = decision.evaluate(json!({}).into()).await.unwrap(); + let response = decision + .evaluate_with_opts(json!({}).into(), crate::support::Clock::options()) + .await + .unwrap(); #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] @@ -242,7 +307,11 @@ async fn engine_switch_node() { let engine = DecisionEngine::default().with_loader(Arc::new(create_fs_loader())); let switch_node_r = engine - .evaluate("switch-node.json", json!({ "color": "yellow" }).into()) + .evaluate_with_opts( + "switch-node.json", + json!({ "color": "yellow" }).into(), + crate::support::Clock::options(), + ) .await; let table = switch_node_r.unwrap(); @@ -293,9 +362,13 @@ async fn engine_graph_tests() { for test_case in test_data.tests { let input = test_case.input.clone(); - let result = decision.evaluate(input.clone()).await.unwrap().result; + let result = decision + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) + .await + .unwrap() + .result; let result_compiled = decision_compiled - .evaluate(input.clone()) + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) .await .unwrap() .result; @@ -314,7 +387,7 @@ async fn engine_graph_tests() { } fn mock_datetime() { - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + crate::support::Clock::set("2025-08-19T16:55:02.078Z"); } #[tokio::test] @@ -371,7 +444,7 @@ async fn engine_snapshot_tests() { input.clone(), EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, - ..Default::default() + ..crate::support::Clock::options() }, ) .await @@ -381,7 +454,7 @@ async fn engine_snapshot_tests() { input.clone(), EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, - ..Default::default() + ..crate::support::Clock::options() }, ) .await @@ -412,7 +485,7 @@ async fn engine_function_v2() { json!({ "input": 12 }).into(), EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, - ..Default::default() + ..crate::support::Clock::options() }, ) .await; @@ -455,22 +528,35 @@ async fn test_validation() { }); assert!(engine - .evaluate("customer-input-schema.json", context_valid.clone().into()) + .evaluate_with_opts( + "customer-input-schema.json", + context_valid.clone().into(), + crate::support::Clock::options() + ) .await .is_ok()); assert!(engine - .evaluate("customer-input-schema.json", context_invalid.clone().into()) + .evaluate_with_opts( + "customer-input-schema.json", + context_invalid.clone().into(), + crate::support::Clock::options() + ) .await .is_err()); assert!(engine - .evaluate("customer-output-schema.json", context_valid.clone().into()) + .evaluate_with_opts( + "customer-output-schema.json", + context_valid.clone().into(), + crate::support::Clock::options() + ) .await .is_ok()); assert!(engine - .evaluate( + .evaluate_with_opts( "customer-output-schema.json", - context_invalid.clone().into() + context_invalid.clone().into(), + crate::support::Clock::options() ) .await .is_err()); @@ -482,7 +568,11 @@ async fn test_nodes_reference() { let engine = DecisionEngine::default().with_loader(Arc::new(create_fs_loader())); let evaluation = engine - .evaluate("$nodes-parent.json", json!({ "hello": "world" }).into()) + .evaluate_with_opts( + "$nodes-parent.json", + json!({ "hello": "world" }).into(), + crate::support::Clock::options(), + ) .await; assert!(evaluation.is_ok()); @@ -559,7 +649,7 @@ async fn decision_table_index_matches_linear_semantics() { for probe in &probes { let indexed = decision - .evaluate(Variable::from(probe)) + .evaluate_with_opts(Variable::from(probe), crate::support::Clock::options()) .await .unwrap() .result; @@ -569,7 +659,7 @@ async fn decision_table_index_matches_linear_semantics() { EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, max_depth: 5, - ..Default::default() + ..crate::support::Clock::options() }, ) .await diff --git a/core/engine/tests/engine_choice.rs b/core/engine/tests/engine_choice.rs index 5bc04c8bf..2204a0168 100644 --- a/core/engine/tests/engine_choice.rs +++ b/core/engine/tests/engine_choice.rs @@ -1,5 +1,6 @@ -mod compiled_default; +mod latest; +use latest::Latest; use serde_json::{json, Value}; use std::sync::Arc; use zen_engine::loader::MemoryLoader; @@ -29,12 +30,12 @@ fn content() -> DecisionContent { fn engine() -> DecisionEngine { let loader = Arc::new(MemoryLoader::default()); loader.add(KEY, content()); - DecisionEngine::default().with_loader(loader) + DecisionEngine::default().latest().with_loader(loader) } fn decision() -> Decision { match content() { - DecisionContent::Graph(graph) => Decision::from(graph), + DecisionContent::Graph(graph) => Decision::from(graph).latest(), DecisionContent::Policy(_) => unreachable!("graph content"), } } diff --git a/core/engine/tests/golden.rs b/core/engine/tests/golden.rs index 26061c305..64d225177 100644 --- a/core/engine/tests/golden.rs +++ b/core/engine/tests/golden.rs @@ -1,8 +1,8 @@ -mod compiled_default; #[allow(dead_code)] mod conformance; #[path = "support/fixture.rs"] mod fixture; +mod latest; #[allow(dead_code)] #[path = "support/policies.rs"] mod policies; @@ -13,6 +13,7 @@ mod support; use conformance::run::{GraphRun, Guard, PolicyRun}; use conformance::{Dialect, Mode, Spec, Suite}; use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND}; +use latest::Latest; use policies::{Anchor, Generated, PolicyCase}; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -148,7 +149,7 @@ impl Graphs { EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, max_depth: 10, - ..Default::default() + ..crate::support::Clock::options() } } @@ -159,7 +160,11 @@ impl Graphs { input: &Variable, traced: bool, ) { - let plain = Outcome::graph(&walker.evaluate(input.depth_clone(64)).await); + let plain = Outcome::graph( + &walker + .evaluate_with_opts(input.depth_clone(64), crate::support::Clock::options()) + .await, + ); let entry = Entry::new(id, &[], input, plain); let entry = match traced { true => { @@ -187,7 +192,11 @@ impl Graphs { let Some(entry) = check.entry(golden, &key) else { return; }; - let plain = Outcome::graph(&decision.evaluate(input.depth_clone(64)).await); + let plain = Outcome::graph( + &decision + .evaluate_with_opts(input.depth_clone(64), crate::support::Clock::options()) + .await, + ); check.same( &key, Mode::Single, @@ -217,7 +226,7 @@ impl Graphs { let structs = built.structs(&fields); let columns = built.columns_with(&structs); let output = decision - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; let mut written = String::new(); let ends = output.write_rows(&mut written); @@ -268,7 +277,7 @@ impl Graphs { .map(|input| Canon::key(id, &[], input)) .collect(); let results = decision - .evaluate_batch(inputs, EvaluationOptions::default()) + .evaluate_batch(inputs, crate::support::Clock::options()) .await; for (key, result) in keys.into_iter().zip(&results) { if let Some(entry) = check.entry(golden, &key) { @@ -310,7 +319,7 @@ impl Modes { let options = EvaluationSerializedOptions { trace: mode, max_depth: 10, - ..Default::default() + ..crate::support::Clock::options() }; let reference = false; let want = Canon::mode( @@ -405,7 +414,10 @@ impl Policies { Mode::Single, "single", &entry.plain, - &Outcome::policy(ws.evaluate(&Self::request(path, input, goals, false))), + &Outcome::policy(ws.evaluate_pinned( + &Self::request(path, input, goals, false), + &crate::support::Clock::options(), + )), ); if let Some(traced) = &entry.traced { check.same( @@ -413,7 +425,10 @@ impl Policies { Mode::Traced, "traced", traced, - &Outcome::policy_traced(ws.evaluate(&Self::request(path, input, goals, true))), + &Outcome::policy_traced(ws.evaluate_pinned( + &Self::request(path, input, goals, true), + &crate::support::Clock::options(), + )), ); } if let Some(enhanced) = &entry.enhanced { @@ -422,9 +437,10 @@ impl Policies { Mode::Traced, "enhanced", enhanced, - &Outcome::policy_traced( - ws.enhance_trace(&Self::request(path, input, goals, false)), - ), + &Outcome::policy_traced(ws.enhance_trace_pinned( + &Self::request(path, input, goals, false), + &crate::support::Clock::options(), + )), ); } } @@ -441,7 +457,10 @@ impl Policies { .iter() .map(|(input, goals)| Self::request(path, input, goals, false)) .collect(); - for ((input, goals), result) in requests.iter().zip(ws.evaluate_batch(&batch)) { + for ((input, goals), result) in requests + .iter() + .zip(ws.evaluate_batch_pinned(&batch, &crate::support::Clock::options())) + { let key = Canon::key(id, goals, input); if let Some(entry) = check.entry(golden, &key) { check.same( @@ -467,7 +486,12 @@ impl Policies { let targets: Vec> = goals.iter().map(|g| Arc::from(g.as_str())).collect(); for (built, structs) in builds { Rows::with(built, *structs, |columns| { - let output = ws.evaluate_columns(&Arc::from(path), &targets, columns); + let output = ws.evaluate_columns_pinned( + &Arc::from(path), + &targets, + columns, + &crate::support::Clock::options(), + ); for row in 0..columns.rows { let input = columns.row(row); let key = Canon::key(id, goals, &input); @@ -934,7 +958,7 @@ impl Corpus { } fn compiled(fixture: &Fixture) -> Decision { - let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())).latest(); compiled.compile(); compiled } @@ -942,7 +966,9 @@ impl Corpus { async fn graph_fixtures(golden: &mut Golden) { let _guard = Nodes::lock(); for fixture in Self::fixtures() { - let walker = Decision::from(Arc::new(fixture.content.clone())).interpreted(); + let walker = Decision::from(Arc::new(fixture.content.clone())) + .latest() + .interpreted(); for input in Self::fixture_inputs(&fixture) { Graphs::record( golden, @@ -1023,9 +1049,11 @@ impl Corpus { async fn modes_graph_fixtures(live: &Golden, check: &mut Check) { let _guard = Nodes::lock(); for fixture in Self::fixtures().into_iter().filter(|f| !Self::slow(f)) { - let walker = Decision::from(Arc::new(fixture.content.clone())).interpreted(); + let walker = Decision::from(Arc::new(fixture.content.clone())) + .latest() + .interpreted(); let compiled = Self::compiled(&fixture); - let uncompiled = Decision::from(Arc::new(fixture.content.clone())); + let uncompiled = Decision::from(Arc::new(fixture.content.clone())).latest(); let inputs = Self::fixture_inputs(&fixture); check.collected(&fixture.name, &inputs); for input in inputs { @@ -1124,7 +1152,11 @@ impl Corpus { { let engine = Outcome::graph( &run.engine - .evaluate(GraphRun::MAIN, case.input.depth_clone(64)) + .evaluate_with_opts( + GraphRun::MAIN, + case.input.depth_clone(64), + crate::support::Clock::options(), + ) .await, ); check.same(&key, Mode::Engine, "engine", &entry.plain, &engine); @@ -1199,10 +1231,11 @@ impl Corpus { .is_none_or(|e| !e.covers(Mode::Engine)) { if let Some(entry) = check.entry(golden, &key) { - let engine = match Guard::block( - run.engine - .evaluate(PolicyRun::MAIN, case.input.depth_clone(64)), - ) { + let engine = match Guard::block(run.engine.evaluate_with_opts( + PolicyRun::MAIN, + case.input.depth_clone(64), + crate::support::Clock::options(), + )) { Ok(response) => Outcome::Ok(Canon::variable(&response.result)), Err(error) => match *error { EvaluationError::Policy(error) => Outcome::policy(Err(error)), @@ -1383,7 +1416,7 @@ impl Corpus { let _guard = Nodes::lock(); for fixture in Self::fixtures() { let compiled = Self::compiled(&fixture); - let uncompiled = Decision::from(Arc::new(fixture.content.clone())); + let uncompiled = Decision::from(Arc::new(fixture.content.clone())).latest(); let inputs = Self::fixture_inputs(&fixture); check.collected(&fixture.name, &inputs); for input in &inputs { diff --git a/core/engine/tests/lane_census.rs b/core/engine/tests/lane_census.rs index 5c48480ca..fb36a45da 100644 --- a/core/engine/tests/lane_census.rs +++ b/core/engine/tests/lane_census.rs @@ -1,4 +1,3 @@ -mod compiled_default; mod conformance; #[allow(dead_code)] #[path = "support/fixture.rs"] diff --git a/core/engine/tests/latest/mod.rs b/core/engine/tests/latest/mod.rs new file mode 100644 index 000000000..a37ae5b7f --- /dev/null +++ b/core/engine/tests/latest/mod.rs @@ -0,0 +1,24 @@ +use zen_engine::policy::PolicyWorkspace; +use zen_engine::{Decision, DecisionEngine, EngineVersion}; + +pub trait Latest { + fn latest(self) -> Self; +} + +impl Latest for Decision { + fn latest(self) -> Self { + self.with_version(EngineVersion::V2) + } +} + +impl Latest for DecisionEngine { + fn latest(self) -> Self { + self.with_version(EngineVersion::V2) + } +} + +impl Latest for PolicyWorkspace { + fn latest(self) -> Self { + self.with_version(EngineVersion::V2) + } +} diff --git a/core/engine/tests/pinned.rs b/core/engine/tests/pinned.rs index 0f469dd18..6df5c0873 100644 --- a/core/engine/tests/pinned.rs +++ b/core/engine/tests/pinned.rs @@ -199,7 +199,7 @@ fn v1_function_nodes_read_the_zone_of_the_context() { } #[test] -fn the_interpreted_engine_ignores_pinning() { +fn the_interpreted_engine_pins_only_the_expression_clock() { let v2 = functions(); let v1 = graph(json!({ "id": "calc", "name": "calc", "type": "functionNode", @@ -207,10 +207,12 @@ fn the_interpreted_engine_ignores_pinning() { })); let zone = zoned_function().interpreted(); let d = expressions().interpreted(); + let pinned_millis = parse_instant(NOW).unwrap().timestamp_millis(); for trace in [TraceFormat::V1, TraceFormat::Legacy, TraceFormat::Off] { let (a, doc) = evaluated(&d, 4, options(trace, NOW, 99)); let (b, _) = evaluated(&d, 4, options(trace, NOW, 99)); - assert!(real_clock(&a["t"]), "{a}"); + assert_eq!(a["t"], json!(pinned_millis), "{a}"); + assert_eq!(a["t"], b["t"]); assert_ne!((&a["r"], &a["s"]), (&b["r"], &b["s"])); if let Some(doc) = doc { assert!(doc.get("version").is_none(), "{doc}"); @@ -244,7 +246,8 @@ fn the_interpreted_engine_ignores_pinning() { }; let (a, doc) = run(options(TraceFormat::V1, NOW, 12)); let (b, _) = run(options(TraceFormat::V1, NOW, 12)); - assert!(real_clock(&a["customer"]["at"]), "{a}"); + assert_eq!(a["customer"]["at"], b["customer"]["at"], "{a}"); + assert!(!real_clock(&a["customer"]["at"]), "{a}"); assert_ne!(a["customer"]["lucky"], b["customer"]["lucky"]); let doc = doc.unwrap(); assert!(doc.get("version").is_none(), "{doc}"); diff --git a/core/engine/tests/policy_runtime.rs b/core/engine/tests/policy_runtime.rs index 3f5948179..7ff99ed2c 100644 --- a/core/engine/tests/policy_runtime.rs +++ b/core/engine/tests/policy_runtime.rs @@ -683,3 +683,44 @@ async fn v1_policy_trace_names_matched_rules() { assert_eq!(tables[1].pointer("/trace/matchedRows"), Some(&positions)); } } + +#[tokio::test] +async fn engine_version_selects_the_engine() { + use zen_engine::EngineVersion; + + assert_eq!(EngineVersion::try_from(1), Ok(EngineVersion::V1)); + assert_eq!(EngineVersion::try_from(2), Ok(EngineVersion::V2)); + assert!(EngineVersion::try_from(3).is_err()); + + let build = || { + let loader = Arc::new(MemoryLoader::default()); + loader.add("policy", make_policy_content(simple_policy_json())); + engine_with(loader) + }; + assert_eq!(build().version(), EngineVersion::V1); + + for (version, format) in [ + (EngineVersion::V1, TraceFormat::Legacy), + (EngineVersion::V2, TraceFormat::V1), + ] { + let engine = build().with_version(version); + assert_eq!(engine.version(), version); + let options = EvaluationSerializedOptions { + trace: TraceFormat::from(true), + ..Default::default() + }; + let response = engine + .evaluate_serialized( + "policy", + json!({ "customer": { "age": 30 } }).into(), + options, + ) + .await + .expect("evaluate ok"); + assert_eq!( + response.pointer("/result/customer/isAdult"), + Some(&json!(true)) + ); + assert_trace_format(response, format); + } +} diff --git a/core/engine/tests/spec.rs b/core/engine/tests/spec.rs index 2c964f923..b953899e8 100644 --- a/core/engine/tests/spec.rs +++ b/core/engine/tests/spec.rs @@ -1,4 +1,3 @@ -mod compiled_default; mod conformance; mod support; @@ -10,7 +9,6 @@ use std::sync::Arc; use support::columns::Built; use support::golden::{Canon, Live, Outcome, Reference}; use zen_engine::policy::EvaluateRequest; -use zen_engine::EvaluationOptions; use zen_expression::Variable; #[derive(Default)] @@ -264,10 +262,17 @@ impl Engines { .collect(); let batch = run .compiled - .evaluate_batch(&cycled, EvaluationOptions::default()) + .evaluate_batch(&cycled, crate::support::Clock::options()) .await; for (i, case) in suite.cases.iter().enumerate() { - let single = GraphRun::outcome(run.compiled.evaluate(case.input.depth_clone(64)).await); + let single = GraphRun::outcome( + run.compiled + .evaluate_with_opts( + case.input.depth_clone(64), + crate::support::Clock::options(), + ) + .await, + ); Differential::compare( suite, case, @@ -278,7 +283,11 @@ impl Engines { ); let engine = GraphRun::outcome( run.engine - .evaluate(GraphRun::MAIN, case.input.depth_clone(64)) + .evaluate_with_opts( + GraphRun::MAIN, + case.input.depth_clone(64), + crate::support::Clock::options(), + ) .await, ); Differential::compare( @@ -322,7 +331,7 @@ impl Engines { let columns = built.columns_with(&structs); let output = run .compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; self.typed += output.paths().typed; self.laned += output.paths().laned; @@ -333,7 +342,14 @@ impl Engines { .graph( || Canon::key(&suite.id(), &[], &input), || async { - match run.walker.evaluate(input.depth_clone(64)).await { + match run + .walker + .evaluate_with_opts( + input.depth_clone(64), + crate::support::Clock::options(), + ) + .await + { Ok(r) => Ok(Built::normalized(r.result.to_value())), Err(e) => Err(GraphRun::error(&e)), } @@ -385,7 +401,9 @@ impl Engines { let requests: Vec = (0..suite.cases.len() * 3) .map(|i| PolicyRun::request(&suite.cases[i % suite.cases.len()])) .collect(); - let batch = run.workspace.evaluate_batch(&requests); + let batch = run + .workspace + .evaluate_batch_pinned(&requests, &crate::support::Clock::options()); for (i, case) in suite.cases.iter().enumerate() { let want = Self::driver(&self.reference, &run, suite, case); let single = run.compiled(case); @@ -461,10 +479,12 @@ impl Engines { targets: &[Arc], columns: &zen_expression::lane::Columns, ) { - let Ok(output) = - run.workspace - .evaluate_columns(&Arc::from(PolicyRun::MAIN), targets, columns) - else { + let Ok(output) = run.workspace.evaluate_columns_pinned( + &Arc::from(PolicyRun::MAIN), + targets, + columns, + &crate::support::Clock::options(), + ) else { return; }; self.hosted += output.paths().hosted; @@ -705,7 +725,7 @@ impl Snapshot { for call in 1..=Self::CALLS { let output = run .compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; let errors = output.errors.iter().flatten().map(|e| format!("{e:?}")); self.lines.push(format!( @@ -749,7 +769,7 @@ impl Snapshot { false => built.columns(), }; for call in 1..=Self::CALLS { - let line = match run.workspace.evaluate_columns(&Arc::from(PolicyRun::MAIN), &targets, &columns) { + let line = match run.workspace.evaluate_columns_pinned(&Arc::from(PolicyRun::MAIN), &targets, &columns, &crate::support::Clock::options()) { Ok(output) => format!( "rows={}\ttyped={}\tlaned={}\thosted={}\terrors=[{}]\tpaths={:016x}\torder={:016x}", output.rows, diff --git a/core/engine/tests/support/golden.rs b/core/engine/tests/support/golden.rs index f6d67c8ef..11424a39d 100644 --- a/core/engine/tests/support/golden.rs +++ b/core/engine/tests/support/golden.rs @@ -674,7 +674,7 @@ impl Golden { pub fn prepare() { std::env::set_var("TZ", "UTC"); - std::env::set_var("__ZEN_MOCK_UTC_TIME", Self::CLOCK); + crate::support::Clock::set(Self::CLOCK); } pub fn new(name: &str) -> Golden { @@ -874,14 +874,14 @@ impl Live { ws: &PolicyWorkspace, req: &EvaluateRequest, ) -> Result { - ws.evaluate_with_driver(req) + ws.evaluate_with_driver(req, crate::support::Clock::now()) } pub fn enhanced( ws: &PolicyWorkspace, req: &EvaluateRequest, ) -> Result { - ws.enhance_trace_with_driver(req) + ws.enhance_trace_with_driver(req, crate::support::Clock::now()) } } @@ -914,7 +914,7 @@ impl Reference { pub fn prepare(live: &str) { match Self::recorded() { true => Golden::prepare(), - false => std::env::set_var("__ZEN_MOCK_UTC_TIME", live), + false => crate::support::Clock::set(live), } } diff --git a/core/engine/tests/support/mod.rs b/core/engine/tests/support/mod.rs index 16b19991c..f4a40f405 100644 --- a/core/engine/tests/support/mod.rs +++ b/core/engine/tests/support/mod.rs @@ -8,6 +8,33 @@ use std::path::Path; use zen_engine::loader::{FilesystemLoader, FilesystemLoaderOptions}; use zen_engine::model::{DecisionContent, GraphContent}; +#[allow(dead_code)] +pub struct Clock; + +#[allow(dead_code)] +impl Clock { + fn cell() -> &'static std::sync::OnceLock> { + static NOW: std::sync::OnceLock> = + std::sync::OnceLock::new(); + &NOW + } + + pub fn set(text: &str) { + let _ = Self::cell().set(zen_engine::context::parse_instant(text)); + } + + pub fn now() -> Option { + Self::cell().get().copied().flatten() + } + + pub fn options() -> zen_engine::EvaluationOptions { + zen_engine::EvaluationOptions { + now: Self::now(), + ..Default::default() + } + } +} + #[allow(dead_code)] pub struct Switches { pub typed: bool, diff --git a/core/engine/tests/support/policies.rs b/core/engine/tests/support/policies.rs index 54b553dbe..79132f9de 100644 --- a/core/engine/tests/support/policies.rs +++ b/core/engine/tests/support/policies.rs @@ -101,7 +101,7 @@ impl Anchor { crate::support::switches(); let literal = conformance::literal::Parser::document(policy).expect("policy literal"); let document = conformance::policy::Policy::expand(&literal[0]).expect("policy expand"); - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().with_version(zen_engine::EngineVersion::V2); ws.set_policy( "anchor", serde_json::from_value(document).expect("policy json"), @@ -474,7 +474,8 @@ impl PolicyCase { file.test .into_iter() .map(|case| { - let mut workspace = PolicyWorkspace::new(); + let mut workspace = + PolicyWorkspace::new().with_version(zen_engine::EngineVersion::V2); for path in &case.policies { let text = std::fs::read_to_string(format!("{}{path}", Self::FIXTURES_DIR)) .expect("fixture"); @@ -581,7 +582,7 @@ impl Generated { pub fn workspace(seed: u64) -> Option { let parsed = serde_json::from_value(Gen::document(seed)).ok()?; - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().with_version(zen_engine::EngineVersion::V2); ws.set_policy(Self::PATH, parsed); Some(ws) } diff --git a/core/engine/tests/table_dialects.rs b/core/engine/tests/table_dialects.rs index 5c5074b18..db9c838f4 100644 --- a/core/engine/tests/table_dialects.rs +++ b/core/engine/tests/table_dialects.rs @@ -1,6 +1,7 @@ -mod compiled_default; +mod latest; mod support; +use latest::Latest; use serde_json::{json, Value}; use std::sync::Arc; use support::columns::Built; @@ -218,7 +219,7 @@ impl Table { else { panic!("not a graph"); }; - let mut decision = Decision::from(graph); + let mut decision = Decision::from(graph).latest(); decision.compile(); decision } @@ -245,7 +246,7 @@ impl Table { {"id": "t", "type": "decisionTable", "props": {"data": self.data("x.", "x.")}} ]}), }; - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().latest(); ws.set_policy("p", serde_json::from_value(doc).expect("policy")); ws } @@ -331,9 +332,11 @@ impl Table { fn run(&self, input: Value) -> Seen { let decision = self.decision(); let context = Variable::from(input.clone()); - let single = Self::graph_result(Self::block(decision.evaluate(context.depth_clone(64)))); + let single = Self::graph_result(Self::block( + decision.evaluate_with_opts(context.depth_clone(64), crate::support::Clock::options()), + )); let batch = Self::block( - decision.evaluate_batch(&[context.depth_clone(64)], EvaluationOptions::default()), + decision.evaluate_batch(&[context.depth_clone(64)], crate::support::Clock::options()), ) .into_iter() .map(Self::graph_result) @@ -344,7 +347,7 @@ impl Table { EvaluationOptions { trace: zen_engine::trace::TraceFormat::Legacy, max_depth: 10, - ..Default::default() + ..crate::support::Clock::options() }, )); let graph_trace = match &traced { @@ -370,9 +373,10 @@ impl Table { ]; graph.push(( "walker", - Self::graph_result(Self::block( - decision.interpreted().evaluate(context.depth_clone(64)), - )), + Self::graph_result(Self::block(decision.interpreted().evaluate_with_opts( + context.depth_clone(64), + crate::support::Clock::options(), + ))), )); let ws = self.workspace(); @@ -389,20 +393,39 @@ impl Table { false => zen_engine::trace::TraceFormat::Off, }, }; - let (compiled, _) = Self::policy_result(ws.evaluate(&request(false))); - let (traced, policy_trace) = Self::policy_result(ws.evaluate(&request(true))); - let batch = Self::policy_result(ws.evaluate_batch(&[request(false)]).remove(0)).0; + let (compiled, _) = Self::policy_result( + ws.evaluate_pinned(&request(false), &crate::support::Clock::options()), + ); + let (traced, policy_trace) = Self::policy_result( + ws.evaluate_pinned(&request(true), &crate::support::Clock::options()), + ); + let batch = Self::policy_result( + ws.evaluate_batch_pinned(&[request(false)], &crate::support::Clock::options()) + .remove(0), + ) + .0; let mut policy = vec![("compiled", compiled), ("batch", batch), ("traced", traced)]; policy.push(( "driver", - Self::policy_result(ws.evaluate_with_driver(&request(false))).0, + Self::policy_result( + ws.evaluate_with_driver(&request(false), crate::support::Clock::now()), + ) + .0, )); let rows = vec![policy_input.clone(); 2]; let built = Built::new(&rows); let columns = built.as_ref().map(|built| built.columns()); let columns = columns .as_ref() - .and_then(|columns| ws.evaluate_columns(&Arc::from("p"), &[], columns).ok()) + .and_then(|columns| { + ws.evaluate_columns_pinned( + &Arc::from("p"), + &[], + columns, + &crate::support::Clock::options(), + ) + .ok() + }) .map(|mut output| { let text = match output.errors[0].take().map(std::rc::Rc::try_unwrap) { Some(Ok(zen_engine::EvaluationError::Policy(error))) => { diff --git a/core/engine/tests/trace_golden.rs b/core/engine/tests/trace_golden.rs index 3ff2906b8..00465b89c 100644 --- a/core/engine/tests/trace_golden.rs +++ b/core/engine/tests/trace_golden.rs @@ -8,15 +8,14 @@ use flate2::Compression; use serde_json::{json, Value}; use std::collections::HashMap; use std::io::Write; -use std::sync::atomic::Ordering; use zen_engine::trace::TraceFormat; -use zen_engine::{DecisionGraphResponse, EvaluationError, EvaluationOptions, ZEN_CONFIG}; +use zen_engine::{DecisionGraphResponse, EngineVersion, EvaluationError, EvaluationOptions}; fn options(format: TraceFormat) -> EvaluationOptions { EvaluationOptions { trace: format, max_depth: 10, - ..Default::default() + ..crate::support::Clock::options() } } @@ -83,18 +82,10 @@ fn policy( }) } -fn serial_tests() -> std::sync::MutexGuard<'static, ()> { - static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - let guard = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - Spec::prepare(); - guard -} - -fn engines(compiled: bool) -> &'static str { - ZEN_CONFIG.compiled.store(compiled, Ordering::Relaxed); +fn engines(compiled: bool) -> (EngineVersion, &'static str) { match compiled { - true => "compiled", - false => "interpreted", + true => (EngineVersion::V2, "compiled"), + false => (EngineVersion::V1, "interpreted"), } } @@ -149,12 +140,13 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { let traced = options(format); let (suites, _) = Spec::suites(Dialect::Graph); for suite in &suites { - let Ok(run) = GraphRun::new(suite) else { + let Ok(mut run) = GraphRun::new(suite) else { continue; }; let id = suite.id(); for flag in [false, true] { - let engine = engines(flag); + let (version, engine) = engines(flag); + run.version(version); for (case, c) in suite.cases.iter().enumerate() { let input = || c.input.depth_clone(64); let mut push = |variant: String, outcome: Value| { @@ -204,7 +196,7 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { ); } } - engines(false); + run.version(EngineVersion::V1); let inputs: Vec<_> = suite .cases .iter() @@ -228,7 +220,7 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { } let (suites, _) = Spec::suites(Dialect::Policy); for suite in &suites { - let Ok(run) = PolicyRun::new(suite) else { + let Ok(mut run) = PolicyRun::new(suite) else { continue; }; let id = suite.id(); @@ -239,7 +231,8 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { req }; for flag in [false, true] { - let engine = engines(flag); + let (version, engine) = engines(flag); + run.version(version); for (case, c) in suite.cases.iter().enumerate() { let mut push = |variant: String, outcome: Value| { sink(Run { @@ -254,7 +247,10 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { }; push( format!("{engine} workspace"), - policy(run.workspace.evaluate(&request(c))), + policy( + run.workspace + .evaluate_pinned(&request(c), &crate::support::Clock::options()), + ), ); let mut enhanced = PolicyRun::request(c); if format == TraceFormat::V1 { @@ -262,7 +258,10 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { } push( format!("{engine} enhanced"), - policy(run.workspace.enhance_trace(&enhanced)), + policy( + run.workspace + .enhance_trace_pinned(&enhanced, &crate::support::Clock::options()), + ), ); if c.goals.is_empty() { push( @@ -284,11 +283,11 @@ fn each(format: TraceFormat, sink: &mut dyn FnMut(Run)) { } } } - engines(false); + run.version(EngineVersion::V1); let requests: Vec<_> = suite.cases.iter().map(request).collect(); for (case, result) in run .workspace - .evaluate_batch(&requests) + .evaluate_batch_pinned(&requests, &crate::support::Clock::options()) .into_iter() .enumerate() { @@ -363,7 +362,7 @@ fn parse(text: &str) -> Value { type Key = (String, String, usize, String); -fn golden() -> HashMap { +fn golden() -> HashMap> { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/trace-base.jsonl.gz"); let file = std::fs::File::open(path).unwrap(); @@ -375,6 +374,7 @@ fn golden() -> HashMap { let kind = v["kind"].as_str().unwrap().to_string(); let suite = v["suite"].as_str().unwrap().to_string(); let case = v["case"].as_u64().unwrap() as usize; + let outcome = std::sync::Arc::new(v["outcome"].clone()); for variant in v["variants"].as_array().unwrap() { out.insert( ( @@ -383,7 +383,7 @@ fn golden() -> HashMap { case, variant.as_str().unwrap().to_string(), ), - v["outcome"].clone(), + outcome.clone(), ); } } @@ -561,7 +561,9 @@ fn compare(format: TraceFormat) { "interpreted" | "compiled" => engine, _ => "compiled", }; - golden.get(&key(&format!("{engine} serialized"))) + golden + .get(&key(&format!("{engine} serialized"))) + .map(|v| &**v) }); let interpreted = run.variant.starts_with("interpreted "); let got = match (format, interpreted) { @@ -682,7 +684,7 @@ fn legacy_and_restored_v1() { #[test] fn legacy_traces_equal_restored_v1_traces() { - let _serial = serial_tests(); + Spec::prepare(); if cfg!(feature = "arbitrary_precision") { big_stack(legacy_and_restored_v1); } @@ -699,7 +701,7 @@ fn big_stack(f: impl FnOnce() + Send + 'static) { #[test] fn legacy_traces_equal_the_base_traces() { - let _serial = serial_tests(); + Spec::prepare(); if cfg!(feature = "arbitrary_precision") { big_stack(|| compare(TraceFormat::Legacy)); } @@ -707,7 +709,7 @@ fn legacy_traces_equal_the_base_traces() { #[test] fn v1_restores_to_the_base_traces() { - let _serial = serial_tests(); + Spec::prepare(); if cfg!(feature = "arbitrary_precision") { big_stack(|| compare(TraceFormat::V1)); } @@ -715,7 +717,7 @@ fn v1_restores_to_the_base_traces() { #[test] fn capture_base_traces() { - let _serial = serial_tests(); + Spec::prepare(); if !cfg!(feature = "arbitrary_precision") { return; } @@ -872,7 +874,7 @@ fn native_and_convert() { #[test] fn native_and_convert_restore_identically() { - let _serial = serial_tests(); + Spec::prepare(); big_stack(native_and_convert); } @@ -950,15 +952,15 @@ fn outcome_of(result: &Result = Vec::new(); for suite in &suites { - let Ok(run) = GraphRun::new(suite) else { + let Ok(mut run) = GraphRun::new(suite) else { continue; }; + run.version(EngineVersion::V2); let inputs: Vec<_> = suite .cases .iter() @@ -993,7 +995,6 @@ fn batch_rows() { } } } - ZEN_CONFIG.compiled.store(previous, Ordering::Relaxed); eprintln!( "batch rows re-evaluated for their facts: {:?}", zen_engine::trace::testing::reevaluations() @@ -1020,7 +1021,7 @@ fn batch_rows() { #[test] fn batch_rows_equal_single_row_traces() { - let _serial = serial_tests(); + Spec::prepare(); big_stack(batch_rows); } @@ -1175,7 +1176,6 @@ const COLUMNAR_INTERMEDIATE: [&str; 3] = [ fn columnar_rows() { Spec::prepare(); - let previous = ZEN_CONFIG.compiled.swap(true, Ordering::Relaxed); let (suites, _) = Spec::suites(Dialect::Graph); let options = options(TraceFormat::V1); let (mut rows, mut equal, mut deviating, mut intermediate, mut skipped) = @@ -1183,9 +1183,10 @@ fn columnar_rows() { let (planned, batched) = zen_engine::trace::testing::columnar_traced(); let mut failures: Vec = Vec::new(); for suite in &suites { - let Ok(run) = GraphRun::new(suite) else { + let Ok(mut run) = GraphRun::new(suite) else { continue; }; + run.version(EngineVersion::V2); let inputs: Vec = suite.cases.iter().map(|c| c.input.to_value()).collect(); let groups: Vec<(Built, Vec)> = match built(&inputs) { Some(all) => vec![(all, (0..inputs.len()).collect())], @@ -1246,7 +1247,6 @@ fn columnar_rows() { } } } - ZEN_CONFIG.compiled.store(previous, Ordering::Relaxed); eprintln!( "columnar rows re-evaluated for their facts: {:?}", zen_engine::trace::testing::reevaluations() @@ -1275,7 +1275,7 @@ fn columnar_rows() { #[test] fn columnar_rows_equal_single_row_traces() { - let _serial = serial_tests(); + Spec::prepare(); big_stack(columnar_rows); } @@ -1299,14 +1299,18 @@ fn policy_native_and_convert() { ) }); for suite in &suites { - let Ok(run) = PolicyRun::new(suite) else { + let Ok(mut run) = PolicyRun::new(suite) else { continue; }; + run.version(EngineVersion::V1); let documents = release(suite); for case in &suite.cases { let mut req = PolicyRun::request(case); req.trace = TraceFormat::Legacy; - let trace = match run.workspace.evaluate(&req) { + let trace = match run + .workspace + .evaluate_pinned(&req, &crate::support::Clock::options()) + { Ok(r) => r.trace.and_then(|t| t.into_legacy()), Err(zen_engine::policy::EvaluationError::ExpressionFailed { partial_trace, @@ -1391,7 +1395,7 @@ fn policy_native_and_convert() { #[test] fn policy_native_and_convert_restore_identically() { - let _serial = serial_tests(); + Spec::prepare(); if cfg!(feature = "arbitrary_precision") { big_stack(policy_native_and_convert); } @@ -1647,27 +1651,30 @@ fn timing_stress(sets: u64) { #[test] fn v1_restores_loop_traces_with_any_timings() { - let _serial = serial_tests(); + Spec::prepare(); big_stack(|| timing_stress(64)); } #[test] fn trace_documents_move_across_threads() { - let _serial = serial_tests(); + Spec::prepare(); fn sendable() {} sendable::(); Spec::prepare(); - engines(true); let (suites, _) = Spec::suites(Dialect::Policy); let mut moved = 0usize; for suite in suites.iter().take(40) { - let Ok(run) = PolicyRun::new(suite) else { + let Ok(mut run) = PolicyRun::new(suite) else { continue; }; + run.version(EngineVersion::V2); for case in &suite.cases { let mut request = PolicyRun::request(case); request.trace = TraceFormat::V1; - let Ok(result) = run.workspace.evaluate(&request) else { + let Ok(result) = run + .workspace + .evaluate_pinned(&request, &crate::support::Clock::options()) + else { continue; }; let Some(doc) = result.trace.as_ref().and_then(|t| t.as_v1()).cloned() else { @@ -1682,7 +1689,6 @@ fn trace_documents_move_across_threads() { moved += 1; } } - engines(false); assert!(moved > 0); } @@ -1748,12 +1754,12 @@ fn dump_all(dir: &str) { let mut interpreted = std::env::var("TRACE_DUMP_INTERPRETED") .is_ok() .then(|| file("interpreted.jsonl")); - let previous = ZEN_CONFIG.compiled.swap(true, Ordering::Relaxed); let (suites, _) = Spec::suites(Dialect::Graph); for suite in &suites { - let Ok(run) = GraphRun::new(suite) else { + let Ok(mut run) = GraphRun::new(suite) else { continue; }; + run.version(EngineVersion::V2); let id = suite.id(); for format in [TraceFormat::V1, TraceFormat::Legacy] { let traced = options(format); @@ -1772,12 +1778,10 @@ fn dump_all(dir: &str) { } if format == TraceFormat::Legacy { if let Some(interpreted) = interpreted.as_mut() { - ZEN_CONFIG.compiled.store(false, Ordering::Relaxed); + let old = run.uncompiled.with_version(EngineVersion::V1); for (case, c) in suite.cases.iter().enumerate() { - let result = Guard::block( - run.uncompiled - .evaluate_with_opts(c.input.depth_clone(64), traced), - ); + let result = + Guard::block(old.evaluate_with_opts(c.input.depth_clone(64), traced)); writeln!( interpreted, "{id} #{case} {name}\t{}", @@ -1785,7 +1789,6 @@ fn dump_all(dir: &str) { ) .unwrap(); } - ZEN_CONFIG.compiled.store(true, Ordering::Relaxed); } } let batch = Guard::block(run.compiled.evaluate_batch(&inputs, traced)); @@ -1827,9 +1830,10 @@ fn dump_all(dir: &str) { } let (suites, _) = Spec::suites(Dialect::Policy); for suite in &suites { - let Ok(run) = PolicyRun::new(suite) else { + let Ok(mut run) = PolicyRun::new(suite) else { continue; }; + run.version(EngineVersion::V2); let id = suite.id(); for format in [TraceFormat::V1, TraceFormat::Legacy] { let name = <&str>::from(format); @@ -1839,7 +1843,10 @@ fn dump_all(dir: &str) { req }; for (case, c) in suite.cases.iter().enumerate() { - let out = policy_dump(run.workspace.evaluate(&request(c))); + let out = policy_dump( + run.workspace + .evaluate_pinned(&request(c), &crate::support::Clock::options()), + ); writeln!(policies, "{id} #{case} {name}\t{out}").unwrap(); if c.goals.is_empty() { let result = Guard::block(run.engine.evaluate_with_opts( @@ -1858,7 +1865,7 @@ fn dump_all(dir: &str) { let requests: Vec<_> = suite.cases.iter().map(request).collect(); for (case, result) in run .workspace - .evaluate_batch(&requests) + .evaluate_batch_pinned(&requests, &crate::support::Clock::options()) .into_iter() .enumerate() { @@ -1871,12 +1878,11 @@ fn dump_all(dir: &str) { } } } - ZEN_CONFIG.compiled.store(previous, Ordering::Relaxed); } #[test] fn dump_traces() { - let _serial = serial_tests(); + Spec::prepare(); if let Ok(dir) = std::env::var("TRACE_DUMP_ALL") { big_stack(move || dump_all(&dir)); } diff --git a/core/engine/tests/verify.rs b/core/engine/tests/verify.rs index 166c8bffa..75bf9f3bb 100644 --- a/core/engine/tests/verify.rs +++ b/core/engine/tests/verify.rs @@ -1,13 +1,14 @@ #[allow(dead_code)] -mod compiled_default; +mod latest; mod support; +use latest::Latest; use serde_json::{json, Value}; use std::sync::Arc; use support::columns::Built; use zen_engine::model::GraphContent; use zen_engine::policy::{EvaluateRequest, EvaluationResult, PolicyWorkspace}; -use zen_engine::{Decision, DecisionGraphResponse, EvaluationError, EvaluationOptions}; +use zen_engine::{Decision, DecisionGraphResponse, EvaluationError}; use zen_expression::Variable; struct Graphs; @@ -60,7 +61,7 @@ impl Graphs { } fn decision(graph: &Value) -> Decision { - Decision::from(Arc::new(Self::content(graph))) + Decision::from(Arc::new(Self::content(graph))).latest() } fn text(result: Result>) -> String { @@ -113,7 +114,7 @@ struct Policies; impl Policies { fn workspace(doc: Value) -> PolicyWorkspace { - let mut ws = PolicyWorkspace::new(); + let mut ws = PolicyWorkspace::new().latest(); ws.set_policy("p", serde_json::from_value(doc).unwrap()); ws } @@ -142,7 +143,14 @@ impl Policies { columns: &zen_expression::lane::Columns, rows: usize, ) -> Vec { - let output = ws.evaluate_columns(&Arc::from("p"), &[], columns).unwrap(); + let output = ws + .evaluate_columns_pinned( + &Arc::from("p"), + &[], + columns, + &crate::support::Clock::options(), + ) + .unwrap(); (0..rows) .map(|row| match &output.errors[row] { Some(error) => format!("ERR {error:?}"), @@ -155,18 +163,28 @@ impl Policies { let ws = Self::workspace(doc); let driver: Vec = inputs .iter() - .map(|input| Self::text(ws.evaluate_with_driver(&Self::request(input, false)))) + .map(|input| { + Self::text(ws.evaluate_with_driver( + &Self::request(input, false), + crate::support::Clock::now(), + )) + }) .collect(); let single = inputs .iter() - .map(|input| Self::text(ws.evaluate(&Self::request(input, false)))) + .map(|input| { + Self::text(ws.evaluate_pinned( + &Self::request(input, false), + &crate::support::Clock::options(), + )) + }) .collect(); let requests: Vec = inputs .iter() .map(|input| Self::request(input, false)) .collect(); let batch = ws - .evaluate_batch(&requests) + .evaluate_batch_pinned(&requests, &crate::support::Clock::options()) .into_iter() .map(Self::text) .collect(); @@ -197,7 +215,6 @@ impl Policies { #[tokio::test] async fn compiled_table_cells_reread_the_clock() { - assert!(std::env::var("__ZEN_MOCK_UTC_TIME").is_err()); let graph = Graphs::chain(vec![ Graphs::expression( "ex", @@ -228,34 +245,55 @@ async fn compiled_table_cells_reread_the_clock() { }; let run = || async { let columnar = compiled - .evaluate_columns(&columns, EvaluationOptions::default()) + .evaluate_columns(&columns, crate::support::Clock::options()) .await; [ ( "walker", - Graphs::text(walker.evaluate(Variable::from(input.clone())).await), + Graphs::text( + walker + .evaluate_with_opts( + Variable::from(input.clone()), + crate::support::Clock::options(), + ) + .await, + ), ), ( "single", - Graphs::text(single.evaluate(Variable::from(input.clone())).await), + Graphs::text( + single + .evaluate_with_opts( + Variable::from(input.clone()), + crate::support::Clock::options(), + ) + .await, + ), ), ( "batch", first( batch - .evaluate_batch(&contexts, EvaluationOptions::default()) + .evaluate_batch(&contexts, crate::support::Clock::options()) .await, ), ), ( "compiled-single", - Graphs::text(compiled.evaluate(Variable::from(input.clone())).await), + Graphs::text( + compiled + .evaluate_with_opts( + Variable::from(input.clone()), + crate::support::Clock::options(), + ) + .await, + ), ), ( "compiled-batch", first( compiled - .evaluate_batch(&contexts, EvaluationOptions::default()) + .evaluate_batch(&contexts, crate::support::Clock::options()) .await, ), ), @@ -380,25 +418,36 @@ fn policy_collects_in_output_order() { }) .unwrap_or_default() }; - let output = Policies::text(ws.evaluate(&request)); - let log = writes(ws.enhance_trace(&request).unwrap()); + let output = Policies::text(ws.evaluate_pinned(&request, &crate::support::Clock::options())); + let log = writes( + ws.enhance_trace_pinned(&request, &crate::support::Clock::options()) + .unwrap(), + ); assert_eq!(log, ["order.a", "order.b", "order.c", "order.d", "order.e"]); let unordered = |text: &str| serde_json::from_str::(text).ok(); - let mut driver_log = writes(ws.enhance_trace_with_driver(&request).unwrap()); + let mut driver_log = writes( + ws.enhance_trace_with_driver(&request, crate::support::Clock::now()) + .unwrap(), + ); driver_log.sort(); assert_eq!(driver_log, log); assert_eq!( - unordered(&Policies::text(ws.evaluate_with_driver(&request))), + unordered(&Policies::text( + ws.evaluate_with_driver(&request, crate::support::Clock::now()) + )), unordered(&output) ); for run in 0..32 { assert_eq!( - Policies::text(ws.evaluate(&request)), + Policies::text(ws.evaluate_pinned(&request, &crate::support::Clock::options())), output, "run {run}: output order" ); assert_eq!( - writes(ws.enhance_trace(&request).unwrap()), + writes( + ws.enhance_trace_pinned(&request, &crate::support::Clock::options()) + .unwrap() + ), log, "run {run}: write log order" ); @@ -417,16 +466,21 @@ async fn sub_decisions_reuse_stripped_functions() { let input = Variable::from(json!({ "x": 1 })); let top = Graphs::text( Decision::from(Arc::new(Stripped::primed())) - .evaluate(input.clone()) + .latest() + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) .await, ); assert!( top.contains("cache"), "top-level function must use the stripped cache: {top}" ); - let single = Graphs::text(parent.evaluate(input.clone()).await); + let single = Graphs::text( + parent + .evaluate_with_opts(input.clone(), crate::support::Clock::options()) + .await, + ); let batch: Vec = parent - .evaluate_batch(&[input.clone(), input], EvaluationOptions::default()) + .evaluate_batch(&[input.clone(), input], crate::support::Clock::options()) .await .into_iter() .map(Graphs::text) diff --git a/core/expression/src/config.rs b/core/expression/src/config.rs deleted file mode 100644 index 21810aff5..000000000 --- a/core/expression/src/config.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::sync::atomic::AtomicBool; - -#[derive(Debug)] -pub struct ZenExpressionConfig { - pub lane: AtomicBool, -} - -impl ZenExpressionConfig { - const fn new() -> Self { - Self { - lane: AtomicBool::new(false), - } - } -} - -impl Default for ZenExpressionConfig { - fn default() -> Self { - Self::new() - } -} - -pub static ZEN_EXPRESSION_CONFIG: ZenExpressionConfig = ZenExpressionConfig::new(); diff --git a/core/expression/src/context.rs b/core/expression/src/context.rs index ffa782e8f..c52914a03 100644 --- a/core/expression/src/context.rs +++ b/core/expression/src/context.rs @@ -147,13 +147,7 @@ thread_local! { static UNROWED: AtomicU64 = AtomicU64::new(0); pub fn system_now() -> Instant { - static MOCK: OnceLock> = OnceLock::new(); - MOCK.get_or_init(|| { - std::env::var("__ZEN_MOCK_UTC_TIME") - .ok() - .and_then(|v| v.parse::().ok()) - }) - .unwrap_or_else(Utc::now) + Utc::now() } pub fn system_timezone() -> Tz { diff --git a/core/expression/src/isolate.rs b/core/expression/src/isolate.rs index 5f7b239c7..beddb2745 100644 --- a/core/expression/src/isolate.rs +++ b/core/expression/src/isolate.rs @@ -1,7 +1,6 @@ use ahash::HashMap; use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; -use std::sync::atomic::Ordering; use std::sync::Arc; use thiserror::Error; @@ -12,7 +11,7 @@ use crate::parser::{Parser, ParserError}; use crate::scope::Scope; use crate::variable::Variable; use crate::vm::{VMError, VM}; -use crate::{Expression, ExpressionKind, ZEN_EXPRESSION_CONFIG}; +use crate::{Expression, ExpressionKind}; use bumpalo::Bump; use zen_types::symbol::Symbol; @@ -32,7 +31,8 @@ pub struct Isolate { scope: Scope, references: HashMap, cache: Option>, - lane: crate::lane::Backend, + lane: Option, + now: Option, } impl Isolate { @@ -47,7 +47,8 @@ impl Isolate { scope: Scope::default(), references: Default::default(), cache: None, - lane: Default::default(), + lane: None, + now: None, } } @@ -63,6 +64,21 @@ impl Isolate { self } + pub fn with_now(mut self, now: Option) -> Self { + self.set_now(now); + self + } + + pub fn set_now(&mut self, now: Option) { + self.now = now; + self.vm.set_now(now); + } + + pub fn with_lane(mut self, lane: bool) -> Self { + self.lane = lane.then(Default::default); + self + } + pub fn set_environment(&mut self, variable: Variable) { self.scope.set_base(variable); self.references.clear(); @@ -145,8 +161,8 @@ impl Isolate { } pub fn run_standard(&mut self, source: &str) -> Result { - if ZEN_EXPRESSION_CONFIG.lane.load(Ordering::Relaxed) { - return self.lane.run(source, ExpressionKind::Standard, &self.scope); + if let Some(lane) = &mut self.lane { + return lane.run(source, ExpressionKind::Standard, &self.scope, self.now); } let cached = self @@ -178,10 +194,9 @@ impl Isolate { } pub fn run_unary(&mut self, source: &str) -> Result { - if ZEN_EXPRESSION_CONFIG.lane.load(Ordering::Relaxed) { - return self - .lane - .run(source, ExpressionKind::Unary, &self.scope)? + if let Some(lane) = &mut self.lane { + return lane + .run(source, ExpressionKind::Unary, &self.scope, self.now)? .as_bool() .ok_or(IsolateError::ValueCastError); } diff --git a/core/expression/src/lane/date/helpers.rs b/core/expression/src/lane/date/helpers.rs index d273abc40..cfa1dd487 100644 --- a/core/expression/src/lane/date/helpers.rs +++ b/core/expression/src/lane/date/helpers.rs @@ -100,10 +100,8 @@ pub(crate) fn date_time(str: &str, context: &EvaluationContext) -> VMResult VMResult { - let now = context.now(); - if str == "now" { - return Ok(now.naive_utc().time()); + return Ok(context.now().naive_utc().time()); } NaiveTime::parse_from_str(str, DATE_TIME) diff --git a/core/expression/src/lane/mod.rs b/core/expression/src/lane/mod.rs index 830318bee..eb494244a 100644 --- a/core/expression/src/lane/mod.rs +++ b/core/expression/src/lane/mod.rs @@ -1455,6 +1455,7 @@ impl Backend { source: &str, kind: ExpressionKind, scope: &Scope, + now: Option, ) -> Result { let programs = match kind { ExpressionKind::Standard => &mut self.standard, @@ -1466,7 +1467,11 @@ impl Backend { } let program = &programs[source]; let mut runner = Self::RUNNER.take(); - let result = runner.evaluate_one(program, &EvaluationContext::default(), scope); + let context = EvaluationContext::new(crate::context::Pinned { + now, + ..Default::default() + }); + let result = runner.evaluate_one(program, &context, scope); Self::RUNNER.set(runner); result } diff --git a/core/expression/src/lib.rs b/core/expression/src/lib.rs index f98d720b2..34b1fab4a 100644 --- a/core/expression/src/lib.rs +++ b/core/expression/src/lib.rs @@ -57,7 +57,6 @@ #![forbid(unsafe_code)] -mod config; pub mod context; mod isolate; @@ -78,7 +77,6 @@ pub mod validate; pub mod variable; pub mod vm; -pub use config::{ZenExpressionConfig, ZEN_EXPRESSION_CONFIG}; pub use dates::DateValue; pub use exports::{ compile_expression, compile_unary_expression, evaluate_expression, evaluate_unary_expression, diff --git a/core/expression/src/typed/tests/exact.rs b/core/expression/src/typed/tests/exact.rs index 2e6021517..5d16e416a 100644 --- a/core/expression/src/typed/tests/exact.rs +++ b/core/expression/src/typed/tests/exact.rs @@ -25,7 +25,6 @@ struct Report { impl Lab { fn new(workload: Workload, rows: Vec) -> Self { - Workload::mock(); let hir = workload.hir().expect("lowering"); let oracle = Oracle::new(&workload, &hir); let expected = rows @@ -212,24 +211,14 @@ impl Bench { let program = Program::new(hir).expect("program"); let mut out = program.outputs(); program - .run( - &batch, - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&batch, &mut out, None, &Workload::context()) .expect("run"); let mut best = f64::MAX; for _ in 0..reps { let t = Instant::now(); for _ in 0..50 { program - .run( - &batch, - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&batch, &mut out, None, &Workload::context()) .expect("run"); } best = best.min(t.elapsed().as_nanos() as f64 / 50.0 / size as f64); diff --git a/core/expression/src/typed/tests/oracle.rs b/core/expression/src/typed/tests/oracle.rs index ce58feb27..b1d0ea7e0 100644 --- a/core/expression/src/typed/tests/oracle.rs +++ b/core/expression/src/typed/tests/oracle.rs @@ -86,7 +86,7 @@ impl fmt::Display for Val { impl Oracle { pub(crate) fn new(workload: &Workload, hir: &Hir) -> Self { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(Workload::now()); let mut standard = |source: &str| -> Code { isolate .compile_standard(source) @@ -115,6 +115,7 @@ impl Oracle { true => None, false => Some( Isolate::new() + .with_now(Workload::now()) .compile_unary(cell) .map(|e| e.bytecode().clone()) .expect("unary cell"), @@ -204,7 +205,7 @@ impl Oracle { } pub(crate) fn run(&self, input: Variable) -> RowResult { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(Workload::now()); let result = Variable::empty_object(); isolate.set_environment(input.shallow_clone()); for step in &self.steps { @@ -226,7 +227,7 @@ impl Oracle { } } env.dot_insert(alias, item.shallow_clone()); - let mut member = Isolate::new(); + let mut member = Isolate::new().with_now(Workload::now()); member.set_environment(env.shallow_clone()); let value = member.run_compiled(code).map_err(|e| e.to_string())?; env.dot_insert(key, value); diff --git a/core/expression/src/typed/tests/scale.rs b/core/expression/src/typed/tests/scale.rs index 9131ca373..ff5603707 100644 --- a/core/expression/src/typed/tests/scale.rs +++ b/core/expression/src/typed/tests/scale.rs @@ -59,12 +59,7 @@ impl Case { let frame = Frame::new(&self.hir, &self.workload.spec, rows, 0); let mut out = self.program.outputs(); self.program - .run( - &frame.batch(), - &mut out, - select, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, select, &Workload::context()) .expect("run"); (0..rows.len()) .map(|r| { @@ -432,12 +427,7 @@ fn member_outputs_with_offset_lists() { let frame = Frame::new(&hir, &workload.spec, &rows, shift); let mut out = program.outputs(); program - .run( - &frame.batch(), - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, None, &Workload::context()) .expect("run"); for (r, row) in rows.iter().enumerate() { if out.faults().get(r) { @@ -478,12 +468,7 @@ fn outputs_move_out() { ); let mut out = case.program.outputs(); case.program - .run( - &frame.batch(), - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, None, &Workload::context()) .expect("run"); let (mant, scale, valid) = out.slot_mut(0).and_then(|s| s.take_num()).expect("num"); assert_eq!((mant[0], scale[0], valid[0] & 1), (2, 0, 1)); @@ -491,12 +476,7 @@ fn outputs_move_out() { let (bits, _) = out.slot_mut(1).and_then(|s| s.take_bool()).expect("bool"); assert_eq!(bits[0] & 1, 0); case.program - .run( - &frame.batch(), - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, None, &Workload::context()) .expect("rerun"); assert_eq!(out.slots()[0].num(0), Some(Dec::int(2))); } @@ -555,12 +535,7 @@ fn rules_fault_strictly() { let frame = Frame::new(&hir, &spec, &rows, 0); let mut out = program.outputs(); program - .run( - &frame.batch(), - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, None, &Workload::context()) .expect("run"); let got: Vec = (0..rows.len()) .map(|r| { @@ -613,12 +588,7 @@ fn programs_share_across_threads() { let frame = Frame::new(hir, spec, chunk, 0); let mut out = program.outputs(); program - .run( - &frame.batch(), - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, None, &Workload::context()) .expect("run"); for r in (0..chunk.len()).filter(|r| !out.faults().get(*r)) { let got: Vec = out @@ -703,12 +673,7 @@ fn wide_lanes_stay_exact() { let frame = Frame::new(&case.hir, &case.workload.spec, &rows, 0); let mut out = case.program.outputs(); case.program - .run( - &frame.batch(), - &mut out, - None, - &crate::context::EvaluationContext::default(), - ) + .run(&frame.batch(), &mut out, None, &Workload::context()) .expect("run"); assert!(!out.slots()[0].wide.is_empty()); assert!(!out.slots()[2].wide.is_empty()); diff --git a/core/expression/src/typed/tests/workload.rs b/core/expression/src/typed/tests/workload.rs index b701fa7f5..2d5261c78 100644 --- a/core/expression/src/typed/tests/workload.rs +++ b/core/expression/src/typed/tests/workload.rs @@ -1104,14 +1104,13 @@ impl Workload { const CLOCK: &'static str = "2025-03-20T10:15:30Z"; - pub(crate) fn mock() { - static MOCK: std::sync::Once = std::sync::Once::new(); - MOCK.call_once(|| std::env::set_var("__ZEN_MOCK_UTC_TIME", Self::CLOCK)); + pub(crate) fn now() -> Option { + crate::context::parse_instant(Self::CLOCK) } pub(crate) fn context() -> crate::context::EvaluationContext { crate::context::EvaluationContext::new(crate::context::Pinned { - now: crate::context::parse_instant(Self::CLOCK), + now: Self::now(), ..Default::default() }) } @@ -1134,7 +1133,6 @@ impl Workload { } fn w14() -> Workload { - Self::mock(); let rules = [ ("< d('2000-01-01')", "'old'", "d('1999-12-31')"), ( @@ -1171,7 +1169,6 @@ impl Workload { } fn w15() -> Workload { - Self::mock(); Workload { name: "W15", spec: Self::w14_spec(), @@ -1185,7 +1182,6 @@ impl Workload { } fn w19() -> Workload { - Self::mock(); Workload { name: "W19", spec: Self::w14_spec(), @@ -1294,7 +1290,6 @@ impl Workload { } fn w18() -> Workload { - Self::mock(); Workload { name: "W18", spec: Spec { @@ -1391,7 +1386,6 @@ impl Workload { } fn w16() -> Workload { - Self::mock(); Workload { name: "W16", spec: Self::w16_spec(), @@ -1405,7 +1399,6 @@ impl Workload { } fn w17() -> Workload { - Self::mock(); Workload { name: "W17", spec: Self::w16_spec(), diff --git a/core/expression/src/vm/date/mod.rs b/core/expression/src/vm/date/mod.rs index 672bbb058..6b418d30c 100644 --- a/core/expression/src/vm/date/mod.rs +++ b/core/expression/src/vm/date/mod.rs @@ -10,7 +10,6 @@ use std::cell::OnceCell; use std::cmp::Ordering; use std::fmt::{Display, Formatter}; use std::rc::Rc; -use std::sync::OnceLock; // Duration is a modified copy of `humantime` mod duration; @@ -649,16 +648,24 @@ impl DynamicVariableExt for dyn DynamicVariable { } } -pub(crate) fn utc_now() -> DateTime { - static CURRENT_DATE_VALUE: OnceLock>> = OnceLock::new(); +thread_local! { + static PINNED: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} - CURRENT_DATE_VALUE - .get_or_init(|| match std::env::var("__ZEN_MOCK_UTC_TIME") { - Ok(v) => { - let now = v.parse::>().unwrap(); - Some(now) - } - Err(_) => None, - }) - .unwrap_or_else(|| Utc::now()) +pub(crate) struct PinnedNow(Option>); + +impl PinnedNow { + pub(crate) fn enter(now: Option>) -> Self { + Self(PINNED.replace(now)) + } +} + +impl Drop for PinnedNow { + fn drop(&mut self) { + PINNED.set(self.0); + } +} + +pub(crate) fn utc_now() -> DateTime { + PINNED.get().unwrap_or_else(Utc::now) } diff --git a/core/expression/src/vm/helpers.rs b/core/expression/src/vm/helpers.rs index 2ce36a3d3..b53879f38 100644 --- a/core/expression/src/vm/helpers.rs +++ b/core/expression/src/vm/helpers.rs @@ -26,10 +26,8 @@ pub(crate) fn date_time(str: &str) -> VMResult { } pub(crate) fn time(str: &str) -> VMResult { - let now = utc_now(); - if str == "now" { - return Ok(now.naive_utc().time()); + return Ok(utc_now().naive_utc().time()); } return NaiveTime::parse_from_str(str, DATE_TIME) diff --git a/core/expression/src/vm/vm.rs b/core/expression/src/vm/vm.rs index e45962657..57986062a 100644 --- a/core/expression/src/vm/vm.rs +++ b/core/expression/src/vm/vm.rs @@ -28,6 +28,7 @@ pub struct LoopScope { pub struct VM { scopes: Vec, stack: Vec, + now: Option>, } impl VM { @@ -35,12 +36,18 @@ impl VM { Self { scopes: Default::default(), stack: Default::default(), + now: None, } } + pub fn set_now(&mut self, now: Option>) { + self.now = now; + } + pub fn run(&mut self, bytecode: &[Opcode], scope: &Scope) -> VMResult { self.stack.clear(); self.scopes.clear(); + let _pinned = crate::vm::date::PinnedNow::enter(self.now); let s = VMInner::new(bytecode, &mut self.stack, &mut self.scopes).run(scope); Ok(s?) diff --git a/core/expression/tests/conformance/mod.rs b/core/expression/tests/conformance/mod.rs index 364ecdd9d..9134ff600 100644 --- a/core/expression/tests/conformance/mod.rs +++ b/core/expression/tests/conformance/mod.rs @@ -50,8 +50,25 @@ impl SpecCase { Spec::guard(|| self.run_stack(Spec::describe).map(Spec::settle)) } + pub fn laned(&self) -> Result { + Spec::guard(|| { + self.run_isolate( + Isolate::new().with_now(Spec::now()).with_lane(true), + Spec::describe, + ) + .map(Spec::settle) + }) + } + fn run_stack(&self, render: impl Fn(&IsolateError) -> String) -> Result { - let mut isolate = Isolate::new(); + self.run_isolate(Isolate::new().with_now(Spec::now()), render) + } + + fn run_isolate( + &self, + mut isolate: Isolate, + render: impl Fn(&IsolateError) -> String, + ) -> Result { if let Some(input) = &self.input { isolate.set_environment(input.depth_clone(64)); } @@ -133,7 +150,19 @@ impl Spec { "TZ", std::env::var("SPEC_TZ").unwrap_or_else(|_| "UTC".to_string()), ); - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + } + + pub const CLOCK: &'static str = "2025-03-20T10:15:30Z"; + + pub fn now() -> Option { + zen_expression::context::parse_instant(Self::CLOCK) + } + + pub fn context() -> zen_expression::context::EvaluationContext { + zen_expression::context::EvaluationContext::new(zen_expression::context::Pinned { + now: Self::now(), + ..Default::default() + }) } pub fn files() -> Vec<(ExpressionKind, PathBuf)> { diff --git a/core/expression/tests/isolate.rs b/core/expression/tests/isolate.rs index 0412ca00e..5fe3d5351 100644 --- a/core/expression/tests/isolate.rs +++ b/core/expression/tests/isolate.rs @@ -671,7 +671,9 @@ fn isolate_standard_test() { }, ]); - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); for TestEnv { env, cases } in tests { isolate.set_environment(env.into()); @@ -791,7 +793,9 @@ fn isolate_unary_tests() { }, ]); - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); for UnaryTestEnv { env, cases, @@ -811,7 +815,9 @@ fn isolate_unary_tests() { fn isolate_does_not_mutate_environment() { let environment: Variable = json!({ "a": 1, "nested": { "b": 2 } }).into(); - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); isolate.set_environment(environment.clone()); isolate.set_reference("a").unwrap(); @@ -850,7 +856,9 @@ fn isolate_does_not_mutate_environment() { fn assignments_do_not_leak_between_runs() { let environment: Variable = json!({ "a": 1 }).into(); - let mut isolate = Isolate::with_environment(environment.clone()); + let mut isolate = Isolate::with_environment(environment.clone()).with_now( + zen_expression::context::parse_instant("2025-03-20T10:15:30Z"), + ); assert_eq!( isolate.run_standard("b = a + 1; b").unwrap().to_value(), json!(2) @@ -888,7 +896,9 @@ mod test { let output: Value = serde_json5::from_str(output_str).unwrap(); - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); if !input_str.is_empty() { let input: Value = serde_json5::from_str(input_str).unwrap(); isolate.set_environment(input.into()); @@ -909,7 +919,9 @@ mod test { #[test] fn isolate_test_decimals() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); let result = isolate.run_standard("9223372036854775807").unwrap(); assert_eq!(result.to_value(), Value::from(9223372036854775807i64)); @@ -948,7 +960,9 @@ mod test { let output: Value = serde_json5::from_str(output_str).unwrap(); - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); if !input_str.is_empty() { let input: Value = serde_json5::from_str(input_str).unwrap(); isolate.set_environment(input.into()); @@ -969,7 +983,9 @@ mod test { #[test] fn arithmetic_overflow_errors_instead_of_panicking() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); let max = "79228162514264337593543950335"; assert!(isolate.run_standard(&format!("{max} + 1")).is_err()); @@ -988,7 +1004,9 @@ fn arithmetic_overflow_errors_instead_of_panicking() { #[test] fn division_and_modulo_by_zero_return_null() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); let division = isolate.run_standard("1 / 0").unwrap(); assert_eq!(division, Variable::Null); @@ -999,7 +1017,9 @@ fn division_and_modulo_by_zero_return_null() { #[test] fn assigned_closure_with_inner_assignment_scopes_nest() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); isolate.set_environment(json!({}).into()); let assigned = isolate @@ -1025,7 +1045,9 @@ fn assigned_closure_with_inner_assignment_scopes_nest() { #[test] fn date_add_out_of_range_is_invalid_instead_of_panicking() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); let huge_seconds = isolate .run_standard("d('2020-01-01').add(10000000000000000, 's').isValid()") @@ -1040,7 +1062,9 @@ fn date_add_out_of_range_is_invalid_instead_of_panicking() { #[test] fn string_index_at_usize_max_returns_null() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(zen_expression::context::parse_instant( + "2025-03-20T10:15:30Z", + )); isolate.set_environment(json!({ "s": "abc", "i": 18446744073709551615u64 }).into()); let result = isolate.run_standard("s[i]").unwrap(); diff --git a/core/expression/tests/lane.rs b/core/expression/tests/lane.rs index c8ddc6625..d6114ac6b 100644 --- a/core/expression/tests/lane.rs +++ b/core/expression/tests/lane.rs @@ -4,7 +4,6 @@ use rust_decimal::Decimal; use serde_json::{json, Value}; use std::collections::BTreeMap; use std::ops::Index; -use zen_expression::context::EvaluationContext; use zen_expression::lane::{Column, Columns, Fusion, LaneProgram, LaneRunner, Output, Values}; use zen_expression::variable::VariableType; use zen_expression::{ExpressionKind, Isolate, Scope, Variable}; @@ -28,7 +27,6 @@ impl Differential { "TZ", std::env::var("LANE_TZ").unwrap_or_else(|_| "UTC".to_string()), ); - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); Self { kind, runner: LaneRunner::new(), @@ -64,7 +62,7 @@ impl Differential { } fn stack_of(&self, expression: &str, input: Option) -> Result { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(conformance::Spec::now()); if let Some(input) = input { isolate.set_environment(input); } @@ -138,7 +136,7 @@ impl Differential { .expect("typed compile"); let batch = self .runner - .evaluate(&typed, &EvaluationContext::default(), &scopes); + .evaluate(&typed, &conformance::Spec::context(), &scopes); for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { self.compared += 1; let got = self.lane(got); @@ -153,7 +151,7 @@ impl Differential { for (input, exp) in inputs.iter().zip(&expected) { let got = self.runner.evaluate_one( &specialized, - &EvaluationContext::default(), + &conformance::Spec::context(), &Self::scope(input), ); let got = self.lane(got); @@ -166,7 +164,7 @@ impl Differential { } let batch = self .runner - .evaluate(&specialized, &EvaluationContext::default(), &scopes); + .evaluate(&specialized, &conformance::Spec::context(), &scopes); for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { self.compared += 1; let got = self.lane(got); @@ -178,7 +176,7 @@ impl Differential { } let batch = self .runner - .evaluate(&program, &EvaluationContext::default(), &scopes); + .evaluate(&program, &conformance::Spec::context(), &scopes); for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { self.compared += 1; let got = self.lane(got); @@ -193,7 +191,7 @@ impl Differential { for (input, exp) in inputs.iter().zip(&expected) { let got = self.runner.evaluate_one( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &Self::scope(input), ); let got = self.lane(got); @@ -238,7 +236,7 @@ impl Differential { let mut raw = Vec::new(); self.runner.evaluate_columns( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &columns, |i, r| raw.push((i, r)), ); @@ -257,7 +255,7 @@ impl Differential { let mut out = Output::new(); self.runner.evaluate_columns_into( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &columns, &mut out, ); @@ -607,7 +605,7 @@ fn lane_struct_outputs_stay_typed() { .expect("specialize"); let mut runner = LaneRunner::new(); let mut out = Output::new(); - runner.evaluate_columns_into(&program, &EvaluationContext::default(), &columns, &mut out); + runner.evaluate_columns_into(&program, &conformance::Spec::context(), &columns, &mut out); let fields = out.fields(); assert_eq!( fields.iter().map(|(k, _)| k.as_ref()).collect::>(), @@ -1318,11 +1316,11 @@ fn lane_cell_sets_match_unary_evaluation() { &values, &envs, &mut out, - &EvaluationContext::default(), + &conformance::Spec::context(), ); let words = set.words(); for (row, value) in values.iter().enumerate() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(conformance::Spec::now()); for (rule, cell) in cells.iter().enumerate() { let expected = match cell.trim() { "" => true, @@ -1441,7 +1439,7 @@ fn lane_many_matches_expression_node_semantics() { let mut got: Vec> = vec![None; inputs.len()]; runner.evaluate_many( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &scopes, Some(&mask), |row, r| { @@ -1459,7 +1457,8 @@ fn lane_many_matches_expression_node_semantics() { } continue; } - let mut isolate = Isolate::with_environment(input.clone().into()); + let mut isolate = + Isolate::with_environment(input.clone().into()).with_now(conformance::Spec::now()); let mut outputs = Vec::new(); let mut expected: Result, (usize, String)> = Ok(Vec::new()); for (index, (key, source)) in entries.iter().enumerate() { @@ -2495,7 +2494,7 @@ impl SpecLane { for case in cases.iter() { self.rows += 1; if self - .guarded(|_| program.try_kernel(&Self::scope(case), &EvaluationContext::default())) + .guarded(|_| program.try_kernel(&Self::scope(case), &conformance::Spec::context())) .flatten() .is_some() { @@ -2504,7 +2503,7 @@ impl SpecLane { } for (case, want) in cases.iter().zip(&want) { let got = match self.guarded(|r| { - r.evaluate_one(&plain, &EvaluationContext::default(), &Self::scope(case)) + r.evaluate_one(&plain, &conformance::Spec::context(), &Self::scope(case)) .map(conformance::Spec::settle) }) { Some(got) => Self::normalize(&kind, got), @@ -2523,7 +2522,7 @@ impl SpecLane { } for (case, want) in cases.iter().zip(&want) { let got = match self.guarded(|r| { - r.evaluate_one(&program, &EvaluationContext::default(), &Self::scope(case)) + r.evaluate_one(&program, &conformance::Spec::context(), &Self::scope(case)) .map(conformance::Spec::settle) }) { Some(got) => Self::normalize(&kind, got), @@ -2548,13 +2547,13 @@ impl SpecLane { } let n = cases.len(); let batch = self - .guarded(|r| r.evaluate(&program, &EvaluationContext::default(), &scopes())) + .guarded(|r| r.evaluate(&program, &conformance::Spec::context(), &scopes())) .unwrap_or_else(|| Self::panicked(n)); for ((case, want), got) in cases.iter().zip(&want).zip(batch) { self.compare("batch", case, want, Self::normalize(&kind, got)); } let batch = self - .guarded(|r| r.evaluate(&plain, &EvaluationContext::default(), &scopes())) + .guarded(|r| r.evaluate(&plain, &conformance::Spec::context(), &scopes())) .unwrap_or_else(|| Self::panicked(n)); for ((case, want), got) in cases.iter().zip(&want).zip(batch) { self.compare( @@ -2569,7 +2568,7 @@ impl SpecLane { let got = match self.guarded(|r| { r.evaluate_one( &specialized, - &EvaluationContext::default(), + &conformance::Spec::context(), &Self::scope(case), ) .map(conformance::Spec::settle) @@ -2580,7 +2579,7 @@ impl SpecLane { self.compare("specialized", case, want, got); } let batch = self - .guarded(|r| r.evaluate(&specialized, &EvaluationContext::default(), &scopes())) + .guarded(|r| r.evaluate(&specialized, &conformance::Spec::context(), &scopes())) .unwrap_or_else(|| Self::panicked(n)); for ((case, want), got) in cases.iter().zip(&want).zip(batch) { self.compare("specialized batch", case, want, Self::normalize(&kind, got)); @@ -2591,7 +2590,7 @@ impl SpecLane { LaneProgram::compile_typed(expression, kind.clone(), &VariableType::from(&shape)) { let batch = self - .guarded(|r| r.evaluate(&typed, &EvaluationContext::default(), &scopes())) + .guarded(|r| r.evaluate(&typed, &conformance::Spec::context(), &scopes())) .unwrap_or_else(|| Self::panicked(n)); for ((case, want), got) in cases.iter().zip(&want).zip(batch) { self.compare("typed", case, want, Self::normalize(&kind, got)); @@ -2674,6 +2673,7 @@ fn lane_regression_cloned_programs_keep_object_keys() { let src = "{a: {x: 1, y: 2}, b: {p: 3, q: 4}}"; let scope = Scope::new(Variable::from(json!({}))); let expected = Isolate::new() + .with_now(conformance::Spec::now()) .run_standard(src) .expect("old vm") .to_value() @@ -2681,13 +2681,13 @@ fn lane_regression_cloned_programs_keep_object_keys() { for _ in 0..40 { let mut runner = LaneRunner::new(); let first = LaneProgram::standard(src).expect("compile"); - let _ = runner.evaluate_one(&first, &EvaluationContext::default(), &scope); + let _ = runner.evaluate_one(&first, &conformance::Spec::context(), &scope); let second = first.clone(); drop(first); let mut current = second.clone(); for _ in 0..50 { let got = runner - .evaluate_one(¤t, &EvaluationContext::default(), &scope) + .evaluate_one(¤t, &conformance::Spec::context(), &scope) .expect("lane") .to_value() .to_string(); @@ -2712,7 +2712,8 @@ fn lane_regression_many_entries_do_not_share_assignments() { ]; let mut runner = LaneRunner::new(); for (entries, input) in cases { - let mut isolate = Isolate::with_environment(input.clone().into()); + let mut isolate = + Isolate::with_environment(input.clone().into()).with_now(conformance::Spec::now()); let mut expected = Vec::new(); for (key, source) in entries.iter() { let v = isolate.run_standard(source).expect("old vm"); @@ -2723,7 +2724,7 @@ fn lane_regression_many_entries_do_not_share_assignments() { let mut got = None; runner.evaluate_many( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &[Scope::new(input.clone().into())], None, |_, r| { @@ -2743,17 +2744,17 @@ fn lane_regression_empty_many_program_does_not_panic() { let program = LaneProgram::compile_many(&[], true).expect("compile"); let mut runner = LaneRunner::new(); let scope = Scope::new(Variable::from(json!({"a": 1}))); - let _ = runner.evaluate_one(&program, &EvaluationContext::default(), &scope); + let _ = runner.evaluate_one(&program, &conformance::Spec::context(), &scope); runner.evaluate_many( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), std::slice::from_ref(&scope), None, |_, _| {}, ); let columns = Columns::new(3); let mut out = Output::new(); - runner.evaluate_columns_into(&program, &EvaluationContext::default(), &columns, &mut out); + runner.evaluate_columns_into(&program, &conformance::Spec::context(), &columns, &mut out); conformance::Spec::no_fallbacks(); } @@ -2770,12 +2771,13 @@ fn lane_regression_dates_cross_between_engines() { ]; let mut runner = LaneRunner::new(); let old_date = Isolate::new() + .with_now(conformance::Spec::now()) .run_standard("d('2024-03-15 10:00:00')") .expect("old vm"); let lane_date = runner .evaluate_one( &LaneProgram::standard("d('2024-03-15 10:00:00')").expect("compile"), - &EvaluationContext::default(), + &conformance::Spec::context(), &Scope::default(), ) .expect("lane"); @@ -2784,6 +2786,7 @@ fn lane_regression_dates_cross_between_engines() { input.dot_insert("x", date); for e in expressions { let want = Isolate::with_environment(input.depth_clone(64)) + .with_now(conformance::Spec::now()) .run_standard(e) .map(|v| v.to_value()) .map_err(|e| conformance::Spec::describe(&e)); @@ -2791,7 +2794,7 @@ fn lane_regression_dates_cross_between_engines() { let got = runner .evaluate_one( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &Scope::new(input.depth_clone(64)), ) .map(|v| v.to_value()) @@ -2800,13 +2803,14 @@ fn lane_regression_dates_cross_between_engines() { let again = runner .evaluate_one( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &Scope::new(input.depth_clone(64)), ) .expect("lane"); let back = Variable::from(json!({"y": null})); back.dot_insert("y", again); let reread = Isolate::with_environment(back) + .with_now(conformance::Spec::now()) .run_standard("y") .map(|v| v.to_value()) .map_err(|e| conformance::Spec::describe(&e)); @@ -2830,12 +2834,13 @@ impl Rows { let mut out = Output::new(); runner.evaluate_columns_into( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), columns, &mut out, ); for r in 0..columns.rows { let want = Isolate::with_environment(columns.row(r)) + .with_now(conformance::Spec::now()) .run_standard(e) .map(|v| v.to_value()) .ok(); @@ -2906,7 +2911,7 @@ fn lane_regression_rand_is_not_memoized() { let mut out = Output::new(); LaneRunner::new().evaluate_columns_into( &LaneProgram::standard("rand(a)").expect("compile"), - &EvaluationContext::default(), + &conformance::Spec::context(), &columns, &mut out, ); @@ -2945,11 +2950,11 @@ fn lane_regression_cells_near_decimal_max() { &values, &envs, &mut out, - &EvaluationContext::default(), + &conformance::Spec::context(), ); for (row, value) in values.iter().enumerate() { for (rule, cell) in cells.iter().enumerate() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(conformance::Spec::now()); let _ = isolate.set_reference_value(value.clone()); let expected = isolate.run_unary(cell).unwrap_or(false); let got = out[row * set.words() + rule / 64] >> (rule % 64) & 1 == 1; @@ -3038,7 +3043,8 @@ fn lane_regression_chained_dollar_matches_isolate() { ]; let mut runner = LaneRunner::new(); for (entries, input) in cases { - let mut isolate = Isolate::with_environment(input.clone().into()); + let mut isolate = + Isolate::with_environment(input.clone().into()).with_now(conformance::Spec::now()); let mut expected = Vec::new(); for (key, source) in entries.iter() { let v = isolate.run_standard(source).map(|v| v.to_value()).ok(); @@ -3056,7 +3062,7 @@ fn lane_regression_chained_dollar_matches_isolate() { let mut got = None; runner.evaluate_many( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), std::slice::from_ref(&scope), None, |_, r| { @@ -3098,11 +3104,12 @@ fn lane_regression_cells_survive_invalid_neighbours() { &values, &envs, &mut out, - &EvaluationContext::default(), + &conformance::Spec::context(), ); for (row, value) in values.iter().enumerate() { for (rule, cell) in cells.iter().enumerate() { - let mut isolate = Isolate::with_environment(json!({"limit": 2}).into()); + let mut isolate = Isolate::with_environment(json!({"limit": 2}).into()) + .with_now(conformance::Spec::now()); let _ = isolate.set_reference_value(value.clone()); let expected = cell .and_then(|c| isolate.run_unary(c).ok()) @@ -3138,11 +3145,11 @@ fn lane_regression_cells_probe_between_close_bounds() { &values, &envs, &mut out, - &EvaluationContext::default(), + &conformance::Spec::context(), ); for (row, value) in values.iter().enumerate() { for (rule, cell) in cells.iter().enumerate() { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(conformance::Spec::now()); let _ = isolate.set_reference_value(value.clone()); let expected = isolate.run_unary(cell).unwrap_or(false); let got = out[row * set.words() + rule / 64] >> (rule % 64) & 1 == 1; @@ -3260,6 +3267,7 @@ fn lane_regression_date_inputs_keep_their_text() { .collect(); let want = |e: &str, s: &Scope| { Isolate::with_environment(s.base().clone()) + .with_now(conformance::Spec::now()) .run_standard(e) .map(|v| v.to_value()) .ok() @@ -3279,7 +3287,7 @@ fn lane_regression_date_inputs_keep_their_text() { ]; for program in &programs { let got: Vec<_> = runner - .evaluate(program, &EvaluationContext::default(), &scopes) + .evaluate(program, &conformance::Spec::context(), &scopes) .into_iter() .map(|r| r.map(|v| v.to_value()).ok()) .collect(); @@ -3288,7 +3296,7 @@ fn lane_regression_date_inputs_keep_their_text() { } let columns = Columns::new(values.len()).column("x", Column::new(Values::Any(&values))); let mut out = Output::new(); - runner.evaluate_columns_into(&plain, &EvaluationContext::default(), &columns, &mut out); + runner.evaluate_columns_into(&plain, &conformance::Spec::context(), &columns, &mut out); for (r, s) in scopes.iter().enumerate() { assert_eq!( out.variable(r).and_then(|x| x.ok()).map(|v| v.to_value()), @@ -3303,7 +3311,6 @@ fn lane_regression_date_inputs_keep_their_text() { #[test] fn lane_regression_constant_folding_keeps_runtime_semantics() { std::env::set_var("TZ", "UTC"); - std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); let cases = [ "1 + 2 * 3", "(1 / 0) ?? 5", @@ -3335,13 +3342,14 @@ fn lane_regression_constant_folding_keeps_runtime_semantics() { let scope = Scope::new(Variable::from(json!({"x": false}))); for e in cases { let want = Isolate::with_environment(Variable::from(json!({"x": false}))) + .with_now(conformance::Spec::now()) .run_standard(e) .map(|v| v.to_value()) .ok(); let program = LaneProgram::standard(e).expect("compile"); for _ in 0..2 { let got = runner - .evaluate_one(&program, &EvaluationContext::default(), &scope) + .evaluate_one(&program, &conformance::Spec::context(), &scope) .map(|v| v.to_value()) .ok(); assert_eq!(got, want, "{e}"); @@ -3351,7 +3359,7 @@ fn lane_regression_constant_folding_keeps_runtime_semantics() { let values: std::collections::BTreeSet = (0..20) .filter_map(|_| { runner - .evaluate_one(&rand, &EvaluationContext::default(), &scope) + .evaluate_one(&rand, &conformance::Spec::context(), &scope) .ok() }) .map(|v| v.to_value().to_string()) @@ -3388,7 +3396,7 @@ fn lane_regression_long_strings_and_list_membership() { program.specialize(&rows).expect("specialize"), ] { let got: Vec<_> = runner - .evaluate(&program, &EvaluationContext::default(), &rows) + .evaluate(&program, &conformance::Spec::context(), &rows) .into_iter() .map(|r| r.map(|v| v.to_value()).ok()) .collect(); @@ -3396,6 +3404,7 @@ fn lane_regression_long_strings_and_list_membership() { .iter() .map(|s| { Isolate::with_environment(s.base().clone()) + .with_now(conformance::Spec::now()) .run_standard(e) .map(|v| v.to_value()) .ok() @@ -3474,7 +3483,8 @@ fn lane_regression_chained_dotted_keys_resolve() { ]; let mut runner = LaneRunner::new(); for (entries, input) in cases { - let mut isolate = Isolate::with_environment(input.clone().into()); + let mut isolate = + Isolate::with_environment(input.clone().into()).with_now(conformance::Spec::now()); let mut expected = Vec::new(); for (key, source) in entries.iter() { let v = isolate.run_standard(source).map(|v| v.to_value()).ok(); @@ -3486,7 +3496,7 @@ fn lane_regression_chained_dotted_keys_resolve() { let mut got = None; runner.evaluate_many( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), std::slice::from_ref(&scope), None, |_, r| { @@ -3520,7 +3530,8 @@ fn lane_builtin_failures_keep_messages() { let mut runner = LaneRunner::new(); let mut mismatches = Vec::new(); for expression in expressions { - let mut isolate = Isolate::with_environment(Variable::from(input.clone())); + let mut isolate = Isolate::with_environment(Variable::from(input.clone())) + .with_now(conformance::Spec::now()); let stack = isolate .run_standard(expression) .map(|v| v.to_value()) @@ -3531,7 +3542,7 @@ fn lane_builtin_failures_keep_messages() { let lane = runner .evaluate( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), std::slice::from_ref(&scope), ) .remove(0) @@ -3588,7 +3599,7 @@ fn lane_isolated_cells_keep_evaluating_after_a_fault() { let mut failures = Vec::new(); runner.evaluate_bound_into( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &scopes, &columns, &bind, @@ -3856,19 +3867,20 @@ impl StructLists { let mut out = Output::new(); runner.evaluate_columns_into( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &columns, &mut out, ); let mut values = Vec::new(); runner.evaluate_columns( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &columns, |_, r| values.push(r.map(|v| v.to_value()).ok()), ); for r in 0..columns.rows { let want = Isolate::with_environment(columns.row(r)) + .with_now(conformance::Spec::now()) .run_standard(e) .map(|v| v.to_value()) .ok(); @@ -4138,7 +4150,8 @@ impl Fused { fn expected(env: Variable, entries: &[Fusion]) -> Option> { let mut outputs = Vec::new(); for entry in entries { - let mut isolate = Isolate::with_environment(env.depth_clone(usize::MAX)); + let mut isolate = Isolate::with_environment(env.depth_clone(usize::MAX)) + .with_now(conformance::Spec::now()); let (key, value) = match entry { Fusion::Output { key, source } | Fusion::Hidden { key, source } => { (key, isolate.run_standard(source).ok()?) @@ -4186,7 +4199,7 @@ impl Fused { let mut failed = vec![false; rows.len()]; runner.evaluate_columns_many( &program, - &EvaluationContext::default(), + &conformance::Spec::context(), &columns, &mut outs, |row, _, _| failed[row] = true, diff --git a/core/expression/tests/lane_config.rs b/core/expression/tests/lane_config.rs index 2bced529e..681009975 100644 --- a/core/expression/tests/lane_config.rs +++ b/core/expression/tests/lane_config.rs @@ -1,8 +1,6 @@ mod conformance; use conformance::Spec; -use std::sync::atomic::Ordering; -use zen_expression::ZEN_EXPRESSION_CONFIG; #[test] fn isolate_matches_on_both_engines_when_lane_is_enabled() { @@ -13,16 +11,14 @@ fn isolate_matches_on_both_engines_when_lane_is_enabled() { "malformed spec:\n{}", problems.join("\n") ); - let run = || -> Vec { - cases - .iter() - .map(|case| case.verdict(&case.exact()).is_none()) - .collect() - }; - let stack = run(); - ZEN_EXPRESSION_CONFIG.lane.store(true, Ordering::Relaxed); - let lane = run(); - ZEN_EXPRESSION_CONFIG.lane.store(false, Ordering::Relaxed); + let stack: Vec = cases + .iter() + .map(|case| case.verdict(&case.exact()).is_none()) + .collect(); + let lane: Vec = cases + .iter() + .map(|case| case.verdict(&case.laned()).is_none()) + .collect(); let failures: Vec = cases .iter() .zip(stack.iter().zip(&lane)) diff --git a/core/expression/tests/session.rs b/core/expression/tests/session.rs index 23a192977..0388c8937 100644 --- a/core/expression/tests/session.rs +++ b/core/expression/tests/session.rs @@ -191,8 +191,10 @@ struct Pair<'r> { impl<'r> Pair<'r> { fn new(report: &'r mut Report, label: &str, programs: Option>) -> Self { Self { - isolate: Isolate::new(), - session: Session::new().with_programs(programs), + isolate: Isolate::new().with_now(conformance::Spec::now()), + session: Session::new() + .with_context(conformance::Spec::context()) + .with_programs(programs), report, label: label.to_string(), } @@ -650,6 +652,7 @@ fn session_programs_are_shared_across_threads() { let programs = programs.clone(); std::thread::spawn(move || { let mut session = Session::with_environment(Variable::from(json!({"a": i}))) + .with_context(conformance::Spec::context()) .with_programs(Some(programs)); let value = session.run_standard("a + 1").map(|v| v.to_value()); let _ = session.set_reference_value(Variable::from(json!(i))); @@ -694,7 +697,7 @@ fn session_compile_errors_match_isolate_exactly() { ]; let mut failures = Vec::new(); for (source, kind) in sources { - let mut isolate = Isolate::new(); + let mut isolate = Isolate::new().with_now(conformance::Spec::now()); let want = match kind { ExpressionKind::Standard => isolate.compile_standard(source).map(|_| ()), ExpressionKind::Unary => isolate.compile_unary(source).map(|_| ()), @@ -817,8 +820,10 @@ fn session_shares_rc_like_isolate() { let mut rows = Vec::new(); let mut differences = Vec::new(); for (name, source) in cases { - let mut isolate = Isolate::with_environment(env.deep_clone()); - let mut session = Session::with_environment(env.deep_clone()); + let mut isolate = + Isolate::with_environment(env.deep_clone()).with_now(conformance::Spec::now()); + let mut session = + Session::with_environment(env.deep_clone()).with_context(conformance::Spec::context()); isolate.set_local(Variable::nodes_key(), nodes.deep_clone()); session.set_local(Variable::nodes_key(), nodes.deep_clone()); isolate diff --git a/core/expression/tests/typed.rs b/core/expression/tests/typed.rs index 96597d9aa..9f27ecc16 100644 --- a/core/expression/tests/typed.rs +++ b/core/expression/tests/typed.rs @@ -3,7 +3,6 @@ mod conformance; use rust_decimal::Decimal; use std::collections::BTreeMap; use std::sync::Arc; -use zen_expression::context::EvaluationContext; use zen_expression::lane::{Column, Fusion, Values}; use zen_expression::typed::{ Batch, Class, Data, Hir, List, Lowering, Program, Resolve, Resolved, Slot, @@ -343,7 +342,7 @@ impl Report { } let mut out = program.outputs(); let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - program.run(&batch, &mut out, None, &EvaluationContext::default()) + program.run(&batch, &mut out, None, &conformance::Spec::context()) })); match ran { Ok(Ok(())) => {}