diff --git a/.github/workflows/node.yaml b/.github/workflows/node.yaml index 8c85c4a3..c8a24492 100644 --- a/.github/workflows/node.yaml +++ b/.github/workflows/node.yaml @@ -31,6 +31,7 @@ jobs: settings: - host: windows-latest target: 'x86_64-pc-windows-msvc' + toolchain: '1.99' build: | yarn build -- --target x86_64-pc-windows-msvc -- --locked @@ -124,7 +125,7 @@ jobs: - name: Install uses: dtolnay/rust-toolchain@stable with: - toolchain: stable + toolchain: ${{ matrix.settings.toolchain || 'stable' }} targets: ${{ matrix.settings.target }} - name: Rust cache + sccache (+ zig for linux legs) diff --git a/.github/workflows/uniffi.yaml b/.github/workflows/uniffi.yaml index 04284ae1..3fb12a14 100644 --- a/.github/workflows/uniffi.yaml +++ b/.github/workflows/uniffi.yaml @@ -27,6 +27,7 @@ jobs: settings: - host: windows-latest target: 'x86_64-pc-windows-msvc' + toolchain: '1.99' output: '{0}.dll' lib_dir: 'win32-x86-64' - host: macos-latest @@ -60,6 +61,7 @@ jobs: - name: Setup Rust Toolchain uses: dtolnay/rust-toolchain@stable with: + toolchain: ${{ matrix.settings.toolchain || 'stable' }} target: ${{ matrix.settings.target }} - uses: ./.github/actions/setup-rust @@ -81,6 +83,7 @@ jobs: with: working-directory: ${{ env.UNIFFI_DIRECTORY }} target: ${{ matrix.settings.target }} + toolchain: ${{ matrix.settings.toolchain || 'stable' }} args: '--lib --release --locked ${{ matrix.settings.extra_args }}' - name: Verify max glibc requirement diff --git a/Cargo.lock b/Cargo.lock index 9da9811a..cc57864d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6061,6 +6061,7 @@ dependencies = [ "arc-swap", "async-trait", "base64", + "chrono", "criterion", "ctor", "downcast-rs", @@ -6110,7 +6111,6 @@ dependencies = [ "chrono-tz", "criterion", "csv", - "fastrand", "humantime", "iana-time-zone", "nohash-hasher", diff --git a/Cargo.toml b/Cargo.toml index d803dd37..eb357666 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,6 @@ ahash = "0.8" bumpalo = "3" chrono = "0.4" criterion = "0.5" -fastrand = "2" humantime = "2" tokio = "1" tokio-util = "0.7" diff --git a/benchmark/rust/src/main.rs b/benchmark/rust/src/main.rs index 207d9af4..a3e5cbb6 100644 --- a/benchmark/rust/src/main.rs +++ b/benchmark/rust/src/main.rs @@ -57,6 +57,7 @@ async fn main() { let opts = || EvaluationOptions { trace, max_depth: 10, + ..Default::default() }; engine .evaluate_with_opts(e.file.as_str(), input.clone(), opts()) diff --git a/bindings/c/src/engine.rs b/bindings/c/src/engine.rs index 5db2ff04..ba16def8 100644 --- a/bindings/c/src/engine.rs +++ b/bindings/c/src/engine.rs @@ -57,13 +57,34 @@ pub(crate) struct ZenEngineStruct { pub struct ZenEngineEvaluationOptions { trace: bool, max_depth: u8, + now: *const c_char, + timezone: *const c_char, + has_seed: bool, + seed: u64, +} + +impl Default for ZenEngineEvaluationOptions { + fn default() -> Self { + Self { + trace: false, + max_depth: 5, + now: std::ptr::null(), + timezone: std::ptr::null(), + has_seed: false, + seed: 0, + } + } } impl Into for ZenEngineEvaluationOptions { fn into(self) -> EvaluationOptions { + use zen_engine::context::{parse_instant, parse_timezone}; EvaluationOptions { trace: self.trace, max_depth: self.max_depth, + now: safe_str_from_ptr(self.now).and_then(parse_instant), + timezone: safe_str_from_ptr(self.timezone).and_then(parse_timezone), + seed: self.has_seed.then_some(self.seed), } } } @@ -321,6 +342,7 @@ mod tests { ZenEngineEvaluationOptions { trace: false, max_depth: 5, + ..Default::default() }, ); @@ -412,6 +434,7 @@ mod tests { ZenEngineEvaluationOptions { trace: false, max_depth: 5, + ..Default::default() }, ); diff --git a/bindings/c/zen_engine.h b/bindings/c/zen_engine.h index c76ecc1a..da535538 100644 --- a/bindings/c/zen_engine.h +++ b/bindings/c/zen_engine.h @@ -26,6 +26,10 @@ typedef struct ZenResult_c_char { typedef struct ZenEngineEvaluationOptions { bool trace; uint8_t max_depth; + const char *now; + const char *timezone; + bool has_seed; + uint64_t seed; } ZenEngineEvaluationOptions; typedef struct ZenEngineStruct { diff --git a/bindings/nodejs/src/decision.rs b/bindings/nodejs/src/decision.rs index 3b4df2f9..12edc866 100644 --- a/bindings/nodejs/src/decision.rs +++ b/bindings/nodejs/src/decision.rs @@ -30,15 +30,13 @@ impl ZenDecision { opts: Option, ) -> napi::Result { let decision = self.0.clone(); - let result = spawn_worker(move || { - let options = opts.unwrap_or_default(); - - async move { - let context = zen_engine::Variable::try_from_value(context).map_err( - |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), - )?; - decision.evaluate_serialized(context, options.into()).await - } + let options: zen_engine::EvaluationSerializedOptions = + opts.unwrap_or_default().try_into()?; + let result = spawn_worker(move || async move { + let context = zen_engine::Variable::try_from_value(context).map_err( + |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), + )?; + decision.evaluate_serialized(context, options).await }) .await .map_err(|_| anyhow!("Hook timed out"))? diff --git a/bindings/nodejs/src/engine.rs b/bindings/nodejs/src/engine.rs index 3372d2e5..659a6454 100644 --- a/bindings/nodejs/src/engine.rs +++ b/bindings/nodejs/src/engine.rs @@ -87,6 +87,11 @@ pub struct ZenEvaluateOptions { pub max_depth: Option, #[napi(ts_type = "boolean | 'string' | 'reference' | 'referenceString'")] pub trace: Option, + #[napi(ts_type = "string | number")] + pub now: Option>, + pub timezone: Option, + #[napi(ts_type = "number | string")] + pub seed: Option>, } impl Default for ZenEvaluateOptions { @@ -94,16 +99,73 @@ impl Default for ZenEvaluateOptions { Self { max_depth: Some(5), trace: Some(JsEvaluationTraceKind::default()), + now: None, + timezone: None, + seed: None, } } } -impl From for EvaluationSerializedOptions { - fn from(value: ZenEvaluateOptions) -> Self { - Self { +const MAX_SAFE_INTEGER: f64 = 9007199254740991.0; + +impl TryFrom for EvaluationSerializedOptions { + type Error = napi::Error; + + fn try_from(value: ZenEvaluateOptions) -> Result { + use zen_engine::context::{instant_from_millis, parse_instant, parse_timezone}; + let now = match value.now { + None => None, + Some(Either::A(text)) => Some( + parse_instant(&text) + .ok_or_else(|| anyhow!("invalid now '{text}', expected an RFC 3339 instant"))?, + ), + Some(Either::B(ms)) if ms.is_finite() && ms.fract() == 0.0 => Some( + instant_from_millis(ms as i64) + .ok_or_else(|| anyhow!("invalid now {ms}, out of range"))?, + ), + Some(Either::B(ms)) => { + return Err(anyhow!("invalid now {ms}, expected whole epoch milliseconds").into()) + } + }; + let timezone = match value.timezone { + None => None, + Some(name) => Some( + parse_timezone(&name) + .ok_or_else(|| anyhow!("invalid timezone '{name}', expected an IANA name"))?, + ), + }; + let seed = match value.seed { + None => None, + Some(Either::A(n)) if (0.0..=MAX_SAFE_INTEGER).contains(&n) && n.fract() == 0.0 => { + Some(n as u64) + } + Some(Either::A(n)) => { + return Err(anyhow!( + "invalid seed {n}, expected a whole number from 0 to 2^53 - 1, or a string" + ) + .into()) + } + Some(Either::B(text)) => Some(text.parse::().map_err(|_| { + anyhow!("invalid seed '{text}', expected an unsigned 64-bit integer") + })?), + }; + Ok(Self { max_depth: value.max_depth.unwrap_or(5), trace: value.trace.unwrap_or_default().0, - } + now, + timezone, + seed, + }) + } +} + +pub(crate) fn unserialized(options: &EvaluationSerializedOptions) -> EvaluationOptions { + EvaluationOptions { + trace: options.trace != EvaluationTraceKind::None, + max_depth: options.max_depth, + now: options.now, + timezone: options.timezone, + seed: options.seed, } } @@ -251,13 +313,10 @@ impl ZenEngine { opts: Option, ) -> napi::Result { let graph = self.graph.clone(); - let result = spawn_worker(|| { - let serialized: EvaluationSerializedOptions = opts.unwrap_or_default().into(); + let serialized: EvaluationSerializedOptions = opts.unwrap_or_default().try_into()?; + let result = spawn_worker(move || { let mode = serialized.trace; - let options = EvaluationOptions { - trace: mode != EvaluationTraceKind::None, - max_depth: serialized.max_depth, - }; + let options = unserialized(&serialized); async move { let context = zen_engine::Variable::try_from_value(context).map_err( @@ -342,19 +401,15 @@ impl ZenEngine { requests: Vec, opts: Option, ) -> napi::Result> { - let options: EvaluationSerializedOptions = opts.unwrap_or_default().into(); + let options: EvaluationSerializedOptions = opts.unwrap_or_default().try_into()?; let mode = options.trace; - let max_depth = options.max_depth; let mut handles = Vec::with_capacity(requests.len()); for req in requests { let engine = self.graph.clone(); let EvaluateBatchRequest { key, context } = req; handles.push(spawn_worker(move || async move { - let eval_opts = EvaluationOptions { - trace: mode != EvaluationTraceKind::None, - max_depth, - }; + let eval_opts = unserialized(&options); let context = zen_engine::Variable::try_from_value(context).map_err( |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), diff --git a/bindings/python/src/engine.rs b/bindings/python/src/engine.rs index 081eb2d9..d1d8521f 100644 --- a/bindings/python/src/engine.rs +++ b/bindings/python/src/engine.rs @@ -14,7 +14,6 @@ use pyo3::{pyclass, pymethods, Bound, FromPyObject, IntoPyObjectExt, Py, PyAny, use pyo3_async_runtimes::tokio::get_current_locals; use pyo3_async_runtimes::{tokio, TaskLocals}; use pythonize::{depythonize, pythonize}; -use serde::{Deserialize, Serialize}; use serde_json::Value; use zen_engine::loader::{DynamicLoader, LoaderConfig}; use zen_engine::{DecisionEngine, EvaluationOptions}; @@ -25,10 +24,13 @@ pub struct PyZenEngine { engine: Arc, } -#[derive(Serialize, Deserialize)] +#[derive(Default)] pub struct PyZenEvaluateOptions { pub trace: Option, pub max_depth: Option, + pub now: Option, + pub timezone: Option, + pub seed: Option, } impl From for EvaluationOptions { @@ -36,10 +38,69 @@ impl From for EvaluationOptions { Self { max_depth: value.max_depth.unwrap_or(5), trace: value.trace.unwrap_or_default(), + now: value.now, + timezone: value.timezone, + seed: value.seed, } } } +fn present<'py>(dict: &Bound<'py, PyDict>, key: &str) -> PyResult>> { + Ok(dict.get_item(key)?.filter(|v| !v.is_none())) +} + +fn invalid(message: String) -> pyo3::PyErr { + pyo3::exceptions::PyValueError::new_err(message) +} + +fn instant(value: &Bound<'_, PyAny>) -> PyResult { + use zen_engine::context::{instant_from_millis, parse_instant}; + if value.is_instance_of::() { + return Err(invalid( + "invalid now, expected epoch milliseconds or an RFC 3339 string".into(), + )); + } + if let Ok(ms) = value.extract::() { + return instant_from_millis(ms) + .ok_or_else(|| invalid(format!("invalid now {ms}, out of range"))); + } + let text = + match value.extract::() { + Ok(text) => text, + Err(_) if value.hasattr("isoformat")? => { + value.call_method0("isoformat")?.extract::()? + } + Err(_) => return Err(invalid( + "invalid now, expected epoch milliseconds, an RFC 3339 string or an aware datetime" + .into(), + )), + }; + parse_instant(&text).ok_or_else(|| { + invalid(format!( + "invalid now '{text}', expected an RFC 3339 instant with an offset" + )) + }) +} + +fn seed(value: &Bound<'_, PyAny>) -> PyResult { + if value.is_instance_of::() { + return Err(invalid( + "invalid seed, expected an unsigned 64-bit integer".into(), + )); + } + if let Ok(seed) = value.extract::() { + return Ok(seed); + } + let text = value + .extract::() + .map_err(|_| invalid("invalid seed, expected an unsigned 64-bit integer".into()))?; + text.parse::().map_err(|_| { + invalid(format!( + "invalid seed '{text}', expected an unsigned 64-bit integer" + )) + }) +} + impl<'py> FromPyObject<'py> for PyZenEvaluateOptions { fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult { let dict = ob.downcast::()?; @@ -54,16 +115,24 @@ impl<'py> FromPyObject<'py> for PyZenEvaluateOptions { .map(|v| v.extract::()) .transpose()?; - Ok(PyZenEvaluateOptions { trace, max_depth }) - } -} + let now = present(dict, "now")?.map(|v| instant(&v)).transpose()?; + let timezone = present(dict, "timezone")? + .map(|v| { + let name = v.extract::()?; + zen_engine::context::parse_timezone(&name).ok_or_else(|| { + invalid(format!("invalid timezone '{name}', expected an IANA name")) + }) + }) + .transpose()?; + let seed = present(dict, "seed")?.map(|v| seed(&v)).transpose()?; -impl Default for PyZenEvaluateOptions { - fn default() -> Self { - Self { - trace: None, - max_depth: None, - } + Ok(PyZenEvaluateOptions { + trace, + max_depth, + now, + timezone, + seed, + }) } } diff --git a/bindings/python/zen.pyi b/bindings/python/zen.pyi index 0da522b3..e9251432 100644 --- a/bindings/python/zen.pyi +++ b/bindings/python/zen.pyi @@ -1,10 +1,14 @@ from collections.abc import Awaitable, Callable +from datetime import datetime from typing import Any, Optional, TypedDict, Literal, TypeAlias, Union class DecisionEvaluateOptions(TypedDict, total=False): max_depth: int trace: bool + now: Union[int, str, datetime] + timezone: str + seed: Union[int, str] class EvaluateResponse(TypedDict): diff --git a/bindings/uniffi/src/engine.rs b/bindings/uniffi/src/engine.rs index f6f8cb69..3bfefe83 100644 --- a/bindings/uniffi/src/engine.rs +++ b/bindings/uniffi/src/engine.rs @@ -21,6 +21,12 @@ pub(crate) struct ZenEngine { pub struct ZenEvaluateOptions { pub max_depth: Option, pub trace: Option, + #[uniffi(default = None)] + pub now: Option, + #[uniffi(default = None)] + pub timezone: Option, + #[uniffi(default = None)] + pub seed: Option, } impl Default for ZenEvaluateOptions { @@ -28,15 +34,22 @@ impl Default for ZenEvaluateOptions { Self { max_depth: Some(5), trace: Some(false), + now: None, + timezone: None, + seed: None, } } } impl From for EvaluationOptions { fn from(value: ZenEvaluateOptions) -> Self { + use zen_engine::context::{parse_instant, parse_timezone}; Self { max_depth: value.max_depth.unwrap_or(5), trace: value.trace.unwrap_or(false), + now: value.now.as_deref().and_then(parse_instant), + timezone: value.timezone.as_deref().and_then(parse_timezone), + seed: value.seed, } } } diff --git a/bindings/uniffi/tests/csharp/ZenEngineTests.cs b/bindings/uniffi/tests/csharp/ZenEngineTests.cs index 069d8707..50fa2e99 100644 --- a/bindings/uniffi/tests/csharp/ZenEngineTests.cs +++ b/bindings/uniffi/tests/csharp/ZenEngineTests.cs @@ -157,7 +157,7 @@ public class ZenEngineTests public async Task TraceOption() { using var engine = new ZenEngine(new ZenLoader.Filesystem(TestDataRoot())); - var options = new ZenEvaluateOptions(5, true); + var options = new ZenEvaluateOptions(5, true, null, null, null); var response = await engine.Evaluate("table.json", new JsonBuffer("{\"input\":12}"), options); Assert.NotNull(response.Trace); Assert.NotEmpty(response.Trace); diff --git a/bindings/uniffi/tests/java/io/gorules/zen_engine/ZenEngineTest.java b/bindings/uniffi/tests/java/io/gorules/zen_engine/ZenEngineTest.java index 274b6170..01f49ef8 100644 --- a/bindings/uniffi/tests/java/io/gorules/zen_engine/ZenEngineTest.java +++ b/bindings/uniffi/tests/java/io/gorules/zen_engine/ZenEngineTest.java @@ -161,7 +161,7 @@ class ZenEngineTest { @Test void traceOption() throws Exception { try (var engine = new ZenEngine(new ZenLoader.Filesystem(testDataRoot().toString()), null)) { - var options = new ZenEvaluateOptions((byte) 5, true); + var options = new ZenEvaluateOptions((byte) 5, true, null, null, null); var response = engine.evaluate("table.json", new JsonBuffer("{\"input\":12}"), options).get(); assertNotNull(response.trace()); assertFalse(response.trace().isEmpty()); diff --git a/core/engine/Cargo.toml b/core/engine/Cargo.toml index f3bb17fa..a0b7372e 100644 --- a/core/engine/Cargo.toml +++ b/core/engine/Cargo.toml @@ -12,6 +12,7 @@ homepage = "https://gorules.io" doctest = false [dependencies] +chrono = { workspace = true } ahash = { workspace = true } anyhow = { workspace = true } base64 = "0.22" diff --git a/core/engine/src/compiled/bound.rs b/core/engine/src/compiled/bound.rs index 2cf279b3..5dc60782 100644 --- a/core/engine/src/compiled/bound.rs +++ b/core/engine/src/compiled/bound.rs @@ -1,6 +1,7 @@ use crate::compiled::core::special::Specialized; use std::cell::RefCell; use std::rc::Rc; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{Binding, Columns, Fault, Kind, LaneProgram, LaneRunner, Output}; use zen_expression::{IsolateError, Scope, Variable}; @@ -19,6 +20,7 @@ impl Scopes { } pub(crate) struct Bound<'a> { + pub context: EvaluationContext, pub scopes: Scopes, pub columns: Columns<'a>, pub bind: Box Binding + 'a>, @@ -91,9 +93,10 @@ impl<'a> Bound<'a> { } } - pub fn plain(scopes: Vec) -> Self { + pub fn plain(scopes: Vec, context: EvaluationContext) -> Self { let rows = scopes.len(); Self { + context, scopes: Scopes::Owned(scopes), columns: Columns::new(rows), bind: Box::new(|_| Binding::Row), @@ -145,6 +148,7 @@ impl<'a> Bound<'a> { let program = specialized.as_deref().unwrap_or(program); runner.evaluate_bound( program, + &self.context, self.scopes(), &self.columns, &*self.bind, @@ -177,6 +181,7 @@ impl<'a> Bound<'a> { let program = specialized.as_deref().unwrap_or(program); runner.evaluate_bound_into( program, + &self.context, self.scopes(), &self.columns, bind, diff --git a/core/engine/src/compiled/core/exec.rs b/core/engine/src/compiled/core/exec.rs index a6bf1a9a..859302ef 100644 --- a/core/engine/src/compiled/core/exec.rs +++ b/core/engine/src/compiled/core/exec.rs @@ -51,7 +51,11 @@ pub(crate) struct Dedup { } impl TypedCall<'_, '_> { - pub fn run(self, program: &Program) -> Option { + pub fn run( + self, + program: &Program, + context: &zen_expression::context::EvaluationContext, + ) -> Option { let mut batch = Batch::new(self.rows); self.columns .iter() @@ -69,7 +73,7 @@ impl TypedCall<'_, '_> { }); } let mut out = program.outputs(); - program.run(&batch, &mut out, self.select).ok()?; + program.run(&batch, &mut out, self.select, context).ok()?; Some(out) } } @@ -238,6 +242,7 @@ impl Dedup { codes: &[Hint], positions: Option<&Rc<[usize]>>, rows: usize, + context: &zen_expression::context::EvaluationContext, ) -> Option<(Outputs, Vec)> { let (reps, ids) = Self::distinct(leaves, codes, positions, rows)?; let picks: Rc<[usize]> = reps.into(); @@ -248,7 +253,7 @@ impl Dedup { lists: Vec::new(), select: None, }; - Some((call.run(program)?, ids)) + Some((call.run(program, context)?, ids)) } pub fn coded( @@ -257,8 +262,9 @@ impl Dedup { codes: &[Hint], positions: Option<&Rc<[usize]>>, rows: usize, + context: &zen_expression::context::EvaluationContext, ) -> Option { - let (mut out, ids) = Self::reps(program, leaves, codes, positions, rows)?; + let (mut out, ids) = Self::reps(program, leaves, codes, positions, rows, context)?; out.spread(rows, &ids, positions.map(|p| &p[..])) .then_some(out) } diff --git a/core/engine/src/compiled/decision.rs b/core/engine/src/compiled/decision.rs index e7b0bd5e..10e55079 100644 --- a/core/engine/src/compiled/decision.rs +++ b/core/engine/src/compiled/decision.rs @@ -1,5 +1,6 @@ use crate::compiled::content::Content; use crate::compiled::host::NodeHandlerExtensions; +use crate::compiled::pinning; use crate::compiled::prepared::Prepared; use crate::compiled::traced::Traced; use crate::compiled::{ColumnarOutput, CompiledGraph, CompiledPlan, Invalid}; @@ -12,6 +13,7 @@ use crate::nodes::function::http_handler::DynamicHttpHandler; use crate::EvaluationError; use std::cell::OnceCell; use std::sync::{Arc, OnceLock}; +use zen_expression::context::EvaluationContext; use zen_expression::lane::Columns; use zen_expression::variable::Variable; @@ -53,13 +55,41 @@ impl CompiledDecision { Arc::ptr_eq(&self.source, content) } - pub(crate) async fn evaluate_with_opts( + pub(crate) async fn evaluate_pinned( &self, - context: Variable, + input: Variable, options: EvaluationOptions, + ) -> Result> { + let context = pinning::single(options.pinned()); + self.evaluate_with_opts(input, options, &context).await + } + + pub(crate) async fn evaluate_batch_pinned( + &self, + contexts: &[Variable], + options: EvaluationOptions, + ) -> Vec>> { + let context = pinning::batch(options.pinned()); + self.evaluate_batch(contexts, options, &context).await + } + + pub(crate) async fn evaluate_columns_pinned<'a>( + &self, + columns: &'a Columns<'a>, + options: EvaluationOptions, + ) -> ColumnarOutput<'a> { + let context = pinning::batch(options.pinned()); + self.evaluate_columns(columns, options, &context).await + } + + pub(crate) async fn evaluate_with_opts( + &self, + input: Variable, + options: EvaluationOptions, + context: &EvaluationContext, ) -> Result> { if options.trace { - return self.traced(context, options).await; + return self.traced(input, options, context).await; } let (compiled, content) = Self::compiled(self.single()).map_err(Invalid::evaluation)?; @@ -67,9 +97,9 @@ impl CompiledDecision { compiled .evaluate_one( &content, - &self.extensions(&content), + &self.extensions(&content, context), options.max_depth, - context, + input, ) .await } @@ -78,12 +108,15 @@ impl CompiledDecision { &self, contexts: &[Variable], options: EvaluationOptions, + context: &EvaluationContext, ) -> Vec>> { let owned: Vec = contexts.iter().map(Variable::deep_clone).collect(); if options.trace { let mut responses = Vec::with_capacity(owned.len()); - for context in owned { - responses.push(self.evaluate_with_opts(context, options).await); + for (row, input) in owned.into_iter().enumerate() { + responses.push( + Box::pin(self.evaluate_with_opts(input, options, &context.at(row))).await, + ); } return responses; } @@ -94,7 +127,7 @@ impl CompiledDecision { compiled .evaluate( &content, - &self.extensions(&content), + &self.extensions(&content, context), options.max_depth, &owned, ) @@ -108,6 +141,7 @@ impl CompiledDecision { &self, columns: &'a Columns<'a>, options: EvaluationOptions, + context: &EvaluationContext, ) -> ColumnarOutput<'a> { match Self::compiled(self.prepared()) { Ok((compiled, content)) => { @@ -115,7 +149,7 @@ impl CompiledDecision { compiled .evaluate_columns( &content, - &self.extensions(&content), + &self.extensions(&content, context), options.max_depth, columns, ) @@ -128,7 +162,7 @@ impl CompiledDecision { trace: false, ..options }; - let results = self.evaluate_batch(&contexts, options).await; + let results = Box::pin(self.evaluate_batch(&contexts, options, context)).await; ColumnarOutput::from_results(results) } } @@ -136,12 +170,13 @@ impl CompiledDecision { async fn traced( &self, - context: Variable, + input: Variable, options: EvaluationOptions, + context: &EvaluationContext, ) -> Result> { let (compiled, content) = Self::compiled(self.tracing()).map_err(Invalid::evaluation)?; let content = compiled.schemas(content, &self.loader).await; - let extensions = self.extensions(&content); + let extensions = self.extensions(&content, context); let traced = Traced { graph: compiled, content: &content, @@ -150,7 +185,7 @@ impl CompiledDecision { iteration: 0, parent: None, }; - traced.evaluate(context).await + traced.evaluate(input).await } fn prepared(&self) -> (&Arc, &CompiledPlan) { @@ -191,7 +226,7 @@ impl CompiledDecision { } #[allow(clippy::arc_with_non_send_sync)] - fn extensions(&self, content: &Content) -> NodeHandlerExtensions { + fn extensions(&self, content: &Content, context: &EvaluationContext) -> NodeHandlerExtensions { NodeHandlerExtensions { function_runtime: Default::default(), loader: self.loader.clone(), @@ -201,6 +236,7 @@ impl CompiledDecision { stripped_functions: content.stripped_functions.clone(), validator_cache: Arc::new(OnceCell::from(content.validator_cache.clone())), prepared: self.children.clone(), + context: context.clone(), } } diff --git a/core/engine/src/compiled/engine.rs b/core/engine/src/compiled/engine.rs index 1289c5ca..faf3d039 100644 --- a/core/engine/src/compiled/engine.rs +++ b/core/engine/src/compiled/engine.rs @@ -1,10 +1,11 @@ use crate::compiled::decision::CompiledDecision; use crate::compiled::host::graph::graph::Responses; +use crate::compiled::pinning; use crate::compiled::policy::artifact::Artifact; use crate::compiled::policy::validator::InputSchema; use crate::compiled::prepared::{Decisions, Policies, Prepared}; use crate::decision_graph::graph::DecisionGraphResponse; -use crate::engine::{EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind}; +use crate::engine::{EvaluationOptions, EvaluationSerializedOptions}; use crate::loader::{DynamicLoader, LoaderResult}; use crate::model::{DecisionContent, GraphContent}; use crate::nodes::custom::DynamicCustomNode; @@ -20,6 +21,7 @@ use arc_swap::ArcSwapOption; use serde_json::Value; use std::collections::VecDeque; use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::variable::Variable; pub(crate) struct Parts<'e> { @@ -108,22 +110,58 @@ impl Caches { }) } + pub(crate) async fn evaluate_pinned( + &self, + parts: &Parts<'_>, + key: &str, + input: Variable, + options: EvaluationOptions, + ) -> LoaderResult>> { + let context = pinning::single(options.pinned()); + self.evaluate(parts, key, input, options, &context).await + } + + pub(crate) async fn evaluate_serialized_pinned( + &self, + parts: &Parts<'_>, + key: &str, + input: Variable, + options: EvaluationSerializedOptions, + ) -> Result { + let context = pinning::single(options.pinned()); + self.evaluate_serialized(parts, key, input, options, &context) + .await + } + + pub(crate) async fn evaluate_batch_pinned( + &self, + parts: &Parts<'_>, + key: &str, + contexts: &[Variable], + options: EvaluationOptions, + ) -> Vec>> { + let context = pinning::batch(options.pinned()); + self.evaluate_batch(parts, key, contexts, options, &context) + .await + } + pub(crate) async fn evaluate( &self, parts: &Parts<'_>, key: &str, - context: Variable, + input: Variable, options: EvaluationOptions, + context: &EvaluationContext, ) -> LoaderResult>> { if let Some(entry) = self.entry(key) { return Ok(match entry { Entry::Policy(artifact) => artifact - .evaluate_entry(key, context, options.trace) + .evaluate_entry(key, input, options.trace, context) .map(Responses::policy) .map_err(|e| Box::new(EvaluationError::Policy(e))), Entry::Graph(graph) => { self.decision(parts, key, &graph) - .evaluate_with_opts(context, options) + .evaluate_with_opts(input, options, context) .await } }); @@ -132,11 +170,11 @@ impl Caches { Ok(match content.as_ref() { DecisionContent::Graph(graph) => { self.decision(parts, key, graph) - .evaluate_with_opts(context, options) + .evaluate_with_opts(input, options, context) .await } DecisionContent::Policy(_) => { - self.policy(parts.loader, key, content.clone(), context, options) + self.policy(parts.loader, key, content.clone(), input, options, context) .await } }) @@ -146,14 +184,14 @@ impl Caches { &self, parts: &Parts<'_>, key: &str, - context: Variable, + input: Variable, options: EvaluationSerializedOptions, + context: &EvaluationContext, ) -> Result { - let opts = EvaluationOptions { - trace: options.trace != EvaluationTraceKind::None, - max_depth: options.max_depth, - }; - match self.evaluate(parts, key, context, opts).await { + match self + .evaluate(parts, key, input, options.unserialized(), context) + .await + { Ok(response) => Responses::serialized(response, options.trace), Err(err) => Err(Value::String(err.to_string())), } @@ -165,21 +203,22 @@ impl Caches { key: &str, contexts: &[Variable], options: EvaluationOptions, + context: &EvaluationContext, ) -> Vec>> { if let Some(entry) = self.entry(key) { return match entry { Entry::Policy(artifact) => { let requests: Vec = contexts .iter() - .map(|context| EvaluateRequest { + .map(|input| EvaluateRequest { policy_path: Arc::from(key), - input: context.clone(), + input: input.clone(), goals: Vec::new(), trace: options.trace, }) .collect(); artifact - .evaluate_batch(&requests) + .evaluate_batch(&requests, context) .into_iter() .map(|result| { result @@ -190,7 +229,7 @@ impl Caches { } Entry::Graph(graph) => { self.decision(parts, key, &graph) - .evaluate_batch(contexts, options) + .evaluate_batch(contexts, options, context) .await } }; @@ -199,16 +238,21 @@ impl Caches { if let DecisionContent::Graph(graph) = content.as_ref() { return self .decision(parts, key, graph) - .evaluate_batch(contexts, options) + .evaluate_batch(contexts, options, context) .await; } } let mut results = Vec::with_capacity(contexts.len()); - for context in contexts { + for (row, input) in contexts.iter().enumerate() { results.push( - match self - .evaluate(parts, key, context.deep_clone(), options) - .await + match Box::pin(self.evaluate( + parts, + key, + input.deep_clone(), + options, + &context.at(row), + )) + .await { Ok(result) => result, Err(error) => Err(Box::::from(error)), @@ -225,6 +269,7 @@ impl Caches { entry_content: Arc, input: Variable, options: EvaluationOptions, + context: &EvaluationContext, ) -> Result> { let entry_path: Arc = Arc::from(entry_key); let documents = Self::documents(loader, entry_path.clone(), entry_content).await?; @@ -254,7 +299,7 @@ impl Caches { }; let result = artifact - .evaluate_entry(&entry_path, input, options.trace) + .evaluate_entry(&entry_path, input, options.trace, context) .map_err(|e| Box::new(EvaluationError::Policy(e)))?; Ok(Responses::policy(result)) diff --git a/core/engine/src/compiled/exact/graph/expression.rs b/core/engine/src/compiled/exact/graph/expression.rs index 59d60956..f370450f 100644 --- a/core/engine/src/compiled/exact/graph/expression.rs +++ b/core/engine/src/compiled/exact/graph/expression.rs @@ -2,6 +2,7 @@ use super::{Ctx, Row}; use crate::compiled::host::expression::ExpressionNodeTrace; use crate::compiled::host::graph::tracer::ExpressionNodeTraceItem; use crate::compiled::host::NodeResult; +use crate::compiled::pinning::Located; use std::rc::Rc; use zen_expression::variable::Variable; use zen_types::decision::ExpressionNodeContent; @@ -17,6 +18,7 @@ impl Row<'_> { continue; } + session.locate(Located::expression(ctx.row.id, &expression.key)); let value = match session.run_standard(&expression.value) { Ok(value) => value, Err(_) => { diff --git a/core/engine/src/compiled/exact/graph/mod.rs b/core/engine/src/compiled/exact/graph/mod.rs index e99531a0..c52af82e 100644 --- a/core/engine/src/compiled/exact/graph/mod.rs +++ b/core/engine/src/compiled/exact/graph/mod.rs @@ -7,6 +7,7 @@ use crate::compiled::host::{NodeError, NodeResponse, NodeResult}; use std::future::Future; use std::sync::Arc; use std::task::{Context, Poll, Waker}; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{Programs, Session}; use zen_expression::variable::{ToVariable, Variable}; use zen_types::decision::{DecisionNode, DecisionNodeKind, TransformAttributes}; @@ -18,6 +19,7 @@ pub(crate) struct Row<'a> { pub(crate) nodes: Option, pub(crate) programs: Option<&'a Arc>, pub(crate) trace: bool, + pub(crate) context: EvaluationContext, } pub(crate) struct Ctx<'a, T> { @@ -27,8 +29,9 @@ pub(crate) struct Ctx<'a, T> { impl<'a> Row<'a> { pub(crate) fn session(&self) -> Session { - let mut session = - Session::with_environment(self.input.clone()).with_programs(self.programs.cloned()); + let mut session = Session::with_environment(self.input.clone()) + .with_programs(self.programs.cloned()) + .with_context(self.context.clone()); if let Some(nodes) = &self.nodes { session.set_local(Variable::nodes_key(), nodes.clone()); } @@ -36,9 +39,10 @@ impl<'a> Row<'a> { session } - pub(crate) fn with_input(&self, input: Variable) -> Self { + pub(crate) fn with_input(&self, input: Variable, context: EvaluationContext) -> Self { Self { input, + context, ..self.clone() } } @@ -56,8 +60,8 @@ impl<'a> Row<'a> { true => &content.transform_attributes, false => &plain, }; - self.transform(attributes, |input, _| { - let row = self.with_input(input); + self.transform(attributes, |input, _, context| { + let row = self.with_input(input, context); async move { row.expression(content) } }) .await @@ -67,8 +71,8 @@ impl<'a> Row<'a> { true => &content.transform_attributes, false => &plain, }; - self.transform(attributes, |input, _| { - let row = self.with_input(input); + self.transform(attributes, |input, _, context| { + let row = self.with_input(input, context); async move { RowTable::graph(row, content, index) } }) .await diff --git a/core/engine/src/compiled/exact/graph/transform.rs b/core/engine/src/compiled/exact/graph/transform.rs index e734475c..db6092ec 100644 --- a/core/engine/src/compiled/exact/graph/transform.rs +++ b/core/engine/src/compiled/exact/graph/transform.rs @@ -1,7 +1,9 @@ use super::Row; use crate::compiled::host::{NodeError, NodeResponse, NodeResult}; +use crate::compiled::pinning::Located; use std::future::Future; use std::ops::Deref; +use zen_expression::context::EvaluationContext; use zen_expression::Variable; use zen_types::decision::{TransformAttributes, TransformExecutionMode}; @@ -12,7 +14,7 @@ impl Row<'_> { evaluate: F, ) -> NodeResult where - F: Fn(Variable, bool) -> Fut, + F: Fn(Variable, bool, EvaluationContext) -> Fut, Fut: Future, { let mut trace = self.trace.then_some(Variable::Null); @@ -20,6 +22,7 @@ impl Row<'_> { None => self.input.clone(), Some(input_field) => { let mut session = self.session(); + session.locate(Located::input(self.id)); session.run_standard(input_field.deref()).map_err(|err| { self.fault(&trace, crate::compiled::exact::Failure::input(err)) })? @@ -28,7 +31,7 @@ impl Row<'_> { let output = match attributes.execution_mode { TransformExecutionMode::Single => { - let response = evaluate(input, false).await?; + let response = evaluate(input, false, self.context.clone()).await?; if let Some(td) = response.trace_data { if let Some(t) = &mut trace { *t = td; @@ -49,7 +52,8 @@ impl Row<'_> { let mut output_array = Vec::with_capacity(input_array.len()); for (index, input) in input_array.iter().enumerate() { let has_more = index < input_array.len() - 1; - let response = evaluate(input.clone(), has_more).await?; + let response = + evaluate(input.clone(), has_more, self.context.item(index)).await?; if let Some(td) = response.trace_data { if let Some(Variable::Array(arr)) = &trace { arr.borrow_mut().push(td); diff --git a/core/engine/src/compiled/exact/policy/assertion.rs b/core/engine/src/compiled/exact/policy/assertion.rs index 1372f870..c03665e0 100644 --- a/core/engine/src/compiled/exact/policy/assertion.rs +++ b/core/engine/src/compiled/exact/policy/assertion.rs @@ -1,6 +1,7 @@ use zen_expression::variable::Variable; use super::Exact; +use crate::compiled::pinning::Located; use crate::policy::blocks::{AssertionIr, ExecutionError}; use crate::workspace::types::{BlockTrace, ConditionTrace}; @@ -29,6 +30,8 @@ impl Exact<'_> { ) -> Result { let mut results = Vec::with_capacity(ir.conditions.len()); for condition in &ir.conditions { + self.session + .locate(Located::condition(self.site.block_id, &condition.id)); let cond_result = self .session .run_standard(&condition.expression) diff --git a/core/engine/src/compiled/exact/policy/expression.rs b/core/engine/src/compiled/exact/policy/expression.rs index 6467a32c..70830282 100644 --- a/core/engine/src/compiled/exact/policy/expression.rs +++ b/core/engine/src/compiled/exact/policy/expression.rs @@ -1,6 +1,7 @@ use zen_expression::variable::Variable; use super::Exact; +use crate::compiled::pinning::Located; use crate::policy::blocks::{ExecutionError, ExpressionIr}; use crate::workspace::types::BlockTrace; @@ -16,6 +17,7 @@ impl Exact<'_> { }); } + self.session.locate(Located::block(self.site.block_id)); let result = self .session .run_standard(&ir.value) diff --git a/core/engine/src/compiled/exact/policy/matching.rs b/core/engine/src/compiled/exact/policy/matching.rs index 9dd700fc..d47ba9ef 100644 --- a/core/engine/src/compiled/exact/policy/matching.rs +++ b/core/engine/src/compiled/exact/policy/matching.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use zen_expression::variable::Variable; use super::Exact; +use crate::compiled::pinning::Located; use crate::compiled::policy::blocks::MatchSelection; use crate::policy::blocks::{ExecutionError, MatchIr}; use crate::workspace::types::{BlockTrace, ConditionTrace}; @@ -19,6 +20,8 @@ impl Exact<'_> { let matches = if arm.condition.is_empty() { true } else { + self.session + .locate(Located::arm(self.site.block_id, &arm.id)); match self.session.run_standard(&arm.condition) { Ok(value) => value.as_bool().unwrap_or(false), Err(_) if self.site.extras && matched_arm.is_some() => false, @@ -47,10 +50,13 @@ impl Exact<'_> { .as_ref() .and_then(|id| ir.arms.iter().find(|a| &a.id == id)); let value = match matched { - Some(arm) if !arm.value.is_empty() => self - .session - .run_standard(&arm.value) - .map_err(|e| self.site.expression_error(&arm.value, e))?, + Some(arm) if !arm.value.is_empty() => { + self.session + .locate(Located::value(self.site.block_id, &arm.id)); + self.session + .run_standard(&arm.value) + .map_err(|e| self.site.expression_error(&arm.value, e))? + } _ => Variable::Null, }; diff --git a/core/engine/src/compiled/exact/policy/mod.rs b/core/engine/src/compiled/exact/policy/mod.rs index 86924d0e..dd35c0ad 100644 --- a/core/engine/src/compiled/exact/policy/mod.rs +++ b/core/engine/src/compiled/exact/policy/mod.rs @@ -34,6 +34,7 @@ impl Exact<'_> { RowTable::new( self.session, &ir.inputs, + self.site.block_id, self.site.indexes.of(ir).as_ref().as_ref(), Some(self.site), ) @@ -45,8 +46,14 @@ impl Exact<'_> { ir: &DecisionTableIr, selection: &TableSelection, ) -> Result { - RowTable::new(self.session, &ir.inputs, None, Some(self.site)) - .commit(ir, selection, self.site) + RowTable::new( + self.session, + &ir.inputs, + self.site.block_id, + None, + Some(self.site), + ) + .commit(ir, selection, self.site) } fn execute_table(&mut self, ir: &DecisionTableIr) -> Result { diff --git a/core/engine/src/compiled/exact/table.rs b/core/engine/src/compiled/exact/table.rs index 8618f136..67e0aa9d 100644 --- a/core/engine/src/compiled/exact/table.rs +++ b/core/engine/src/compiled/exact/table.rs @@ -2,6 +2,7 @@ use crate::compiled::exact::graph::{Ctx, Row}; use crate::compiled::host::decision_table::index::TableIndex; use crate::compiled::host::graph::tracer::{DecisionTableNodeTrace, DecisionTableRowTrace}; use crate::compiled::host::{NodeResponse, NodeResult}; +use crate::compiled::pinning::Located; use crate::compiled::policy::blocks::TableSelection; use crate::compiled::policy::site::Site; use crate::policy::blocks::{DecisionTableIr, ExecutionError}; @@ -24,6 +25,7 @@ type Cells = (Option, Vec<(usize, Variable)>); pub(crate) struct RowTable<'t, 's> { pub session: &'t mut Session, pub inputs: &'t [DecisionTableInputField], + owner: &'t str, index: Option<&'t TableIndex>, site: Option<&'t Site<'s>>, refs: Vec>, @@ -33,18 +35,29 @@ impl<'t, 's> RowTable<'t, 's> { pub fn new( session: &'t mut Session, inputs: &'t [DecisionTableInputField], + owner: &'t str, index: Option<&'t TableIndex>, site: Option<&'t Site<'s>>, ) -> Self { Self { session, inputs, + owner, index, site, refs: vec![None; inputs.len()], } } + pub fn rule_id(rule: &Rule) -> &str { + rule.get("_id").map_or("", |id| id.as_ref()) + } + + fn locate(&mut self, rule: &Rule, column: &str) { + self.session + .locate(Located::cell(self.owner, Self::rule_id(rule), column)); + } + fn fail( &self, source: &Arc, @@ -72,6 +85,8 @@ impl<'t, 's> RowTable<'t, 's> { let Some(field) = self.field(col) else { return Ok(None); }; + self.session + .locate(Located::field(self.owner, &self.inputs[col].id)); match self.session.run_standard(field) { Ok(value) => { self.refs[col] = Some(value.shallow_clone()); @@ -143,6 +158,7 @@ impl<'t, 's> RowTable<'t, 's> { return Ok(true); }; if self.field(col).is_none() { + self.locate(rule, &self.inputs[col].id); return match self.session.run_standard(cell) { Ok(result) => Ok(result.as_bool().unwrap_or(false)), Err(error) => self.fail(cell, error, false), @@ -151,6 +167,7 @@ impl<'t, 's> RowTable<'t, 's> { if !self.bind(col)? { return Ok(false); } + self.locate(rule, &self.inputs[col].id); match self.session.run_unary(cell) { Ok(pass) => Ok(pass), Err(error) => self.fail(cell, error, false), @@ -196,7 +213,13 @@ impl<'t, 's> RowTable<'t, 's> { .collect() } - pub fn output(&mut self, cell: &Arc) -> Result, ExecutionError> { + pub fn output( + &mut self, + rule: &Rule, + column: &str, + cell: &Arc, + ) -> Result, ExecutionError> { + self.locate(rule, column); match self.session.run_standard(cell) { Ok(value) => Ok(Some(value)), Err(error) => self.fail(cell, error, None), @@ -240,7 +263,7 @@ impl RowTable<'_, '_> { let Some(cell) = rule.get(&output.id).filter(|c| !c.is_empty()) else { continue; }; - let value = self.output(cell).ok()??.deep_clone(); + let value = self.output(rule, &output.id, cell).ok()??.deep_clone(); match (collect, &object) { (true, _) => lists.push((column, value)), (false, Some(object)) => { @@ -290,9 +313,11 @@ impl RowTable<'_, '_> { let mut ctx = Ctx::::new(row); let mut session = ctx.row.session(); let traced = ctx.row.trace; + let owner = ctx.row.id.clone(); let mut table = RowTable::new( &mut session, &content.inputs, + &owner, index.filter(|_| !traced), None, ); @@ -463,7 +488,7 @@ impl RowTable<'_, '_> { else { continue; }; - let value = self.output(cell)?.unwrap_or(Variable::Null); + let value = self.output(rule, &col.id, cell)?.unwrap_or(Variable::Null); if site.trace { outputs.insert(col.field.clone(), value.deep_clone()); } diff --git a/core/engine/src/compiled/graph/batched.rs b/core/engine/src/compiled/graph/batched.rs index 5230c9bd..359d9177 100644 --- a/core/engine/src/compiled/graph/batched.rs +++ b/core/engine/src/compiled/graph/batched.rs @@ -80,6 +80,7 @@ impl CompiledGraph { extensions: &NodeHandlerExtensions, ) -> Result, Failure> { let call = Call { + node: "", key, extensions, max_depth: 0, @@ -162,6 +163,7 @@ impl CompiledGraph { .collect(); } let call = Call { + node: &step.node.id, key: &content.key, extensions, max_depth, @@ -170,7 +172,7 @@ impl CompiledGraph { let content = compiled.schemas(graph, extensions.loader()).await; let extensions = NodeHandlerExtensions { function_runtime: Default::default(), - ..call.sub_extensions(&content) + ..call.sub_extensions(&content, &extensions.context) }; let parents: Vec> = (0..inputs.len()) .map(|row| nodes.get(row).cloned().flatten()) diff --git a/core/engine/src/compiled/graph/call.rs b/core/engine/src/compiled/graph/call.rs index 81af7955..f8965d9a 100644 --- a/core/engine/src/compiled/graph/call.rs +++ b/core/engine/src/compiled/graph/call.rs @@ -3,17 +3,20 @@ use super::{CompiledGraph, Host, Nesting}; use crate::compiled::content::Content; use crate::compiled::exact::graph::Row; use crate::compiled::host::{NodeError, NodeHandlerExtensions, NodeResponse, NodeResult}; +use crate::compiled::pinning::Located; use crate::decision_graph::graph::DecisionGraphResponse; use crate::loader::LoaderError; use crate::EvaluationError; use std::cell::{OnceCell, RefCell}; use std::error::Error; use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::variable::ToVariable; use zen_expression::Variable; use zen_types::decision::TransformAttributes; pub(crate) struct Call<'a> { + pub(crate) node: &'a str, pub(crate) key: &'a str, pub(crate) extensions: &'a NodeHandlerExtensions, pub(crate) max_depth: u8, @@ -60,8 +63,13 @@ impl Call<'_> { } #[allow(clippy::arc_with_non_send_sync)] - pub(super) fn sub_extensions(&self, content: &Content) -> NodeHandlerExtensions { + pub(super) fn sub_extensions( + &self, + content: &Content, + context: &EvaluationContext, + ) -> NodeHandlerExtensions { NodeHandlerExtensions { + context: context.nested(Located::decision(self.node, self.key)), dt_indexes: content.dt_indexes.clone(), stripped_functions: content.stripped_functions.clone(), validator_cache: Arc::new(OnceCell::from(content.validator_cache.clone())), @@ -74,10 +82,11 @@ impl Call<'_> { graph: &Arc, input: Variable, parent: Option, + context: &EvaluationContext, ) -> Result> { let compiled = Self::compiled(graph)?; let content = compiled.schemas(graph, self.extensions.loader()).await; - let extensions = self.sub_extensions(&content); + let extensions = self.sub_extensions(&content, context); let parents = [parent]; let inputs = [input]; let nesting = Nesting { @@ -108,10 +117,11 @@ impl Call<'_> { graph: &Arc, input: Variable, parent: Option, + context: &EvaluationContext, ) -> Result> { let compiled = Self::compiled(graph)?; let content = compiled.schemas(graph, self.extensions.loader()).await; - let extensions = self.sub_extensions(&content); + let extensions = self.sub_extensions(&content, context); let traced = Traced { graph: compiled, content: &content, @@ -129,7 +139,7 @@ impl Call<'_> { let id = row.id; let nodes = &row.nodes; let traced = row.trace; - row.transform(attributes, |input, _| async move { + row.transform(attributes, |input, _, context| async move { let fault = |source: Box, trace: Option| { NodeError::traced(id.clone(), trace, source) }; @@ -148,7 +158,7 @@ impl Call<'_> { }; if !traced { let output = self - .run(&graph, input, nodes.clone()) + .run(&graph, input, nodes.clone(), &context) .await .map_err(|e| fault(e, None))?; return Ok(NodeResponse { @@ -156,7 +166,7 @@ impl Call<'_> { trace_data: None, }); } - match self.traced(&graph, input, nodes.clone()).await { + match self.traced(&graph, input, nodes.clone(), &context).await { Err(source) => Err(fault(source, blank)), Ok(Ok(response)) => Ok(NodeResponse { output: response.result, diff --git a/core/engine/src/compiled/graph/columnar.rs b/core/engine/src/compiled/graph/columnar.rs index 22653897..8a5be8af 100644 --- a/core/engine/src/compiled/graph/columnar.rs +++ b/core/engine/src/compiled/graph/columnar.rs @@ -250,9 +250,16 @@ impl CompiledGraph { let inputs: Vec = rows.iter().map(|&row| inputs[row].clone()).collect(); let completed = completed.subset(&rows); - let results = self - .resumed(content, extensions, max_depth, &inputs, Some(&completed)) - .await; + extensions.context.restart(&rows); + let scoped = extensions.scoped(extensions.context.rows(&rows)); + let results = Box::pin(self.resumed( + content, + &scoped, + max_depth, + &inputs, + Some(&completed), + )) + .await; return output.splice(&rows, results); } } diff --git a/core/engine/src/compiled/graph/plan/mod.rs b/core/engine/src/compiled/graph/plan/mod.rs index eafd2e7e..68898209 100644 --- a/core/engine/src/compiled/graph/plan/mod.rs +++ b/core/engine/src/compiled/graph/plan/mod.rs @@ -12,6 +12,7 @@ use crate::compiled::graph::call::Call; use crate::compiled::graph::schedule::{End, Outcome, Segment}; use crate::compiled::graph::{Body, CompiledGraph, Condition, Kind, Step}; use crate::compiled::leaf::Literal; +use crate::compiled::pinning::Located; use crate::compiled::table::Table; use crate::model::DecisionNodeKind; use petgraph::prelude::NodeIndex; @@ -620,10 +621,14 @@ impl<'g> Builder<'g> { .iter() .map(|kept| (kept.entry.0.as_ref(), kept.fragment.as_ref())) .collect(); + let labels: Vec = kept + .iter() + .map(|kept| Located::expression(&step.node.id, &kept.entry.0)) + .collect(); match kept.is_empty() { true => None, false => Some(Reduced { - program: LaneProgram::compile_many(&refs, true) + program: LaneProgram::compile_many_located(&refs, true, &labels) .map_err(|e| Refusal::Uncompiled(Arc::from(e.to_string())))?, entries: kept.into_iter().map(|kept| kept.entry).collect(), }), @@ -1478,7 +1483,11 @@ impl<'g> Builder<'g> { true => { let scope = zen_expression::Scope::default(); let truth = zen_expression::lane::LaneRunner::new() - .evaluate_one(program, &scope); + .evaluate_one( + program, + &zen_expression::context::EvaluationContext::default(), + &scope, + ); match truth { Ok(zen_expression::Variable::Bool(true)) => Cond::Always, _ => Cond::Never, diff --git a/core/engine/src/compiled/graph/plan/run/child.rs b/core/engine/src/compiled/graph/plan/run/child.rs index 7c7dae49..56a61bf9 100644 --- a/core/engine/src/compiled/graph/plan/run/child.rs +++ b/core/engine/src/compiled/graph/plan/run/child.rs @@ -163,6 +163,7 @@ impl<'a> Run<'_, 'a> { .collect::>(), }; let call = Call { + node: id, key: &content.key, extensions: self.host.extensions, max_depth: self.host.max_depth, @@ -170,7 +171,10 @@ impl<'a> Run<'_, 'a> { }; let extensions = NodeHandlerExtensions { function_runtime: Default::default(), - ..call.sub_extensions(&op.content) + ..call.sub_extensions( + &op.content, + &self.host.extensions.context.picked(at.clone()), + ) }; let named: Vec<(&Arc, Symbol, Leaf<'a>)> = op .nodes @@ -276,16 +280,20 @@ impl<'a> Run<'_, 'a> { failed: Vec::new(), }; }; - let results = CompiledGraph::nested_results( + let scoped = self + .host + .extensions + .scoped(self.host.extensions.context.picked(at.clone())); + let results = Box::pin(CompiledGraph::nested_results( step, content, &op.content, &inputs, &nodes, - self.host.extensions, + &scoped, self.host.max_depth, self.iteration, - ) + )) .await; let mut failed = Vec::new(); let values: Vec> = results diff --git a/core/engine/src/compiled/graph/plan/run/lane.rs b/core/engine/src/compiled/graph/plan/run/lane.rs index 3cee31e3..3e95cd12 100644 --- a/core/engine/src/compiled/graph/plan/run/lane.rs +++ b/core/engine/src/compiled/graph/plan/run/lane.rs @@ -124,6 +124,7 @@ impl<'a> Run<'_, 'a> { }; self.runner.evaluate_sites( program, + &self.host.extensions.context, scopes.slice(), &columns, &op.bound, @@ -195,7 +196,11 @@ impl<'a> Run<'_, 'a> { let scope = zen_expression::Scope::new(columns.row(row)); let message = match self .runner - .evaluate(source, std::slice::from_ref(&scope)) + .evaluate( + source, + &self.host.extensions.context.at(row), + std::slice::from_ref(&scope), + ) .into_iter() .next() { diff --git a/core/engine/src/compiled/graph/plan/run/loops.rs b/core/engine/src/compiled/graph/plan/run/loops.rs index 29ca8af0..3f58c52c 100644 --- a/core/engine/src/compiled/graph/plan/run/loops.rs +++ b/core/engine/src/compiled/graph/plan/run/loops.rs @@ -38,12 +38,14 @@ impl<'a> Run<'_, 'a> { None => (0..rows).collect(), }; let mut native: Option<(Leaf<'a>, Vec)> = None; - match leaf.items() { + let draws = CompiledGraph::draws(body); + match leaf.items().filter(|_| !draws) { Some(items) => { if self.native_loop(step, body, transform.pass_through, &items, out, &at) { return; } } + None if draws => {} None => { if let Some((records, odd)) = self.shredded(&leaf, rows) { let (rest, lifted): (Vec, Vec) = @@ -68,12 +70,16 @@ impl<'a> Run<'_, 'a> { } } let mut items: Vec = Vec::new(); + let mut owners: Vec<(usize, usize)> = Vec::new(); let mut spans: Vec<(usize, usize, usize)> = Vec::with_capacity(at.len()); for &row in &at { match leaf.get(row).as_array() { Some(array) => { let start = items.len(); items.extend(array.borrow().iter().cloned()); + if draws { + owners.extend((0..items.len() - start).map(|index| (row, index))); + } spans.push((row, start, items.len())); } None => self @@ -82,7 +88,11 @@ impl<'a> Run<'_, 'a> { .fail(row, &step.node, Rc::from("Expected an array")), } } - let produced = CompiledGraph::items(&mut self.runner, step, body, &items, &[]); + let context = match draws { + true => self.host.extensions.context.items(&owners), + false => self.host.extensions.context.clone(), + }; + let produced = CompiledGraph::items(&mut self.runner, &context, step, body, &items, &[]); let mut values = vec![Variable::Null; rows]; for (row, start, end) in spans { let mut collected = Vec::with_capacity(end - start); @@ -235,7 +245,13 @@ impl<'a> Run<'_, 'a> { } let items: Rc<[usize]> = (0..count).collect(); let data = Data::record(&items, Layer::new(keys.into(), leaves, Some(present)), None); - let (output, failures) = CompiledGraph::item_run(&mut self.runner, step, body, &data); + let (output, failures) = CompiledGraph::item_run( + &mut self.runner, + &self.host.extensions.context, + step, + body, + &data, + ); let paths: Vec<(Arc, Leaf<'a>)> = output.leaves().to_vec(); let shaped = matches!(output.shape, DataShape::Patched { base: None, .. }) && paths diff --git a/core/engine/src/compiled/graph/plan/run/rows.rs b/core/engine/src/compiled/graph/plan/run/rows.rs index 6e7991fb..e91cd743 100644 --- a/core/engine/src/compiled/graph/plan/run/rows.rs +++ b/core/engine/src/compiled/graph/plan/run/rows.rs @@ -238,16 +238,20 @@ impl<'a> Run<'_, 'a> { Ok(graph) => { let (at, inputs, nodes) = self.inputs(seg, Some(&op.view), &op.nodes, positions); - let results = CompiledGraph::batch( + let scoped = self + .host + .extensions + .scoped(self.host.extensions.context.rows(&at)); + let results = Box::pin(CompiledGraph::batch( step, content, &graph, &inputs, &nodes, - self.host.extensions, + &scoped, self.host.max_depth, self.iteration, - ) + )) .await; { self.completed @@ -270,21 +274,24 @@ impl<'a> Run<'_, 'a> { let values: Vec = match &step.kind { Kind::Host(_) => { Census::mark("hosted"); + let scoped = self + .host + .extensions + .scoped(self.host.extensions.context.rows(&at)); let results = match &step.node.kind { DecisionNodeKind::CustomNode { content } => { - CompiledGraph::custom(step, content, inputs, nodes, self.host.extensions) - .await + Box::pin(CompiledGraph::custom(step, content, inputs, nodes, &scoped)).await } _ => { - CompiledGraph::hosted( + Box::pin(CompiledGraph::hosted( step, &inputs, &nodes, - self.host.extensions, + &scoped, self.host.max_depth, self.iteration, self.store.rows > 1, - ) + )) .await } }; @@ -313,7 +320,9 @@ impl<'a> Run<'_, 'a> { _ => { let data = data.unwrap_or_else(|| Data::plain((0..inputs.len()).collect(), inputs.into())); - let (output, failures) = graph.rowwise(&mut self.runner, step, data, &nodes); + let context = self.host.extensions.context.rows(&at); + let (output, failures) = + graph.rowwise(&mut self.runner, &context, step, data, &nodes); for (i, message) in failures { self.store.errors.fail(at[i], &step.node, Rc::from(message)); } @@ -398,7 +407,16 @@ impl<'a> Run<'_, 'a> { .enumerate() .map(|(i, input)| CompiledGraph::scope(input, nodes.get(i).and_then(Option::as_ref))) .collect(); - for (result, &row) in self.runner.evaluate(program, &scopes).into_iter().zip(&at) { + let context = match program.program().draws { + true => self.host.extensions.context.rows(&at), + false => self.host.extensions.context.clone(), + }; + for (result, &row) in self + .runner + .evaluate(program, &context, &scopes) + .into_iter() + .zip(&at) + { if matches!(result, Ok(Variable::Bool(true))) { Bits::set(&mut bits, row, true); } diff --git a/core/engine/src/compiled/graph/plan/run/table.rs b/core/engine/src/compiled/graph/plan/run/table.rs index acfddf15..4900e873 100644 --- a/core/engine/src/compiled/graph/plan/run/table.rs +++ b/core/engine/src/compiled/graph/plan/run/table.rs @@ -24,6 +24,11 @@ impl<'a> Run<'_, 'a> { return; }; let local = positions.map_or(self.store.rows, |p| p.len()); + let context = match positions.filter(|_| table.programs().iter().any(|p| p.program().draws)) + { + Some(positions) => self.host.extensions.context.rows(positions), + None => self.host.extensions.context.clone(), + }; let mut leaves: Vec>> = op .reads .iter() @@ -100,6 +105,7 @@ impl<'a> Run<'_, 'a> { } } let bound = Bound { + context, scopes: Bound::blank(evaluated), columns, bind: Box::new(move |key: &str| match key.starts_with('$') { diff --git a/core/engine/src/compiled/graph/plan/run/typed.rs b/core/engine/src/compiled/graph/plan/run/typed.rs index 4253044e..46384733 100644 --- a/core/engine/src/compiled/graph/plan/run/typed.rs +++ b/core/engine/src/compiled/graph/plan/run/typed.rs @@ -409,7 +409,7 @@ impl<'a> Run<'_, 'a> { select: None, }; Some(Lowered { - out: call.run(&op.program)?, + out: call.run(&op.program, &self.host.extensions.context)?, keyed: Some(ids), select: None, prefault, @@ -500,7 +500,7 @@ impl<'a> Run<'_, 'a> { .collect(), select, }; - call.run(&op.program) + call.run(&op.program, &self.host.extensions.context) } fn coded( @@ -524,6 +524,14 @@ impl<'a> Run<'_, 'a> { }; codes.push(code); } - Dedup::reps(&op.program, leaves, &codes, positions, rows).map(|(out, ids)| (out, Some(ids))) + Dedup::reps( + &op.program, + leaves, + &codes, + positions, + rows, + &self.host.extensions.context, + ) + .map(|(out, ids)| (out, Some(ids))) } } diff --git a/core/engine/src/compiled/graph/state/exec.rs b/core/engine/src/compiled/graph/state/exec.rs index 6eea9067..8d5ae8d6 100644 --- a/core/engine/src/compiled/graph/state/exec.rs +++ b/core/engine/src/compiled/graph/state/exec.rs @@ -11,6 +11,7 @@ use crate::compiled::host::{NodeContextConfig, NodeHandlerExtensions}; use crate::model::DecisionNodeKind; use std::rc::Rc; use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::lane::LaneRunner; use zen_expression::Variable; use zen_types::decision::FunctionNodeContent; @@ -48,21 +49,22 @@ impl CompiledGraph { if matches!(step.kind, Kind::Host(_)) { let materialized = data.materialized(); let batched = state.errors.len() > 1; + let scoped = extensions.scoped(state.context.picked(rows.clone())); let replayed = state .nesting .completed .and_then(|completed| completed.replay(event.node, rows)); let results = match replayed { None => { - Self::hosted( + Box::pin(Self::hosted( step, &materialized, &nodes, - extensions, + &scoped, max_depth, state.nesting.iteration, batched, - ) + )) .await } Some(replayed) => { @@ -77,15 +79,17 @@ impl CompiledGraph { let mut fresh = match missing.is_empty() { true => Vec::new(), false => { - Self::hosted( + let at: Vec = missing.iter().map(|&i| rows[i]).collect(); + let scoped = extensions.scoped(state.context.rows(&at)); + Box::pin(Self::hosted( step, &inputs, &parents, - extensions, + &scoped, max_depth, state.nesting.iteration, batched, - ) + )) .await } } @@ -132,7 +136,7 @@ impl CompiledGraph { .await; (Data::plain(rows.clone(), values.into()), failures) } - Kind::Node { .. } => self.node(step, rows, &data, &nodes, &extra), + Kind::Node { .. } => self.node(&state.context, step, rows, &data, &nodes, &extra), }; for (i, message) in failures { @@ -202,15 +206,15 @@ impl CompiledGraph { for (i, value) in inputs.iter().enumerate() { let nodes = nodes.get(i).cloned().flatten(); results.push( - Self::host( + Box::pin(Self::host( step, value.clone(), nodes, - extensions, + &extensions.scoped(extensions.context.at(i)), max_depth, iteration, batched, - ) + )) .await, ); } @@ -231,18 +235,19 @@ impl CompiledGraph { let mut results = Vec::with_capacity(inputs.len()); for (i, value) in inputs.iter().enumerate() { let nodes = nodes.get(i).cloned().flatten(); - match batch.call(value, nodes.as_ref()) { + let context = extensions.context.at(i); + match batch.call(value, nodes.as_ref(), &context) { Some(result) => results.push(result), None => results.push( - Self::host( + Box::pin(Self::host( step, value.clone(), nodes, - extensions, + &extensions.scoped(context), max_depth, iteration, batched, - ) + )) .await, ), } @@ -290,6 +295,7 @@ impl CompiledGraph { pub(in crate::compiled::graph) fn rowwise<'a>( &self, runner: &mut LaneRunner, + context: &EvaluationContext, step: &Step, data: Data<'a>, nodes: &[Option], @@ -303,7 +309,8 @@ impl CompiledGraph { .iter() .enumerate() .map(|(i, value)| { - match Self::walked(step, value.clone(), nodes.get(i).cloned().flatten(), true) { + let node = nodes.get(i).cloned().flatten(); + match Self::walked(step, value.clone(), node, true, &context.at(i)) { Ok(output) => output, Err(message) => { failures.push((i, message)); @@ -314,24 +321,28 @@ impl CompiledGraph { .collect(); return (Data::plain(rows, values), failures); } - self.node_with(runner, step, &rows, &data, nodes, &[]) + self.node_with(runner, context, step, &rows, &data, nodes, &[]) } fn node<'a>( &self, + context: &EvaluationContext, step: &Step, rows: &Rc<[usize]>, data: &Data<'a>, nodes: &[Option], extra: &[NodeColumn<'a>], ) -> (Data<'a>, Vec<(usize, String)>) { - Self::RUNNER - .with_borrow_mut(|runner| self.node_with(runner, step, rows, data, nodes, extra)) + Self::RUNNER.with_borrow_mut(|runner| { + self.node_with(runner, context, step, rows, data, nodes, extra) + }) } + #[allow(clippy::too_many_arguments)] fn node_with<'a>( &self, runner: &mut LaneRunner, + context: &EvaluationContext, step: &Step, rows: &Rc<[usize]>, data: &Data<'a>, @@ -360,13 +371,13 @@ impl CompiledGraph { match (rebase, &transform.output_path, wide) { (Some(rebase), None, true) if !overlapping => { crate::compiled::census::Census::mark("layered"); - Self::bound(step, data, nodes, extra, rebase, |bound| { + Self::bound(context, step, data, nodes, extra, rebase, |bound| { Self::layered(runner, body, transform.pass_through, data, bound, None) }) } (Some(rebase), Some(path), true) if keyed && expression && !overlapping => { crate::compiled::census::Census::mark("layered-path"); - Self::bound(step, data, nodes, extra, rebase, |bound| { + Self::bound(context, step, data, nodes, extra, rebase, |bound| { Self::layered( runner, body, @@ -379,7 +390,7 @@ impl CompiledGraph { } (Some(None), Some(path), true) if keyed => { crate::compiled::census::Census::mark("placed"); - Self::bound(step, data, nodes, extra, None, |bound| { + Self::bound(context, step, data, nodes, extra, None, |bound| { Self::placed(runner, body, path, transform.pass_through, data, bound) }) } @@ -392,13 +403,28 @@ impl CompiledGraph { .is_some_and(|(program, _)| program.path().is_some()) => { crate::compiled::census::Census::mark("looped"); - Self::looped(runner, step, body, transform, path, data) + Self::looped( + runner, + &context.picked(rows.clone()), + step, + body, + transform, + path, + data, + ) } _ => { crate::compiled::census::Census::mark("transformed"); let materialized = data.materialized(); - let results = - Self::transformed(runner, step, body, transform, &materialized, nodes); + let results = Self::transformed( + runner, + &context.picked(rows.clone()), + step, + body, + transform, + &materialized, + nodes, + ); let mut failures = Vec::new(); let values: Col = results .into_iter() @@ -469,16 +495,13 @@ impl CompiledGraph { false => Vec::new(), }; let mut failures = Vec::new(); + let context = state.context.picked(rows.clone()); let outputs: Vec = values .iter() .enumerate() .map(|(i, value)| { - match Self::walked( - step, - value.clone(), - nodes.get(i).cloned().flatten(), - true, - ) { + let node = nodes.get(i).cloned().flatten(); + match Self::walked(step, value.clone(), node, true, &context.at(i)) { Ok(output) => output, Err(message) => { failures.push((i, message)); @@ -497,7 +520,7 @@ impl CompiledGraph { rows, step.column_path(rows.len()), ); - self.node(step, rows, &data, &nodes, &extra) + self.node(&state.context, step, rows, &data, &nodes, &extra) } _ => (data, Vec::new()), }; diff --git a/core/engine/src/compiled/graph/state/host.rs b/core/engine/src/compiled/graph/state/host.rs index d9659c9a..e75974b7 100644 --- a/core/engine/src/compiled/graph/state/host.rs +++ b/core/engine/src/compiled/graph/state/host.rs @@ -335,6 +335,7 @@ impl CompiledGraph { } DecisionNodeKind::DecisionNode { content } => { let call = call::Call { + node: &node.id, key: &content.key, extensions: &base.extensions, max_depth: base.config.max_depth, @@ -346,6 +347,7 @@ impl CompiledGraph { nodes: base.nodes.clone(), programs: None, trace, + context: base.extensions.context.clone(), }; call.node(row, &content.transform_attributes).await } @@ -362,6 +364,7 @@ impl CompiledGraph { nodes: base.nodes.clone(), programs, trace, + context: base.extensions.context.clone(), }; row.node(node, index, true).await } diff --git a/core/engine/src/compiled/graph/state/loops.rs b/core/engine/src/compiled/graph/state/loops.rs index ffc1594f..63cef68f 100644 --- a/core/engine/src/compiled/graph/state/loops.rs +++ b/core/engine/src/compiled/graph/state/loops.rs @@ -7,6 +7,7 @@ use crate::compiled::leaf::Mask; use crate::compiled::leaf::{ColumnBuilder, Leaf}; use std::rc::Rc; use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{LaneProgram, LaneRunner}; use zen_expression::{Scope, Variable}; use zen_types::path::DotPath; @@ -14,6 +15,7 @@ use zen_types::path::DotPath; impl CompiledGraph { pub(in crate::compiled::graph) fn transformed( runner: &mut LaneRunner, + context: &EvaluationContext, step: &Step, body: &Body, transform: &Transform, @@ -29,7 +31,7 @@ impl CompiledGraph { .map(|(row, i)| Self::scope(i, nodes.get(row).and_then(Option::as_ref))) .collect(); runner - .evaluate(program, &scopes) + .evaluate(program, context, &scopes) .into_iter() .map(|r| r.map_err(crate::compiled::exact::Failure::input)) .collect() @@ -49,15 +51,22 @@ impl CompiledGraph { .iter() .map(|&r| nodes.get(r).cloned().flatten()) .collect(); - let mut produced = - Self::items(runner, step, body, &body_inputs, &body_nodes).into_iter(); + let mut produced = Self::items( + runner, + &context.rows(&rows), + step, + body, + &body_inputs, + &body_nodes, + ) + .into_iter(); effective .into_iter() .map(|e| e.and_then(|_| produced.next().unwrap_or_else(|| Ok(Variable::Null)))) .collect() } true => { - let mut owners: Vec = Vec::new(); + let mut owners: Vec<(usize, usize)> = Vec::new(); let mut items: Vec = Vec::new(); let mut item_nodes: Vec> = Vec::new(); let mut shaped: Vec> = Vec::with_capacity(inputs.len()); @@ -69,8 +78,8 @@ impl CompiledGraph { Some(array) => { let array = array.borrow(); shaped.push(Ok(array.len())); - for item in array.iter() { - owners.push(row); + for (index, item) in array.iter().enumerate() { + owners.push((row, index)); items.push(item.clone()); item_nodes.push(nodes.get(row).cloned().flatten()); } @@ -78,7 +87,12 @@ impl CompiledGraph { }, } } - let mut produced = Self::items(runner, step, body, &items, &item_nodes).into_iter(); + let looped = match Self::draws(body) { + true => context.items(&owners), + false => context.clone(), + }; + let mut produced = + Self::items(runner, &looped, step, body, &items, &item_nodes).into_iter(); let mut item_inputs = items.into_iter(); shaped .into_iter() @@ -126,6 +140,7 @@ impl CompiledGraph { pub(in crate::compiled::graph) fn looped<'a>( runner: &mut LaneRunner, + context: &EvaluationContext, step: &Step, body: &Body, transform: &Transform, @@ -139,6 +154,8 @@ impl CompiledGraph { .unwrap_or_default(); let lists = data.subtree(source); let mut items: Vec = Vec::new(); + let mut owners: Vec<(usize, usize)> = Vec::new(); + let draws = Self::draws(body); let mut spans: Vec> = Vec::with_capacity(lists.len()); let mut failures = Vec::new(); for (row, list) in lists.iter().enumerate() { @@ -146,6 +163,9 @@ impl CompiledGraph { Some(array) => { let start = items.len(); items.extend(array.borrow().iter().cloned()); + if draws { + owners.extend((0..items.len() - start).map(|index| (row, index))); + } spans.push(Some((start, items.len()))); } None => { @@ -154,7 +174,11 @@ impl CompiledGraph { } } } - let produced = Self::items(runner, step, body, &items, &[]); + let looped = match draws { + true => context.items(&owners), + false => context.clone(), + }; + let produced = Self::items(runner, &looped, step, body, &items, &[]); let mut values = Vec::with_capacity(spans.len()); for (row, span) in spans.into_iter().enumerate() { let Some((start, end)) = span else { @@ -198,6 +222,7 @@ impl CompiledGraph { pub(in crate::compiled::graph) fn items( runner: &mut LaneRunner, + context: &EvaluationContext, step: &Step, body: &Body, inputs: &[Variable], @@ -212,22 +237,33 @@ impl CompiledGraph { .iter() .map(|&i| nodes.get(i).cloned().flatten()) .collect(); - let mut produced = - Self::items(runner, step, body, &kept_inputs, &kept_nodes).into_iter(); + let mut produced = Self::items( + runner, + &context.rows(&kept), + step, + body, + &kept_inputs, + &kept_nodes, + ) + .into_iter(); return inputs .iter() .enumerate() .map(|(i, input)| match Self::foreign(input) { - true => { - Self::walked(step, input.clone(), nodes.get(i).cloned().flatten(), false) - } + true => Self::walked( + step, + input.clone(), + nodes.get(i).cloned().flatten(), + false, + &context.at(i), + ), false => produced.next().unwrap_or(Ok(Variable::Null)), }) .collect(); } match Self::item_data(step, body, inputs, nodes) { Some(data) => { - let (output, failures) = Self::item_run(runner, step, body, &data); + let (output, failures) = Self::item_run(runner, context, step, body, &data); let values = output.materialized(); let mut results: Vec> = values.iter().cloned().map(Ok).collect(); @@ -238,7 +274,14 @@ impl CompiledGraph { } results } - None => Self::body(runner, body, inputs, nodes), + None => Self::body(runner, context, body, inputs, nodes), + } + } + + pub(in crate::compiled::graph) fn draws(body: &Body) -> bool { + match body { + Body::Expression { program, .. } => program.program().draws, + Body::Table(table) => table.programs().iter().any(|p| p.program().draws), } } @@ -251,6 +294,7 @@ impl CompiledGraph { input: Variable, nodes: Option, transforms: bool, + context: &EvaluationContext, ) -> Result { let row = Row { id: &step.node.id, @@ -258,6 +302,7 @@ impl CompiledGraph { nodes, programs: step.shared_programs(), trace: false, + context: context.clone(), }; row.now(&step.node, None, transforms) .map(|response| response.output) @@ -296,11 +341,12 @@ impl CompiledGraph { pub(in crate::compiled::graph) fn item_run<'a>( runner: &mut LaneRunner, + context: &EvaluationContext, step: &Step, body: &Body, data: &Data<'a>, ) -> (Data<'a>, Vec<(usize, String)>) { - Self::bound(step, data, &[], &[], None, |bound| { + Self::bound(context, step, data, &[], &[], None, |bound| { Self::layered(runner, body, false, data, bound, None) }) } @@ -340,6 +386,7 @@ impl CompiledGraph { fn body( runner: &mut LaneRunner, + context: &EvaluationContext, body: &Body, inputs: &[Variable], nodes: &[Option], @@ -354,7 +401,7 @@ impl CompiledGraph { program, entries, .. } => { let mut out: Vec> = vec![Ok(Variable::Null); scopes.len()]; - runner.evaluate_many(program, &scopes, None, |row, result| { + runner.evaluate_many(program, context, &scopes, None, |row, result| { out[row] = match result { Some(Ok(values)) => { let object = Variable::empty_object(); @@ -375,7 +422,7 @@ impl CompiledGraph { out } Body::Table(table) => table - .evaluate(runner, &Bound::plain(scopes)) + .evaluate(runner, &Bound::plain(scopes, context.clone())) .into_iter() .map(|o| Ok(table.value(o))) .collect(), diff --git a/core/engine/src/compiled/graph/state/mod.rs b/core/engine/src/compiled/graph/state/mod.rs index 11d8c064..feaab934 100644 --- a/core/engine/src/compiled/graph/state/mod.rs +++ b/core/engine/src/compiled/graph/state/mod.rs @@ -19,6 +19,7 @@ use petgraph::prelude::NodeIndex; use std::rc::Rc; use std::sync::atomic::Ordering; use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{Binding, Columns}; use zen_expression::{Scope, Variable}; use zen_types::symbol::Symbol; @@ -32,6 +33,7 @@ pub(in crate::compiled::graph) struct Host<'r> { } pub(crate) struct State<'a> { + context: EvaluationContext, nodes: Vec>>>, pub(crate) errors: RowErrors>, pub(in crate::compiled::graph) results: Vec>, @@ -232,6 +234,7 @@ impl CompiledGraph { } = host; let count = inputs.len(); let mut state = State { + context: extensions.context.clone(), nodes: vec![Vec::new(); self.steps.len()], errors: RowErrors::new(count), results: vec![None; count], @@ -378,6 +381,7 @@ impl CompiledGraph { } fn bound<'a, R>( + context: &EvaluationContext, step: &Step, data: &Data<'a>, nodes: &[Option], @@ -385,6 +389,7 @@ impl CompiledGraph { rebase: Option<&str>, f: impl FnOnce(&Bound) -> R, ) -> R { + let context = context.picked(data.rows.clone()); let with_nodes = |scope: Scope, row: usize| match nodes.get(row).cloned().flatten() { None => scope, Some(n) => { @@ -413,7 +418,7 @@ impl CompiledGraph { .enumerate() .map(|(row, v)| with_nodes(Scope::new(v.clone()), row)) .collect(); - return f(&Bound::plain(scopes)); + return f(&Bound::plain(scopes, context)); } let blank = nodes.iter().all(Option::is_none) && matches!(&data.shape, data::Shape::Patched { base: None, .. }); @@ -451,6 +456,7 @@ impl CompiledGraph { .map(|(p, _)| p.clone()) .collect(); let bound = Bound { + context, scopes, columns, bind: Box::new(move |key: &str| { @@ -491,7 +497,7 @@ impl CompiledGraph { let data = Self::input_of(state, parents, rows); let (nodes, extra) = self.node_inputs(step, state, visible, rows, true); let hits: Vec = Self::RUNNER.with_borrow_mut(|runner| { - Self::bound(step, &data, &nodes, &extra, None, |bound| { + Self::bound(&state.context, step, &data, &nodes, &extra, None, |bound| { conditions .iter() .map(|(_, condition)| match condition { diff --git a/core/engine/src/compiled/graph/step.rs b/core/engine/src/compiled/graph/step.rs index 2edb6d9f..163734a9 100644 --- a/core/engine/src/compiled/graph/step.rs +++ b/core/engine/src/compiled/graph/step.rs @@ -2,6 +2,7 @@ use crate::compiled::content::Content; use crate::compiled::graph::schedule::Replay; use crate::compiled::graph::{CompiledGraph, Invalid}; use crate::compiled::host::graph::graph::DecisionGraph; +use crate::compiled::pinning::Located; use crate::compiled::table::{Table, TableIr}; use crate::decision_graph::schema_dict; use crate::model::DecisionNodeKind; @@ -209,12 +210,15 @@ impl CompiledGraph { }) } - fn transform(attributes: &TransformAttributes) -> Result<(Transform, Vec>), String> { + fn transform( + node: &str, + attributes: &TransformAttributes, + ) -> Result<(Transform, Vec>), String> { let input_field = attributes .input_field .as_ref() .map(|f| { - LaneProgram::standard(f) + LaneProgram::located(f, ExpressionKind::Standard, Located::input(node)) .map(|p| (p, f.clone())) .map_err(|e| e.to_string()) }) @@ -237,6 +241,7 @@ impl CompiledGraph { } fn expression_kind( + node: &str, content: &ExpressionNodeContent, sources: &mut Vec>, ) -> Result { @@ -266,8 +271,10 @@ impl CompiledGraph { let mut expanded: Vec<(Arc, Arc, Arc)> = Vec::with_capacity(entries.len()); for (key, source) in entries.iter() { let read = format!("$.{}", key.split('.').next().unwrap_or_default()); - let flat = - !opaque && !overlapping && !entries.iter().any(|(_, v)| v.contains(read.as_str())); + let flat = !opaque + && !overlapping + && !entries.iter().any(|(_, v)| v.contains(read.as_str())) + && !SourceInfo::draws(source); match flat { true => Self::expand(key, source, source, &mut expanded), false => expanded.push((key.clone(), source.clone(), source.clone())), @@ -277,7 +284,12 @@ impl CompiledGraph { .iter() .map(|(k, _, v)| (k.as_ref(), v.as_ref())) .collect(); - let program = LaneProgram::compile_many(&refs, true).map_err(|e| e.to_string())?; + let labels: Vec = expanded + .iter() + .map(|(key, _, _)| Located::expression(node, key)) + .collect(); + let program = + LaneProgram::compile_many_located(&refs, true, &labels).map_err(|e| e.to_string())?; let empty: Box<[bool]> = expanded .iter() .map(|(_, _, fragment)| fragment.trim() == "{}") @@ -290,7 +302,7 @@ impl CompiledGraph { .into_iter() .map(|(key, source, _)| (key, source)) .collect(); - let (transform, extra) = Self::transform(&content.transform_attributes)?; + let (transform, extra) = Self::transform(node, &content.transform_attributes)?; sources.extend(extra); Ok(Kind::Node { transform: Box::new(transform), @@ -307,6 +319,7 @@ impl CompiledGraph { } fn table_kind( + node: &str, content: &DecisionTableContent, sources: &mut Vec>, cells: &mut Vec>, @@ -325,8 +338,15 @@ impl CompiledGraph { } } sources.extend(content.inputs.iter().filter_map(|i| i.field.clone())); + if sources + .iter() + .chain(cells.iter()) + .any(|s| SourceInfo::draws(s)) + { + return Err("table draws".into()); + } let table = Table::compile(TableIr::graph(content))?; - let (transform, extra) = Self::transform(&content.transform_attributes)?; + let (transform, extra) = Self::transform(node, &content.transform_attributes)?; sources.extend(extra); Ok(Kind::Node { body: Body::Table(Box::new(table)), @@ -360,9 +380,13 @@ impl CompiledGraph { sources.push(s.condition.clone()); let condition = match s.condition.is_empty() { true => Condition::Always, - false => LaneProgram::standard(&s.condition) - .map(|p| Condition::Program(Box::new(p))) - .unwrap_or_else(|e| Condition::Invalid(Arc::from(e.to_string()))), + false => LaneProgram::located( + &s.condition, + ExpressionKind::Standard, + Located::statement(&node.id, &s.id), + ) + .map(|p| Condition::Program(Box::new(p))) + .unwrap_or_else(|e| Condition::Invalid(Arc::from(e.to_string()))), }; (s.id.clone(), condition) }) @@ -379,11 +403,11 @@ impl CompiledGraph { Kind::Host(None) } DecisionNodeKind::ExpressionNode { content } => { - Self::expression_kind(content, &mut sources) + Self::expression_kind(&node.id, content, &mut sources) .unwrap_or_else(|why| Kind::Host(Some(Arc::from(why)))) } DecisionNodeKind::DecisionTableNode { content } => { - Self::table_kind(content, &mut sources, &mut cells) + Self::table_kind(&node.id, content, &mut sources, &mut cells) .unwrap_or_else(|why| Kind::Host(Some(Arc::from(why)))) } DecisionNodeKind::FunctionNode { .. } diff --git a/core/engine/src/compiled/graph/traced.rs b/core/engine/src/compiled/graph/traced.rs index dea25bdf..fea88b58 100644 --- a/core/engine/src/compiled/graph/traced.rs +++ b/core/engine/src/compiled/graph/traced.rs @@ -8,6 +8,7 @@ use crate::compiled::host::graph::walker::GraphWalker; use crate::compiled::host::{ NodeContextBase, NodeContextConfig, NodeError, NodeHandlerExtensions, NodeResponse, NodeResult, }; +use crate::compiled::pinning::Located; use crate::decision_graph::cleaner::VariableCleaner; use crate::decision_graph::graph::{DecisionGraphResponse, EvaluationTrace}; use crate::model::DecisionNodeKind; @@ -20,7 +21,7 @@ use std::sync::Arc; use std::time::Instant; use zen_expression::lane::Session; use zen_expression::variable::{ToVariable, Variable}; -use zen_types::decision::{SwitchNodeContent, SwitchStatementHitPolicy}; +use zen_types::decision::{SwitchNodeContent, SwitchStatement, SwitchStatementHitPolicy}; use zen_types::symbol::Symbol; pub(crate) struct Traced<'g> { @@ -179,7 +180,7 @@ impl Traced<'_> { let DecisionNodeKind::SwitchNode { content } = &step.node.kind else { return Outcome::from(Vec::new()); }; - let statements = Self::statements(step, content, &input, nodes); + let statements = Self::statements(step, content, &input, nodes, &self.extensions.context); if let Some(mut record) = tracer.trace_callback() { let output = input.depth_clone(1); record(DecisionGraphTrace { @@ -209,29 +210,35 @@ impl Traced<'_> { content: &SwitchNodeContent, input: &Variable, nodes: Option, + context: &zen_expression::context::EvaluationContext, ) -> Vec { - let mut session = - Session::with_environment(input.clone()).with_programs(Some(step.programs().clone())); + let mut session = Session::with_environment(input.clone()) + .with_programs(Some(step.programs().clone())) + .with_context(context.clone()); if let Some(nodes) = nodes { session.set_local(Variable::nodes_key(), nodes); } - let mut passes = |condition: &str| { - condition.is_empty() - || session - .run_standard(condition) - .is_ok_and(|value| value.as_bool().unwrap_or(false)) + let node = &step.node.id; + let mut passes = |statement: &SwitchStatement| { + if statement.condition.is_empty() { + return true; + } + session.locate(Located::statement(node, &statement.id)); + session + .run_standard(&statement.condition) + .is_ok_and(|value| value.as_bool().unwrap_or(false)) }; let mut statements = content.statements.iter(); match content.hit_policy { SwitchStatementHitPolicy::First => statements - .find(|statement| passes(&statement.condition)) + .find(|statement| passes(statement)) .into_iter() .cloned() .map(SwitchStatementTraceRow::from) .collect(), SwitchStatementHitPolicy::Collect => statements - .filter(|statement| passes(&statement.condition)) + .filter(|statement| passes(statement)) .cloned() .map(SwitchStatementTraceRow::from) .collect(), diff --git a/core/engine/src/compiled/host/extensions.rs b/core/engine/src/compiled/host/extensions.rs index b72391d8..9968bd24 100644 --- a/core/engine/src/compiled/host/extensions.rs +++ b/core/engine/src/compiled/host/extensions.rs @@ -21,6 +21,7 @@ pub struct NodeHandlerExtensions { pub(crate) stripped_functions: Option, Arc>>>, pub(crate) dt_indexes: Option, TableIndex>>>, pub(crate) prepared: Arc, + pub(crate) context: zen_expression::context::EvaluationContext, } impl Default for NodeHandlerExtensions { @@ -35,6 +36,7 @@ impl Default for NodeHandlerExtensions { dt_indexes: None, http_handler: None, prepared: Default::default(), + context: Default::default(), } } } @@ -43,7 +45,9 @@ impl NodeHandlerExtensions { pub async fn function_runtime(&self) -> anyhow::Result<&Function> { self.function_runtime .get_or_try_init(|| { + let slot = crate::compiled::pinning::JsSlot::default(); Function::create(FunctionConfig { + slot: slot.clone(), listeners: Some(vec![ Box::new(ConsoleListener), Box::new(HttpListener { @@ -54,6 +58,7 @@ impl NodeHandlerExtensions { loader: self.loader.clone(), custom_node: self.custom_node.clone(), http_handler: self.http_handler.clone(), + slot, }), ]), }) @@ -62,6 +67,13 @@ impl NodeHandlerExtensions { .context("Failed to create function") } + pub(crate) fn scoped(&self, context: zen_expression::context::EvaluationContext) -> Self { + Self { + context, + ..self.clone() + } + } + pub fn validator_cache(&self) -> &ValidatorCache { self.validator_cache .get_or_init(|| ValidatorCache::default()) diff --git a/core/engine/src/compiled/host/function/purity.rs b/core/engine/src/compiled/host/function/purity.rs index 3fb59ed2..283e66b3 100644 --- a/core/engine/src/compiled/host/function/purity.rs +++ b/core/engine/src/compiled/host/function/purity.rs @@ -124,8 +124,8 @@ impl Purity { &[ "abs", "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "cbrt", "ceil", "clz32", "cos", "cosh", "exp", "expm1", "floor", "fround", "hypot", "imul", "log", - "log10", "log1p", "log2", "max", "min", "pow", "random", "round", "sign", "sin", - "sinh", "sqrt", "tan", "tanh", "trunc", + "log10", "log1p", "log2", "max", "min", "pow", "round", "sign", "sin", "sinh", + "sqrt", "tan", "tanh", "trunc", ], ), ("JSON", &["stringify", "parse"]), @@ -1581,7 +1581,11 @@ mod tests { .await .expect("module"); let response = function - .call_handler(&name, JsValueWithNodes(JsValue(Variable::Null))) + .call_handler( + &name, + JsValueWithNodes(JsValue(Variable::Null)), + &zen_expression::context::EvaluationContext::default(), + ) .await .expect("names"); let names = response diff --git a/core/engine/src/compiled/host/function/v1/mod.rs b/core/engine/src/compiled/host/function/v1/mod.rs index 03661082..e66cab7d 100644 --- a/core/engine/src/compiled/host/function/v1/mod.rs +++ b/core/engine/src/compiled/host/function/v1/mod.rs @@ -9,6 +9,7 @@ use crate::compiled::host::function::v1::runtime::create_runtime; use crate::compiled::host::function::v1::script::{Script, Session}; use crate::compiled::host::result::NodeResult; use crate::compiled::host::{NodeContext, NodeContextBase, NodeContextExt, NodeError}; +use crate::compiled::pinning::Located; use serde_json::Value; use zen_expression::variable::ToVariable; use zen_expression::Variable; @@ -33,7 +34,13 @@ impl NodeHandler for FunctionV1NodeHandler { runtime.set_interrupt_handler(Some(interrupt_handler)); let mut script = Script::new(runtime.clone()); - let result_response = script.call(ctx.node.deref(), &ctx.input_with_nodes()).await; + let result_response = script + .call( + ctx.node.deref(), + &ctx.input_with_nodes(), + &ctx.extensions.context.nested(Located::function(&ctx.id)), + ) + .await; runtime.set_interrupt_handler(None); @@ -75,13 +82,18 @@ impl Batch { &mut self, input: &Variable, nodes: Option<&Variable>, + context: &zen_expression::context::EvaluationContext, ) -> Option> { if self.session.is_none() && !self.failed { self.session = Session::open(&self.source, MAX_DURATION); self.failed = self.session.is_none(); } let session = self.session.as_ref()?; - let result = session.call(&self.layout, &NodeContextBase::joined(input, nodes)); + let result = session.call( + &self.layout, + &NodeContextBase::joined(input, nodes), + &context.nested(Located::function(&self.id)), + ); if result.is_err() || !session.settled() { self.session = None; } diff --git a/core/engine/src/compiled/host/function/v1/script.rs b/core/engine/src/compiled/host/function/v1/script.rs index 21057504..ea30e95c 100644 --- a/core/engine/src/compiled/host/function/v1/script.rs +++ b/core/engine/src/compiled/host/function/v1/script.rs @@ -1,4 +1,5 @@ use crate::compiled::host::function::v2::serde::JsValue; +use crate::compiled::pinning::JsSlot; use anyhow::Context as _; use rquickjs::{Context, Ctx, Error as QError, FromJs, Module, Runtime}; use serde::{Deserialize, Serialize}; @@ -7,6 +8,7 @@ use std::fmt::Debug; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; +use zen_expression::context::EvaluationContext; use zen_expression::variable::Variable; #[derive(Debug, Deserialize)] @@ -18,25 +20,35 @@ pub struct EvaluateResponse { pub struct Script { runtime: Runtime, + slot: JsSlot, } impl Script { pub fn new(runtime: Runtime) -> Self { - Self { runtime } + Self { + runtime, + slot: JsSlot::default(), + } } - pub async fn call

(&mut self, source: &str, args: &P) -> anyhow::Result + pub async fn call

( + &mut self, + source: &str, + args: &P, + context: &EvaluationContext, + ) -> anyhow::Result where P: Serialize, { + let _entered = self.slot.enter(context.clone()); let runtime = &self.runtime; - let context = Context::full(runtime).context("Failed to create context")?; + let js_context = Context::full(runtime).context("Failed to create context")?; let args_str = serde_json::to_string(args).context("Failed to serialize function arguments")?; - let json_response = context.with(|ctx| -> anyhow::Result { - Self::prepare(&ctx)?; + let json_response = js_context.with(|ctx| -> anyhow::Result { + Self::prepare(&ctx, &self.slot)?; ctx.eval::(format!("{source};main({args_str})")) .map_err(|e| map_js_error(&ctx, e)) })?; @@ -44,7 +56,8 @@ impl Script { Self::response(&json_response) } - fn prepare(ctx: &Ctx) -> anyhow::Result<()> { + fn prepare(ctx: &Ctx, slot: &JsSlot) -> anyhow::Result<()> { + slot.install(ctx).map_err(|e| map_js_error(ctx, e))?; Module::evaluate( ctx.clone(), "main", @@ -70,6 +83,7 @@ pub(crate) struct Session { context: Context, base: Instant, started: Arc, + slot: JsSlot, } impl Session { @@ -87,20 +101,28 @@ impl Session { > limit }))); let context = Context::full(&runtime).ok()?; - let ready = - context.with(|ctx| Script::prepare(&ctx).is_ok() && ctx.eval::<(), _>(source).is_ok()); + let slot = JsSlot::default(); + let ready = context + .with(|ctx| Script::prepare(&ctx, &slot).is_ok() && ctx.eval::<(), _>(source).is_ok()); (ready && !runtime.is_job_pending()).then_some(Self { runtime, context, base, started, + slot, }) } - pub(crate) fn call

(&self, layout: &str, args: &P) -> anyhow::Result + pub(crate) fn call

( + &self, + layout: &str, + args: &P, + context: &EvaluationContext, + ) -> anyhow::Result where P: Serialize, { + let _entered = self.slot.enter(context.clone()); let args_str = serde_json::to_string(args).context("Failed to serialize function arguments")?; self.started @@ -114,6 +136,8 @@ impl Session { true => format!("{layout};main(({}))", Self::ROW), false => format!("{layout};main({args_str})"), }; + ctx.eval::<(), _>("globalThis.now = Date.now();") + .map_err(|e| map_js_error(&ctx, e))?; ctx.eval::(script) .map_err(|e| map_js_error(&ctx, e)) })?; diff --git a/core/engine/src/compiled/host/function/v2/function.rs b/core/engine/src/compiled/host/function/v2/function.rs index 86bf8189..0ef64ec2 100644 --- a/core/engine/src/compiled/host/function/v2/function.rs +++ b/core/engine/src/compiled/host/function/v2/function.rs @@ -9,15 +9,18 @@ use crate::compiled::host::function::v2::listener::{RuntimeEvent, RuntimeListene use crate::compiled::host::function::v2::module::console::{Console, Log}; use crate::compiled::host::function::v2::module::ModuleLoader; use crate::compiled::host::function::v2::serde::{JsValue, JsValueWithNodes}; +use crate::compiled::pinning::JsSlot; use rquickjs::prelude::Func; use rquickjs::promise::MaybePromise; use rquickjs::{async_with, AsyncContext, AsyncRuntime, CatchResultExt, Ctx, Module, Object}; use serde::{Deserialize, Serialize}; use std::rc::Rc; +use zen_expression::context::EvaluationContext; use zen_expression::variable::{ToVariable, Variable}; pub struct FunctionConfig { pub(crate) listeners: Option>>, + pub(crate) slot: JsSlot, } pub struct Function { @@ -26,6 +29,7 @@ pub struct Function { listeners: Vec>, module_loader: ModuleLoader, declared: RefCell>, + slot: JsSlot, } impl Debug for Function { @@ -49,9 +53,17 @@ impl Function { module_loader, listeners: config.listeners.unwrap_or_default(), declared: RefCell::new(HashMap::new()), + slot: config.slot, }; this.dispatch_event(RuntimeEvent::Startup).await?; + let slot = this.slot.clone(); + let installed: FunctionResult = async_with!(&this.ctx => |ctx| { + slot.install(&ctx).catch(&ctx)?; + Ok(()) + }) + .await; + installed?; Ok(this) } @@ -132,7 +144,9 @@ impl Function { &self, name: &str, data: JsValueWithNodes, + context: &EvaluationContext, ) -> FunctionResult { + let _entered = self.slot.enter(context.clone()); let k: FunctionResult = async_with!(&self.ctx => |ctx| { self.dispatch_event_inner(&ctx, RuntimeEvent::SoftReset).await?; @@ -158,7 +172,9 @@ impl Function { config: (u8, u8, bool), rows: Vec<(Variable, Option)>, tick: &dyn Fn(), + context: &EvaluationContext, ) -> Vec> { + let _entered = self.slot.enter(context.clone()); let count = rows.len(); let current: Rc> = Rc::new(RefCell::new(Variable::Null)); let shared = current.clone(); diff --git a/core/engine/src/compiled/host/function/v2/mod.rs b/core/engine/src/compiled/host/function/v2/mod.rs index 7df9aecd..42e3810a 100644 --- a/core/engine/src/compiled/host/function/v2/mod.rs +++ b/core/engine/src/compiled/host/function/v2/mod.rs @@ -11,6 +11,7 @@ use crate::compiled::host::function::v2::module::console::Log; use crate::compiled::host::function::v2::serde::{JsValue, JsValueWithNodes}; use crate::compiled::host::result::NodeResult; use crate::compiled::host::{NodeContext, NodeContextConfig, NodeError, NodeHandlerExtensions}; +use crate::compiled::pinning::Located; use rquickjs::prelude::Func; use rquickjs::{async_with, CatchResultExt, Object}; use serde_json::json; @@ -70,7 +71,11 @@ impl NodeHandler for FunctionV2NodeHandler { .await?; let response_result = function - .call_handler(&module_name, JsValueWithNodes(JsValue(ctx.input.clone()))) + .call_handler( + &module_name, + JsValueWithNodes(JsValue(ctx.input.clone())), + &ctx.extensions.context.nested(Located::function(&ctx.id)), + ) .await; function.runtime().set_interrupt_handler(None).await; @@ -132,9 +137,10 @@ impl FunctionV2NodeHandler { return Self::run(id, &source, extensions, config, iteration, rows).await; } let mut results = Vec::with_capacity(rows.len()); - for row in rows { + for (at, row) in rows.into_iter().enumerate() { let fresh = NodeHandlerExtensions { function_runtime: Default::default(), + context: extensions.context.at(at), ..extensions.clone() }; results.extend(Self::run(id, &source, &fresh, config, iteration, vec![row]).await); @@ -189,6 +195,7 @@ impl FunctionV2NodeHandler { (iteration, config.max_depth, config.trace), rows, &tick, + &extensions.context.nested(Located::function(id)), ) .await; function.runtime().set_interrupt_handler(None).await; diff --git a/core/engine/src/compiled/host/function/v2/module/zen.rs b/core/engine/src/compiled/host/function/v2/module/zen.rs index f62473c8..fddf65dc 100644 --- a/core/engine/src/compiled/host/function/v2/module/zen.rs +++ b/core/engine/src/compiled/host/function/v2/module/zen.rs @@ -21,6 +21,7 @@ pub(crate) struct ZenListener { pub loader: DynamicLoader, pub custom_node: DynamicCustomNode, pub http_handler: DynamicHttpHandler, + pub slot: crate::compiled::pinning::JsSlot, } impl ZenListener { @@ -34,6 +35,7 @@ impl ZenListener { ) -> rquickjs::Result { let start = Instant::now(); let call = Call { + node: "", key, extensions: &extensions, max_depth, @@ -49,7 +51,7 @@ impl ZenListener { } }; let result = call - .run(&graph, context.0, None) + .run(&graph, context.0, None, &extensions.context) .await .map_err(|error| rquickjs::Exception::throw_message(ctx, &error.to_string()))?; Ok(DecisionGraphResponse { @@ -68,6 +70,7 @@ impl ZenListener { iteration: u8, ) -> rquickjs::Result { let call = Call { + node: "", key, extensions: &extensions, max_depth, @@ -82,7 +85,7 @@ impl ZenListener { )) } }; - call.traced(&graph, context.0, None) + call.traced(&graph, context.0, None, &extensions.context) .await .map_err(|error| rquickjs::Exception::throw_message(ctx, &error.to_string()))? .or_throw(ctx) @@ -99,6 +102,7 @@ impl RuntimeListener for ZenListener { let loader = self.loader.clone(); let custom_node = self.custom_node.clone(); let http_handler = self.http_handler.clone(); + let slot = self.slot.clone(); Box::pin(async move { if event != RuntimeEvent::Startup { @@ -111,12 +115,13 @@ impl RuntimeListener for ZenListener { Func::from(Async( move |ctx: Ctx<'js>, key: String, - context: JsValue, + input: JsValue, opts: Opt>| { let prepared = prepared.clone(); let loader = loader.clone(); let custom_node = custom_node.clone(); let http_handler = http_handler.clone(); + let context = slot.current().unwrap_or_default(); async move { let config: Object = ctx.globals().get("config").or_throw(&ctx)?; @@ -133,18 +138,19 @@ impl RuntimeListener for ZenListener { custom_node: custom_node.clone(), http_handler: http_handler.clone(), prepared: prepared.clone(), + context, ..Default::default() }; let response = match trace { true => { Self::walk( - &ctx, &key, context, extensions, max_depth, iteration, + &ctx, &key, input, extensions, max_depth, iteration, ) .await? } false => { Self::call( - &ctx, &key, context, extensions, max_depth, iteration, + &ctx, &key, input, extensions, max_depth, iteration, ) .await? } diff --git a/core/engine/src/compiled/leaf/literal.rs b/core/engine/src/compiled/leaf/literal.rs index 9f583f04..a87349a2 100644 --- a/core/engine/src/compiled/leaf/literal.rs +++ b/core/engine/src/compiled/leaf/literal.rs @@ -17,7 +17,14 @@ impl Literal { if !p.site_keys.is_empty() || p.opaque() || p.writes_env || p.chain || !p.timeless() { return None; } - match runner.evaluate_one(program, &Scope::default()).ok()? { + match runner + .evaluate_one( + program, + &zen_expression::context::EvaluationContext::default(), + &Scope::default(), + ) + .ok()? + { Variable::Null => Some(Literal::Null), Variable::Bool(b) => Some(Literal::Bool(b)), Variable::Number(n) => Some(Literal::Num(n)), diff --git a/core/engine/src/compiled/mod.rs b/core/engine/src/compiled/mod.rs index 2c6b8dac..25fe8c64 100644 --- a/core/engine/src/compiled/mod.rs +++ b/core/engine/src/compiled/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod host; mod leaf; mod lowered; mod output; +pub(crate) mod pinning; pub(crate) mod policy; pub(crate) mod prepared; mod shred; diff --git a/core/engine/src/compiled/pinning.js b/core/engine/src/compiled/pinning.js new file mode 100644 index 00000000..6c1dc0f8 --- /dev/null +++ b/core/engine/src/compiled/pinning.js @@ -0,0 +1,199 @@ +(() => { + if (globalThis.__zenPinned) return; + const Native = Date; + const proto = Native.prototype; + const now = globalThis.__zenNow; + const random = globalThis.__zenRandom; + const offsetAt = globalThis.__zenOffset; + const utcAt = globalThis.__zenUtc; + const zoneOf = globalThis.__zenZone; + const canonicalZone = globalThis.__zenCanonicalZone; + const N = {}; + for (const name of [ + 'getTime', 'setTime', 'getUTCFullYear', 'getUTCMonth', 'getUTCDate', 'getUTCDay', + 'getUTCHours', 'getUTCMinutes', 'getUTCSeconds', 'getUTCMilliseconds', 'setUTCFullYear', + 'setUTCHours', 'getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds', + 'getMilliseconds', + ]) N[name] = proto[name]; + const call = (f, self, ...args) => f.apply(self, args); + const time = (d) => call(N.getTime, d); + const define = (target, name, value) => + Object.defineProperty(target, name, { value, writable: true, configurable: true, enumerable: false }); + + const offset = (t, zone) => { + const o = offsetAt(t, zone); + if (o === undefined) throw new RangeError('Invalid time zone specified: ' + zone); + return o; + }; + const fields = (t, zone) => { + const o = offset(t, zone); + const s = new Native(t + o * 60000); + return { + y: call(N.getUTCFullYear, s), mo: call(N.getUTCMonth, s), d: call(N.getUTCDate, s), + wd: call(N.getUTCDay, s), h: call(N.getUTCHours, s), mi: call(N.getUTCMinutes, s), + s: call(N.getUTCSeconds, s), ms: call(N.getUTCMilliseconds, s), o, + }; + }; + const localTime = (parts) => { + if (parts.some((p) => !Number.isFinite(p))) return NaN; + const s = new Native(0); + call(N.setUTCFullYear, s, parts[0], parts[1], parts[2]); + call(N.setUTCHours, s, parts[3], parts[4], parts[5], parts[6]); + return time(s); + }; + const fromLocal = (parts, zone) => { + const local = localTime(parts); + if (Number.isNaN(local)) return NaN; + const utc = utcAt(local, zone); + return utc === undefined ? NaN : utc; + }; + + const getters = { getFullYear: 'y', getMonth: 'mo', getDate: 'd', getDay: 'wd', getHours: 'h', getMinutes: 'mi', getSeconds: 's', getMilliseconds: 'ms' }; + for (const [name, key] of Object.entries(getters)) { + define(proto, name, function () { + const t = time(this); + return Number.isNaN(t) ? NaN : fields(t)[key]; + }); + } + define(proto, 'getTimezoneOffset', function () { + const t = time(this); + return Number.isNaN(t) ? NaN : -offset(t); + }); + if (proto.getYear) { + define(proto, 'getYear', function () { + const y = this.getFullYear(); + return Number.isNaN(y) ? NaN : y - 1900; + }); + } + const setters = [['setFullYear', 0, 3], ['setMonth', 1, 2], ['setDate', 2, 1], ['setHours', 3, 4], ['setMinutes', 4, 3], ['setSeconds', 5, 2], ['setMilliseconds', 6, 1]]; + for (const [name, at, count] of setters) { + define(proto, name, function (...args) { + const t = time(this); + let parts; + if (Number.isNaN(t)) { + if (name !== 'setFullYear') return NaN; + parts = [1970, 0, 1, 0, 0, 0, 0]; + } else { + const f = fields(t); + parts = [f.y, f.mo, f.d, f.h, f.mi, f.s, f.ms]; + } + const given = args.length === 0 ? [NaN] : args.slice(0, count).map(Number); + given.forEach((value, i) => { parts[at + i] = value; }); + const next = fromLocal(parts.map(Math.trunc)); + call(N.setTime, this, next); + return time(this); + }); + } + + const isoDate = /^\s*[+-]?\d{4,6}(?:-\d\d(?:-\d\d)?)?\s*$/; + const zoned = /(?:\d[Zz]\s*$|[+-]\d\d:?\d\d\s*(?:\(.*\))?\s*$|\b(?:GMT|UTC|UT)\b)/; + const parse = (text) => { + const source = String(text); + const t = Native.parse(source); + if (Number.isNaN(t) || isoDate.test(source) || zoned.test(source)) return t; + const d = new Native(t); + return fromLocal([ + call(N.getFullYear, d), call(N.getMonth, d), call(N.getDate, d), call(N.getHours, d), + call(N.getMinutes, d), call(N.getSeconds, d), call(N.getMilliseconds, d), + ]); + }; + const valueOf = (value) => { + if (value instanceof Native) return time(value); + const primitive = typeof value === 'object' && value !== null ? value.valueOf() : value; + return typeof primitive === 'string' ? parse(primitive) : Number(primitive); + }; + + function PinnedDate(...args) { + if (!new.target) return new PinnedDate(now()).toString(); + let t; + if (args.length === 0) { + t = now(); + } else if (args.length === 1) { + t = valueOf(args[0]); + } else { + const parts = args.slice(0, 7).map(Number); + while (parts.length < 7) parts.push(parts.length === 2 ? 1 : 0); + let y = parts[0]; + if (Number.isFinite(y)) { + y = Math.trunc(y); + if (y >= 0 && y <= 99) y += 1900; + } + parts[0] = y; + t = fromLocal(parts.map((p) => (Number.isFinite(p) ? Math.trunc(p) : p))); + } + return Reflect.construct(Native, [t], new.target); + } + PinnedDate.prototype = proto; + PinnedDate.now = () => now(); + PinnedDate.parse = (text) => parse(text); + PinnedDate.UTC = Native.UTC; + define(proto, 'constructor', PinnedDate); + globalThis.Date = PinnedDate; + Math.random = () => random(); + + const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + const pad = (n, width = 2) => String(n).padStart(width, '0'); + const year = (y) => (y < 0 ? '-' + pad(-y, 6) : pad(y, 4)); + const gmt = (o) => { + const a = Math.abs(Math.round(o)); + return 'GMT' + (o < 0 ? '-' : '+') + pad(Math.floor(a / 60)) + pad(a % 60); + }; + const datePart = (f) => `${DAYS[f.wd]} ${MONTHS[f.mo]} ${pad(f.d)} ${year(f.y)}`; + const timePart = (f) => `${pad(f.h)}:${pad(f.mi)}:${pad(f.s)} ${gmt(f.o)}`; + define(proto, 'toString', function () { + const t = time(this); + if (Number.isNaN(t)) return 'Invalid Date'; + const f = fields(t); + return `${datePart(f)} ${timePart(f)}`; + }); + define(proto, 'toDateString', function () { + const t = time(this); + return Number.isNaN(t) ? 'Invalid Date' : datePart(fields(t)); + }); + define(proto, 'toTimeString', function () { + const t = time(this); + return Number.isNaN(t) ? 'Invalid Date' : timePart(fields(t)); + }); + + const resolveZone = (options) => { + const zone = options && options.timeZone; + if (zone === undefined) return undefined; + const canonical = canonicalZone(String(zone)); + if (canonical === undefined || canonical === null) throw new RangeError('Invalid time zone specified: ' + zone); + return canonical; + }; + const localized = (t, zone, kind) => { + if (Number.isNaN(t)) return 'Invalid Date'; + const f = fields(t, zone); + const date = `${pad(f.mo + 1)}/${pad(f.d)}/${pad(f.y, 4)}`; + const clock = `${pad(f.h % 12 || 12)}:${pad(f.mi)}:${pad(f.s)} ${f.h < 12 ? 'AM' : 'PM'}`; + if (kind === 'date') return date; + if (kind === 'time') return clock; + return `${date}, ${clock}`; + }; + for (const [name, kind] of [['toLocaleString', 'both'], ['toLocaleDateString', 'date'], ['toLocaleTimeString', 'time']]) { + define(proto, name, function (locales, options) { + return localized(time(this), resolveZone(options), kind); + }); + } + + if (typeof globalThis.Intl === 'undefined') { + function DateTimeFormat(locales, options) { + if (!new.target) return new DateTimeFormat(locales, options); + define(this, '__zone', resolveZone(options)); + } + define(DateTimeFormat.prototype, 'resolvedOptions', function () { + return { + locale: 'en-US', + calendar: 'gregory', + numberingSystem: 'latn', + timeZone: this.__zone === undefined ? zoneOf() : this.__zone, + }; + }); + const Intl = {}; + define(Intl, 'DateTimeFormat', DateTimeFormat); + define(globalThis, 'Intl', Intl); + } + globalThis.__zenPinned = true; +})(); diff --git a/core/engine/src/compiled/pinning.rs b/core/engine/src/compiled/pinning.rs new file mode 100644 index 00000000..d5b4f8b7 --- /dev/null +++ b/core/engine/src/compiled/pinning.rs @@ -0,0 +1,181 @@ +use chrono::{DateTime, Duration, LocalResult, Offset, TimeZone}; +use rquickjs::prelude::Func; +use std::cell::RefCell; +use std::rc::Rc; +use zen_expression::context::{ + location, parse_timezone, system_now, system_timezone, EvaluationContext, Pinned, Site, + Timezone, +}; + +pub(crate) fn single(pinned: Pinned) -> EvaluationContext { + EvaluationContext::new(pinned) +} + +pub(crate) fn batch(pinned: Pinned) -> EvaluationContext { + EvaluationContext::batch(pinned) +} + +pub(crate) struct Located; + +impl Located { + pub(crate) fn expression(node: &str, key: &str) -> u64 { + location(&["expression", node, key]) + } + + pub(crate) fn input(node: &str) -> u64 { + location(&["input", node]) + } + + pub(crate) fn statement(node: &str, statement: &str) -> u64 { + location(&["switch", node, statement]) + } + + pub(crate) fn cell(node: &str, rule: &str, column: &str) -> u64 { + location(&["cell", node, rule, column]) + } + + pub(crate) fn field(node: &str, column: &str) -> u64 { + location(&["field", node, column]) + } + + pub(crate) fn function(node: &str) -> u64 { + location(&["function", node]) + } + + pub(crate) fn decision(node: &str, key: &str) -> u64 { + location(&["decision", node, key]) + } + + pub(crate) fn block(block: &str) -> u64 { + location(&["block", block]) + } + + pub(crate) fn condition(block: &str, condition: &str) -> u64 { + location(&["condition", block, condition]) + } + + pub(crate) fn arm(block: &str, arm: &str) -> u64 { + location(&["arm", block, arm]) + } + + pub(crate) fn value(block: &str, arm: &str) -> u64 { + location(&["value", block, arm]) + } +} + +const PIN_JS: &str = include_str!("pinning.js"); + +#[derive(Debug, Clone, Default)] +pub(crate) struct JsSlot(Rc>>); + +pub(crate) struct Entered { + slot: JsSlot, + previous: Option, +} + +impl Drop for Entered { + fn drop(&mut self) { + *self.slot.0.borrow_mut() = self.previous.take(); + } +} + +impl JsSlot { + pub(crate) fn enter(&self, context: EvaluationContext) -> Entered { + Entered { + slot: self.clone(), + previous: self.0.borrow_mut().replace(context), + } + } + + pub(crate) fn current(&self) -> Option { + self.0.borrow().clone() + } + + fn now(&self) -> f64 { + let now = match self.0.borrow().as_ref() { + Some(context) => context.now(), + None => system_now(), + }; + now.timestamp_millis() as f64 + } + + fn random(&self) -> f64 { + match self.0.borrow().as_ref() { + Some(context) => context.random_f64(0, Site::SCRIPT), + None => EvaluationContext::default().random_f64(0, Site::SCRIPT), + } + } + + fn timezone(&self) -> Timezone { + match self.0.borrow().as_ref() { + Some(context) => context.timezone(), + None => system_timezone(), + } + } + + fn zone(&self, name: Option) -> Option { + match name { + Some(name) => parse_timezone(&name), + None => Some(self.timezone()), + } + } + + fn offset(&self, ms: f64, name: Option) -> Option { + let zone = self.zone(name)?; + if !ms.is_finite() { + return None; + } + let at = DateTime::from_timestamp_millis(ms as i64)?.naive_utc(); + let seconds = zone.offset_from_utc_datetime(&at).fix().local_minus_utc(); + Some(seconds as f64 / 60.0) + } + + fn utc(&self, local: f64, name: Option) -> Option { + let zone = self.zone(name)?; + if !local.is_finite() { + return None; + } + let naive = DateTime::from_timestamp_millis(local as i64)?.naive_utc(); + let offset = match zone.offset_from_local_datetime(&naive) { + LocalResult::Single(offset) => offset.fix(), + LocalResult::Ambiguous(earlier, _) => earlier.fix(), + LocalResult::None => zone + .offset_from_local_datetime(&(naive - Duration::hours(3))) + .earliest()? + .fix(), + }; + let utc = naive - Duration::seconds(offset.local_minus_utc() as i64); + Some(utc.and_utc().timestamp_millis() as f64) + } + + pub(crate) fn install(&self, ctx: &rquickjs::Ctx<'_>) -> rquickjs::Result<()> { + let globals = ctx.globals(); + if globals.get::<_, bool>("__zenPinned").unwrap_or(false) { + return Ok(()); + } + let slot = self.clone(); + globals.set("__zenNow", Func::from(move || slot.now()))?; + let slot = self.clone(); + globals.set("__zenRandom", Func::from(move || slot.random()))?; + let slot = self.clone(); + globals.set( + "__zenOffset", + Func::from(move |ms: f64, zone: Option| slot.offset(ms, zone)), + )?; + let slot = self.clone(); + globals.set( + "__zenUtc", + Func::from(move |local: f64, zone: Option| slot.utc(local, zone)), + )?; + let slot = self.clone(); + globals.set( + "__zenZone", + Func::from(move || slot.timezone().name().to_string()), + )?; + globals.set( + "__zenCanonicalZone", + Func::from(|name: String| parse_timezone(&name).map(|zone| zone.name().to_string())), + )?; + ctx.eval::<(), _>(PIN_JS) + } +} diff --git a/core/engine/src/compiled/policy/artifact.rs b/core/engine/src/compiled/policy/artifact.rs index 430523e7..111aa923 100644 --- a/core/engine/src/compiled/policy/artifact.rs +++ b/core/engine/src/compiled/policy/artifact.rs @@ -4,6 +4,7 @@ use crate::compiled::policy::{Host, PolicyPlan}; use crate::policy::evaluator::EvalArtifact; use std::ops::Deref; use std::sync::{Arc, Mutex, OnceLock}; +use zen_expression::context::EvaluationContext; use ahash::{HashMap, HashMapExt, HashSet, HashSetExt}; use zen_expression::variable::Variable; @@ -303,6 +304,7 @@ impl Runtime { db: &Db, artifacts: &Artifacts, req: &EvaluateRequest, + context: &EvaluationContext, ) -> Result { if db.is_graph(&req.policy_path) { return Err(EvaluationError::GraphNotEvaluable(req.policy_path.clone())); @@ -311,13 +313,16 @@ impl Runtime { return Err(EvaluationError::PolicyNotFound(req.policy_path.clone())); } Self::check_imports_resolved(db, &req.policy_path)?; - artifacts.get(db, &req.policy_path).evaluate(req, false) + artifacts + .get(db, &req.policy_path) + .evaluate(req, false, context) } pub(crate) fn enhance_trace( db: &Db, artifacts: &Artifacts, req: &EvaluateRequest, + context: &EvaluationContext, ) -> Result { if db.is_graph(&req.policy_path) { return Err(EvaluationError::GraphNotEvaluable(req.policy_path.clone())); @@ -328,7 +333,9 @@ impl Runtime { Self::check_imports_resolved(db, &req.policy_path)?; let mut req = req.clone(); req.trace = true; - artifacts.get(db, &req.policy_path).evaluate(&req, true) + artifacts + .get(db, &req.policy_path) + .evaluate(&req, true, context) } pub(crate) fn evaluate_columns<'a>( @@ -337,6 +344,7 @@ impl Runtime { policy_path: &Arc, goals: &[Arc], columns: &'a zen_expression::lane::Columns<'a>, + context: &EvaluationContext, ) -> Result, EvaluationError> { let probe = EvaluateRequest { policy_path: policy_path.clone(), @@ -348,13 +356,14 @@ impl Runtime { let artifact = artifacts.get(db, policy_path); Ok(artifact .plan(goals) - .evaluate_columns(&artifact, policy_path, goals, columns)) + .evaluate_columns(&artifact, policy_path, goals, columns, context)) } pub(crate) fn evaluate_batch( db: &Db, artifacts: &Artifacts, requests: &[EvaluateRequest], + context: &EvaluationContext, ) -> Vec> { let mut results: Vec>> = (0..requests.len()).map(|_| None).collect(); @@ -372,7 +381,8 @@ impl Runtime { let artifact = artifacts.get(db, &path); let batch: Vec = members.iter().map(|&i| requests[i].clone()).collect(); - for (index, result) in members.into_iter().zip(artifact.evaluate_batch(&batch)) { + let evaluated = artifact.evaluate_batch(&batch, &context.rows(&members)); + for (index, result) in members.into_iter().zip(evaluated) { results[index] = Some(result); } } @@ -423,6 +433,7 @@ impl Artifact { key: &str, input: Variable, trace: bool, + context: &EvaluationContext, ) -> Result { let request = EvaluateRequest { policy_path: Arc::from(key), @@ -430,21 +441,25 @@ impl Artifact { goals: Vec::new(), trace, }; - self.evaluate(&request, false) + self.evaluate(&request, false, context) } pub(crate) fn evaluate( &self, req: &EvaluateRequest, extras: bool, + context: &EvaluationContext, ) -> Result { let plan = self.plan(&req.goals); if !req.trace && !extras { - if let Some(result) = plan.evaluate(self, std::slice::from_ref(req)).pop() { + if let Some(result) = plan + .evaluate(self, std::slice::from_ref(req), context) + .pop() + { return result; } } - plan.traced(self, req, extras) + plan.traced(self, req, extras, context) } const GOAL_PLANS: usize = 32; @@ -482,6 +497,7 @@ impl Artifact { pub(crate) fn evaluate_batch( &self, requests: &[EvaluateRequest], + context: &EvaluationContext, ) -> Vec> { let owned: Vec = requests .iter() @@ -497,7 +513,12 @@ impl Artifact { for (index, request) in requests.iter().enumerate() { match request.trace { true => { - results[index] = Some(self.plan(&request.goals).traced(self, request, false)) + results[index] = Some(self.plan(&request.goals).traced( + self, + request, + false, + &context.at(index), + )) } false => match groups .iter_mut() @@ -511,10 +532,10 @@ impl Artifact { for (goals, members) in groups { let batch: Vec = members.iter().map(|&i| requests[i].clone()).collect(); - for (index, result) in members - .into_iter() - .zip(self.plan(goals).evaluate(self, &batch)) - { + let evaluated = self + .plan(goals) + .evaluate(self, &batch, &context.rows(&members)); + for (index, result) in members.into_iter().zip(evaluated) { results[index] = Some(result); } } diff --git a/core/engine/src/compiled/policy/columnar/evaluate.rs b/core/engine/src/compiled/policy/columnar/evaluate.rs index a065f8d8..07958301 100644 --- a/core/engine/src/compiled/policy/columnar/evaluate.rs +++ b/core/engine/src/compiled/policy/columnar/evaluate.rs @@ -9,6 +9,7 @@ use crate::compiled::ColumnarOutput; use crate::workspace::types::{EvaluateRequest, EvaluationError}; use std::cell::{OnceCell, RefCell}; use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{Columns, Kind as LaneKind, LaneProgram}; use zen_expression::Variable; use zen_types::path::DotPath; @@ -190,6 +191,7 @@ impl PolicyPlan { policy_path: &Arc, goals: &[Arc], columns: &'a Columns<'a>, + context: &EvaluationContext, ) -> ColumnarOutput<'a> { let rows = columns.rows; let request = |row: usize| EvaluateRequest { @@ -201,7 +203,7 @@ impl PolicyPlan { let sheet = Sheet::new(columns); let Some(mut sheet) = sheet else { let requests: Vec = (0..rows).map(request).collect(); - return from_results(rows, self.evaluate(artifact, &requests)); + return from_results(rows, self.evaluate(artifact, &requests, context)); }; let mut errors: Vec> = (0..rows).map(|_| None).collect(); let stores: Vec> = (0..rows).map(|_| OnceCell::new()).collect(); @@ -277,6 +279,7 @@ impl PolicyPlan { arms: ByBlock::default(), stores: &stores, state: Rows { + context: context.clone(), hosts: Vec::new(), picks: Vec::new(), failures: errors, @@ -367,7 +370,9 @@ impl PolicyPlan { _ => shredder.visit(&sheet.object(row), 0, row), } } - for (&row, result) in hosted.iter().zip(self.evaluate(artifact, &requests)) { + context.restart(&hosted); + let evaluated = self.evaluate(artifact, &requests, &context.rows(&hosted)); + for (&row, result) in hosted.iter().zip(evaluated) { match result { Ok(result) => shredder.visit(&result.output, 0, row), Err(error) => errors[row] = Some(error), diff --git a/core/engine/src/compiled/policy/columnar/host.rs b/core/engine/src/compiled/policy/columnar/host.rs index 39da54a3..30bc1317 100644 --- a/core/engine/src/compiled/policy/columnar/host.rs +++ b/core/engine/src/compiled/policy/columnar/host.rs @@ -20,6 +20,7 @@ impl<'s, 'a> Pass<'s, 'a> { false, false, &self.plan.programs, + self.state.context.at(row), )); self.synced[row] = match prepared { true => self.base, diff --git a/core/engine/src/compiled/policy/columnar/lane.rs b/core/engine/src/compiled/policy/columnar/lane.rs index d62734c8..dd9dc676 100644 --- a/core/engine/src/compiled/policy/columnar/lane.rs +++ b/core/engine/src/compiled/policy/columnar/lane.rs @@ -49,8 +49,12 @@ impl<'s, 'a> Pass<'s, 'a> { if p.writes_env || p.chain || p.opaque() || p.rows { let scopes: Vec = positions.iter().map(|&row| self.scope(row)).collect(); let mut values = vec![Variable::Null; positions.len()]; + let context = match p.draws { + true => self.state.context.rows(positions), + false => self.state.context.clone(), + }; self.runner - .evaluate_with(program, &scopes, |at, result| match result { + .evaluate_with(program, &context, &scopes, |at, result| match result { Ok(value) => values[at] = value, Err(_) => failed[at] = true, }); @@ -211,6 +215,7 @@ impl<'s, 'a> Pass<'s, 'a> { Self::prefer_codes(program, &mut outs); self.runner.evaluate_sites( program, + &self.state.context, scopes.slice(), &columns, &bound, diff --git a/core/engine/src/compiled/policy/columnar/member.rs b/core/engine/src/compiled/policy/columnar/member.rs index 6a9051dd..80ab2f32 100644 --- a/core/engine/src/compiled/policy/columnar/member.rs +++ b/core/engine/src/compiled/policy/columnar/member.rs @@ -284,8 +284,13 @@ impl<'s, 'a> Pass<'s, 'a> { let special = self.plan.special(program, &columns); let program = special.as_deref().unwrap_or(program); Self::prefer_codes(program, &mut outs); + let context = match program.program().draws { + true => self.state.context.rows(parents), + false => self.state.context.clone(), + }; self.runner.evaluate_sites( program, + &context, scopes.slice(), &columns, &bound, diff --git a/core/engine/src/compiled/policy/columnar/table.rs b/core/engine/src/compiled/policy/columnar/table.rs index 77317959..4a13fef3 100644 --- a/core/engine/src/compiled/policy/columnar/table.rs +++ b/core/engine/src/compiled/policy/columnar/table.rs @@ -17,7 +17,13 @@ impl<'s, 'a> Pass<'s, 'a> { Some(leaf) => leaf, None => self.evaluate(units, field), }; - table.matched(self.runner, input, &leaf, &mut matching); + table.matched( + self.runner, + &self.state.context, + input, + &leaf, + &mut matching, + ); } let Matching { all, host, .. } = matching; let outputs = table.picked().len(); diff --git a/core/engine/src/compiled/policy/columnar/typed.rs b/core/engine/src/compiled/policy/columnar/typed.rs index 443f2ae9..72cd9fbd 100644 --- a/core/engine/src/compiled/policy/columnar/typed.rs +++ b/core/engine/src/compiled/policy/columnar/typed.rs @@ -444,7 +444,14 @@ impl<'s, 'a> Pass<'s, 'a> { }) .collect::>()?; let positions: Option> = (!full).then(|| rows.into()); - Dedup::coded(program, &leaves, &codes, positions.as_ref(), total) + Dedup::coded( + program, + &leaves, + &codes, + positions.as_ref(), + total, + &self.state.context, + ) } fn execute( @@ -508,7 +515,7 @@ impl<'s, 'a> Pass<'s, 'a> { .collect(), select, }; - call.run(program) + call.run(program, &self.state.context) } fn listing( diff --git a/core/engine/src/compiled/policy/host.rs b/core/engine/src/compiled/policy/host.rs index 325a710b..b3c9be13 100644 --- a/core/engine/src/compiled/policy/host.rs +++ b/core/engine/src/compiled/policy/host.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{Programs, Session}; use zen_expression::variable::Variable; use zen_expression::ExpressionKind; @@ -23,10 +24,13 @@ impl<'a> Host<'a> { trace: bool, extras: bool, programs: &Arc, + context: EvaluationContext, ) -> Self { Self { state: HostState::new(artifact, store, entry, trace, extras), - session: Session::new().with_programs(Some(programs.clone())), + session: Session::new() + .with_programs(Some(programs.clone())) + .with_context(context), } } diff --git a/core/engine/src/compiled/policy/mod.rs b/core/engine/src/compiled/policy/mod.rs index 9deaa5e2..9defaa72 100644 --- a/core/engine/src/compiled/policy/mod.rs +++ b/core/engine/src/compiled/policy/mod.rs @@ -12,6 +12,7 @@ pub(crate) use host::Host; use crate::compiled::core::special::Specialized; use crate::compiled::leaf::Literal; +use crate::compiled::pinning::Located; use crate::compiled::policy::artifact::{Artifact as EvalArtifact, Iteration}; use crate::compiled::policy::blocks::MatchSelection; use crate::compiled::policy::site::{HostState, InstanceSlot, Iterated, Pick, Picked}; @@ -24,9 +25,10 @@ use schedule::{Blocks, Demand, End, Event, Replay, Segment}; use std::cell::RefCell; use std::sync::Arc; use std::time::Instant; +use zen_expression::context::EvaluationContext; use zen_expression::lane::SourceInfo; use zen_expression::lane::{LaneProgram, LaneRunner, Programs}; -use zen_expression::{Scope, Variable}; +use zen_expression::{ExpressionKind, Scope, Variable}; use zen_types::path::DotPath; enum Native { @@ -65,18 +67,22 @@ impl std::fmt::Display for Refused { } impl Native { - fn program(source: &str) -> Result { - LaneProgram::standard(source).map_err(|e| Refused::Compile(Arc::from(e.to_string()))) + fn program(source: &str, label: u64) -> Result { + LaneProgram::located(source, ExpressionKind::Standard, label) + .map_err(|e| Refused::Compile(Arc::from(e.to_string()))) } - fn optional(source: &str) -> Result, Refused> { + fn optional(source: &str, label: u64) -> Result, Refused> { match source.is_empty() { true => Ok(None), - false => Self::program(source).map(Some), + false => Self::program(source, label).map(Some), } } fn pick(ir: &MatchIr) -> Option> { + if ir.arms.iter().any(|arm| SourceInfo::draws(&arm.condition)) { + return None; + } let mut source = String::new(); let mut open = 0usize; let mut tail = String::from("null"); @@ -93,10 +99,11 @@ impl Native { LaneProgram::standard(&source).ok().map(Box::new) } - fn compile(kind: &BlockKind) -> Result { - match kind { + fn compile(block: &Block) -> Result { + let id = &block.id; + match &block.kind { BlockKind::Expression(ir) if !ir.key.is_empty() && !ir.value.is_empty() => { - Self::program(&ir.value).map(|program| Native::Expression { + Self::program(&ir.value, Located::block(id)).map(|program| Native::Expression { key: ir.key.clone(), program: Box::new(program), }) @@ -106,14 +113,14 @@ impl Native { conditions: ir .conditions .iter() - .map(|c| Self::program(&c.expression)) + .map(|c| Self::program(&c.expression, Located::condition(id, &c.id))) .collect::, _>>()?, }), BlockKind::Match(ir) => { let values = ir .arms .iter() - .map(|arm| Self::optional(&arm.value)) + .map(|arm| Self::optional(&arm.value, Located::value(id, &arm.id))) .collect::, _>>()?; let mut runner = LaneRunner::new(); let constants = values @@ -125,7 +132,7 @@ impl Native { conditions: ir .arms .iter() - .map(|arm| Self::optional(&arm.condition)) + .map(|arm| Self::optional(&arm.condition, Located::arm(id, &arm.id))) .collect::, _>>()?, values, pick: Self::pick(ir), @@ -191,6 +198,7 @@ pub(crate) struct PolicyPlan { } struct Rows<'a> { + context: EvaluationContext, hosts: Vec>>, picks: Vec>, failures: Vec>, @@ -250,9 +258,9 @@ impl PolicyPlan { .map(|(rule, owner)| { let iteration = artifact.iteration(rule); let (native, iterated) = match &iteration { - None => (Native::compile(&rule.kind), false), + None => (Native::compile(rule), false), Some((_, path, _)) if Self::lane_safe(artifact, owner, rule, path) => { - (Native::compile(&rule.kind), true) + (Native::compile(rule), true) } Some(_) => (Err(Refused::Iterated), false), }; @@ -260,12 +268,12 @@ impl PolicyPlan { native, iterated, table: match &rule.kind { - BlockKind::DecisionTable(ir) => Table::compile(TableIr::policy(ir)).ok(), + BlockKind::DecisionTable(ir) if !ir.draws() => { + Table::compile(TableIr::policy(ir)).ok() + } _ => None, }, - member: iteration - .as_ref() - .and_then(|_| Native::compile(&rule.kind).ok()), + member: iteration.as_ref().and_then(|_| Native::compile(rule).ok()), iteration, } }) @@ -374,6 +382,7 @@ impl PolicyPlan { &self, artifact: &EvalArtifact, requests: &[EvaluateRequest], + context: &EvaluationContext, ) -> Vec> { let start = Instant::now(); let count = requests.len(); @@ -390,10 +399,12 @@ impl PolicyPlan { }) .collect(); let mut state = Rows { + context: context.clone(), hosts: stores .iter() .zip(requests) - .map(|(store, request)| { + .enumerate() + .map(|(row, (store, request))| { store.as_ref().map(|store| { Host::new( artifact, @@ -402,6 +413,7 @@ impl PolicyPlan { false, false, &self.programs, + context.at(row), ) }) }) @@ -551,15 +563,36 @@ impl PolicyPlan { .unzip() } - fn run( + fn drawn( + context: &EvaluationContext, program: &LaneProgram, - scopes: &[Scope], - sink: impl FnMut(usize, Result), - ) { - Self::RUNNER.with_borrow_mut(|runner| runner.evaluate_with(program, scopes, sink)); + rows: &[usize], + ) -> EvaluationContext { + match program.program().draws { + true => context.rows(rows), + false => context.clone(), + } } - fn arms(ir: &MatchIr, conditions: &[Option], scopes: Vec) -> Vec { + fn run( + context: &EvaluationContext, + program: &LaneProgram, + scopes: &[Scope], + rows: &[usize], + sink: impl FnMut(usize, Result), + ) { + let context = Self::drawn(context, program, rows); + Self::RUNNER + .with_borrow_mut(|runner| runner.evaluate_with(program, &context, scopes, sink)); + } + + fn arms( + context: &EvaluationContext, + ir: &MatchIr, + conditions: &[Option], + scopes: Vec, + rows: &[usize], + ) -> Vec { let mut outcome: Vec> = (0..scopes.len()).map(|_| None).collect(); let mut open: Vec = (0..scopes.len()).collect(); let mut scopes = scopes; @@ -574,7 +607,8 @@ impl PolicyPlan { break; }; let mut hit = vec![None; open.len()]; - Self::run(program, &scopes, |i, result| { + let at: Vec = open.iter().map(|&lane| rows[lane]).collect(); + Self::run(context, program, &scopes, &at, |i, result| { hit[i] = Some(result.map(|v| v.as_bool().unwrap_or(false)).ok()) }); let mut next_open = Vec::with_capacity(open.len()); @@ -614,7 +648,8 @@ impl PolicyPlan { ) -> Vec { let (live, scopes) = Self::scopes(rows, state); let mut delegated = Vec::new(); - for (row, arm) in live.into_iter().zip(Self::arms(ir, conditions, scopes)) { + let arms = Self::arms(&state.context, ir, conditions, scopes, &live); + for (row, arm) in live.into_iter().zip(arms) { match arm { Arm::Failed => delegated.push(row), Arm::Matched(matched_arm) => { @@ -684,7 +719,8 @@ impl PolicyPlan { .iter() .map(|l| Scope::new(l.root.shallow_clone())) .collect(); - let arms = Self::arms(ir, conditions, scopes); + let owners: Vec = lanes.iter().map(|l| captured[l.owner].row).collect(); + let arms = Self::arms(&state.context, ir, conditions, scopes, &owners); let mut delegated = Vec::new(); for Capture { row, @@ -727,21 +763,25 @@ impl PolicyPlan { .iter() .map(|l| Scope::new(l.root.shallow_clone())) .collect(); + let owners: Vec = lanes.iter().map(|l| captured[l.owner].row).collect(); + let context = state.context.clone(); let mut writes: Vec>> = (0..lanes.len()).map(|_| None).collect(); match native { - Native::Expression { key, program } => Self::run(program, &scopes, |i, result| { - writes[i] = result.ok().map(|value| { - Some(Write { - path: key.clone(), - value, + Native::Expression { key, program } => { + Self::run(&context, program, &scopes, &owners, |i, result| { + writes[i] = result.ok().map(|value| { + Some(Write { + path: key.clone(), + value, + }) }) }) - }), + } Native::Assertion { ir, conditions } => { let mut results: Vec>> = (0..lanes.len()).map(|_| Some(Vec::new())).collect(); for program in conditions { - Self::run(program, &scopes, |i, result| { + Self::run(&context, program, &scopes, &owners, |i, result| { match (result, &mut results[i]) { (Ok(value), Some(r)) => r.push(value.as_bool().unwrap_or(false)), _ => results[i] = None, @@ -788,7 +828,8 @@ impl PolicyPlan { continue; }; let subset: Vec = members.iter().map(|&i| scopes[i].clone()).collect(); - Self::run(program, &subset, |j, result| { + let at: Vec = members.iter().map(|&i| owners[i]).collect(); + Self::run(&context, program, &subset, &at, |j, result| { writes[members[j]] = result .ok() .map(|value| key.clone().map(|path| Write { path, value })) @@ -809,8 +850,8 @@ impl PolicyPlan { true => delegated.push(row), false => { if let Some(host) = state.hosts[row].as_mut() { - if let Err(error) = host.commit(owner, rule, Picked::Iterated(iterated)) - { + let committed = host.commit(owner, rule, Picked::Iterated(iterated)); + if let Err(error) = committed { state.failures[row] = Some(error); } } @@ -866,7 +907,9 @@ impl PolicyPlan { }; let (live, scopes) = Self::scopes(&members, state); let mut results: Vec> = vec![None; live.len()]; - Self::run(program, &scopes, |i, result| results[i] = result.ok()); + Self::run(&state.context, program, &scopes, &live, |i, result| { + results[i] = result.ok() + }); for (row, result) in live.into_iter().zip(results) { match result { Some(value) => { @@ -893,10 +936,16 @@ impl PolicyPlan { let mut results: Vec> = vec![Vec::with_capacity(conditions.len()); live.len()]; let mut failed = vec![false; live.len()]; for program in conditions { - Self::run(program, &scopes, |i, result| match result { - Ok(value) => results[i].push(value.as_bool().unwrap_or(false)), - Err(_) => failed[i] = true, - }); + Self::run( + &state.context, + program, + &scopes, + &live, + |i, result| match result { + Ok(value) => results[i].push(value.as_bool().unwrap_or(false)), + Err(_) => failed[i] = true, + }, + ); } let mut delegated = Vec::new(); for (i, row) in live.into_iter().enumerate() { @@ -921,8 +970,9 @@ impl PolicyPlan { ) -> Vec { let (live, scopes) = Self::scopes(rows, state); let mut delegated = Vec::new(); + let context = Self::drawn(&state.context, program, &live); Self::RUNNER.with_borrow_mut(|runner| { - runner.evaluate_with(program, &scopes, |i, result| { + runner.evaluate_with(program, &context, &scopes, |i, result| { let row = live[i]; match (result, state.hosts[row].as_ref()) { (Ok(value), Some(host)) => host.state.write(key, value), diff --git a/core/engine/src/compiled/policy/traced.rs b/core/engine/src/compiled/policy/traced.rs index 9e2aa7f0..fc1d6b65 100644 --- a/core/engine/src/compiled/policy/traced.rs +++ b/core/engine/src/compiled/policy/traced.rs @@ -13,6 +13,7 @@ impl PolicyPlan { artifact: &EvalArtifact, req: &EvaluateRequest, extras: bool, + context: &zen_expression::context::EvaluationContext, ) -> Result { let start = Instant::now(); let (store, order_to_run) = artifact.prepare(req)?; @@ -23,6 +24,7 @@ impl PolicyPlan { req.trace, extras, &self.programs, + context.clone(), ); let outcome = self.replay(artifact, &mut host); diff --git a/core/engine/src/compiled/table/cells.rs b/core/engine/src/compiled/table/cells.rs index e34d5bc9..2cbf4557 100644 --- a/core/engine/src/compiled/table/cells.rs +++ b/core/engine/src/compiled/table/cells.rs @@ -35,7 +35,11 @@ impl<'c> OutputCells<'c> { let p = program.program(); match p.site_keys.is_empty() && p.timeless() && !p.opaque() { true => LaneRunner::new() - .evaluate_one(&program, &zen_expression::Scope::default()) + .evaluate_one( + &program, + &zen_expression::context::EvaluationContext::default(), + &zen_expression::Scope::default(), + ) .ok(), false => None, } diff --git a/core/engine/src/compiled/table/dispatch.rs b/core/engine/src/compiled/table/dispatch.rs index 05aacfe6..bd86bb88 100644 --- a/core/engine/src/compiled/table/dispatch.rs +++ b/core/engine/src/compiled/table/dispatch.rs @@ -98,7 +98,7 @@ impl Table { let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); let view = direct.or_else(|| typed.as_ref().map(Array::column)); match view { - Some(view) => cells.classify(p, &view, rows, &mut pieces), + Some(view) => cells.classify(p, &view, rows, &mut pieces, bound.context.timezone()), None => pieces.iter_mut().for_each(|x| *x = p.failed), } let stride = *stride as u32; @@ -163,7 +163,7 @@ impl Table { let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); let view = direct.or_else(|| typed.as_ref().map(Array::column)); match view { - Some(view) => cells.classify(p, &view, rows, &mut pieces), + Some(view) => cells.classify(p, &view, rows, &mut pieces, bound.context.timezone()), None => pieces.iter_mut().for_each(|x| *x = p.failed), } for (piece, failed) in pieces.iter_mut().zip(&failed) { diff --git a/core/engine/src/compiled/table/mod.rs b/core/engine/src/compiled/table/mod.rs index c83b4864..7b28d478 100644 --- a/core/engine/src/compiled/table/mod.rs +++ b/core/engine/src/compiled/table/mod.rs @@ -650,7 +650,7 @@ impl Table { let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); let column = direct.or_else(|| typed.as_ref().map(Array::column)); if let (Some(truths), Some(view), true) = (&fused, direct, self.fuses(index)) { - cells.indexed_column(&view, rows, &mut bits); + cells.indexed_column(&view, rows, &mut bits, bound.context.timezone()); for other in 0..cells.others() { let (Some((_, rules)), Some(truth)) = ( cells.other(other), @@ -674,7 +674,7 @@ impl Table { let peeled = cells.others() > 0 && cells.peelable() && column.is_some_and(|column| { - Self::peeled(runner, cells, &column, rows, &mut bits) + Self::peeled(runner, &bound.context, cells, &column, rows, &mut bits) }); match ( lazy && !peeled, @@ -684,13 +684,21 @@ impl Table { ) { _ if peeled => {} (_, false, Some(column), _) => { - cells.indexed_column(&column, rows, &mut bits) - } - (true, true, Some(column), _) => { - cells.evaluate_indexed_column(&column, rows, &mut bits) + cells.indexed_column(&column, rows, &mut bits, bound.context.timezone()) } + (true, true, Some(column), _) => cells.evaluate_indexed_column( + &column, + rows, + &mut bits, + bound.context.timezone(), + ), (false, true, Some(column), Some(reference)) => { - cells.indexed_column(&column, rows, &mut bits); + cells.indexed_column( + &column, + rows, + &mut bits, + bound.context.timezone(), + ); for other in 0..cells.others() { let Some((_, rules)) = cells.other(other) else { continue; @@ -723,6 +731,7 @@ impl Table { } _ => { let env = CellEnv { + context: &bound.context, scopes, columns: &bound.columns, bind: &*bound.bind, @@ -837,6 +846,7 @@ impl Table { fn peeled( runner: &mut LaneRunner, + context: &zen_expression::context::EvaluationContext, cells: &CellSet, column: &LaneColumn, rows: usize, @@ -916,6 +926,7 @@ impl Table { let scopes = Bound::blank(values.len()); let columns = zen_expression::lane::Columns::new(values.len()); let env = CellEnv { + context, scopes: scopes.slice(), columns: &columns, bind: &|_| Binding::Row, @@ -976,6 +987,7 @@ impl Table { ), (false, None) => { let env = CellEnv { + context: &bound.context, scopes: bound.scopes(), columns: &bound.columns, bind: &*bound.bind, diff --git a/core/engine/src/compiled/table/strict.rs b/core/engine/src/compiled/table/strict.rs index dd246cb2..3557221d 100644 --- a/core/engine/src/compiled/table/strict.rs +++ b/core/engine/src/compiled/table/strict.rs @@ -123,6 +123,7 @@ impl Table { pub fn matched( &self, runner: &mut LaneRunner, + context: &zen_expression::context::EvaluationContext, input: usize, leaf: &Leaf, matching: &mut Matching, @@ -148,9 +149,10 @@ impl Table { } } } - cells.indexed_column(&column, count, bits); + cells.indexed_column(&column, count, bits, context.timezone()); let columns = Columns::new(count); let env = CellEnv { + context, scopes: &[], columns: &columns, bind: &|_| Binding::Row, diff --git a/core/engine/src/decision.rs b/core/engine/src/decision.rs index d9560e7b..945bf5ea 100644 --- a/core/engine/src/decision.rs +++ b/core/engine/src/decision.rs @@ -1,5 +1,5 @@ use crate::decision_graph::graph::{DecisionGraph, DecisionGraphConfig, DecisionGraphResponse}; -use crate::engine::{EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind}; +use crate::engine::{EvaluationOptions, EvaluationSerializedOptions}; use crate::loader::{DynamicLoader, NoopLoader}; use crate::model::GraphContent; use crate::nodes::custom::{DynamicCustomNode, NoopCustomNode}; @@ -82,7 +82,7 @@ impl Decision { options: EvaluationOptions, ) -> Result> { if self.engine.compiled() { - return self.compiled().evaluate_with_opts(context, options).await; + return self.compiled().evaluate_pinned(context, options).await; } let mut decision_graph = DecisionGraph::try_new(DecisionGraphConfig { content: self.content.clone(), @@ -112,13 +112,7 @@ impl Decision { options: EvaluationSerializedOptions, ) -> Result { let response = self - .evaluate_with_opts( - context, - EvaluationOptions { - trace: options.trace != EvaluationTraceKind::None, - max_depth: options.max_depth, - }, - ) + .evaluate_with_opts(context, options.unserialized()) .await; match response { @@ -157,7 +151,9 @@ impl Decision { contexts: &[Variable], options: EvaluationOptions, ) -> Vec>> { - self.compiled().evaluate_batch(contexts, options).await + self.compiled() + .evaluate_batch_pinned(contexts, options) + .await } pub async fn evaluate_columns<'a>( @@ -165,7 +161,9 @@ impl Decision { columns: &'a crate::columns::Columns<'a>, options: EvaluationOptions, ) -> crate::ColumnarOutput<'a> { - self.compiled().evaluate_columns(columns, options).await + self.compiled() + .evaluate_columns_pinned(columns, options) + .await } pub(crate) fn with_engine(mut self, engine: crate::compiled::Engine) -> Self { diff --git a/core/engine/src/engine.rs b/core/engine/src/engine.rs index a67029d1..04c73658 100644 --- a/core/engine/src/engine.rs +++ b/core/engine/src/engine.rs @@ -36,10 +36,31 @@ impl Debug for DecisionEngine { } } +/// Options for one evaluation. +/// +/// `now`, `timezone` and `seed` pin the evaluation context of the compiled engine: +/// `d()`, `rand()` and the date helpers in expressions, and `Date`, `Math.random` and local time +/// in function nodes read them instead of the host clock, zone and +/// random source. Each one left `None` is resolved lazily: `now` from the host clock once per +/// evaluation (once per batch), `timezone` from the host zone and `seed` at random on the first +/// draw. In a batch, row `i` draws from its own stream seeded with +/// `zen_engine::context::row_seed(seed, i)`, so it replays alone with that seed. +/// +/// The interpreted engine (`compiled: false`) ignores these three fields and keeps using the host +/// clock, the host zone and an unseeded random source. +/// +/// Outbound HTTP from function nodes is not captured by the context, so replaying a graph that +/// makes such calls is not guaranteed to reproduce its result. #[derive(Debug, Clone, Copy)] pub struct EvaluationOptions { pub trace: bool, pub max_depth: u8, + /// Instant the evaluation runs at. + pub now: Option, + /// IANA time zone for local dates, e.g. `Europe/Berlin`. + pub timezone: Option, + /// Seed of the random streams. + pub seed: Option, } impl Default for EvaluationOptions { @@ -47,14 +68,24 @@ impl Default for EvaluationOptions { Self { trace: false, max_depth: 10, + now: None, + timezone: None, + seed: None, } } } +/// [`EvaluationOptions`] with a serialized trace; the context fields behave the same. #[derive(Debug, Clone, Copy)] pub struct EvaluationSerializedOptions { pub trace: EvaluationTraceKind, pub max_depth: u8, + /// Instant the evaluation runs at. + pub now: Option, + /// IANA time zone for local dates, e.g. `Europe/Berlin`. + pub timezone: Option, + /// Seed of the random streams. + pub seed: Option, } impl Default for EvaluationSerializedOptions { @@ -62,6 +93,9 @@ impl Default for EvaluationSerializedOptions { Self { trace: EvaluationTraceKind::None, max_depth: 10, + now: None, + timezone: None, + seed: None, } } } @@ -95,6 +129,32 @@ impl EvaluationTraceKind { } } +impl EvaluationOptions { + pub(crate) fn pinned(&self) -> zen_expression::context::Pinned { + zen_expression::context::Pinned { + now: self.now, + timezone: self.timezone, + seed: self.seed, + } + } +} + +impl EvaluationSerializedOptions { + pub(crate) fn pinned(&self) -> zen_expression::context::Pinned { + self.unserialized().pinned() + } + + pub(crate) fn unserialized(&self) -> EvaluationOptions { + EvaluationOptions { + trace: self.trace != EvaluationTraceKind::None, + max_depth: self.max_depth, + now: self.now, + timezone: self.timezone, + seed: self.seed, + } + } +} + impl Default for DecisionEngine { fn default() -> Self { Self { @@ -201,7 +261,7 @@ impl DecisionEngine { if self.engine.compiled() { return self .caches - .evaluate(&self.parts(), key_str, context, options) + .evaluate_pinned(&self.parts(), key_str, context, options) .await?; } if self.engine.scopes() { @@ -261,7 +321,7 @@ impl DecisionEngine { if self.engine.compiled() { return self .caches - .evaluate_serialized(&self.parts(), key_str, context, options) + .evaluate_serialized_pinned(&self.parts(), key_str, context, options) .await; } if self.engine.scopes() { @@ -316,10 +376,7 @@ impl DecisionEngine { decision.evaluate_serialized(context, options).await } DecisionContent::Policy(_) => { - let inner_opts = EvaluationOptions { - trace: options.trace != EvaluationTraceKind::None, - max_depth: options.max_depth, - }; + let inner_opts = options.unserialized(); let trace_mode = options.trace; let response = crate::policy::runtime::evaluate_policy( &self.loader, @@ -351,7 +408,7 @@ impl DecisionEngine { K: AsRef, { self.caches - .evaluate_batch(&self.parts(), key.as_ref(), contexts, options) + .evaluate_batch_pinned(&self.parts(), key.as_ref(), contexts, options) .await } diff --git a/core/engine/src/lib.rs b/core/engine/src/lib.rs index 1143ff94..a94596be 100644 --- a/core/engine/src/lib.rs +++ b/core/engine/src/lib.rs @@ -123,6 +123,12 @@ #![allow(clippy::module_inception)] mod analysis; +pub mod context { + pub use zen_expression::context::{ + clock_reads, instant_from_millis, parse_instant, parse_timezone, row_seed, unrowed_draws, + Instant, Timezone, + }; +} mod compiled; mod config; mod decision; diff --git a/core/engine/src/policy/blocks/decision_table.rs b/core/engine/src/policy/blocks/decision_table.rs index 88a48a25..880426d5 100644 --- a/core/engine/src/policy/blocks/decision_table.rs +++ b/core/engine/src/policy/blocks/decision_table.rs @@ -1019,6 +1019,18 @@ enum ColumnRef<'a> { } impl DecisionTableIr { + pub(crate) fn draws(&self) -> bool { + let draws = zen_expression::lane::SourceInfo::draws; + self.inputs + .iter() + .filter_map(|input| input.field.as_deref()) + .any(draws) + || self.rules.iter().any(|rule| { + rule.iter() + .any(|(column, cell)| !column.starts_with('_') && draws(cell)) + }) + } + fn column_by_id(&self, id: &Arc) -> Option> { if let Some(c) = self.inputs.iter().find(|c| c.id == *id) { return Some(ColumnRef::Input(c)); diff --git a/core/engine/src/workspace/mod.rs b/core/engine/src/workspace/mod.rs index 96909e16..42c2c187 100644 --- a/core/engine/src/workspace/mod.rs +++ b/core/engine/src/workspace/mod.rs @@ -87,11 +87,20 @@ impl Workspace { } pub fn evaluate(&self, req: &EvaluateRequest) -> Result { + self.evaluate_pinned(req, &Default::default()) + } + + pub fn evaluate_pinned( + &self, + req: &EvaluateRequest, + options: &crate::EvaluationOptions, + ) -> Result { if self.engine.compiled() { return crate::compiled::policy::artifact::Runtime::evaluate( &self.db, &self.compiled, req, + &crate::compiled::pinning::single(options.pinned()), ); } self.db.evaluate(req) @@ -106,6 +115,7 @@ impl Workspace { &self.db, &self.compiled, req, + &crate::compiled::pinning::single(Default::default()), ); } self.db.enhance_trace(req) @@ -114,11 +124,20 @@ impl Workspace { pub fn evaluate_batch( &self, requests: &[EvaluateRequest], + ) -> Vec> { + self.evaluate_batch_pinned(requests, &Default::default()) + } + + pub fn evaluate_batch_pinned( + &self, + requests: &[EvaluateRequest], + options: &crate::EvaluationOptions, ) -> Vec> { crate::compiled::policy::artifact::Runtime::evaluate_batch( &self.db, &self.compiled, requests, + &crate::compiled::pinning::batch(options.pinned()), ) } @@ -127,6 +146,16 @@ impl Workspace { policy_path: &Arc, goals: &[Arc], columns: &'a crate::columns::Columns<'a>, + ) -> Result, EvaluationError> { + self.evaluate_columns_pinned(policy_path, goals, columns, &Default::default()) + } + + pub fn evaluate_columns_pinned<'a>( + &self, + policy_path: &Arc, + goals: &[Arc], + columns: &'a crate::columns::Columns<'a>, + options: &crate::EvaluationOptions, ) -> Result, EvaluationError> { crate::compiled::policy::artifact::Runtime::evaluate_columns( &self.db, @@ -134,6 +163,7 @@ impl Workspace { policy_path, goals, columns, + &crate::compiled::pinning::batch(options.pinned()), ) } diff --git a/core/engine/tests/columnar_subdecisions.rs b/core/engine/tests/columnar_subdecisions.rs index f23253bf..3061d643 100644 --- a/core/engine/tests/columnar_subdecisions.rs +++ b/core/engine/tests/columnar_subdecisions.rs @@ -302,6 +302,7 @@ impl Scenario { let options = EvaluationOptions { trace: false, max_depth: self.max_depth, + ..Default::default() }; let xs: Vec = (1..=Self::ROWS).collect(); let columns = Columns::new(xs.len()).column("x", Column::new(Values::I64(&xs))); diff --git a/core/engine/tests/compiled.rs b/core/engine/tests/compiled.rs index eb8dc2aa..83246944 100644 --- a/core/engine/tests/compiled.rs +++ b/core/engine/tests/compiled.rs @@ -940,6 +940,7 @@ async fn single_row_latency() { let traced = EvaluationOptions { trace: true, max_depth: 10, + ..Default::default() }; let mut columns: [Vec; 5] = Default::default(); println!( diff --git a/core/engine/tests/compiled_policy.rs b/core/engine/tests/compiled_policy.rs index 5c0936bb..50958000 100644 --- a/core/engine/tests/compiled_policy.rs +++ b/core/engine/tests/compiled_policy.rs @@ -504,7 +504,13 @@ impl Anchor { } program }); - runner.evaluate_columns_many(program, columns, outs, |_, _, _| {}); + runner.evaluate_columns_many( + program, + &zen_expression::context::EvaluationContext::default(), + columns, + outs, + |_, _, _| {}, + ); stages[index] += start.elapsed().as_nanos() as f64 / rows as f64; }; let mut member: Vec = (0..2).map(|_| Output::new()).collect(); @@ -707,7 +713,12 @@ impl Anchor { _ => 1, }; for _ in 0..repeat { - runner.evaluate_columns_into(program, columns, out); + runner.evaluate_columns_into( + program, + &zen_expression::context::EvaluationContext::default(), + columns, + out, + ); } stages[index] += start.elapsed().as_nanos() as f64 / rows as f64 / repeat as f64; }; diff --git a/core/engine/tests/concurrent.rs b/core/engine/tests/concurrent.rs new file mode 100644 index 00000000..9cdb0493 --- /dev/null +++ b/core/engine/tests/concurrent.rs @@ -0,0 +1,272 @@ +use serde_json::{json, Value}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use zen_engine::context::{parse_instant, parse_timezone}; +use zen_engine::loader::{DecisionLoader, LoaderResponse, MemoryLoader}; +use zen_engine::model::DecisionContent; +use zen_engine::{DecisionEngine, EvaluationOptions, Variable}; + +#[derive(Debug, Default)] +struct Yielding { + memory: MemoryLoader, + inflight: AtomicUsize, + overlapped: AtomicUsize, +} + +impl DecisionLoader for Yielding { + fn load<'a>( + &'a self, + key: &'a str, + ) -> Pin + 'a + Send>> { + Box::pin(async move { + let others = self.inflight.fetch_add(1, Ordering::SeqCst); + self.overlapped.fetch_max(others, Ordering::SeqCst); + tokio::task::yield_now().await; + tokio::task::yield_now().await; + self.inflight.fetch_sub(1, Ordering::SeqCst); + self.memory.load(key).await + }) + } +} + +fn child() -> Value { + json!({ + "nodes": [ + {"id": "in", "name": "in", "type": "inputNode"}, + {"id": "calc", "name": "calc", "type": "expressionNode", "content": {"expressions": [ + {"id": "c1", "key": "c", "value": "rand(1000000)"}, + {"id": "c2", "key": "ct", "value": "d().timestamp()"}, + {"id": "c3", "key": "cz", "value": "d().offsetName()"} + ]}}, + {"id": "out", "name": "out", "type": "outputNode"} + ], + "edges": [ + {"id": "e1", "sourceId": "in", "targetId": "calc", "type": "edge"}, + {"id": "e2", "sourceId": "calc", "targetId": "out", "type": "edge"} + ] + }) +} + +fn main_graph() -> Value { + json!({ + "nodes": [ + {"id": "in", "name": "in", "type": "inputNode"}, + {"id": "calc", "name": "calc", "type": "expressionNode", "content": {"expressions": [ + {"id": "x1", "key": "r", "value": "rand(1000000)"}, + {"id": "x2", "key": "t", "value": "d().timestamp()"}, + {"id": "x3", "key": "zone", "value": "d().offsetName()"}, + {"id": "x4", "key": "local", "value": "d('2026-01-02 10:00').timestamp()"} + ]}}, + {"id": "sub", "name": "sub", "type": "decisionNode", "content": { + "key": "child", "transformAttributes": {"executionMode": "single", "passThrough": true} + }}, + {"id": "fn", "name": "fn", "type": "functionNode", "content": { + "source": "import zen from 'zen';\nexport const handler = async (input) => {\n const before = Math.random();\n const nested = await zen.evaluate('child', input);\n const local = new Date().toString();\n const formatted = new Date().toLocaleString();\n const intl = Intl.DateTimeFormat().resolvedOptions();\n return { ...input, before, nested: nested.result, now: Date.now(), after: Math.random(), local, formatted, jsZone: intl.timeZone, };\n};" + }}, + {"id": "out", "name": "out", "type": "outputNode"} + ], + "edges": [ + {"id": "e1", "sourceId": "in", "targetId": "calc", "type": "edge"}, + {"id": "e2", "sourceId": "calc", "targetId": "sub", "type": "edge"}, + {"id": "e3", "sourceId": "sub", "targetId": "fn", "type": "edge"}, + {"id": "e4", "sourceId": "fn", "targetId": "out", "type": "edge"}, + {"id": "e5", "sourceId": "calc", "targetId": "fn", "type": "edge"} + ] + }) +} + +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( + key, + serde_json::from_value::(graph).unwrap(), + ); + } + ( + DecisionEngine::default().with_loader(loader.clone()), + loader, + ) +} + +fn runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() +} + +#[derive(Clone, Copy)] +struct Pin3 { + now: &'static str, + zone: &'static str, + seed: u64, + local: &'static str, + formatted: &'static str, +} + +const A: Pin3 = Pin3 { + now: "2026-11-04T09:30:00.125Z", + zone: "Europe/Berlin", + seed: 11, + local: "Wed Nov 04 2026 10:30:00 GMT+0100", + formatted: "11/04/2026, 10:30:00 AM", +}; + +const B: Pin3 = Pin3 { + now: "2031-02-17T23:15:42.500Z", + zone: "America/New_York", + seed: 97, + local: "Mon Feb 17 2031 18:15:42 GMT-0500", + formatted: "02/17/2031, 06:15:42 PM", +}; + +fn options(pin: Pin3, trace: bool) -> EvaluationOptions { + EvaluationOptions { + trace, + now: parse_instant(pin.now), + timezone: parse_timezone(pin.zone), + seed: Some(pin.seed), + ..Default::default() + } +} + +fn millis(pin: Pin3) -> i64 { + parse_instant(pin.now).unwrap().timestamp_millis() +} + +fn input() -> Variable { + Variable::from(json!({"x": 1})) +} + +fn untimed(v: Value) -> Value { + match v { + Value::Object(map) => Value::Object( + map.into_iter() + .filter(|(k, _)| k != "perf" && k != "performance" && k != "timings") + .map(|(k, x)| (k, untimed(x))) + .collect(), + ), + Value::Array(items) => Value::Array(items.into_iter().map(untimed).collect()), + other => other, + } +} + +async fn single(engine: &DecisionEngine, pin: Pin3, trace: bool) -> (Value, Option) { + let response = engine + .evaluate_with_opts("main", input(), options(pin, trace)) + .await + .unwrap(); + ( + serde_json::to_value(&response.result).unwrap(), + response + .trace + .map(|t| untimed(serde_json::to_value(&t).unwrap())), + ) +} + +async fn batch(engine: &DecisionEngine, pin: Pin3) -> Vec { + let inputs: Vec = (0..4).map(|x| Variable::from(json!({"x": x}))).collect(); + engine + .evaluate_batch("main", &inputs, options(pin, false)) + .await + .into_iter() + .map(|r| serde_json::to_value(r.unwrap().result).unwrap()) + .collect() +} + +fn sees_its_own_clock(value: &Value, pin: Pin3) { + let at = millis(pin); + assert_eq!(value["t"], json!(at), "{value}"); + assert_eq!(value["now"], json!(at), "{value}"); + assert_eq!(value["ct"], json!(at), "{value}"); + assert_eq!(value["nested"]["ct"], json!(at), "{value}"); + assert_eq!(value["zone"], json!(pin.zone), "{value}"); + assert_eq!(value["cz"], json!(pin.zone), "{value}"); + assert_eq!(value["nested"]["cz"], json!(pin.zone), "{value}"); + assert_eq!(value["jsZone"], json!(pin.zone), "{value}"); + assert_eq!(value["local"], json!(pin.local), "{value}"); + assert_eq!(value["formatted"], json!(pin.formatted), "{value}"); +} + +struct Expected { + a: (Value, Option), + b: (Value, Option), + batch_a: Vec, + batch_b: Vec, +} + +fn expected(engine: &DecisionEngine) -> Expected { + let rt = runtime(); + let expected = Expected { + a: rt.block_on(single(engine, A, true)), + b: rt.block_on(single(engine, B, true)), + batch_a: rt.block_on(batch(engine, A)), + batch_b: rt.block_on(batch(engine, B)), + }; + sees_its_own_clock(&expected.a.0, A); + sees_its_own_clock(&expected.b.0, B); + assert_ne!(expected.a.0["r"], expected.b.0["r"]); + assert_ne!(expected.a.0["local"], expected.b.0["local"]); + expected +} + +#[test] +fn interleaved_evaluations_on_one_thread_see_their_own_clock() { + let (engine, loader) = engine(); + let want = expected(&engine); + assert_eq!(loader.overlapped.load(Ordering::SeqCst), 0); + let rt = runtime(); + for _ in 0..3 { + let (a, b, batch_b, batch_a) = rt.block_on(async { + tokio::join!( + single(&engine, A, true), + single(&engine, B, true), + batch(&engine, B), + batch(&engine, A), + ) + }); + assert_eq!(a, want.a); + assert_eq!(b, want.b); + assert_eq!(batch_a, want.batch_a); + assert_eq!(batch_b, want.batch_b); + } + assert!(loader.overlapped.load(Ordering::SeqCst) > 0); + for (value, pin) in want + .batch_a + .iter() + .map(|v| (v, A)) + .chain(want.batch_b.iter().map(|v| (v, B))) + { + sees_its_own_clock(value, pin); + } +} + +#[test] +fn evaluations_on_two_threads_see_their_own_clock() { + let (engine, _) = engine(); + let want = expected(&engine); + std::thread::scope(|scope| { + let workers: Vec<_> = [(A, &want.a, &want.batch_a), (B, &want.b, &want.batch_b)] + .into_iter() + .map(|(pin, alone, batched)| { + let engine = &engine; + scope.spawn(move || { + let rt = runtime(); + for _ in 0..20 { + assert_eq!(&rt.block_on(single(engine, pin, true)), alone); + assert_eq!(&rt.block_on(batch(engine, pin)), batched); + } + }) + }) + .collect(); + for worker in workers { + worker.join().unwrap(); + } + }); +} diff --git a/core/engine/tests/draws.rs b/core/engine/tests/draws.rs new file mode 100644 index 00000000..1ffdc55a --- /dev/null +++ b/core/engine/tests/draws.rs @@ -0,0 +1,1005 @@ +mod support; + +use serde_json::{json, Value}; +use std::sync::Arc; +use support::columns::Built; +use zen_engine::context::{parse_instant, parse_timezone, row_seed, unrowed_draws}; +use zen_engine::loader::MemoryLoader; +use zen_engine::model::DecisionContent; +use zen_engine::{Decision, DecisionEngine, EvaluationOptions, Variable}; + +const NOW: &str = "2026-11-04T09:30:00.125Z"; +const ROWS: usize = 7; + +fn block(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .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() + .map(|n| n["id"].as_str().unwrap().to_string()) + .collect(); + let edges: Vec = ids + .windows(2) + .map(|w| json!({"id": format!("{}-{}", w[0], w[1]), "sourceId": w[0], "targetId": w[1], "type": "edge"})) + .collect(); + json!({"nodes": nodes, "edges": edges}) +} + +fn input() -> Value { + json!({"id": "in", "name": "in", "type": "inputNode"}) +} + +fn output() -> Value { + json!({"id": "out", "name": "out", "type": "outputNode"}) +} + +fn expressions(id: &str, fields: &[(&str, &str)], extra: Value) -> Value { + let expressions: Vec = fields + .iter() + .enumerate() + .map(|(i, (key, value))| json!({"id": format!("{id}{i}"), "key": key, "value": value})) + .collect(); + let mut content = json!({"expressions": expressions}); + if let (Some(map), Some(extra)) = (content.as_object_mut(), extra.as_object()) { + map.extend(extra.clone()); + } + json!({"id": id, "name": id, "type": "expressionNode", "content": content}) +} + +fn content(graph: Value) -> Arc { + Arc::new(serde_json::from_value(graph).unwrap()) +} + +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_loader(loader) + .create_decision(content(graph)) + .unwrap() +} + +fn top_level() -> Decision { + decision( + chain(vec![ + input(), + expressions( + "calc", + &[ + ("a", "rand(1000000)"), + ("b", "x + rand(1000000)"), + ("c", "x > 2 ? rand(100) : -1"), + ], + json!({}), + ), + output(), + ]), + &[], + ) +} + +fn closures() -> Decision { + decision( + chain(vec![ + input(), + expressions( + "calc", + &[ + ("m", "map(xs, rand(1000000))"), + ("two", "map(xs, rand(1000) * 1000 + rand(1000))"), + ("f", "filter(xs, rand(10) > 4)"), + ("some", "some(xs, rand(10) > 7)"), + ( + "nested", + "map(filter(xs, # < 3), map(filter(xs, # < 4), rand(1000)))", + ), + ("fixed", "map([1, 2, 3, 4, 5], rand(1000000))"), + ("after", "rand(1000000)"), + ], + json!({}), + ), + output(), + ]), + &[], + ) +} + +fn looped() -> Decision { + decision( + chain(vec![ + input(), + expressions( + "calc", + &[ + ("r", "rand(1000000)"), + ("s", "n + rand(1000)"), + ("inner", "map([1, 2], rand(1000))"), + ], + json!({"inputField": "items", "outputPath": "looped", "executionMode": "loop"}), + ), + expressions( + "after", + &[("z", "rand(1000000)")], + json!({"passThrough": true}), + ), + output(), + ]), + &[], + ) +} + +fn child() -> Value { + chain(vec![ + input(), + expressions( + "inner", + &[("c", "rand(1000000)"), ("d", "map([1, 2, 3], rand(1000))")], + json!({}), + ), + output(), + ]) +} + +fn sub_decisions() -> Decision { + decision( + chain(vec![ + input(), + expressions( + "before", + &[("a", "rand(1000000)")], + json!({"passThrough": true}), + ), + json!({"id": "call", "name": "call", "type": "decisionNode", "content": {"key": "child"}}), + expressions( + "after", + &[("b", "rand(1000000)")], + json!({"passThrough": true}), + ), + output(), + ]), + &[("child", child())], + ) +} + +fn looped_sub_decisions() -> Decision { + decision( + chain(vec![ + input(), + json!({"id": "call", "name": "call", "type": "decisionNode", "content": { + "key": "child", "inputField": "items", "outputPath": "children", "executionMode": "loop" + }}), + expressions( + "after", + &[("b", "rand(1000000)")], + json!({"passThrough": true}), + ), + output(), + ]), + &[("child", child())], + ) +} + +fn functions() -> Decision { + decision( + chain(vec![ + input(), + expressions( + "before", + &[("a", "rand(1000000)")], + json!({"passThrough": true}), + ), + json!({"id": "fn", "name": "fn", "type": "functionNode", "content": { + "source": "export const handler = async (input) => ({ ...input, r: Math.random(), q: Math.random() })" + }}), + json!({"id": "fn1", "name": "fn1", "type": "functionNode", "content": + "const handler = (input) => ({ ...input, v1: Math.random() })" + }), + expressions( + "after", + &[("b", "rand(1000000)")], + json!({"passThrough": true}), + ), + output(), + ]), + &[], + ) +} + +fn tables() -> Decision { + decision( + chain(vec![ + input(), + json!({"id": "dt", "name": "dt", "type": "decisionTableNode", "content": { + "hitPolicy": "collect", + "inputs": [{"id": "i1", "name": "x", "field": "x"}], + "outputs": [{"id": "o1", "name": "r", "field": "r"}, {"id": "o2", "name": "k", "field": "k"}], + "rules": [ + {"_id": "r1", "i1": "> 1", "o1": "rand(1000000)", "o2": "1"}, + {"_id": "r2", "i1": "", "o1": "rand(1000000)", "o2": "2"} + ] + }}), + output(), + ]), + &[], + ) +} + +fn branches() -> Decision { + let graph = json!({ + "nodes": [ + input(), + {"id": "sw", "name": "sw", "type": "switchNode", "content": { + "hitPolicy": "first", + "statements": [ + {"id": "s1", "condition": "x > 2"}, + {"id": "s2", "condition": ""} + ] + }}, + expressions( + "high", + &[("h", "rand(1000000)"), ("hs", "map(xs, rand(100))")], + json!({"passThrough": true}), + ), + {"id": "low", "name": "low", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [{"id": "i1", "name": "x", "field": "x"}], + "outputs": [{"id": "o1", "name": "l", "field": "l"}], + "rules": [ + {"_id": "r1", "i1": "rand(10) > 6", "o1": "rand(1000000)"}, + {"_id": "r2", "i1": "rand(10) > 3", "o1": "-rand(1000)"}, + {"_id": "r3", "i1": "", "o1": "0"} + ] + }}, + expressions( + "each", + &[("e", "rand(1000) + n")], + json!({"inputField": "items", "outputPath": "each", "executionMode": "loop", "passThrough": true}), + ), + output() + ], + "edges": [ + {"id": "e0", "sourceId": "in", "targetId": "sw", "type": "edge"}, + {"id": "e1", "sourceId": "sw", "sourceHandle": "s1", "targetId": "high", "type": "edge"}, + {"id": "e2", "sourceId": "sw", "sourceHandle": "s2", "targetId": "low", "type": "edge"}, + {"id": "e3", "sourceId": "high", "targetId": "each", "type": "edge"}, + {"id": "e4", "sourceId": "low", "targetId": "out", "type": "edge"}, + {"id": "e5", "sourceId": "each", "targetId": "out", "type": "edge"} + ] + }); + decision(graph, &[]) +} + +fn row(x: usize) -> Variable { + let xs: Vec = (0..(3 + x * 23)).collect(); + let items: Vec = (0..(1 + x * 13 % 70)).map(|n| json!({"n": n})).collect(); + Variable::from(json!({"x": x, "xs": xs, "items": items})) +} + +fn options(trace: bool, seed: u64) -> EvaluationOptions { + EvaluationOptions { + trace, + now: parse_instant(NOW), + timezone: parse_timezone("Europe/Berlin"), + seed: Some(seed), + ..Default::default() + } +} + +fn untimed(v: Value) -> Value { + match v { + Value::Object(map) => Value::Object( + map.into_iter() + .filter(|(k, _)| k != "perf" && k != "performance" && k != "timings") + .map(|(k, x)| (k, untimed(x))) + .collect(), + ), + Value::Array(items) => Value::Array(items.into_iter().map(untimed).collect()), + other => other, + } +} + +fn alone(d: &Decision, x: usize, seed: u64) -> (Value, Value) { + let r = block(d.evaluate_with_opts(row(x), options(true, seed))).unwrap(); + let off = block(d.evaluate_with_opts(row(x), options(false, seed))).unwrap(); + let result = serde_json::to_value(&r.result).unwrap(); + assert_eq!( + result, + serde_json::to_value(&off.result).unwrap(), + "traced and untraced single row {x}" + ); + (result, serde_json::to_value(r.trace.unwrap()).unwrap()) +} + +fn rows_match_alone(name: &str, d: &Decision, base: u64) -> Vec { + let inputs: Vec = (0..ROWS).map(row).collect(); + let singles: Vec<(Value, Value)> = (0..ROWS).map(|x| alone(d, x, row_seed(base, x))).collect(); + for trace in [true, false] { + let batch = block(d.evaluate_batch(&inputs, options(trace, base))); + for (x, result) in batch.into_iter().enumerate() { + let result = result.unwrap(); + let (want, doc) = &singles[x]; + assert_eq!( + &serde_json::to_value(&result.result).unwrap(), + want, + "{name}: batch row {x} ({trace:?})" + ); + assert_eq!(result.trace.is_some(), trace, "{name}: trace of row {x}"); + if let Some(t) = result.trace { + let t = serde_json::to_value(&t).unwrap(); + assert_eq!(untimed(t), untimed(doc.clone()), "{name}: batch trace {x}"); + } + } + } + singles.into_iter().map(|(v, _)| v).collect() +} + +fn row_json(x: usize) -> Value { + serde_json::to_value(row(x)).unwrap() +} + +fn columns_match_alone(name: &str, d: &Decision, base: u64, json: impl Fn(usize) -> Value) { + let rows: Vec = (0..ROWS).map(&json).collect(); + let built = Built::nested(&rows) + .or_else(|| Built::lists(&rows)) + .or_else(|| Built::new(&rows)) + .expect("columns"); + let columns = built.columns(); + let output = block(d.evaluate_columns(&columns, options(false, base))); + for (x, row) in rows.iter().enumerate() { + let input = Variable::from(row.clone()); + let single = block(d.evaluate_with_opts(input, options(false, row_seed(base, x)))).unwrap(); + let got = serde_json::to_value(output.row(x)).unwrap(); + assert_eq!( + got, + serde_json::to_value(&single.result).unwrap(), + "{name}: columnar row {x}" + ); + } +} + +fn distinct(values: impl IntoIterator) -> usize { + let mut seen: Vec = values.into_iter().map(|v| v.to_string()).collect(); + seen.sort(); + seen.dedup(); + seen.len() +} + +#[test] +fn top_level_draws_follow_each_rows_stream() { + let d = top_level(); + let rows = rows_match_alone("top level", &d, 41); + assert_eq!(distinct(rows.iter().map(|r| r["a"].clone())), ROWS); + columns_match_alone("top level", &d, 41, row_json); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn closure_items_draw_independently() { + let d = closures(); + let rows = rows_match_alone("closures", &d, 7); + for r in &rows { + let m = r["m"].as_array().unwrap(); + assert!(distinct(m.iter().cloned()) > m.len() / 2, "{r}"); + let fixed = r["fixed"].as_array().unwrap(); + assert!(distinct(fixed.iter().cloned()) > 2, "{r}"); + let nested = r["nested"].as_array().unwrap(); + assert!(distinct(nested.iter().flat_map(|n| n.as_array().unwrap().clone())) > 3); + } + assert_eq!(distinct(rows.iter().map(|r| r["fixed"].clone())), ROWS); + let fixed = decision( + chain(vec![ + input(), + expressions( + "calc", + &[ + ("m", "map([1, 2, 3, 4, 5, 6], rand(1000000) + x)"), + ("two", "map([1, 2, 3], rand(1000) * 1000 + rand(1000))"), + ("f", "filter([1, 2, 3, 4, 5, 6, 7, 8], rand(10) > 4)"), + ], + json!({}), + ), + output(), + ]), + &[], + ); + columns_match_alone("closures", &d, 7, row_json); + columns_match_alone("fixed closures", &fixed, 7, |x| json!({"x": x})); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn loop_nodes_draw_per_row() { + let d = looped(); + let rows = rows_match_alone("loops", &d, 3); + assert_eq!(distinct(rows.iter().map(|r| r["z"].clone())), ROWS); + let first: Vec = rows.iter().map(|r| r["looped"][0]["r"].clone()).collect(); + assert_eq!(distinct(first), ROWS); + columns_match_alone("loops", &d, 3, row_json); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn sub_decisions_draw_from_the_callers_row() { + let d = sub_decisions(); + let rows = rows_match_alone("sub decisions", &d, 19); + assert_eq!(distinct(rows.iter().map(|r| r["c"].clone())), ROWS); + columns_match_alone("sub decisions", &d, 19, row_json); + let d = looped_sub_decisions(); + rows_match_alone("looped sub decisions", &d, 23); + columns_match_alone("looped sub decisions", &d, 23, row_json); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn function_nodes_draw_per_row() { + let d = functions(); + let rows = rows_match_alone("functions", &d, 5); + assert_eq!(distinct(rows.iter().map(|r| r["r"].clone())), ROWS); + assert_eq!(distinct(rows.iter().map(|r| r["v1"].clone())), ROWS); + for r in &rows { + assert_ne!(r["r"], r["q"]); + } + columns_match_alone("functions", &d, 5, row_json); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn table_outputs_draw_per_row() { + let d = tables(); + rows_match_alone("tables", &d, 11); + columns_match_alone("tables", &d, 11, row_json); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn switch_branches_draw_per_row() { + let d = branches(); + rows_match_alone("branches", &d, 13); + columns_match_alone("branches", &d, 13, row_json); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn rows_with_different_seeds_differ() { + let d = top_level(); + let a = block(d.evaluate_with_opts(row(1), options(false, 1))).unwrap(); + let b = block(d.evaluate_with_opts(row(1), options(false, 2))).unwrap(); + assert_ne!( + serde_json::to_value(a.result).unwrap(), + serde_json::to_value(b.result).unwrap() + ); +} + +fn policy_document() -> zen_engine::policy::PolicyDocument { + serde_json::from_value(json!({ + "blocks": [ + {"id": "dm-customer", "type": "dataModel", "props": {"data": { + "name": "customer", + "properties": [ + {"id": "p0", "name": "age", "type": "number", "array": false, "optional": false}, + {"id": "p1", "name": "companies", "type": "relationship", "target": "company", "array": true, "optional": false} + ] + }}}, + {"id": "dm-company", "type": "dataModel", "props": {"data": { + "name": "company", + "properties": [ + {"id": "p2", "name": "revenue", "type": "number", "array": false, "optional": false} + ] + }}}, + {"id": "e1", "type": "expression", "props": {"data": { + "key": "customer.lucky", "value": "rand(1000000) + customer.age" + }}}, + {"id": "e2", "type": "expression", "props": {"data": { + "key": "company.score", "value": "rand(1000) + company.revenue" + }}}, + {"id": "e3", "type": "expression", "props": {"data": { + "key": "customer.draws", "value": "map(customer.companies as c, rand(1000))" + }}}, + {"id": "e4", "type": "expression", "props": {"data": { + "key": "customer.after", "value": "rand(1000000)" + }}} + ] + })) + .unwrap() +} + +fn policy_input(x: usize) -> Value { + let companies: Vec = (0..(1 + x * 11 % 40)) + .map(|i| json!({"revenue": i * 10})) + .collect(); + json!({"customer": {"age": x, "companies": companies}}) +} + +fn policy_request(x: usize, trace: bool) -> zen_engine::policy::EvaluateRequest { + zen_engine::policy::EvaluateRequest { + policy_path: Arc::from("policy"), + input: Variable::from(policy_input(x)), + goals: Vec::new(), + trace, + } +} + +fn pinned(seed: u64) -> EvaluationOptions { + EvaluationOptions { + now: parse_instant(NOW), + timezone: parse_timezone("UTC"), + seed: Some(seed), + ..Default::default() + } +} + +fn policy_trace(result: &zen_engine::policy::EvaluationResult) -> Value { + untimed(serde_json::to_value(result.trace.as_ref().unwrap()).unwrap()) +} + +#[test] +fn policy_rows_draw_from_their_streams() { + compiled(); + let mut ws = zen_engine::Workspace::new(); + ws.set_policy("policy", policy_document()); + let base = 29; + let singles: Vec<(Value, Value)> = (0..ROWS) + .map(|x| { + let seed = row_seed(base, x); + let traced = ws + .evaluate_pinned(&policy_request(x, true), &pinned(seed)) + .unwrap(); + let plain = ws + .evaluate_pinned(&policy_request(x, false), &pinned(seed)) + .unwrap(); + let value = serde_json::to_value(&traced.output).unwrap(); + assert_eq!( + value, + serde_json::to_value(&plain.output).unwrap(), + "row {x}" + ); + (value, policy_trace(&traced)) + }) + .collect(); + for trace in [true, false] { + let requests: Vec<_> = (0..ROWS).map(|x| policy_request(x, trace)).collect(); + let batch = ws.evaluate_batch_pinned(&requests, &pinned(base)); + for (x, result) in batch.into_iter().enumerate() { + let result = result.unwrap(); + assert_eq!( + serde_json::to_value(&result.output).unwrap(), + singles[x].0, + "policy batch row {x} ({trace:?})" + ); + if trace { + assert_eq!(policy_trace(&result), singles[x].1, "policy trace {x}"); + } + } + } + let rows: Vec = (0..ROWS).map(policy_input).collect(); + let built = Built::nested(&rows).expect("columns"); + let columns = built.columns(); + let output = ws + .evaluate_columns_pinned(&Arc::from("policy"), &[], &columns, &pinned(base)) + .unwrap(); + for (x, (single, _)) in singles.iter().enumerate() { + assert_eq!( + &serde_json::to_value(output.row(x)).unwrap(), + single, + "policy columnar row {x}" + ); + } + let distinct_lucky = distinct(singles.iter().map(|(v, _)| v["customer"]["lucky"].clone())); + assert_eq!(distinct_lucky, ROWS); + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn engine_policy_batches_draw_per_row() { + compiled(); + let loader = Arc::new(MemoryLoader::default()); + loader.add( + "policy", + DecisionContent::Policy(zen_engine::model::PolicyContent( + Arc::new(policy_document()), + )), + ); + let engine = DecisionEngine::default().with_loader(loader); + let inputs: Vec = (0..ROWS).map(|x| Variable::from(policy_input(x))).collect(); + for trace in [true, false] { + let batch = block(engine.evaluate_batch("policy", &inputs, options(trace, 31))); + for (x, result) in batch.into_iter().enumerate() { + let result = result.unwrap(); + let single = block(engine.evaluate_with_opts( + "policy", + inputs[x].clone(), + options(trace, row_seed(31, x)), + )) + .unwrap(); + assert_eq!( + serde_json::to_value(&result.result).unwrap(), + serde_json::to_value(&single.result).unwrap(), + "engine policy row {x} ({trace:?})" + ); + if let (Some(a), Some(b)) = (result.trace, single.trace) { + let (a, b) = ( + serde_json::to_value(a).unwrap(), + serde_json::to_value(b).unwrap(), + ); + assert_eq!(untimed(a), untimed(b), "engine policy trace {x}"); + } + } + } + assert_eq!(unrowed_draws(), 0); +} + +fn located(d: &Decision, x: usize, seed: u64) -> Value { + let result = block(d.evaluate_with_opts(row(x), options(false, seed))).unwrap(); + serde_json::to_value(result.result).unwrap() +} + +fn agree(name: &str, d: &Decision, base: u64) -> Vec { + let rows = rows_match_alone(name, d, base); + columns_match_alone(name, d, base, row_json); + rows +} + +fn graph(nodes: Vec, edges: &[(&str, &str)]) -> Value { + let edges: Vec = edges + .iter() + .map(|(from, to)| json!({"id": format!("{from}-{to}"), "sourceId": from, "targetId": to, "type": "edge"})) + .collect(); + json!({"nodes": nodes, "edges": edges}) +} + +fn passing(id: &str, fields: &[(&str, &str)]) -> Value { + expressions(id, fields, json!({"passThrough": true})) +} + +#[test] +fn an_inserted_draw_leaves_other_draws_alone() { + let plain = decision( + chain(vec![ + input(), + passing( + "calc", + &[ + ("copy", "x"), + ("b", "rand(1000000)"), + ("m", "map(xs, rand(1000))"), + ("o", "{u: rand(1000000), v: rand(1000000)}"), + ], + ), + output(), + ]), + &[], + ); + let inserted = decision( + chain(vec![ + input(), + passing("pre", &[("p", "rand(1000000)")]), + passing( + "calc", + &[ + ("a", "rand(1000000)"), + ("copy", "x"), + ("b", "rand(1000000)"), + ("m", "map(xs, rand(1000))"), + ("o", "{u: rand(1000000), v: rand(1000000)}"), + ], + ), + output(), + ]), + &[], + ); + let base = 101; + let before = agree("plain", &plain, base); + let after = agree("inserted", &inserted, base); + for (x, (a, b)) in before.iter().zip(&after).enumerate() { + assert_eq!(a["b"], b["b"], "row {x}"); + assert_eq!(a["m"], b["m"], "row {x}"); + assert_eq!(a["o"], b["o"], "row {x}"); + assert_ne!(a["o"]["u"], a["o"]["v"], "row {x}"); + assert_ne!(b["a"], b["b"], "row {x}"); + assert_ne!(b["p"], b["b"], "row {x}"); + } + assert_eq!(located(&plain, 2, 5), located(&plain, 2, 5)); +} + +#[test] +fn draws_in_one_expression_differ_and_ignore_evaluation_order() { + let parallel = |order: [&str; 2]| { + let node = |id: &str| match id { + "left" => passing("left", &[("l", "[rand(1000000), rand(1000000)]")]), + _ => passing( + "right", + &[("r", "x > 2 ? rand(1000000) : rand(1000000) + 1")], + ), + }; + decision( + graph( + vec![input(), node(order[0]), node(order[1]), output()], + &[ + ("in", "left"), + ("in", "right"), + ("left", "out"), + ("right", "out"), + ], + ), + &[], + ) + }; + let base = 103; + let a = agree("left first", ¶llel(["left", "right"]), base); + let b = agree("right first", ¶llel(["right", "left"]), base); + assert_eq!(a, b); + for r in &a { + assert_ne!(r["l"][0], r["l"][1], "{r}"); + } + let swapped = decision( + chain(vec![ + input(), + expressions( + "calc", + &[ + ("c", "x > 2 ? rand(100) : -1"), + ("b", "x + rand(1000000)"), + ("a", "rand(1000000)"), + ], + json!({}), + ), + output(), + ]), + &[], + ); + let original = agree("top level", &top_level(), 41); + let reordered = agree("reordered keys", &swapped, 41); + assert_eq!(original, reordered); +} + +#[test] +fn repeated_runs_agree_across_paths() { + for (name, d) in [ + ("top level", top_level()), + ("closures", closures()), + ("loops", looped()), + ("sub decisions", sub_decisions()), + ("tables", tables()), + ("branches", branches()), + ] { + let first = agree(name, &d, 107); + let second = agree(name, &d, 107); + assert_eq!(first, second, "{name}"); + } +} + +#[test] +fn closures_and_loops_draw_stably_per_item() { + let rows = agree("closures", &closures(), 7); + let rerun = decision( + chain(vec![ + input(), + passing("extra", &[("e", "map(xs, rand(1000000))")]), + expressions( + "calc", + &[ + ("m", "map(xs, rand(1000000))"), + ("two", "map(xs, rand(1000) * 1000 + rand(1000))"), + ("f", "filter(xs, rand(10) > 4)"), + ("some", "some(xs, rand(10) > 7)"), + ( + "nested", + "map(filter(xs, # < 3), map(filter(xs, # < 4), rand(1000)))", + ), + ("fixed", "map([1, 2, 3, 4, 5], rand(1000000))"), + ("after", "rand(1000000)"), + ], + json!({}), + ), + output(), + ]), + &[], + ); + let again = agree("closures with a node before", &rerun, 7); + assert_eq!(rows, again); + let loops = agree("loops", &looped(), 3); + let shifted = decision( + chain(vec![ + input(), + passing("first", &[("q", "rand(1000000)")]), + expressions( + "calc", + &[ + ("r", "rand(1000000)"), + ("s", "n + rand(1000)"), + ("inner", "map([1, 2], rand(1000))"), + ], + json!({"inputField": "items", "outputPath": "looped", "executionMode": "loop"}), + ), + expressions( + "after", + &[("z", "rand(1000000)")], + json!({"passThrough": true}), + ), + output(), + ]), + &[], + ); + let moved = agree("loops with a node before", &shifted, 3); + for (a, b) in loops.iter().zip(&moved) { + assert_eq!(a["looped"], b["looped"]); + assert_eq!(a["z"], b["z"]); + let items = a["looped"].as_array().unwrap(); + if items.len() > 3 { + assert!(distinct(items.iter().map(|i| i["r"].clone())) > items.len() / 2); + } + } +} + +fn twice_called() -> Decision { + decision( + chain(vec![ + input(), + json!({"id": "one", "name": "one", "type": "decisionNode", "content": {"key": "child", "outputPath": "one", "passThrough": true}}), + json!({"id": "two", "name": "two", "type": "decisionNode", "content": {"key": "child", "outputPath": "two", "passThrough": true}}), + output(), + ]), + &[("child", child())], + ) +} + +#[test] +fn a_sub_decision_draws_per_calling_node() { + let rows = agree("twice called", &twice_called(), 109); + for r in &rows { + assert_ne!(r["one"]["c"], r["two"]["c"], "{r}"); + assert_ne!(r["one"]["d"], r["two"]["d"], "{r}"); + } + let alone = decision( + chain(vec![ + input(), + json!({"id": "two", "name": "two", "type": "decisionNode", "content": {"key": "child", "outputPath": "two", "passThrough": true}}), + output(), + ]), + &[("child", child())], + ); + let single = agree("called once", &alone, 109); + for (a, b) in rows.iter().zip(&single) { + assert_eq!(a["two"], b["two"]); + } + let looped = agree("looped sub decisions", &looped_sub_decisions(), 23); + assert_eq!( + looped, + agree("looped sub decisions", &looped_sub_decisions(), 23) + ); +} + +fn script(id: &str, field: &str) -> Value { + json!({"id": id, "name": id, "type": "functionNode", "content": { + "source": format!("export const handler = async (input) => ({{ ...input, {field}: Math.random(), {field}2: Math.random() }})") + }}) +} + +#[test] +fn function_nodes_draw_independently_of_other_nodes() { + let plain = decision(chain(vec![input(), script("fn", "r"), output()]), &[]); + let preceded = decision( + chain(vec![ + input(), + script("pre", "p"), + passing("calc", &[("a", "rand(1000000)")]), + script("fn", "r"), + output(), + ]), + &[], + ); + let a = agree("one function", &plain, 113); + let b = agree("preceded function", &preceded, 113); + for (x, (a, b)) in a.iter().zip(&b).enumerate() { + assert_eq!(a["r"], b["r"], "row {x}"); + assert_eq!(a["r2"], b["r2"], "row {x}"); + assert_ne!(a["r"], a["r2"], "row {x}"); + assert_ne!(b["p"], b["r"], "row {x}"); + } +} + +fn located_tables(extra: bool) -> Decision { + let mut rules = vec![ + json!({"_id": "r1", "i1": "> 1", "o1": "rand(1000000)", "o2": "1"}), + json!({"_id": "r2", "i1": "", "o1": "rand(1000000)", "o2": "2"}), + json!({"_id": "r3", "i1": "", "o1": "rand(1000000)", "o2": "3"}), + ]; + if extra { + rules.insert( + 0, + json!({"_id": "r0", "i1": "rand(10) >= 0", "o1": "rand(1000000)", "o2": "0"}), + ); + } + decision( + chain(vec![ + input(), + json!({"id": "dt", "name": "dt", "type": "decisionTableNode", "content": { + "hitPolicy": "collect", + "inputs": [{"id": "i1", "name": "x", "field": "x"}], + "outputs": [{"id": "o1", "name": "r", "field": "r"}, {"id": "o2", "name": "k", "field": "k"}], + "rules": rules + }}), + output(), + ]), + &[], + ) +} + +#[test] +fn table_rules_draw_by_rule_and_column() { + let plain = agree("tables", &located_tables(false), 127); + let extra = agree("tables with a rule before", &located_tables(true), 127); + for (a, b) in plain.iter().zip(&extra) { + let a = a.as_array().unwrap(); + let b = b.as_array().unwrap(); + assert_eq!(&b[1..], &a[..]); + assert_ne!(a[a.len() - 1]["r"], a[a.len() - 2]["r"]); + } +} + +fn located_policy(extra: bool) -> zen_engine::policy::PolicyDocument { + let mut document = serde_json::to_value(policy_document()).unwrap(); + if extra { + let blocks = document["blocks"].as_array_mut().unwrap(); + blocks.insert( + 2, + json!({"id": "e0", "type": "expression", "props": {"data": { + "key": "customer.first", "value": "rand(1000000)" + }}}), + ); + } + serde_json::from_value(document).unwrap() +} + +#[test] +fn policies_draw_by_block() { + compiled(); + let run = |extra: bool| { + let mut ws = zen_engine::Workspace::new(); + ws.set_policy("policy", located_policy(extra)); + let singles: Vec = (0..ROWS) + .map(|x| { + let r = ws + .evaluate_pinned(&policy_request(x, false), &pinned(row_seed(131, x))) + .unwrap(); + serde_json::to_value(&r.output).unwrap() + }) + .collect(); + let requests: Vec<_> = (0..ROWS).map(|x| policy_request(x, false)).collect(); + let batch = ws.evaluate_batch_pinned(&requests, &pinned(131)); + for (x, result) in batch.into_iter().enumerate() { + assert_eq!( + serde_json::to_value(&result.unwrap().output).unwrap(), + singles[x], + "policy batch row {x} ({extra})" + ); + } + singles + }; + let plain = run(false); + let extra = run(true); + for (a, b) in plain.iter().zip(&extra) { + let mut b = b.clone(); + assert!(b["customer"]["first"].is_number()); + b["customer"].as_object_mut().unwrap().remove("first"); + assert_eq!(a, &b); + assert_ne!(a["customer"]["lucky"], a["customer"]["after"]); + } +} diff --git a/core/engine/tests/engine.rs b/core/engine/tests/engine.rs index bceae4c5..0c4f1d48 100644 --- a/core/engine/tests/engine.rs +++ b/core/engine/tests/engine.rs @@ -569,6 +569,7 @@ async fn decision_table_index_matches_linear_semantics() { EvaluationOptions { trace: true, max_depth: 5, + ..Default::default() }, ) .await diff --git a/core/engine/tests/golden.rs b/core/engine/tests/golden.rs index 92060d53..ae5ed1b0 100644 --- a/core/engine/tests/golden.rs +++ b/core/engine/tests/golden.rs @@ -149,6 +149,7 @@ impl Graphs { EvaluationOptions { trace: true, max_depth: 10, + ..Default::default() } } @@ -156,6 +157,7 @@ impl Graphs { EvaluationSerializedOptions { trace: EvaluationTraceKind::Reference, max_depth: 10, + ..Default::default() } } @@ -331,6 +333,7 @@ impl Modes { let options = EvaluationSerializedOptions { trace: mode, max_depth: 10, + ..Default::default() }; let reference = matches!( mode, diff --git a/core/engine/tests/pinned.rs b/core/engine/tests/pinned.rs new file mode 100644 index 00000000..1c141b45 --- /dev/null +++ b/core/engine/tests/pinned.rs @@ -0,0 +1,436 @@ +use serde_json::{json, Value}; +use std::sync::Arc; +use zen_engine::columns::{Column, Columns, Values}; +use zen_engine::context::{clock_reads, parse_instant, parse_timezone, row_seed}; +use zen_engine::model::DecisionContent; +use zen_engine::{Decision, DecisionEngine, EvaluationOptions, Variable}; + +fn block(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(f) +} + +fn graph(middle: Value) -> Decision { + let content: DecisionContent = serde_json::from_value(json!({ + "nodes": [ + {"id": "in", "name": "in", "type": "inputNode"}, + middle, + {"id": "out", "name": "out", "type": "outputNode"} + ], + "edges": [ + {"id": "e1", "sourceId": "in", "targetId": "calc", "type": "edge"}, + {"id": "e2", "sourceId": "calc", "targetId": "out", "type": "edge"} + ] + })) + .unwrap(); + DecisionEngine::default() + .compiled_engine() + .create_decision(Arc::new(content)) + .unwrap() +} + +fn expressions() -> Decision { + graph(json!({ + "id": "calc", "name": "calc", "type": "expressionNode", + "content": {"expressions": [ + {"id": "x0", "key": "v", "value": "1"}, + {"id": "x1", "key": "v", "value": "x + 1"}, + {"id": "x2", "key": "r", "value": "rand(1000000)"}, + {"id": "x3", "key": "s", "value": "rand(1000000)"}, + {"id": "x4", "key": "t", "value": "d().timestamp()"}, + {"id": "x5", "key": "today", "value": "d().isToday()"}, + {"id": "x6", "key": "zone", "value": "d().offsetName()"}, + {"id": "x7", "key": "parsed", "value": "d('2026-01-02 10:00').timestamp()"} + ]} + })) +} + +fn functions() -> Decision { + graph(json!({ + "id": "calc", "name": "calc", "type": "functionNode", + "content": {"source": "export const handler = async (input) => ({ now: Date.now(), iso: new Date().toISOString(), same: Date.now() === new Date().getTime(), r: Math.random(), q: Math.random(), x: input.x })"} + })) +} + +fn input(x: i64) -> Variable { + Variable::from(json!({"x": x})) +} + +fn options(trace: bool, now: &str, seed: u64) -> EvaluationOptions { + EvaluationOptions { + trace, + now: parse_instant(now), + timezone: parse_timezone("Europe/Berlin"), + seed: Some(seed), + ..Default::default() + } +} + +fn untimed(v: Value) -> Value { + match v { + Value::Object(map) => Value::Object( + map.into_iter() + .filter(|(k, _)| k != "perf" && k != "performance" && k != "timings") + .map(|(k, x)| (k, untimed(x))) + .collect(), + ), + Value::Array(items) => Value::Array(items.into_iter().map(untimed).collect()), + other => other, + } +} + +fn evaluated(d: &Decision, x: i64, o: EvaluationOptions) -> (Value, Option) { + let r = block(d.evaluate_with_opts(input(x), o)).unwrap(); + let doc = r.trace.map(|t| serde_json::to_value(&t).unwrap()); + (serde_json::to_value(&r.result).unwrap(), doc) +} + +const NOW: &str = "2026-11-04T09:30:00.125Z"; + +#[test] +fn supplied_now_seed_and_zone_reproduce_results_and_traces() { + let d = expressions(); + let (a, da) = evaluated(&d, 4, options(true, NOW, 99)); + let (b, db) = evaluated(&d, 4, options(true, NOW, 99)); + assert_eq!(a, b); + assert_eq!(untimed(da.clone().unwrap()), untimed(db.unwrap())); + assert_eq!(da.unwrap()["calc"]["traceData"]["t"]["result"], a["t"]); + assert_eq!(a["t"], json!(1_793_784_600_125i64)); + assert_eq!(a["today"], json!(true)); + assert_eq!(a["zone"], json!("Europe/Berlin")); + assert_eq!(a["parsed"], json!(1_767_344_400_000i64)); + assert_ne!(a["r"], a["s"]); + let (c, _) = evaluated(&d, 4, options(false, NOW, 99)); + assert_eq!(a, c); + let (other, _) = evaluated(&d, 4, options(false, NOW, 100)); + assert_ne!((&a["r"], &a["s"]), (&other["r"], &other["s"])); +} + +fn real_clock(millis: &Value) -> bool { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + millis + .as_i64() + .is_some_and(|m| (now - m).abs() < 60_000 && m != 1_793_784_600_125i64) +} + +fn zoned_function() -> Decision { + graph(json!({ + "id": "calc", "name": "calc", "type": "functionNode", + "content": {"source": "export const handler = async (input) => { const d = new Date(Date.UTC(2026, 0, 15, 12, 34, 56)); const o = Intl.DateTimeFormat().resolvedOptions(); return { text: d.toString(), hours: d.getHours(), offset: d.getTimezoneOffset(), date: d.toDateString(), time: d.toTimeString(), local: d.toLocaleString(), localDate: d.toLocaleDateString(), localTime: d.toLocaleTimeString(), utc: d.toLocaleString(undefined, { timeZone: 'UTC' }), tagged: d.toLocaleDateString('de-DE'), zone: o.timeZone, midnight: new Date(2026, 0, 15).getTime(), parsed: new Date('2026-01-15T10:00:00').getTime(), iso: new Date('2026-01-15').getTime(), set: (() => { const x = new Date(Date.UTC(2026, 0, 15, 12)); x.setHours(0, 0, 0, 0); return x.toISOString(); })(), now: new Date().toString(), call: Date(), r: Math.random() }; }"} + })) +} + +fn zoned(zone: &str) -> EvaluationOptions { + EvaluationOptions { + timezone: parse_timezone(zone), + ..options(false, NOW, 3) + } +} + +#[test] +fn function_nodes_read_the_zone_of_the_context() { + let d = zoned_function(); + let (berlin, _) = evaluated(&d, 1, zoned("Europe/Berlin")); + let (tokyo, _) = evaluated(&d, 1, zoned("Asia/Tokyo")); + assert_eq!(berlin["text"], json!("Thu Jan 15 2026 13:34:56 GMT+0100")); + assert_eq!(tokyo["text"], json!("Thu Jan 15 2026 21:34:56 GMT+0900")); + assert_eq!( + (&berlin["hours"], &tokyo["hours"]), + (&json!(13), &json!(21)) + ); + assert_eq!( + (&berlin["offset"], &tokyo["offset"]), + (&json!(-60), &json!(-540)) + ); + assert_eq!(berlin["date"], json!("Thu Jan 15 2026")); + assert_eq!(tokyo["time"], json!("21:34:56 GMT+0900")); + assert_eq!(berlin["local"], json!("01/15/2026, 01:34:56 PM")); + assert_eq!(berlin["localDate"], json!("01/15/2026")); + assert_eq!(berlin["localTime"], json!("01:34:56 PM")); + assert_eq!(berlin["utc"], json!("01/15/2026, 12:34:56 PM")); + assert_eq!(berlin["tagged"], json!("01/15/2026")); + assert_eq!(tokyo["local"], json!("01/15/2026, 09:34:56 PM")); + assert_eq!(tokyo["localDate"], json!("01/15/2026")); + assert_eq!(tokyo["localTime"], json!("09:34:56 PM")); + assert_eq!(tokyo["utc"], json!("01/15/2026, 12:34:56 PM")); + assert_eq!(berlin["zone"], json!("Europe/Berlin")); + assert_eq!(tokyo["zone"], json!("Asia/Tokyo")); + assert_eq!(berlin["midnight"], json!(1_768_431_600_000i64)); + assert_eq!(tokyo["midnight"], json!(1_768_402_800_000i64)); + assert_eq!(berlin["parsed"], json!(1_768_467_600_000i64)); + assert_eq!(tokyo["parsed"], json!(1_768_438_800_000i64)); + assert_eq!(berlin["iso"], tokyo["iso"]); + assert_eq!(berlin["set"], json!("2026-01-14T23:00:00.000Z")); + assert_eq!(tokyo["set"], json!("2026-01-14T15:00:00.000Z")); + assert_eq!(berlin["now"], json!("Wed Nov 04 2026 10:30:00 GMT+0100")); + assert_eq!(tokyo["call"], json!("Wed Nov 04 2026 18:30:00 GMT+0900")); + assert_eq!(berlin["r"], tokyo["r"]); + for (zone, want) in [("Europe/Berlin", &berlin), ("Asia/Tokyo", &tokyo)] { + let (again, _) = evaluated(&d, 1, zoned(zone)); + assert_eq!(&again, want); + } +} + +#[test] +fn v1_function_nodes_read_the_zone_of_the_context() { + let d = graph(json!({ + "id": "calc", "name": "calc", "type": "functionNode", + "content": "const handler = (input) => ({ text: new Date(Date.UTC(2026, 0, 15, 12)).toString(), local: new Date(Date.UTC(2026, 0, 15, 12)).toLocaleDateString(), zone: Intl.DateTimeFormat().resolvedOptions().timeZone })" + })); + let (berlin, _) = evaluated(&d, 1, zoned("Europe/Berlin")); + let (york, _) = evaluated(&d, 1, zoned("America/New_York")); + assert_eq!(berlin["text"], json!("Thu Jan 15 2026 13:00:00 GMT+0100")); + assert_eq!(york["text"], json!("Thu Jan 15 2026 07:00:00 GMT-0500")); + assert_eq!(berlin["local"], json!("01/15/2026")); + assert_eq!(york["local"], json!("01/15/2026")); + assert_eq!(york["zone"], json!("America/New_York")); +} + +#[test] +fn the_interpreted_engine_ignores_pinning() { + let v2 = functions(); + let v1 = graph(json!({ + "id": "calc", "name": "calc", "type": "functionNode", + "content": "const handler = (input) => ({ now: Date.now(), r: Math.random(), q: Math.random() })" + })); + let zone = zoned_function().interpreted(); + let d = expressions().interpreted(); + for trace in [true, false] { + 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_ne!((&a["r"], &a["s"]), (&b["r"], &b["s"])); + if let Some(doc) = doc { + assert_eq!(doc["calc"]["traceData"]["t"]["result"], a["t"]); + } + for f in [&v2, &v1] { + let (pinned, _) = evaluated(f, 1, options(trace, NOW, 6)); + let (a, _) = evaluated(&f.interpreted(), 1, options(trace, NOW, 6)); + assert!(real_clock(&a["now"]), "{a}"); + assert_ne!((&a["r"], &a["q"]), (&pinned["r"], &pinned["q"])); + } + } + let r = block(zone.evaluate_with_opts(input(1), zoned("Asia/Tokyo"))); + assert!( + r.is_err(), + "the interpreted host has no Intl and no zone shim" + ); + let engine = policy_engine().interpreted(); + let run = |o: EvaluationOptions| { + let r = block(engine.evaluate_with_opts( + "policy", + Variable::from(json!({"customer": {"age": 3}})), + o, + )) + .unwrap(); + ( + serde_json::to_value(&r.result).unwrap(), + r.trace.map(|t| serde_json::to_value(&t).unwrap()), + ) + }; + let (a, doc) = run(options(true, NOW, 12)); + let (b, _) = run(options(true, NOW, 12)); + assert!(real_clock(&a["customer"]["at"]), "{a}"); + assert_ne!(a["customer"]["lucky"], b["customer"]["lucky"]); + let doc = doc.unwrap(); + assert!(doc["properties"].is_object()); + assert!(doc["executions"].is_array()); +} + +#[test] +fn an_unpinned_evaluation_uses_the_host_clock_and_a_fresh_seed() { + let d = expressions(); + let (a, _) = evaluated(&d, 7, EvaluationOptions::default()); + let (b, _) = evaluated(&d, 7, EvaluationOptions::default()); + assert!(real_clock(&a["t"]), "{a}"); + assert_ne!((&a["r"], &a["s"]), (&b["r"], &b["s"])); + let f = functions(); + let (a, _) = evaluated(&f, 7, EvaluationOptions::default()); + assert!(real_clock(&a["now"]), "{a}"); + assert_eq!(a["same"], json!(true)); +} + +#[test] +fn function_nodes_see_the_pinned_clock_and_stream() { + let d = functions(); + let (a, _) = evaluated(&d, 1, options(true, NOW, 5)); + assert_eq!(a["now"], json!(1_793_784_600_125i64)); + assert_eq!(a["iso"], json!(NOW)); + assert_eq!(a["same"], json!(true)); + assert_ne!(a["r"], a["q"]); + let (b, _) = evaluated(&d, 1, options(false, NOW, 5)); + assert_eq!(a, b); +} + +#[test] +fn batch_rows_replay_alone() { + let d = expressions(); + let inputs: Vec = (0..6).map(input).collect(); + for trace in [true, false] { + let batch = block(d.evaluate_batch(&inputs, options(trace, NOW, 31))); + let mut seen = Vec::new(); + for (row, result) in batch.into_iter().enumerate() { + let result = result.unwrap(); + let got = serde_json::to_value(&result.result).unwrap(); + let seed = row_seed(31, row); + let (alone, doc) = evaluated(&d, row as i64, options(true, NOW, seed)); + assert_eq!(got, alone, "row {row}"); + if let Some(t) = result.trace { + let t = serde_json::to_value(&t).unwrap(); + assert_eq!(untimed(t), untimed(doc.unwrap())); + } + seen.push(got["r"].clone()); + } + seen.dedup(); + assert!(seen.len() > 1, "rows draw from their own streams"); + } +} + +#[test] +fn columnar_rows_replay_alone() { + let d = expressions(); + let xs: Vec = (0..6).map(rust_decimal::Decimal::from).collect(); + let bits = vec![u64::MAX]; + let columns = Columns::new(6).column("x", Column::with_validity(Values::Dec(&xs), &bits, 0)); + let output = block(d.evaluate_columns(&columns, options(false, NOW, 8))); + for row in 0..6 { + let got = serde_json::to_value(output.row(row)).unwrap(); + let (alone, _) = evaluated(&d, row as i64, options(false, NOW, row_seed(8, row))); + assert_eq!(got, alone, "row {row}"); + } +} + +#[test] +fn the_clock_is_read_once_per_evaluation_and_batch() { + let d = graph(json!({ + "id": "calc", "name": "calc", "type": "expressionNode", + "content": {"expressions": [ + {"id": "a", "key": "a", "value": "x * 2"}, + {"id": "b", "key": "t", "value": "d().timestamp()"}, + {"id": "c", "key": "u", "value": "d().timestamp() + 0"}, + {"id": "e", "key": "today", "value": "d().isToday()"} + ]} + })); + let f = functions(); + let plain = graph(json!({ + "id": "calc", "name": "calc", "type": "expressionNode", + "content": {"expressions": [{"id": "a", "key": "a", "value": "x * 2"}]} + })); + let unpinned = EvaluationOptions::default(); + let before = clock_reads(); + let (one, _) = evaluated(&d, 1, unpinned); + assert_eq!(one["t"], one["u"]); + assert_eq!(clock_reads() - before, 1); + let before = clock_reads(); + let (one, _) = evaluated(&f, 1, unpinned); + assert_eq!(one["same"], json!(true)); + assert_eq!(clock_reads() - before, 1); + let inputs: Vec = (0..40).map(input).collect(); + let before = clock_reads(); + let batch = block(d.evaluate_batch(&inputs, unpinned)); + assert_eq!(clock_reads() - before, 1); + let stamps: Vec = batch + .into_iter() + .map(|r| serde_json::to_value(r.unwrap().result).unwrap()["t"].clone()) + .collect(); + assert!(stamps.iter().all(|t| t == &stamps[0])); + let xs: Vec = (0..40).map(rust_decimal::Decimal::from).collect(); + let bits = vec![u64::MAX]; + let columns = Columns::new(40).column("x", Column::with_validity(Values::Dec(&xs), &bits, 0)); + let before = clock_reads(); + let output = block(d.evaluate_columns(&columns, unpinned)); + assert_eq!(clock_reads() - before, 1); + let first = serde_json::to_value(output.row(0)).unwrap()["t"].clone(); + assert!((0..40).all(|row| serde_json::to_value(output.row(row)).unwrap()["t"] == first)); + let before = clock_reads(); + let _ = block(plain.evaluate_batch(&inputs, unpinned)); + let _ = evaluated(&plain, 1, unpinned); + assert_eq!(clock_reads() - before, 0); + let before = clock_reads(); + let _ = block(d.evaluate_batch(&inputs, options(false, NOW, 1))); + assert_eq!(clock_reads() - before, 0); +} + +fn policy_engine() -> DecisionEngine { + let policy: zen_engine::policy::PolicyDocument = serde_json::from_value(json!({ + "blocks": [ + {"id": "dm", "type": "dataModel", "props": {"data": {"name": "customer", "properties": [ + {"id": "p1", "name": "age", "type": "number", "array": false, "optional": false} + ]}}, "children": []}, + {"id": "e1", "type": "expression", "props": {"data": { + "key": "customer.lucky", "value": "rand(1000000) + customer.age" + }}}, + {"id": "e2", "type": "expression", "props": {"data": { + "key": "customer.at", "value": "d().timestamp()" + }}} + ] + })) + .unwrap(); + let loader = Arc::new(zen_engine::loader::MemoryLoader::default()); + loader.add( + "policy", + DecisionContent::Policy(zen_engine::model::PolicyContent(Arc::new(policy))), + ); + DecisionEngine::default().with_loader(loader) +} + +#[test] +fn policies_pin_the_clock_and_stream() { + let engine = policy_engine().compiled_engine(); + let run = |o: EvaluationOptions| { + let r = block(engine.evaluate_with_opts( + "policy", + Variable::from(json!({"customer": {"age": 3}})), + o, + )) + .unwrap(); + ( + serde_json::to_value(&r.result).unwrap(), + r.trace.map(|t| serde_json::to_value(&t).unwrap()), + ) + }; + let (a, doc) = run(options(true, NOW, 12)); + let (b, again) = run(options(true, NOW, 12)); + let (c, _) = run(options(false, NOW, 12)); + assert_eq!(a, b); + assert_eq!(a, c); + assert_eq!(untimed(doc.unwrap()), untimed(again.unwrap())); + assert_eq!(a["customer"]["at"], json!(1_793_784_600_125i64)); + let inputs: Vec = (0..4) + .map(|age| Variable::from(json!({"customer": {"age": age}}))) + .collect(); + let batch = block(engine.evaluate_batch("policy", &inputs, options(false, NOW, 12))); + for (row, result) in batch.into_iter().enumerate() { + let got = serde_json::to_value(result.unwrap().result).unwrap(); + let r = block(engine.evaluate_with_opts( + "policy", + inputs[row].clone(), + options(false, NOW, row_seed(12, row)), + )) + .unwrap(); + assert_eq!(got, serde_json::to_value(r.result).unwrap(), "row {row}"); + } +} + +#[test] +fn v1_function_nodes_see_the_pinned_clock_and_stream() { + { + let d = graph(json!({ + "id": "calc", "name": "calc", "type": "functionNode", + "content": "const handler = (input) => ({ now: Date.now(), global: now, iso: new Date().toISOString(), r: Math.random(), q: Math.random() })" + })); + let (a, _) = evaluated(&d, 1, options(true, NOW, 6)); + assert_eq!(a["now"], json!(1_793_784_600_125i64)); + assert_eq!(a["global"], json!(1_793_784_600_125i64)); + assert_eq!(a["iso"], json!(NOW)); + assert_ne!(a["r"], a["q"]); + let (b, _) = evaluated(&d, 1, options(false, NOW, 6)); + assert_eq!(a, b); + } +} diff --git a/core/engine/tests/table_dialects.rs b/core/engine/tests/table_dialects.rs index b6eec5a7..cd58a8cc 100644 --- a/core/engine/tests/table_dialects.rs +++ b/core/engine/tests/table_dialects.rs @@ -343,6 +343,7 @@ impl Table { EvaluationOptions { trace: true, max_depth: 10, + ..Default::default() }, )); let graph_trace = match &traced { diff --git a/core/engine/tests/workspace_graph_enhance.rs b/core/engine/tests/workspace_graph_enhance.rs index 24981ab2..2b086629 100644 --- a/core/engine/tests/workspace_graph_enhance.rs +++ b/core/engine/tests/workspace_graph_enhance.rs @@ -66,6 +66,7 @@ async fn graph_trace(documents: &[(&str, Value)], entry: &str, input: Value) -> EvaluationOptions { trace: true, max_depth: 10, + ..Default::default() }, ) .await diff --git a/core/expression/Cargo.toml b/core/expression/Cargo.toml index 3040c2e2..104e6387 100644 --- a/core/expression/Cargo.toml +++ b/core/expression/Cargo.toml @@ -17,7 +17,6 @@ bumpalo = { workspace = true, features = ["collections"] } chrono = { workspace = true } chrono-tz = "0.10" humantime = { workspace = true } -fastrand = { workspace = true } once_cell = { workspace = true } regex = { workspace = true, optional = true } regex-lite = { workspace = true, optional = true } diff --git a/core/expression/benches/lane.rs b/core/expression/benches/lane.rs index f97982e6..9623d7b8 100644 --- a/core/expression/benches/lane.rs +++ b/core/expression/benches/lane.rs @@ -3,6 +3,7 @@ use serde_json::Value; use std::collections::BTreeMap; use std::hint::black_box; use std::time::{Duration, Instant}; +use zen_expression::context::EvaluationContext; use zen_expression::lane::{Column, Columns, LaneProgram, LaneRunner, Values}; use zen_expression::variable::VariableType; use zen_expression::vm::VM; @@ -615,7 +616,11 @@ fn micro() -> bool { }, || { for scope in &scopes { - black_box(runner.evaluate_one(&program, scope).is_ok()); + black_box( + runner + .evaluate_one(&program, &EvaluationContext::default(), scope) + .is_ok(), + ); } }, ) / rows as f64; @@ -625,7 +630,9 @@ fn micro() -> bool { } let batch = Bench::timed(budget, || { let mut n = 0usize; - runner.evaluate_with(&program, &scopes, |_, r| n += r.is_ok() as usize); + runner.evaluate_with(&program, &EvaluationContext::default(), &scopes, |_, r| { + n += r.is_ok() as usize + }); black_box(n); }) / rows as f64; let table = Table::build(&scopes); @@ -642,7 +649,7 @@ fn micro() -> bool { let mut out = zen_expression::lane::Output::new(); if let (Ok(_), Some(p)) = (std::env::var("LANE_PROFILE_COLS"), &columnar) { let ns = Bench::timed(Duration::from_secs(4), || { - runner.evaluate_columns_into(p, &columns, &mut out); + runner.evaluate_columns_into(p, &EvaluationContext::default(), &columns, &mut out); black_box(out.len()); }) / rows as f64; println!("{entry} cols {ns:.1}"); @@ -651,7 +658,12 @@ fn micro() -> bool { let cols = match &columnar { Some(p) => { Bench::timed(budget, || { - runner.evaluate_columns_into(p, &columns, &mut out); + runner.evaluate_columns_into( + p, + &EvaluationContext::default(), + &columns, + &mut out, + ); black_box(out.len()); }) / rows as f64 } @@ -665,12 +677,18 @@ fn micro() -> bool { .expect("lane compile"); let cold1 = Bench::timed(budget, || { for scope in &scopes { - black_box(runner.evaluate_one(&generic, scope).is_ok()); + black_box( + runner + .evaluate_one(&generic, &EvaluationContext::default(), scope) + .is_ok(), + ); } }) / rows as f64; let cold64 = Bench::timed(budget, || { let mut n = 0usize; - runner.evaluate_with(&generic, &scopes, |_, r| n += r.is_ok() as usize); + runner.evaluate_with(&generic, &EvaluationContext::default(), &scopes, |_, r| { + n += r.is_ok() as usize + }); black_box(n); }) / rows as f64; println!( @@ -759,7 +777,13 @@ fn cells() -> bool { let mut runner = LaneRunner::new(); let mut out = Vec::new(); let lane = Bench::timed(Duration::from_millis(400), || { - set.evaluate(&mut runner, &values, &envs, &mut out); + set.evaluate( + &mut runner, + &values, + &envs, + &mut out, + &EvaluationContext::default(), + ); black_box(out.len()); }) / ROWS as f64; println!("cells rules {rules:5}: evaluate every cell (stack VM) {stack:10.0} ns/row | cell set {lane:8.1} ns/row | {:6.1}x", stack / lane); @@ -858,15 +882,27 @@ fn nodes() -> bool { }) / ROWS as f64; let one = Bench::timed(budget, || { for scope in &scopes { - runner.evaluate_many(&program, std::slice::from_ref(scope), None, |_, r| { - black_box(r.is_some()); - }); + runner.evaluate_many( + &program, + &EvaluationContext::default(), + std::slice::from_ref(scope), + None, + |_, r| { + black_box(r.is_some()); + }, + ); } }) / ROWS as f64; let batch = Bench::timed(budget, || { - runner.evaluate_many(&program, &scopes, None, |_, r| { - black_box(r.is_some()); - }); + runner.evaluate_many( + &program, + &EvaluationContext::default(), + &scopes, + None, + |_, r| { + black_box(r.is_some()); + }, + ); }) / ROWS as f64; stack_all.push(stack); one_all.push(one); @@ -939,12 +975,21 @@ fn main() { }) / ROWS as f64; let one = Bench::timed(budget, || { for scope in &case.scopes { - black_box(runner.evaluate_one(&program, scope).is_ok()); + black_box( + runner + .evaluate_one(&program, &EvaluationContext::default(), scope) + .is_ok(), + ); } }) / ROWS as f64; let batch = Bench::timed(budget, || { let mut n = 0usize; - runner.evaluate_with(&program, &case.scopes, |_, r| n += r.is_ok() as usize); + runner.evaluate_with( + &program, + &EvaluationContext::default(), + &case.scopes, + |_, r| n += r.is_ok() as usize, + ); black_box(n); }) / ROWS as f64; let table = Table::build(&case.scopes); @@ -961,7 +1006,12 @@ fn main() { }, || { let mut n = 0usize; - runner.evaluate_columns(&columnar, &columns, |_, r| n += r.is_ok() as usize); + runner.evaluate_columns( + &columnar, + &EvaluationContext::default(), + &columns, + |_, r| n += r.is_ok() as usize, + ); black_box(n); }, ) / ROWS as f64; @@ -973,7 +1023,12 @@ fn main() { budget }, || { - runner.evaluate_columns_into(&columnar, &columns, &mut out); + runner.evaluate_columns_into( + &columnar, + &EvaluationContext::default(), + &columns, + &mut out, + ); black_box(out.len()); }, ) / ROWS as f64; @@ -1022,12 +1077,18 @@ fn main() { let leg = |p: &LaneProgram, runner: &mut LaneRunner| { let w1 = Bench::timed(budget, || { for scope in &case.scopes { - black_box(runner.evaluate_one(p, scope).is_ok()); + black_box( + runner + .evaluate_one(p, &EvaluationContext::default(), scope) + .is_ok(), + ); } }) / ROWS as f64; let w64 = Bench::timed(budget, || { let mut n = 0usize; - runner.evaluate_with(p, &case.scopes, |_, r| n += r.is_ok() as usize); + runner.evaluate_with(p, &EvaluationContext::default(), &case.scopes, |_, r| { + n += r.is_ok() as usize + }); black_box(n); }) / ROWS as f64; (w1, w64) @@ -1035,7 +1096,12 @@ fn main() { let (g1, g64) = leg(&generic, &mut runner); let (t1, t64) = leg(&typed_program, &mut runner); let gc = Bench::timed(budget, || { - runner.evaluate_columns_into(&generic, &columns, &mut out); + runner.evaluate_columns_into( + &generic, + &EvaluationContext::default(), + &columns, + &mut out, + ); black_box(out.len()); }) / ROWS as f64; typing.push([s, one, batch, typed, g1, g64, gc, t1, t64]); @@ -1525,27 +1591,43 @@ fn scenarios() -> bool { "isolate" => isolate_rows(p), "lane_single" => { for scope in &p.case.scopes { - black_box(runner.evaluate_one(&p.program, scope).is_ok()); + black_box( + runner + .evaluate_one(&p.program, &EvaluationContext::default(), scope) + .is_ok(), + ); } } "lane_batch" => { let mut n = 0usize; - runner.evaluate_with(&p.program, &p.case.scopes, |_, r| { - n += r.is_ok() as usize - }); + runner.evaluate_with( + &p.program, + &EvaluationContext::default(), + &p.case.scopes, + |_, r| n += r.is_ok() as usize, + ); black_box(n); } "lane_columns" => { if let (Some(program), Some(columns)) = (&columnar[i], &columns[i]) { let mut n = 0usize; - runner - .evaluate_columns(program, columns, |_, r| n += r.is_ok() as usize); + runner.evaluate_columns( + program, + &EvaluationContext::default(), + columns, + |_, r| n += r.is_ok() as usize, + ); black_box(n); } } "lane_typed" => { if let (Some(program), Some(columns)) = (&columnar[i], &columns[i]) { - runner.evaluate_columns_into(program, columns, &mut out); + runner.evaluate_columns_into( + program, + &EvaluationContext::default(), + columns, + &mut out, + ); black_box(out.len()); } } @@ -1573,17 +1655,30 @@ fn scenarios() -> bool { let isolate = per(Bench::timed(budget, || isolate_rows(p))); let single = per(Bench::timed(budget, || { for scope in &case.scopes { - black_box(runner.evaluate_one(&p.program, scope).is_ok()); + black_box( + runner + .evaluate_one(&p.program, &EvaluationContext::default(), scope) + .is_ok(), + ); } })); let single_generic = per(Bench::timed(budget, || { for scope in &case.scopes { - black_box(runner.evaluate_one(&p.generic, scope).is_ok()); + black_box( + runner + .evaluate_one(&p.generic, &EvaluationContext::default(), scope) + .is_ok(), + ); } })); let batch = per(Bench::timed(budget, || { let mut n = 0usize; - runner.evaluate_with(&p.program, &case.scopes, |_, r| n += r.is_ok() as usize); + runner.evaluate_with( + &p.program, + &EvaluationContext::default(), + &case.scopes, + |_, r| n += r.is_ok() as usize, + ); black_box(n); })); let (mut columns_ns, mut typed_ns, mut specialize_columns_ns) = (None, None, None); @@ -1596,12 +1691,22 @@ fn scenarios() -> bool { if let Ok(columnar) = p.generic.specialize_columns(&columns) { columns_ns = Some(per(Bench::timed(budget, || { let mut n = 0usize; - runner.evaluate_columns(&columnar, &columns, |_, r| n += r.is_ok() as usize); + runner.evaluate_columns( + &columnar, + &EvaluationContext::default(), + &columns, + |_, r| n += r.is_ok() as usize, + ); black_box(n); }))); let mut out = zen_expression::lane::Output::new(); typed_ns = Some(per(Bench::timed(budget, || { - runner.evaluate_columns_into(&columnar, &columns, &mut out); + runner.evaluate_columns_into( + &columnar, + &EvaluationContext::default(), + &columns, + &mut out, + ); black_box(out.len()); }))); specialize_columns_ns = Some(compile(&mut || { diff --git a/core/expression/src/context.rs b/core/expression/src/context.rs new file mode 100644 index 00000000..8c98b1d6 --- /dev/null +++ b/core/expression/src/context.rs @@ -0,0 +1,990 @@ +use chrono::{DateTime, Utc}; +use chrono_tz::Tz; +use std::cell::{Cell, OnceCell, RefCell}; +use std::collections::BTreeMap; +use std::fmt::Debug; +use std::rc::Rc; +use std::str::FromStr; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; + +pub use chrono_tz::Tz as Timezone; + +pub type Instant = DateTime; + +const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15; +const DRAWN_BITS: u64 = (1 << 53) - 1; + +fn mix(mut z: u64) -> u64 { + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +pub fn row_seed(base: u64, row: usize) -> u64 { + mix(base ^ mix((row as u64).wrapping_add(1).wrapping_mul(GAMMA))) & DRAWN_BITS +} + +const FNV_OFFSET: u64 = 0xCBF2_9CE4_8422_2325; +const FNV_PRIME: u64 = 0x0000_0100_0000_01B3; +const SCOPE_KEY: u64 = 0xA076_1D64_78BD_642F; +const SITE_KEY: u64 = 0xE703_7ED1_A0B4_28DB; + +pub fn location(parts: &[&str]) -> u64 { + let mut hash = FNV_OFFSET; + for part in parts { + for byte in part.bytes().chain(std::iter::once(0xFF)) { + hash = (hash ^ byte as u64).wrapping_mul(FNV_PRIME); + } + } + match mix(hash) { + 0 => 1, + located => located, + } +} + +fn entropy() -> u64 { + use std::hash::{BuildHasher, Hasher}; + static DRAWN: AtomicU64 = AtomicU64::new(0); + let mut hasher = std::collections::hash_map::RandomState::new().build_hasher(); + hasher.write_u64(DRAWN.fetch_add(1, Ordering::Relaxed)); + hasher.write_usize(&hasher as *const _ as usize); + mix(hasher.finish()) +} + +fn nest(scope: u64, part: u64) -> u64 { + mix(scope.wrapping_mul(GAMMA) ^ part ^ SCOPE_KEY) +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Site { + label: u64, + index: u32, +} + +impl Site { + pub const SCRIPT: Site = Site { + label: 0, + index: u32::MAX, + }; + + pub const fn new(label: u64, index: u32) -> Self { + Self { label, index } + } + + pub const fn label(&self) -> u64 { + self.label + } + + pub const fn index(&self) -> u32 { + self.index + } + + pub const fn labelled(self, label: u64) -> Self { + Self { + label, + index: self.index, + } + } + + fn key(&self, scope: u64, field: u64) -> u64 { + let field = match self.label { + 0 => field, + label => label, + }; + let located = mix(mix(scope ^ SITE_KEY) ^ field); + mix(located ^ (self.index as u64).wrapping_add(1).wrapping_mul(GAMMA)) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Draw { + base: u64, + address: u64, +} + +impl Draw { + fn new(base: u64, key: u64, n: u64) -> Self { + Self { + base, + address: mix(mix(key).wrapping_add(n.wrapping_add(1).wrapping_mul(GAMMA))), + } + } + + pub fn word(&self, i: u64) -> u64 { + mix(mix(self.base ^ self.address).wrapping_add(i.wrapping_add(1).wrapping_mul(GAMMA))) + } + + pub fn unit(&self) -> f64 { + (self.word(0) >> 11) as f64 / (1u64 << 53) as f64 + } + + pub fn int(&self, upper: i64) -> Option { + let range = u64::try_from(upper).ok()?.wrapping_add(1); + let mut i = 0; + loop { + let product = self.word(i) as u128 * range as u128; + let low = product as u64; + if low >= range || low >= range.wrapping_neg() % range { + return Some((product >> 64) as i64); + } + i += 1; + } + } + + pub fn fresh() -> Self { + Self { + base: entropy(), + address: entropy(), + } + } +} + +thread_local! { + static CLOCK_READS: Cell = const { Cell::new(0) }; +} + +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) +} + +pub fn system_timezone() -> Tz { + static CACHED: OnceLock = OnceLock::new(); + *CACHED.get_or_init(|| { + iana_time_zone::get_timezone() + .ok() + .and_then(|tz| Tz::from_str(&tz).ok()) + .unwrap_or(Tz::UTC) + }) +} + +pub fn parse_timezone(name: &str) -> Option { + Tz::from_str(name).ok() +} + +pub fn parse_instant(text: &str) -> Option { + DateTime::parse_from_rfc3339(text) + .ok() + .map(|d| d.with_timezone(&Utc)) +} + +pub fn instant_from_millis(ms: i64) -> Option { + DateTime::from_timestamp_millis(ms) +} + +pub fn clock_reads() -> u64 { + CLOCK_READS.get() +} + +pub fn unrowed_draws() -> u64 { + UNROWED.load(Ordering::Relaxed) +} + +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Pinned { + pub now: Option, + pub timezone: Option, + pub seed: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Stream { + Root, + Row(u32), + Item(u32), +} + +#[derive(Debug, Clone, Default)] +struct Node { + seed: Option, + draws: u64, + touched: bool, + counts: Vec<(u64, u64)>, +} + +impl Node { + fn drew(&self) -> bool { + self.draws > 0 || self.touched + } + + fn count(&mut self, key: u64) -> u64 { + self.draws += 1; + match self.counts.binary_search_by_key(&key, |&(k, _)| k) { + Ok(at) => { + let n = self.counts[at].1; + self.counts[at].1 += 1; + n + } + Err(at) => { + self.counts.insert(at, (key, 1)); + 0 + } + } + } +} + +#[derive(Debug)] +struct Item { + parent: Stream, + index: usize, + node: Node, +} + +#[derive(Debug, Default)] +struct Streams { + root: Node, + rows: Vec, + items: Vec, + children: BTreeMap<(Stream, usize), u32>, +} + +impl Streams { + fn row(&mut self, row: u32) -> &mut Node { + let at = row as usize; + if self.rows.len() <= at { + self.rows.resize(at + 1, Node::default()); + } + &mut self.rows[at] + } + + fn node(&mut self, stream: Stream) -> Option<&mut Node> { + match stream { + Stream::Root => Some(&mut self.root), + Stream::Row(row) => Some(self.row(row)), + Stream::Item(item) => self.items.get_mut(item as usize).map(|item| &mut item.node), + } + } + + fn peek(&self, stream: Stream) -> Option<&Node> { + match stream { + Stream::Root => Some(&self.root), + Stream::Row(row) => self.rows.get(row as usize), + Stream::Item(item) => self.items.get(item as usize).map(|item| &item.node), + } + } + + fn parent(&self, stream: Stream) -> Option { + match stream { + Stream::Root => None, + Stream::Row(_) => Some(Stream::Root), + Stream::Item(item) => self.items.get(item as usize).map(|item| item.parent), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn base(&mut self, stream: Stream) -> u64 { + if let Some(seed) = self.node(stream).and_then(|node| node.seed) { + return seed; + } + let seed = match stream { + Stream::Root => entropy() & DRAWN_BITS, + Stream::Row(row) => row_seed(self.base(Stream::Root), row as usize), + Stream::Item(item) => match self.items.get(item as usize) { + Some(&Item { parent, index, .. }) => row_seed(self.base(parent), index), + None => entropy() & DRAWN_BITS, + }, + }; + if let Some(node) = self.node(stream) { + node.seed = Some(seed); + } + seed + } + + fn touch(&mut self, stream: Stream) { + let mut up = self.parent(stream); + while let Some(parent) = up { + match self.node(parent) { + Some(node) if !node.touched => node.touched = true, + _ => break, + } + up = self.parent(parent); + } + } + + fn draw(&mut self, stream: Stream, key: u64) -> Draw { + let base = self.base(stream); + let n = self.node(stream).map_or(0, |node| node.count(key)); + self.touch(stream); + Draw::new(base, key, n) + } + + fn child(&mut self, parent: Stream, index: usize) -> Stream { + if let Some(&item) = self.children.get(&(parent, index)) { + return Stream::Item(item); + } + let item = self.items.len() as u32; + self.items.push(Item { + parent, + index, + node: Node::default(), + }); + self.children.insert((parent, index), item); + Stream::Item(item) + } + + fn restart(&mut self, row: u32) { + if let Some(node) = self.rows.get_mut(row as usize) { + *node = Node::default(); + } + let parent = Stream::Row(row); + let stale: Vec<(Stream, usize)> = self + .children + .range((parent, 0)..=(parent, usize::MAX)) + .map(|(key, _)| *key) + .collect(); + for key in stale { + self.children.remove(&key); + } + } +} + +#[derive(Debug)] +struct Shared { + now: OnceCell, + timezone: Tz, + batch: bool, + streams: RefCell, +} + +impl Shared { + fn new(pinned: Pinned, batch: bool) -> Self { + let streams = Streams { + root: Node { + seed: pinned.seed, + ..Node::default() + }, + ..Streams::default() + }; + Self { + now: pinned.now.map_or_else(OnceCell::new, OnceCell::from), + timezone: pinned.timezone.unwrap_or_else(system_timezone), + batch, + streams: RefCell::new(streams), + } + } + + fn now(&self) -> Instant { + *self.now.get_or_init(|| { + CLOCK_READS.set(CLOCK_READS.get() + 1); + system_now() + }) + } + + fn row_stream(&self, row: usize) -> Stream { + match self.batch { + true => Stream::Row(row as u32), + false => Stream::Root, + } + } + + fn child(&self, parent: Stream, index: usize) -> Stream { + self.streams.borrow_mut().child(parent, index) + } + + fn existing(&self, pick: Pick) -> Option { + match pick { + Pick::Stream(stream) => Some(stream), + Pick::Child(parent, index) => self + .streams + .borrow() + .children + .get(&(parent, index)) + .map(|&item| Stream::Item(item)), + } + } + + fn seed(&self) -> Option { + let streams = self.streams.borrow(); + let root = &streams.root; + let drew = match self.batch { + true => root.draws > 0, + false => root.drew(), + }; + drew.then_some(root.seed).flatten() + } + + fn stream_seed(&self, stream: Stream) -> Option { + if stream == Stream::Root { + return self.seed(); + } + let streams = self.streams.borrow(); + streams + .peek(stream) + .filter(|node| node.drew()) + .and_then(|node| node.seed) + } + + fn draw(&self, stream: Stream, key: u64) -> Draw { + if self.batch && stream == Stream::Root { + UNROWED.fetch_add(1, Ordering::Relaxed); + } + self.streams.borrow_mut().draw(stream, key) + } +} + +#[derive(Debug, Clone, Copy)] +enum Pick { + Stream(Stream), + Child(Stream, usize), +} + +impl Pick { + fn resolve(self, shared: &Shared) -> Stream { + match self { + Pick::Stream(stream) => stream, + Pick::Child(parent, index) => shared.child(parent, index), + } + } +} + +#[derive(Debug, Clone, Default)] +enum Rows { + #[default] + Direct, + One(Pick), + Picked(Rc), + Items(Rc), +} + +#[derive(Debug)] +struct Picked { + rows: Rc<[usize]>, + rest: Rows, +} + +#[derive(Debug)] +struct Items { + items: Rc<[(usize, usize)]>, + rest: Rows, +} + +impl Rows { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn pick(&self, shared: &Shared, row: usize) -> Pick { + match self { + Rows::Direct => Pick::Stream(shared.row_stream(row)), + Rows::One(pick) => *pick, + Rows::Picked(picked) => { + let row = picked.rows.get(row).copied().unwrap_or(row); + picked.rest.pick(shared, row) + } + Rows::Items(items) => match items.items.get(row) { + Some(&(at, index)) => { + Pick::Child(items.rest.pick(shared, at).resolve(shared), index) + } + None => items.rest.pick(shared, row), + }, + } + } +} + +#[derive(Debug, Clone)] +pub struct EvaluationContext { + shared: Rc, + rows: Rows, + scope: u64, + field: u64, +} + +impl Default for EvaluationContext { + fn default() -> Self { + Self::new(Pinned::default()) + } +} + +impl EvaluationContext { + pub fn new(pinned: Pinned) -> Self { + Self { + shared: Rc::new(Shared::new(pinned, false)), + rows: Rows::Direct, + scope: 0, + field: 0, + } + } + + pub fn batch(pinned: Pinned) -> Self { + Self { + shared: Rc::new(Shared::new(pinned, true)), + rows: Rows::Direct, + scope: 0, + field: 0, + } + } + + pub fn is_batch(&self) -> bool { + self.shared.batch + } + + pub fn now(&self) -> Instant { + self.shared.now() + } + + pub fn timezone(&self) -> Tz { + self.shared.timezone + } + + pub fn row(&self, row: usize) -> RowContext<'_> { + RowContext::new(self, row) + } + + pub fn stream(&self, row: usize) -> Stream { + self.rows.pick(&self.shared, row).resolve(&self.shared) + } + + pub fn is_direct(&self) -> bool { + matches!(self.rows, Rows::Direct) + } + + fn uniform(&self) -> bool { + match self.rows { + Rows::Direct => !self.shared.batch, + Rows::One(_) => true, + Rows::Picked(_) | Rows::Items(_) => false, + } + } + + fn narrowed(&self, rows: Rows) -> Self { + Self { + shared: self.shared.clone(), + rows, + scope: self.scope, + field: self.field, + } + } + + pub fn nested(&self, part: u64) -> Self { + Self { + shared: self.shared.clone(), + rows: self.rows.clone(), + scope: nest(self.scope, part), + field: 0, + } + } + + pub fn located(&self, field: u64) -> Self { + Self { + shared: self.shared.clone(), + rows: self.rows.clone(), + scope: self.scope, + field, + } + } + + pub fn scope(&self) -> u64 { + self.scope + } + + pub fn field(&self) -> u64 { + self.field + } + + pub fn rows(&self, rows: &[usize]) -> Self { + if self.uniform() { + return self.clone(); + } + self.picked(Rc::from(rows)) + } + + pub fn picked(&self, rows: Rc<[usize]>) -> Self { + if self.uniform() { + return self.clone(); + } + self.narrowed(Rows::Picked(Rc::new(Picked { + rows, + rest: self.rows.clone(), + }))) + } + + pub fn items(&self, items: &[(usize, usize)]) -> Self { + self.narrowed(Rows::Items(Rc::new(Items { + items: Rc::from(items), + rest: self.rows.clone(), + }))) + } + + pub fn item(&self, index: usize) -> Self { + let parent = self.rows.pick(&self.shared, 0).resolve(&self.shared); + self.narrowed(Rows::One(Pick::Child(parent, index))) + } + + pub fn at(&self, row: usize) -> Self { + if self.uniform() { + return self.clone(); + } + self.narrowed(Rows::One(self.rows.pick(&self.shared, row))) + } + + pub fn restart(&self, rows: &[usize]) { + if !self.is_direct() || !self.shared.batch { + return; + } + let mut streams = self.shared.streams.borrow_mut(); + for &row in rows { + streams.restart(row as u32); + } + } + + pub fn seed(&self) -> Option { + match self.rows { + Rows::One(pick) => self + .shared + .existing(pick) + .and_then(|stream| self.shared.stream_seed(stream)), + _ => self.shared.seed(), + } + } + + pub fn row_seed(&self, row: usize) -> Option { + match (&self.rows, self.shared.batch) { + (Rows::Direct, true) => self.shared.stream_seed(Stream::Row(row as u32)), + _ => self.seed(), + } + } + + pub fn draw(&self, row: usize, site: Site) -> Draw { + let key = site.key(self.scope, self.field); + self.shared.draw(self.stream(row), key) + } + + pub fn next_u64(&self, row: usize, site: Site) -> u64 { + self.draw(row, site).word(0) + } + + pub fn random_f64(&self, row: usize, site: Site) -> f64 { + self.draw(row, site).unit() + } + + pub fn random_int(&self, row: usize, site: Site, upper: i64) -> Option { + self.draw(row, site).int(upper) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct RowContext<'a> { + context: &'a EvaluationContext, + row: usize, + site: Site, +} + +impl<'a> RowContext<'a> { + pub fn new(context: &'a EvaluationContext, row: usize) -> Self { + Self { + context, + row, + site: Site::default(), + } + } + + pub fn with_site(self, site: Site) -> Self { + Self { site, ..self } + } + + pub fn site(&self) -> Site { + self.site + } + + pub fn context(&self) -> &'a EvaluationContext { + self.context + } + + pub fn index(&self) -> usize { + self.row + } + + pub fn now(&self) -> Instant { + self.context.now() + } + + pub fn timezone(&self) -> Tz { + self.context.timezone() + } + + pub fn next_u64(&self) -> u64 { + self.context.next_u64(self.row, self.site) + } + + pub fn random_f64(&self) -> f64 { + self.context.random_f64(self.row, self.site) + } + + pub fn random_int(&self, upper: i64) -> Option { + self.context.random_int(self.row, self.site, upper) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SITE: Site = Site::new(0, 0); + + fn seeded(seed: u64) -> Pinned { + Pinned { + seed: Some(seed), + ..Pinned::default() + } + } + + #[test] + fn a_seeded_context_repeats_its_stream() { + let pinned = Pinned { + timezone: Some(Tz::UTC), + ..seeded(42) + }; + let a = EvaluationContext::new(pinned); + let b = EvaluationContext::new(pinned); + let xs: Vec> = (0..8).map(|_| a.random_int(0, SITE, 1000)).collect(); + let ys: Vec> = (0..8).map(|_| b.random_int(0, SITE, 1000)).collect(); + assert_eq!(xs, ys); + assert_eq!(a.seed(), Some(42)); + } + + #[test] + fn a_context_reads_now_once() { + let before = clock_reads(); + let context = EvaluationContext::default(); + assert_eq!(clock_reads(), before); + let first = context.now(); + std::thread::sleep(std::time::Duration::from_millis(2)); + assert_eq!(context.now(), first); + assert_eq!(context.at(3).item(2).now(), first); + assert_eq!(clock_reads(), before + 1); + assert_eq!(context.seed(), None); + } + + #[test] + fn a_batch_reads_now_once_for_all_rows() { + let before = clock_reads(); + let batch = EvaluationContext::batch(Pinned::default()); + let rows: Vec = (0..16).map(|row| batch.at(row).now()).collect(); + assert!(rows.iter().all(|at| *at == rows[0])); + assert_eq!(clock_reads(), before + 1); + let pinned = EvaluationContext::batch(Pinned { + now: parse_instant("2026-11-04T09:30:00Z"), + ..Pinned::default() + }); + for row in 0..16 { + assert_eq!(pinned.at(row).now(), pinned.now()); + } + assert_eq!(clock_reads(), before + 1); + } + + #[test] + fn narrowing_creates_no_streams() { + let batch = EvaluationContext::batch(seeded(3)); + for row in 0..64 { + let context = batch.at(row); + let _ = context.item(row).at(0).now(); + } + let streams = batch.shared.streams.borrow(); + assert!(streams.rows.is_empty()); + assert!(streams.items.is_empty()); + assert!(streams.children.is_empty()); + } + + #[test] + fn rows_replay_alone() { + let batch = EvaluationContext::batch(seeded(7)); + let drawn: Vec = (0..4).map(|_| batch.next_u64(3, SITE)).collect(); + let alone = EvaluationContext::new(Pinned { + now: Some(batch.now()), + seed: batch.row_seed(3), + ..Pinned::default() + }); + let again: Vec = (0..4).map(|_| alone.next_u64(0, SITE)).collect(); + assert_eq!(drawn, again); + assert_eq!(batch.row_seed(3), Some(row_seed(7, 3))); + assert_eq!(batch.seed(), None); + } + + #[test] + fn items_derive_from_their_row() { + let batch = EvaluationContext::batch(seeded(5)); + let items = batch.rows(&[2, 4]).items(&[(1, 0), (1, 1), (0, 3)]); + let drawn: Vec = (0..3).map(|i| items.next_u64(i, SITE)).collect(); + let alone = EvaluationContext::new(seeded(row_seed(5, 4))); + let looped = alone.items(&[(0, 0), (0, 1)]); + assert_eq!( + drawn[..2], + [looped.next_u64(0, SITE), looped.next_u64(1, SITE)] + ); + assert_eq!(batch.row_seed(4), Some(row_seed(5, 4))); + assert_eq!(alone.seed(), Some(row_seed(5, 4))); + assert_eq!(batch.row_seed(1), None); + } + + #[test] + fn an_item_matches_its_loop_position() { + let alone = EvaluationContext::new(seeded(11)); + let looped = alone.items(&[(0, 0), (0, 1), (0, 2)]); + let expected: Vec = (0..3).map(|i| looped.next_u64(i, SITE)).collect(); + let again = EvaluationContext::new(seeded(11)); + let single: Vec = (0..3).map(|i| again.item(i).next_u64(0, SITE)).collect(); + assert_eq!(expected, single); + } + + #[test] + fn two_contexts_do_not_share_streams() { + let a = EvaluationContext::new(seeded(1)); + let b = EvaluationContext::new(seeded(1)); + let first = a.next_u64(0, SITE); + assert_eq!(b.next_u64(0, SITE), first); + assert_ne!(a.next_u64(0, SITE), first); + } + + #[test] + fn row_contexts_read_their_row() { + let batch = EvaluationContext::batch(seeded(9)); + let row = batch.row(2); + assert_eq!(row.index(), 2); + let drawn = row.next_u64(); + let alone = EvaluationContext::new(seeded(row_seed(9, 2))); + assert_eq!(alone.row(0).next_u64(), drawn); + } + + #[test] + fn sites_draw_independently() { + let label = location(&["expression", "node", "key"]); + let (first, second) = (Site::new(label, 0), Site::new(label, 1)); + let busy = EvaluationContext::new(seeded(4)); + for _ in 0..3 { + busy.next_u64(0, first); + } + let quiet = EvaluationContext::new(seeded(4)); + assert_eq!(busy.next_u64(0, second), quiet.next_u64(0, second)); + assert_eq!(busy.next_u64(0, second), quiet.next_u64(0, second)); + let fresh = EvaluationContext::new(seeded(4)); + assert_ne!(fresh.next_u64(0, first), fresh.next_u64(0, first)); + assert_ne!( + EvaluationContext::new(seeded(4)).next_u64(0, first), + EvaluationContext::new(seeded(4)).next_u64(0, second) + ); + } + + #[test] + fn a_site_label_wins_over_the_located_field() { + let label = location(&["a"]); + let other = location(&["b"]); + let compiled = EvaluationContext::new(seeded(6)) + .located(other) + .next_u64(0, Site::new(label, 2)); + let runtime = EvaluationContext::new(seeded(6)) + .located(label) + .next_u64(0, Site::new(0, 2)); + assert_eq!(compiled, runtime); + let elsewhere = EvaluationContext::new(seeded(6)) + .located(other) + .next_u64(0, Site::new(0, 2)); + assert_ne!(compiled, elsewhere); + } + + #[test] + fn narrowing_keeps_the_scope_and_field() { + let batch = EvaluationContext::batch(seeded(12)) + .nested(location(&["decision", "call", "child"])) + .located(location(&["field"])); + let narrowed = batch.at(3).item(2); + assert_eq!(narrowed.scope(), batch.scope()); + assert_eq!(narrowed.field(), batch.field()); + let nested = batch.nested(location(&["decision", "inner", "child"])); + assert_ne!(nested.scope(), batch.scope()); + assert_eq!(nested.field(), 0); + let alone = EvaluationContext::new(seeded(row_seed(12, 3))) + .nested(location(&["decision", "call", "child"])) + .located(location(&["field"])); + assert_eq!(batch.next_u64(3, SITE), alone.next_u64(0, SITE),); + } + + #[test] + fn locations_are_stable() { + assert_eq!( + location(&["expression", "calc", "a"]), + 0x5D68_576D_4925_C850 + ); + assert_ne!(location(&["ab", "c"]), location(&["a", "bc"])); + assert_ne!(location(&[]), 0); + } + + #[test] + fn draws_are_pinned() { + let field = location(&["expression", "calc", "a"]); + let single = EvaluationContext::new(seeded(42)).located(field); + let batch = EvaluationContext::batch(seeded(42)).located(field); + let drawn = [ + single.next_u64(0, Site::new(0, 0)), + single.next_u64(0, Site::new(0, 0)), + single.next_u64(0, Site::new(0, 1)), + batch.next_u64(3, Site::new(0, 0)), + batch.at(3).item(1).next_u64(0, Site::new(0, 0)), + single + .nested(location(&["decision", "call", "child"])) + .next_u64(0, Site::SCRIPT), + ]; + assert_eq!( + drawn, + [ + 0xE0A0_738B_CB7C_FBB1, + 0x0018_4DB7_C3F4_C198, + 0xDED2_0A83_4EEC_EF04, + 0x718F_0B89_2624_9E10, + 0xCAFA_D1EF_8A7D_F658, + 0x94BB_666A_DEFA_3647, + ] + ); + } + + #[test] + fn integers_are_pinned() { + let field = location(&["expression", "calc", "a"]); + let context = EvaluationContext::new(seeded(42)).located(field); + let site = Site::new(0, 0); + let drawn: Vec> = [0, 1, 6, 100, 1_000_000, i64::MAX, -1] + .into_iter() + .map(|upper| context.random_int(0, site, upper)) + .collect(); + assert_eq!( + drawn, + [ + Some(0), + Some(0), + Some(6), + Some(41), + Some(621_488), + Some(3_167_289_125_447_670_780), + None + ] + ); + } + + #[test] + fn integers_are_uniform() { + let context = EvaluationContext::new(seeded(9)); + let mut counts = [0usize; 7]; + let draws = 70_000; + for index in 0..draws { + let value = context.random_int(0, Site::new(0, index), 6).unwrap(); + counts[value as usize] += 1; + } + let expected = draws as usize / 7; + for count in counts { + assert!(count.abs_diff(expected) < expected / 20, "{counts:?}"); + } + let unit = Draw::new(1, 2, 3); + assert_eq!(unit.int(0), Some(0)); + assert_eq!(unit.int(-5), None); + assert!(unit.int(i64::MAX).is_some_and(|v| v >= 0)); + let wide = (0..2_000) + .filter_map(|i| Draw::new(7, i, 0).int((1 << 62) + (1 << 61))) + .filter(|v| *v >= 1 << 62) + .count(); + assert!((500..833).contains(&wide), "{wide}"); + } +} diff --git a/core/expression/src/functions/internal.rs b/core/expression/src/functions/internal.rs index d5c72444..30081031 100644 --- a/core/expression/src/functions/internal.rs +++ b/core/expression/src/functions/internal.rs @@ -625,7 +625,9 @@ pub(crate) mod imp { let a = args.number(0)?; let upper_range = a.round().to_i64().context("Invalid upper range")?; - let random_number = fastrand::i64(0..=upper_range); + let random_number = crate::context::Draw::fresh() + .int(upper_range) + .context("Invalid upper range")?; Ok(V::Number(Decimal::from(random_number))) } diff --git a/core/expression/src/intellisense/completion.rs b/core/expression/src/intellisense/completion.rs index c0d88f73..5eaf37b4 100644 --- a/core/expression/src/intellisense/completion.rs +++ b/core/expression/src/intellisense/completion.rs @@ -346,7 +346,7 @@ fn function_info(fk: &FunctionKind) -> String { InternalFunction::Min => "Returns the smallest of the elements in the input array", InternalFunction::Max => "Returns the largest of the elements in the input array", InternalFunction::Rand => { - "Generates a random number between 0 (inclusive) and max (inclusive)" + "Generates a random number between 0 (inclusive) and max (inclusive); every call, and every item of a closure, draws anew from the evaluation's seeded stream" } InternalFunction::Median => { "Calculates the median value of all elements in the input array" diff --git a/core/expression/src/lane/builtins/arrays.rs b/core/expression/src/lane/builtins/arrays.rs index d0acb64f..c165ae0f 100644 --- a/core/expression/src/lane/builtins/arrays.rs +++ b/core/expression/src/lane/builtins/arrays.rs @@ -1,4 +1,4 @@ -use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Outcome, Params}; +use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Outcome, Params, RowContext}; use crate::variable::{Variable, VariableMap}; pub(crate) struct Arrays; @@ -7,7 +7,7 @@ impl Arrays { const ARRAY: &'static [(&'static str, bool)] = &[("array", false)]; pub(crate) const FLATTEN: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Array| { Ok(a.with(|values| { let mut flat = Vec::with_capacity(values.len()); @@ -25,7 +25,7 @@ impl Arrays { }; pub(crate) const MERGE: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Array| a.with(Self::merge))], + overloads: &[|_, args| Apply::one(args, |a: Array| a.with(Self::merge))], fail: |args| Params::fail(args, Self::ARRAY), }; @@ -76,7 +76,7 @@ impl Arrays { } pub(crate) const MERGE_DEEP: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Array| { a.with(|values| { let mut result = Variable::empty_object(); @@ -128,7 +128,7 @@ impl Arrays { fail: |_| "Argument on 0 position out of bounds".to_string(), }; - fn keys(args: &[Arg]) -> Outcome { + fn keys(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::one(args, |a: Arg| match a { Arg::Var(Variable::Array(_)) | Arg::List(_) => { let len = match a { @@ -154,7 +154,7 @@ impl Arrays { } pub(crate) const VALUES: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: &Variable| match a { Variable::Object(o) => { Ok(Variable::from_array(o.borrow().values().cloned().collect())) diff --git a/core/expression/src/lane/builtins/convert.rs b/core/expression/src/lane/builtins/convert.rs index 1153125a..d6a12742 100644 --- a/core/expression/src/lane/builtins/convert.rs +++ b/core/expression/src/lane/builtins/convert.rs @@ -1,4 +1,4 @@ -use crate::lane::builtins::{Apply, Arg, Builtin, Params}; +use crate::lane::builtins::{Apply, Arg, Builtin, Params, RowContext}; use crate::lane::date::Date; use crate::variable::Variable; use chrono_tz::Tz; @@ -24,12 +24,12 @@ impl Convert { } pub(crate) const TYPE: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Arg| Ok(a.type_name()))], + overloads: &[|_, args| Apply::one(args, |a: Arg| Ok(a.type_name()))], fail: |_| "Argument on 0 position out of bounds".to_string(), }; pub(crate) const BOOL: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Arg| { Ok(match a { Arg::Null => false, @@ -47,7 +47,7 @@ impl Convert { }; pub(crate) const STRING: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Arg| match a { Arg::Null => Ok("null".to_string()), Arg::Bool(b) => Ok(b.to_string()), @@ -65,7 +65,7 @@ impl Convert { }; pub(crate) const NUMBER: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Arg| match a { Arg::Num(n) => Ok(n), Arg::Str(s) => Self::parse(s).ok_or_else(|| "Invalid number".to_string()), @@ -81,7 +81,7 @@ impl Convert { }; pub(crate) const IS_NUMERIC: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Arg| { Ok(match a { Arg::Num(_) => true, @@ -94,7 +94,7 @@ impl Convert { }; pub(crate) const DATE: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Apply::two(args, |value: Option, zone: Option<&str>| { let zone = match zone { Some(z) => Some(Tz::from_str(z).map_err(|_| "Invalid timezone".to_string())?), @@ -102,9 +102,9 @@ impl Convert { }; Ok(match value { Some(Arg::Date(d)) => zone.map_or(d, |zone| d.tz(zone)), - Some(Arg::Str(s)) => Date::text(s, zone), - Some(v) => Date::new(v.variable(), zone), - None => Date::now(), + Some(Arg::Str(s)) => Date::text(s, zone, ctx.context()), + Some(v) => Date::new(v.variable(), zone, ctx.context()), + None => Date::now(ctx.context()), }) }) }], diff --git a/core/expression/src/lane/builtins/dates.rs b/core/expression/src/lane/builtins/dates.rs index 5643c42a..15181039 100644 --- a/core/expression/src/lane/builtins/dates.rs +++ b/core/expression/src/lane/builtins/dates.rs @@ -1,5 +1,5 @@ use crate::functions::{DateMethod, MethodKind}; -use crate::lane::builtins::{Arg, Builtin, Fail, Out, Outcome}; +use crate::lane::builtins::{Arg, Builtin, Fail, Out, Outcome, RowContext}; use crate::lane::date::Date; use crate::lane::date::{Duration, DurationUnit}; use crate::variable::Variable; @@ -125,11 +125,11 @@ impl Dates { } } - fn other(args: &[Arg]) -> Result { + fn other(ctx: &RowContext, args: &[Arg]) -> Result { Ok(match Self::var(args, 1)? { Arg::Date(d) => d, - Arg::Str(s) => Date::text(s, None), - other => Date::new(other.variable(), None), + Arg::Str(s) => Date::text(s, None, ctx.context()), + other => Date::new(other.variable(), None, ctx.context()), }) } @@ -142,21 +142,21 @@ impl Dates { } pub(crate) const ADD: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| Ok(Self::date(Self::this(args)?.add(Self::duration(args, 1)?)))) }], fail: Self::NEVER, }; pub(crate) const SUB: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| Ok(Self::date(Self::this(args)?.sub(Self::duration(args, 1)?)))) }], fail: Self::NEVER, }; pub(crate) const SET: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| { let this = Self::this(args)?; let unit = Self::unit(args, 1)?; @@ -170,7 +170,7 @@ impl Dates { }; pub(crate) const FORMAT: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| { let this = Self::this(args)?; Ok(this.format(Self::ostr(args, 1)?.as_deref()).into()) @@ -180,24 +180,24 @@ impl Dates { }; pub(crate) const START_OF: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| Ok(Self::date(Self::this(args)?.start_of(Self::unit(args, 1)?)))) }], fail: Self::NEVER, }; pub(crate) const END_OF: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| Ok(Self::date(Self::this(args)?.end_of(Self::unit(args, 1)?)))) }], fail: Self::NEVER, }; pub(crate) const DIFF: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Self::run(|| { let this = Self::this(args)?; - let other = Self::other(args)?; + let other = Self::other(ctx, args)?; let unit = Self::unit_opt(args, 2)?; Ok(match this.diff(&other, unit).and_then(Decimal::from_i64) { Some(n) => Out::Num(n), @@ -209,7 +209,7 @@ impl Dates { }; pub(crate) const TZ: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Self::run(|| { let this = Self::this(args)?; let zone = Tz::from_str(&Self::str(args, 1)?) @@ -220,10 +220,10 @@ impl Dates { fail: Self::NEVER, }; - fn compare(args: &[Arg], op: Compare) -> Outcome { + fn compare(ctx: &RowContext, args: &[Arg], op: Compare) -> Outcome { Self::run(|| { let this = Self::this(args)?; - let other = Self::other(args)?; + let other = Self::other(ctx, args)?; let unit = Self::unit_opt(args, 2)?; Ok(Out::Bool(match op { Compare::Same => this.is_same(&other, unit), @@ -236,27 +236,27 @@ impl Dates { } pub(crate) const IS_SAME: Builtin = Builtin { - overloads: &[|args| Self::compare(args, Compare::Same)], + overloads: &[|ctx, args| Self::compare(ctx, args, Compare::Same)], fail: Self::NEVER, }; pub(crate) const IS_BEFORE: Builtin = Builtin { - overloads: &[|args| Self::compare(args, Compare::Before)], + overloads: &[|ctx, args| Self::compare(ctx, args, Compare::Before)], fail: Self::NEVER, }; pub(crate) const IS_AFTER: Builtin = Builtin { - overloads: &[|args| Self::compare(args, Compare::After)], + overloads: &[|ctx, args| Self::compare(ctx, args, Compare::After)], fail: Self::NEVER, }; pub(crate) const IS_SAME_OR_BEFORE: Builtin = Builtin { - overloads: &[|args| Self::compare(args, Compare::SameOrBefore)], + overloads: &[|ctx, args| Self::compare(ctx, args, Compare::SameOrBefore)], fail: Self::NEVER, }; pub(crate) const IS_SAME_OR_AFTER: Builtin = Builtin { - overloads: &[|args| Self::compare(args, Compare::SameOrAfter)], + overloads: &[|ctx, args| Self::compare(ctx, args, Compare::SameOrAfter)], fail: Self::NEVER, }; @@ -302,7 +302,7 @@ impl Dates { }) } - fn part(args: &[Arg], part: Part) -> Outcome { + fn part(ctx: &RowContext, args: &[Arg], part: Part) -> Outcome { Self::run(|| { let this = Self::this(args)?; if let Part::IsValid = part { @@ -324,12 +324,14 @@ impl Dates { Part::Year => Out::Num(dt.year().into()), Part::Timestamp => Out::Num(dt.timestamp_millis().into()), Part::IsValid => Out::Bool(true), - Part::IsYesterday => { - Out::Bool(this.is_same(&Date::yesterday(), Some(DurationUnit::Day))) + Part::IsYesterday => Out::Bool( + this.is_same(&Date::yesterday(ctx.context()), Some(DurationUnit::Day)), + ), + Part::IsToday => { + Out::Bool(this.is_same(&Date::now(ctx.context()), Some(DurationUnit::Day))) } - Part::IsToday => Out::Bool(this.is_same(&Date::now(), Some(DurationUnit::Day))), Part::IsTomorrow => { - Out::Bool(this.is_same(&Date::tomorrow(), Some(DurationUnit::Day))) + Out::Bool(this.is_same(&Date::tomorrow(ctx.context()), Some(DurationUnit::Day))) } Part::IsLeapYear => Out::Bool(dt.date_naive().leap_year()), Part::OffsetName => dt.timezone().name().into(), @@ -338,71 +340,71 @@ impl Dates { } pub(crate) const SECOND: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Second)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Second)], fail: Self::NEVER, }; pub(crate) const MINUTE: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Minute)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Minute)], fail: Self::NEVER, }; pub(crate) const HOUR: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Hour)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Hour)], fail: Self::NEVER, }; pub(crate) const DAY: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Day)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Day)], fail: Self::NEVER, }; pub(crate) const WEEKDAY: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Weekday)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Weekday)], fail: Self::NEVER, }; pub(crate) const DAY_OF_YEAR: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::DayOfYear)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::DayOfYear)], fail: Self::NEVER, }; pub(crate) const WEEK: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Week)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Week)], fail: Self::NEVER, }; pub(crate) const MONTH: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Month)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Month)], fail: Self::NEVER, }; pub(crate) const QUARTER: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Quarter)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Quarter)], fail: Self::NEVER, }; pub(crate) const YEAR: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Year)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Year)], fail: Self::NEVER, }; pub(crate) const TIMESTAMP: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::Timestamp)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::Timestamp)], fail: Self::NEVER, }; pub(crate) const OFFSET_NAME: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::OffsetName)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::OffsetName)], fail: Self::NEVER, }; pub(crate) const IS_VALID: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::IsValid)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::IsValid)], fail: Self::NEVER, }; pub(crate) const IS_YESTERDAY: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::IsYesterday)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::IsYesterday)], fail: Self::NEVER, }; pub(crate) const IS_TODAY: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::IsToday)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::IsToday)], fail: Self::NEVER, }; pub(crate) const IS_TOMORROW: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::IsTomorrow)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::IsTomorrow)], fail: Self::NEVER, }; pub(crate) const IS_LEAP_YEAR: Builtin = Builtin { - overloads: &[|a| Self::part(a, Part::IsLeapYear)], + overloads: &[|ctx, a| Self::part(ctx, a, Part::IsLeapYear)], fail: Self::NEVER, }; } diff --git a/core/expression/src/lane/builtins/functions.rs b/core/expression/src/lane/builtins/functions.rs index f1265add..96cd4e8f 100644 --- a/core/expression/src/lane/builtins/functions.rs +++ b/core/expression/src/lane/builtins/functions.rs @@ -7,7 +7,7 @@ use crate::lane::builtins::dates::Dates; use crate::lane::builtins::legacy::Legacy; use crate::lane::builtins::math::Math; use crate::lane::builtins::text::Text; -use crate::lane::builtins::{Arg, Builtin, Fail, Out}; +use crate::lane::builtins::{Arg, Builtin, Fail, Out, RowContext}; use crate::lane::exec::{CallFault, Fault}; use crate::lane::ops::Ops; use crate::vm::VMError; @@ -114,13 +114,16 @@ impl Builtins { } } - fn attempt(builtin: &Builtin, args: &[Arg]) -> Option> { - builtin.overloads.iter().find_map(|overload| overload(args)) + fn attempt(builtin: &Builtin, args: &[Arg], ctx: &RowContext) -> Option> { + builtin + .overloads + .iter() + .find_map(|overload| overload(ctx, args)) } #[cold] #[inline(never)] - fn textual(builtin: &Builtin, args: &[Arg]) -> Option> { + fn textual(builtin: &Builtin, args: &[Arg], ctx: &RowContext) -> Option> { let texts: SmallVec<[Option>; 4]> = args .iter() .map(|a| a.date().and_then(|_| a.text())) @@ -138,14 +141,14 @@ impl Builtins { _ => *a, }) .collect(); - Self::attempt(builtin, &converted) + Self::attempt(builtin, &converted, ctx) }) } #[inline] - fn resolve(builtin: &Builtin, args: &[Arg]) -> Result { - Self::attempt(builtin, args) - .or_else(|| Self::textual(builtin, args)) + fn resolve(builtin: &Builtin, args: &[Arg], ctx: &RowContext) -> Result { + Self::attempt(builtin, args, ctx) + .or_else(|| Self::textual(builtin, args, ctx)) .unwrap_or_else(|| Err((builtin.fail)(args))) } @@ -153,8 +156,9 @@ impl Builtins { builtin: &Builtin, kind: &MethodKind, args: &[Arg], + ctx: &RowContext, ) -> Result { - Self::resolve(builtin, args).map_err(|message| { + Self::resolve(builtin, args, ctx).map_err(|message| { Ops::error("CallMethod", format!("Method `{kind}` failed: {message}")) }) } @@ -165,35 +169,37 @@ impl Builtins { kind: &FunctionKind, args: &[Arg], hint: &mut usize, + ctx: &RowContext, ) -> Result { let failed = |message: Fail| CallFault::message(kind, message); if let Some(overload) = builtin.overloads.get(*hint) { - if let Some(result) = overload(args) { + if let Some(result) = overload(ctx, args) { return result.map_err(failed); } } for (index, overload) in builtin.overloads.iter().enumerate() { - if let Some(result) = overload(args) { + if let Some(result) = overload(ctx, args) { *hint = index; return result.map_err(failed); } } - match Self::textual(builtin, args) { + match Self::textual(builtin, args, ctx) { Some(result) => result.map_err(failed), None => Err(CallFault::fail(kind, builtin, args)), } } - pub(crate) fn raw(builtin: &Builtin, args: &[Arg]) -> Result { - Self::resolve(builtin, args) + pub(crate) fn raw(builtin: &Builtin, args: &[Arg], ctx: &RowContext) -> Result { + Self::resolve(builtin, args, ctx) } pub(crate) fn call( builtin: &Builtin, kind: &FunctionKind, args: &[Arg], + ctx: &RowContext, ) -> Result { - Self::resolve(builtin, args).map_err(|message| { + Self::resolve(builtin, args, ctx).map_err(|message| { Ops::error( "CallFunction", format!("Function `{kind}` failed: {message}"), diff --git a/core/expression/src/lane/builtins/legacy.rs b/core/expression/src/lane/builtins/legacy.rs index 1459dcb8..3b9e4448 100644 --- a/core/expression/src/lane/builtins/legacy.rs +++ b/core/expression/src/lane/builtins/legacy.rs @@ -1,4 +1,4 @@ -use crate::lane::builtins::{Apply, Arg, Builtin, Fail, Params}; +use crate::lane::builtins::{Apply, Arg, Builtin, Fail, Params, RowContext}; use crate::lane::date::helpers::{date_time, date_time_end_of, date_time_start_of, time, DateUnit}; use crate::variable::Variable; use chrono::{Datelike, NaiveDateTime, Timelike}; @@ -10,15 +10,15 @@ pub(crate) struct Legacy; impl Legacy { const ANY: fn(&[Arg]) -> Fail = |_| "Argument on 0 position out of bounds".to_string(); - fn convert(timestamp: Arg) -> Result { + fn convert(ctx: &RowContext, timestamp: Arg) -> Result { let instant = timestamp .date() .and_then(|date| date.0) .map(|date| date.naive_local()); let converted = match timestamp { - Arg::Str(s) => date_time(s).ok(), + Arg::Str(s) => date_time(s, ctx.context()).ok(), Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => match timestamp.text() { - Some(text) => date_time(&text).ok().or(instant), + Some(text) => date_time(&text, ctx.context()).ok().or(instant), None => instant, }, #[allow(deprecated)] @@ -31,10 +31,10 @@ impl Legacy { } pub(crate) const DATE: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Apply::one(args, |a: Arg| match a { Arg::Str(s) => { - let dt = date_time(s).map_err(|e| e.to_string())?; + let dt = date_time(s, ctx.context()).map_err(|e| e.to_string())?; #[allow(deprecated)] Ok(Decimal::from(dt.timestamp())) } @@ -42,7 +42,7 @@ impl Legacy { .to_i64() .map(Decimal::from) .ok_or_else(|| "Number overflow".to_string()), - other => Self::convert(other) + other => Self::convert(ctx, other) .map_err(|_| "Unsupported type for date function".to_string()) .map(|dt| { #[allow(deprecated)] @@ -54,10 +54,10 @@ impl Legacy { }; pub(crate) const TIME: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Apply::one(args, |a: Arg| match a { Arg::Str(s) => Ok(Decimal::from( - time(s) + time(s, ctx.context()) .map_err(|e| e.to_string())? .num_seconds_from_midnight(), )), @@ -66,9 +66,9 @@ impl Legacy { .map(Decimal::from) .ok_or_else(|| "Number overflow".to_string()), Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => { - match a.text().map(|text| time(&text)) { + match a.text().map(|text| time(&text, ctx.context())) { Some(Ok(time)) => Ok(Decimal::from(time.num_seconds_from_midnight())), - _ => Self::convert(a) + _ => Self::convert(ctx, a) .map(|dt| Decimal::from(dt.time().num_seconds_from_midnight())), } } @@ -79,7 +79,7 @@ impl Legacy { }; pub(crate) const DURATION: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Arg| match a { Arg::Str(s) => Ok(Decimal::from( humantime::parse_duration(s) @@ -97,16 +97,16 @@ impl Legacy { }; pub(crate) const YEAR: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.year()).into())) + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| Decimal::from(t.year()).into())) }], fail: Self::ANY, }; pub(crate) const DAY_OF_WEEK: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Some( - Self::convert(*args.first()?) + Self::convert(ctx, *args.first()?) .map(|t| Decimal::from(t.weekday().number_from_monday()).into()), ) }], @@ -114,56 +114,61 @@ impl Legacy { }; pub(crate) const DAY_OF_MONTH: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.day()).into())) + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| Decimal::from(t.day()).into())) }], fail: Self::ANY, }; pub(crate) const DAY_OF_YEAR: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.ordinal()).into())) + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| Decimal::from(t.ordinal()).into())) }], fail: Self::ANY, }; pub(crate) const WEEK_OF_YEAR: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.iso_week().week()).into())) + overloads: &[|ctx: &RowContext, args| { + Some( + Self::convert(ctx, *args.first()?) + .map(|t| Decimal::from(t.iso_week().week()).into()), + ) }], fail: Self::ANY, }; pub(crate) const MONTH_OF_YEAR: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.month()).into())) + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| Decimal::from(t.month()).into())) }], fail: Self::ANY, }; pub(crate) const MONTH_STRING: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| t.format("%b").to_string().into())) + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| t.format("%b").to_string().into())) }], fail: Self::ANY, }; pub(crate) const WEEKDAY_STRING: Builtin = Builtin { - overloads: &[|args| { - Some(Self::convert(*args.first()?).map(|t| t.weekday().to_string().into())) + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| t.weekday().to_string().into())) }], fail: Self::ANY, }; pub(crate) const DATE_STRING: Builtin = Builtin { - overloads: &[|args| Some(Self::convert(*args.first()?).map(|t| t.to_string().into()))], + overloads: &[|ctx: &RowContext, args| { + Some(Self::convert(ctx, *args.first()?).map(|t| t.to_string().into())) + }], fail: Self::ANY, }; pub(crate) const START_OF: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Apply::two(args, |timestamp: Arg, unit: &str| { - let datetime = Self::convert(timestamp)?; + let datetime = Self::convert(ctx, timestamp)?; let unit = DateUnit::try_from(unit).map_err(|_| "Invalid date unit".to_string())?; let result = date_time_start_of(datetime, unit) .ok_or_else(|| "Failed to calculate start of period".to_string())?; @@ -175,9 +180,9 @@ impl Legacy { }; pub(crate) const END_OF: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Apply::two(args, |timestamp: Arg, unit: &str| { - let datetime = Self::convert(timestamp)?; + let datetime = Self::convert(ctx, timestamp)?; let unit = DateUnit::try_from(unit).map_err(|_| "Invalid date unit".to_string())?; let result = date_time_end_of(datetime, unit) .ok_or_else(|| "Failed to calculate end of period".to_string())?; diff --git a/core/expression/src/lane/builtins/math.rs b/core/expression/src/lane/builtins/math.rs index bdace8d9..22defc36 100644 --- a/core/expression/src/lane/builtins/math.rs +++ b/core/expression/src/lane/builtins/math.rs @@ -1,4 +1,4 @@ -use crate::lane::builtins::{Apply, Array, Builtin, Fail, Params}; +use crate::lane::builtins::{Apply, Array, Builtin, Fail, Params, RowContext}; use crate::lane::date::Date; use crate::lane::date::DynamicVariableExt; use crate::variable::Variable; @@ -41,22 +41,22 @@ impl Math { } pub(crate) const ABS: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.abs()))], + overloads: &[|_, args| Apply::one(args, |a: Decimal| Ok(a.abs()))], fail: |args| Params::fail(args, Self::NUMBER), }; pub(crate) const CEIL: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.ceil()))], + overloads: &[|_, args| Apply::one(args, |a: Decimal| Ok(a.ceil()))], fail: |args| Params::fail(args, Self::NUMBER), }; pub(crate) const FLOOR: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.floor()))], + overloads: &[|_, args| Apply::one(args, |a: Decimal| Ok(a.floor()))], fail: |args| Params::fail(args, Self::NUMBER), }; pub(crate) const ROUND: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::two(args, |a: Decimal, places: Option| { Ok(a.round_dp_with_strategy( Self::places(places)?, @@ -68,7 +68,7 @@ impl Math { }; pub(crate) const TRUNC: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::two(args, |a: Decimal, places: Option| { Ok(a.trunc_with_scale(Self::places(places)?)) }) @@ -77,20 +77,22 @@ impl Math { }; pub(crate) const RAND: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|ctx: &RowContext, args| { Apply::one(args, |a: Decimal| { let upper = a .round() .to_i64() .ok_or_else(|| "Invalid upper range".to_string())?; - Ok(Decimal::from(fastrand::i64(0..=upper))) + ctx.random_int(upper) + .map(Decimal::from) + .ok_or_else(|| "Invalid upper range".to_string()) }) }], fail: |args| Params::fail(args, Self::NUMBER), }; pub(crate) const SUM: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Array| { let numbers = a .numbers() @@ -102,7 +104,7 @@ impl Math { }; pub(crate) const AVG: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Array| { let numbers = a .numbers() @@ -116,7 +118,7 @@ impl Math { }; pub(crate) const MEDIAN: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Array| { let mut values = Self::numbers(&a)?; values.sort(); @@ -146,7 +148,7 @@ impl Math { }; pub(crate) const MODE: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::one(args, |a: Array| { let mut counts = BTreeMap::new(); for n in Self::numbers(&a)? { @@ -208,12 +210,12 @@ impl Math { } pub(crate) const MIN: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Array| Self::pick(a, false))], + overloads: &[|_, args| Apply::one(args, |a: Array| Self::pick(a, false))], fail: |args| Params::fail(args, Self::ARRAY), }; pub(crate) const MAX: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: Array| Self::pick(a, true))], + overloads: &[|_, args| Apply::one(args, |a: Array| Self::pick(a, true))], fail: |args| Params::fail(args, Self::ARRAY), }; } diff --git a/core/expression/src/lane/builtins/mod.rs b/core/expression/src/lane/builtins/mod.rs index b8210971..70d008dd 100644 --- a/core/expression/src/lane/builtins/mod.rs +++ b/core/expression/src/lane/builtins/mod.rs @@ -10,10 +10,12 @@ pub(crate) use dates::Dates; pub(crate) use functions::Builtins; pub(crate) use text::{Text, TextKernel}; +pub(crate) use crate::context::RowContext; use crate::lane::columns::{Column, Values}; use crate::lane::date::Date; use crate::lane::date::DynamicVariableExt; use crate::variable::Variable; +use chrono_tz::Tz; use rust_decimal::Decimal; use std::borrow::Cow; use zen_types::rccell::RcCell; @@ -68,9 +70,9 @@ impl<'a> Arg<'a> { } } - pub(crate) fn coerce_date(&self) -> Option { + pub(crate) fn coerce_date(&self, tz: Tz) -> Option { match self { - Arg::Str(s) => Some(Date::from_text(s)), + Arg::Str(s) => Some(Date::from_text(s, tz)), other => other.date(), } } @@ -284,7 +286,7 @@ pub(crate) type Fail = String; pub(crate) type Outcome = Option>; -pub(crate) type Overload = for<'a> fn(&[Arg<'a>]) -> Outcome; +pub(crate) type Overload = for<'a, 'b> fn(&RowContext<'b>, &[Arg<'a>]) -> Outcome; pub(crate) struct Apply; diff --git a/core/expression/src/lane/builtins/text.rs b/core/expression/src/lane/builtins/text.rs index bf3e7926..d0701038 100644 --- a/core/expression/src/lane/builtins/text.rs +++ b/core/expression/src/lane/builtins/text.rs @@ -1,5 +1,5 @@ use crate::functions::{FunctionKind, InternalFunction}; -use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Out, Outcome, Params}; +use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Out, Outcome, Params, RowContext}; use crate::variable::Variable; #[cfg(not(feature = "regex-lite"))] use regex::Regex; @@ -166,11 +166,11 @@ impl Text { fail: Self::len_fail, }; - fn len_str(args: &[Arg]) -> Outcome { + fn len_str(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::one(args, |a: &str| Ok(a.len())) } - fn len_array(args: &[Arg]) -> Outcome { + fn len_array(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::one(args, |a: Array| Ok(a.len())) } @@ -186,11 +186,12 @@ impl Text { fail: Self::contains_fail, }; - fn contains_str(args: &[Arg]) -> Outcome { + fn contains_str(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::two(args, |a: &str, b: &str| Ok(a.contains(b))) } - fn contains_array(args: &[Arg]) -> Outcome { + fn contains_array(ctx: &RowContext, args: &[Arg]) -> Outcome { + let tz = ctx.timezone(); Apply::two(args, |a: Array, b: Arg| { Ok(a.any(|x| match (x, b) { (Arg::Num(x), Arg::Num(y)) => x == y, @@ -198,8 +199,8 @@ impl Text { (Arg::Bool(x), Arg::Bool(y)) => x == y, (Arg::Null, Arg::Null) => true, (x, y) => match (x.date(), y.date()) { - (Some(d), _) => d.is_valid() && y.coerce_date() == Some(d), - (None, Some(d)) => d.is_valid() && x.coerce_date() == Some(d), + (Some(d), _) => d.is_valid() && y.coerce_date(tz) == Some(d), + (None, Some(d)) => d.is_valid() && x.coerce_date(tz) == Some(d), (None, None) => false, }, })) @@ -219,17 +220,17 @@ impl Text { } pub(crate) const STARTS_WITH: Builtin = Builtin { - overloads: &[|args| Apply::two(args, |a: &str, b: &str| Ok(a.starts_with(b)))], + overloads: &[|_, args| Apply::two(args, |a: &str, b: &str| Ok(a.starts_with(b)))], fail: |args| Params::fail(args, Self::TWO), }; pub(crate) const ENDS_WITH: Builtin = Builtin { - overloads: &[|args| Apply::two(args, |a: &str, b: &str| Ok(a.ends_with(b)))], + overloads: &[|_, args| Apply::two(args, |a: &str, b: &str| Ok(a.ends_with(b)))], fail: |args| Params::fail(args, Self::TWO), }; pub(crate) const MATCHES: Builtin = Builtin { - overloads: &[|args| { + overloads: &[|_, args| { Apply::two(args, |a: &str, b: &str| { Patterns::with(b, |regex| regex.is_match(a)) }) @@ -238,17 +239,17 @@ impl Text { }; pub(crate) const UPPER: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: &str| Ok(a.to_uppercase()))], + overloads: &[|_, args| Apply::one(args, |a: &str| Ok(a.to_uppercase()))], fail: |args| Params::fail(args, Self::ONE), }; pub(crate) const LOWER: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: &str| Ok(a.to_lowercase()))], + overloads: &[|_, args| Apply::one(args, |a: &str| Ok(a.to_lowercase()))], fail: |args| Params::fail(args, Self::ONE), }; pub(crate) const TRIM: Builtin = Builtin { - overloads: &[|args| Apply::one(args, |a: &str| Ok(Out::from(a.trim())))], + overloads: &[|_, args| Apply::one(args, |a: &str| Ok(Out::from(a.trim())))], fail: |args| Params::fail(args, Self::ONE), }; @@ -257,7 +258,7 @@ impl Text { fail: |args| Params::fail(args, Self::TWO), }; - fn extract(args: &[Arg]) -> Outcome { + fn extract(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::two(args, |a: &str, b: &str| { let captures: Vec = Patterns::with(b, |regex| { regex @@ -280,7 +281,7 @@ impl Text { fail: |args| Params::fail(args, Self::TWO), }; - fn split(args: &[Arg]) -> Outcome { + fn split(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::two(args, |a: &str, b: &str| { Ok(Variable::from_array( a.split(b).map(|s| Variable::String(s.into())).collect(), @@ -297,7 +298,7 @@ impl Text { Decimal::from_f64(strsim::normalized_damerau_levenshtein(a, b)).unwrap_or(Decimal::ZERO) } - fn fuzzy(args: &[Arg]) -> Outcome { + fn fuzzy(_ctx: &RowContext, args: &[Arg]) -> Outcome { Apply::two(args, |a: Arg, b: &str| match a { Arg::Str(a) => Ok(Variable::Number(Self::similarity(a, b))), Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => match a.text() { diff --git a/core/expression/src/lane/cells.rs b/core/expression/src/lane/cells.rs index 5bbb2206..e022a32f 100644 --- a/core/expression/src/lane/cells.rs +++ b/core/expression/src/lane/cells.rs @@ -1,3 +1,4 @@ +use crate::context::EvaluationContext; use crate::lane::date::DynamicVariableExt; use crate::lane::{Binding, Column, Columns, Kind, LaneProgram, LaneRunner, Values}; use crate::lane::{Bits, ShortKey}; @@ -8,6 +9,7 @@ use crate::variable::Variable; use crate::IsolateError; use ahash::HashMap; use bumpalo::Bump; +use chrono_tz::Tz; use rust_decimal::Decimal; use std::sync::Arc; @@ -115,6 +117,7 @@ struct Other { type Keyed = (u64, Box<[u8]>, Vec); pub struct CellEnv<'a> { + pub context: &'a EvaluationContext, pub scopes: &'a [Scope], pub columns: &'a Columns<'a>, pub bind: &'a dyn Fn(&str) -> Binding, @@ -270,7 +273,7 @@ impl CellSet { } } - fn numbers(&self, column: &Column, rows: usize, out: &mut [u64]) -> bool { + fn numbers(&self, column: &Column, rows: usize, out: &mut [u64], tz: Tz) -> bool { let words = self.words; let parts = |row: usize| -> Option<(i64, u8)> { match column.values { @@ -322,7 +325,7 @@ impl CellSet { .iter_mut() .zip(self.always.iter().zip(region)) .for_each(|(b, (a, r))| *b = a | r), - None => self.row_bits(column, row, (true, false, false), bits), + None => self.row_bits(column, row, (true, false, false), bits, tz), } } true @@ -504,9 +507,11 @@ impl CellSet { values: &[Variable], envs: &[Scope], out: &mut Vec, + context: &EvaluationContext, ) { let columns = Columns::new(values.len()); let env = CellEnv { + context, scopes: envs, columns: &columns, bind: &|_| Binding::Row, @@ -536,6 +541,7 @@ impl CellSet { ) { runner.evaluate_bound( program, + env.context, scopes, env.columns, env.bind, @@ -560,7 +566,7 @@ impl CellSet { out: &mut Vec, ) { let words = self.words; - self.indexed(values, out); + self.indexed(values, out, env.context.timezone()); if self.others.is_empty() { return; } @@ -613,7 +619,7 @@ impl CellSet { } } - fn dated(&self, value: &Variable, bits: &mut [u64]) { + fn dated(&self, value: &Variable, bits: &mut [u64], tz: Tz) { let Variable::Dynamic(dynamic) = value else { return; }; @@ -626,7 +632,7 @@ impl CellSet { }; for (key, matched) in keys { let text = Variable::String(String::from_utf8_lossy(key).as_ref().into()); - if date.matches(&text) { + if date.matches(&text, tz) { Bits::or(bits, matched); } } @@ -643,7 +649,7 @@ impl CellSet { self.regions.get(self.region_at(n)) } - pub fn indexed_column(&self, column: &Column, rows: usize, out: &mut Vec) { + pub fn indexed_column(&self, column: &Column, rows: usize, out: &mut Vec, tz: Tz) { let words = self.words; out.clear(); out.resize(rows * words, 0); @@ -652,7 +658,7 @@ impl CellSet { let boolean = matches!(column.values, Values::Bool { .. }); if column.is_empty() && rows > 0 { let (first, rest) = out.split_at_mut(words); - self.row_bits(column, 0, (numeric, text, boolean), first); + self.row_bits(column, 0, (numeric, text, boolean), first, tz); rest.chunks_exact_mut(words) .for_each(|chunk| chunk.copy_from_slice(first)); return; @@ -662,20 +668,20 @@ impl CellSet { let size = dictionary.len(); if keys.len() >= rows && size <= rows.saturating_mul(2) + 64 { let mut table = Vec::new(); - self.indexed_column(&dictionary, size, &mut table); + self.indexed_column(&dictionary, size, &mut table, tz); for (row, bits) in out.chunks_exact_mut(words).enumerate() { let code = usize::try_from(keys[row]).ok().filter(|&c| c < size); match (column.valid(row), code) { (true, Some(code)) => { bits.copy_from_slice(&table[code * words..(code + 1) * words]) } - _ => self.row_bits(column, row, (numeric, text, boolean), bits), + _ => self.row_bits(column, row, (numeric, text, boolean), bits, tz), } } return; } } - if numeric && self.numbers(column, rows, out) { + if numeric && self.numbers(column, rows, out, tz) { return; } if words == 1 && self.indexed_word(column, rows, out) { @@ -687,6 +693,7 @@ impl CellSet { row, (numeric, text, boolean), &mut out[row * words..(row + 1) * words], + tz, ); } } @@ -741,6 +748,7 @@ impl CellSet { row: usize, (numeric, text, boolean): (bool, bool, bool), bits: &mut [u64], + tz: Tz, ) { bits.copy_from_slice(&self.always); if !column.valid(row) { @@ -783,7 +791,7 @@ impl CellSet { if let Some(matched) = self.matched(&value) { Bits::or(bits, matched); } - self.dated(&value, bits); + self.dated(&value, bits, tz); if let Variable::Number(n) = &value { if let Some(region) = self.region(n) { Bits::or(bits, region); @@ -838,7 +846,7 @@ impl CellSet { }) } - fn piece_of(&self, pieces: &Pieces, value: &Variable) -> u32 { + fn piece_of(&self, pieces: &Pieces, value: &Variable, tz: Tz) -> u32 { match value { Variable::Null => pieces.null, Variable::Bool(b) => pieces.truth[usize::from(*b)], @@ -849,9 +857,10 @@ impl CellSet { .keys .iter() .find(|(_, _, key, _)| { - date.matches(&Variable::String( - String::from_utf8_lossy(key).as_ref().into(), - )) + date.matches( + &Variable::String(String::from_utf8_lossy(key).as_ref().into()), + tz, + ) }) .map_or(pieces.other, |(_, _, _, piece)| *piece), None => pieces.other, @@ -901,7 +910,7 @@ impl CellSet { } } - pub fn classify(&self, pieces: &Pieces, column: &Column, rows: usize, out: &mut [u32]) { + pub fn classify(&self, pieces: &Pieces, column: &Column, rows: usize, out: &mut [u32], tz: Tz) { let out = &mut out[..rows]; if column.is_empty() { out.fill(pieces.null); @@ -970,7 +979,7 @@ impl CellSet { let dictionary = values.column(); let size = dictionary.len(); let mut coded = vec![0u32; size]; - self.classify(pieces, &dictionary, size, &mut coded); + self.classify(pieces, &dictionary, size, &mut coded, tz); for (row, piece) in out.iter_mut().enumerate() { let code = keys .get(row) @@ -984,14 +993,20 @@ impl CellSet { } _ => { for (row, piece) in out.iter_mut().enumerate() { - *piece = self.piece_of(pieces, &column.variable(row)); + *piece = self.piece_of(pieces, &column.variable(row), tz); } } } } - pub fn evaluate_indexed_column(&self, column: &Column, rows: usize, out: &mut Vec) { - self.indexed_column(column, rows, out); + pub fn evaluate_indexed_column( + &self, + column: &Column, + rows: usize, + out: &mut Vec, + tz: Tz, + ) { + self.indexed_column(column, rows, out, tz); for row in 0..rows { Bits::or( &mut out[row * self.words..(row + 1) * self.words], @@ -1023,8 +1038,8 @@ impl CellSet { self.owners.get(rule).copied().flatten() } - pub fn evaluate_indexed(&self, values: &[Variable], out: &mut Vec) { - self.indexed(values, out); + pub fn evaluate_indexed(&self, values: &[Variable], out: &mut Vec, tz: Tz) { + self.indexed(values, out, tz); for row in 0..values.len() { Bits::or( &mut out[row * self.words..(row + 1) * self.words], @@ -1044,7 +1059,7 @@ impl CellSet { scope } - fn indexed(&self, values: &[Variable], out: &mut Vec) { - self.indexed_column(&Column::new(Values::Any(values)), values.len(), out); + fn indexed(&self, values: &[Variable], out: &mut Vec, tz: Tz) { + self.indexed_column(&Column::new(Values::Any(values)), values.len(), out, tz); } } diff --git a/core/expression/src/lane/columns.rs b/core/expression/src/lane/columns.rs index 2227655c..0373dd3b 100644 --- a/core/expression/src/lane/columns.rs +++ b/core/expression/src/lane/columns.rs @@ -106,8 +106,8 @@ impl<'a> Dictionary<'a> { self.column().variable(row) } - pub fn equals(self, row: usize, k: &Variable) -> bool { - self.column().equals(row, k) + pub fn equals(self, row: usize, k: &Variable, tz: chrono_tz::Tz) -> bool { + self.column().equals(row, k, tz) } } @@ -381,7 +381,7 @@ impl<'a> Column<'a> { } } - pub fn equals(&self, row: usize, k: &Variable) -> bool { + pub fn equals(&self, row: usize, k: &Variable, tz: chrono_tz::Tz) -> bool { if !self.valid(row) { return matches!(k, Variable::Null); } @@ -406,10 +406,10 @@ impl<'a> Column<'a> { ) => self.bytes(row) == Some(s.as_bytes()), (Values::Any(v), k) => v .get(row) - .is_some_and(|v| crate::lane::ops::Ops::equal(v, k)), - (Values::Dict { values, .. }, k) => { - self.code(row).is_some_and(|code| values.equals(code, k)) - } + .is_some_and(|v| crate::lane::ops::Ops::equal(v, k, tz)), + (Values::Dict { values, .. }, k) => self + .code(row) + .is_some_and(|code| values.equals(code, k, tz)), (Values::List { .. }, _) => false, _ => false, } diff --git a/core/expression/src/lane/compile.rs b/core/expression/src/lane/compile.rs index f1a997ad..348152c3 100644 --- a/core/expression/src/lane/compile.rs +++ b/core/expression/src/lane/compile.rs @@ -1,4 +1,5 @@ use crate::compiler::{Compare, CompilerError, FetchFastTarget}; +use crate::context::Site; use crate::functions::registry::FunctionRegistry; use crate::functions::{ClosureFunction, FunctionKind, InternalFunction, MethodRegistry}; use crate::intellisense::type_provider::TypesProvider; @@ -105,6 +106,7 @@ pub struct LaneCompiler<'a> { assigning: ahash::HashMap, unresolved: bool, indexing: bool, + draws: ahash::HashMap, } impl<'a> LaneCompiler<'a> { @@ -121,7 +123,15 @@ impl<'a> LaneCompiler<'a> { hints: Option<&'a Hints>, types: Option<&'a TypesProvider>, ) -> Result { - Self::build(root, hints, types, false) + Self::build(root, hints, types, false, 0) + } + + pub(crate) fn compile_located( + root: &'a Node<'a>, + hints: Option<&'a Hints>, + label: u64, + ) -> Result { + Self::build(root, hints, None, false, label) } fn build( @@ -129,6 +139,7 @@ impl<'a> LaneCompiler<'a> { hints: Option<&'a Hints>, types: Option<&'a TypesProvider>, folding: bool, + label: u64, ) -> Result { let mut compiler = LaneCompiler { stack: vec![Builder::default()], @@ -146,7 +157,9 @@ impl<'a> LaneCompiler<'a> { assigning: Default::default(), unresolved: false, indexing: false, + draws: Default::default(), }; + compiler.number(root, label); let (out, layout) = match Self::shaped(root) { true => { let layout = compiler.layout(root, &mut Vec::new())?; @@ -229,6 +242,15 @@ impl<'a> LaneCompiler<'a> { roots: &[(&'a str, &'a Node<'a>)], chain: bool, hints: Option<&'a Hints>, + ) -> Result { + Self::compile_many_located(roots, chain, hints, &[]) + } + + pub(crate) fn compile_many_located( + roots: &[(&'a str, &'a Node<'a>)], + chain: bool, + hints: Option<&'a Hints>, + labels: &[u64], ) -> Result { let assigns = roots.iter().any(|(_, n)| Self::assigns(n)); let nested = roots @@ -236,10 +258,10 @@ impl<'a> LaneCompiler<'a> { .any(|(a, _)| roots.iter().any(|(b, _)| DotPath::under(b, a))); let resolvable = chain && !assigns && !nested && roots.iter().all(|(_, n)| Self::dollar_static(n)); - match Self::compile_entries(roots, chain, hints, assigns, resolvable) { + match Self::compile_entries(roots, chain, hints, assigns, resolvable, labels) { Ok(program) => Ok(program), Err(CompilerError::UnexpectedErrorNode) if resolvable => { - Self::compile_entries(roots, chain, hints, assigns, false) + Self::compile_entries(roots, chain, hints, assigns, false, labels) } Err(e) => Err(e), } @@ -249,7 +271,7 @@ impl<'a> LaneCompiler<'a> { roots: &[(&'a str, &'a Node<'a>)], hints: Option<&'a Hints>, ) -> Result { - let mut program = Self::compile_entries(roots, false, hints, true, false)?; + let mut program = Self::compile_entries(roots, false, hints, true, false, &[])?; program.isolated = true; Ok(program) } @@ -260,6 +282,7 @@ impl<'a> LaneCompiler<'a> { hints: Option<&'a Hints>, assigns: bool, resolvable: bool, + labels: &[u64], ) -> Result { let dynamic = chain && !resolvable; let mut compiler = LaneCompiler { @@ -278,6 +301,7 @@ impl<'a> LaneCompiler<'a> { assigning: Default::default(), unresolved: false, indexing: chain, + draws: Default::default(), }; let mut outputs = Vec::with_capacity(roots.len()); for (index, (key, root)) in roots.iter().enumerate() { @@ -287,6 +311,7 @@ impl<'a> LaneCompiler<'a> { compiler.emit(Op::Stage { index: index as u32, }); + compiler.number(root, labels.get(index).copied().unwrap_or(0)); let out = compiler.node(root)?; if compiler.unresolved { return Err(CompilerError::UnexpectedErrorNode); @@ -369,6 +394,7 @@ impl<'a> LaneCompiler<'a> { assigning: Default::default(), unresolved: false, indexing: false, + draws: Default::default(), }; let mut outputs = Vec::with_capacity(roots.len()); for (key, root, output) in roots.iter() { @@ -377,6 +403,7 @@ impl<'a> LaneCompiler<'a> { index: outputs.len() as u32, }); } + compiler.number(root, 0); let out = compiler.node(root)?; if compiler.unresolved || compiler.writes_env { return Err(CompilerError::UnexpectedErrorNode); @@ -1205,6 +1232,7 @@ impl<'a> LaneCompiler<'a> { args: std::iter::once(Input::Reg(scratch)) .chain(args.iter().map(|id| Input::Const(*id))) .collect(), + draw: Site::default(), }; self.emit(Op::LoadCall(Box::new(LoadCall { dst, @@ -1250,6 +1278,10 @@ impl<'a> LaneCompiler<'a> { } fn call(&mut self, kind: FunctionKind, args: Vec) -> Reg { + self.drawn(kind, args, Site::default()) + } + + fn drawn(&mut self, kind: FunctionKind, args: Vec, draw: Site) -> Reg { let listed = matches!(args.as_slice(), [Input::Reg(r)] if self.top().kind(*r) == Kind::List); self.release_args(&args); @@ -1266,10 +1298,91 @@ impl<'a> LaneCompiler<'a> { dst, kind, args: args.into(), + draw, }); dst } + fn number(&mut self, root: &'a Node<'a>, label: u64) { + let mut next = 0u32; + Self::visit(root, &mut |node| { + if let Node::FunctionCall { + kind: FunctionKind::Internal(InternalFunction::Rand), + .. + } = node + { + let key = node as *const Node as usize; + if let std::collections::hash_map::Entry::Vacant(entry) = self.draws.entry(key) { + entry.insert(Site::new(label, next)); + next += 1; + } + } + }); + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn visit<'n>(node: &'n Node<'n>, f: &mut dyn FnMut(&'n Node<'n>)) { + f(node); + match node { + Node::Null + | Node::Bool(_) + | Node::Number(_) + | Node::String(_) + | Node::Pointer + | Node::Identifier(_) + | Node::Root => {} + Node::Error { node, .. } => node.iter().for_each(|n| Self::visit(n, f)), + Node::TemplateString(parts) | Node::Array(parts) => { + parts.iter().for_each(|n| Self::visit(n, f)) + } + Node::Object(pairs) => pairs.iter().for_each(|(k, v)| { + Self::visit(k, f); + Self::visit(v, f); + }), + Node::Assignments { list, output } => { + list.iter().for_each(|(k, v)| { + Self::visit(k, f); + Self::visit(v, f); + }); + output.iter().for_each(|n| Self::visit(n, f)); + } + Node::Closure { body, .. } => Self::visit(body, f), + Node::Parenthesized(inner) => Self::visit(inner, f), + Node::Member { node, property } => { + Self::visit(node, f); + Self::visit(property, f); + } + Node::Slice { node, from, to } => { + Self::visit(node, f); + from.iter().for_each(|n| Self::visit(n, f)); + to.iter().for_each(|n| Self::visit(n, f)); + } + Node::Interval { left, right, .. } | Node::Binary { left, right, .. } => { + Self::visit(left, f); + Self::visit(right, f); + } + Node::Conditional { + condition, + on_true, + on_false, + } => { + Self::visit(condition, f); + Self::visit(on_true, f); + Self::visit(on_false, f); + } + Node::Unary { node, .. } => Self::visit(node, f), + Node::FunctionCall { arguments, .. } => { + arguments.iter().for_each(|n| Self::visit(n, f)) + } + Node::MethodCall { + this, arguments, .. + } => { + Self::visit(this, f); + arguments.iter().for_each(|n| Self::visit(n, f)); + } + } + } + fn element_field(body: &Program) -> Option> { match body.steps.as_slice() { [Step { @@ -1530,6 +1643,7 @@ impl<'a> LaneCompiler<'a> { assigning: Default::default(), unresolved: false, indexing: false, + draws: Default::default(), } } @@ -1537,7 +1651,7 @@ impl<'a> LaneCompiler<'a> { if self.folding || Self::literal(node).is_some() || !self.pure(node) { return None; } - let program = Self::build(node, None, None, true).ok()?; + let program = Self::build(node, None, None, true, 0).ok()?; Some(match crate::lane::LaneRunner::constant(&program)? { Variable::Null => Const::Null, Variable::Bool(b) => Const::Bool(b), @@ -2035,6 +2149,18 @@ impl<'a> LaneCompiler<'a> { } } } + if let FunctionKind::Internal(InternalFunction::Rand) = kind { + let draw = self + .draws + .get(&(node as *const Node as usize)) + .copied() + .unwrap_or_default(); + let args = arguments + .iter() + .map(|a| self.arg(a)) + .collect::>>()?; + return Ok(self.drawn(kind.clone(), args, draw)); + } if let Some(dst) = self.load_call(kind, arguments) { return Ok(dst); } diff --git a/core/expression/src/lane/date/helpers.rs b/core/expression/src/lane/date/helpers.rs index ee301bcc..d273abc4 100644 --- a/core/expression/src/lane/date/helpers.rs +++ b/core/expression/src/lane/date/helpers.rs @@ -1,4 +1,4 @@ -use crate::lane::date::utc_now; +use crate::context::EvaluationContext; use crate::vm::VMError; use chrono::format::{parse, Item, ParseResult, Parsed, StrftimeItems}; use chrono::{DateTime, Datelike, Days, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday}; @@ -82,9 +82,9 @@ impl IsoDate { } } -pub(crate) fn date_time(str: &str) -> VMResult { +pub(crate) fn date_time(str: &str, context: &EvaluationContext) -> VMResult { if str == "now" { - return Ok(utc_now().naive_utc()); + return Ok(context.now().naive_utc()); } if let Some(parsed) = IsoDate::parse(str) { @@ -99,8 +99,8 @@ pub(crate) fn date_time(str: &str) -> VMResult { }) } -pub(crate) fn time(str: &str) -> VMResult { - let now = utc_now(); +pub(crate) fn time(str: &str, context: &EvaluationContext) -> VMResult { + let now = context.now(); if str == "now" { return Ok(now.naive_utc().time()); diff --git a/core/expression/src/lane/date/mod.rs b/core/expression/src/lane/date/mod.rs index 98dc55cb..941d68f8 100644 --- a/core/expression/src/lane/date/mod.rs +++ b/core/expression/src/lane/date/mod.rs @@ -1,14 +1,14 @@ +use crate::context::EvaluationContext; pub(crate) use crate::lane::date::duration::Duration; pub(crate) use crate::lane::date::duration_unit::DurationUnit; use crate::variable::DynamicVariable; use crate::Variable; -use chrono::{DateTime, SecondsFormat, Utc}; +use chrono::{DateTime, SecondsFormat}; use chrono_tz::Tz; use serde_json::Value; use std::any::Any; use std::fmt::{Display, Formatter}; use std::rc::Rc; -use std::sync::OnceLock; mod duration; mod duration_parser; @@ -78,24 +78,28 @@ impl Formats { } impl Date { - pub fn now() -> Self { - Self(Some(helper::now())) + pub fn now(context: &EvaluationContext) -> Self { + Self(Some(helper::now_tz(context, context.timezone()))) } - pub fn yesterday() -> Self { - Self::now().sub(Duration::day()) + pub fn yesterday(context: &EvaluationContext) -> Self { + Self::now(context).sub(Duration::day()) } - pub fn tomorrow() -> Self { - Self::now().add(Duration::day()) + pub fn tomorrow(context: &EvaluationContext) -> Self { + Self::now(context).add(Duration::day()) } - pub fn new(var: Variable, tz_opt: Option) -> Self { - Self(helper::parse_date(var, tz_opt)) + pub fn new(var: Variable, tz_opt: Option, context: &EvaluationContext) -> Self { + Self(helper::parse_date(var, tz_opt, context)) } - pub(crate) fn text(str: &str, tz_opt: Option) -> Self { - Self(helper::parse_str(str, tz_opt.unwrap_or_else(helper::tz))) + pub(crate) fn text(str: &str, tz_opt: Option, context: &EvaluationContext) -> Self { + Self(helper::parse_str( + str, + tz_opt.unwrap_or_else(|| context.timezone()), + context, + )) } pub fn is_valid(&self) -> bool { @@ -219,7 +223,8 @@ impl Date { } mod helper { - use crate::lane::date::{utc_now, Duration, DurationUnit, DynamicVariableExt}; + use crate::context::EvaluationContext; + use crate::lane::date::{Duration, DurationUnit, DynamicVariableExt}; use crate::Variable; use chrono::{ DateTime, Datelike, Days, FixedOffset, LocalResult, Month, Months, NaiveDate, @@ -229,31 +234,19 @@ mod helper { use rust_decimal::prelude::ToPrimitive; use std::ops::Deref; use std::str::FromStr; - use std::sync::OnceLock; - pub(super) fn tz() -> Tz { - static CACHED_TZ: OnceLock = OnceLock::new(); - - *CACHED_TZ.get_or_init(|| { - iana_time_zone::get_timezone() - .ok() - .and_then(|tz| Tz::from_str(&tz).ok()) - .unwrap_or(Tz::UTC) - }) + pub fn now_tz(context: &EvaluationContext, tz: Tz) -> DateTime { + context.now().with_timezone(&tz) } - pub fn now() -> DateTime { - now_tz(tz()) - } - - pub fn now_tz(tz: Tz) -> DateTime { - utc_now().with_timezone(&tz) - } - - pub fn parse_date(var: Variable, tz_opt: Option) -> Option> { + pub fn parse_date( + var: Variable, + tz_opt: Option, + context: &EvaluationContext, + ) -> Option> { match var { Variable::Number(n) => { - let tz = tz_opt.unwrap_or_else(tz); + let tz = tz_opt.unwrap_or_else(|| context.timezone()); let n_i64 = n.to_i64()?; let date_time = match tz.timestamp_millis_opt(n_i64) { LocalResult::Single(date_time) => date_time, @@ -263,7 +256,11 @@ mod helper { Some(date_time) } - Variable::String(str) => parse_str(str.deref(), tz_opt.unwrap_or_else(tz)), + Variable::String(str) => parse_str( + str.deref(), + tz_opt.unwrap_or_else(|| context.timezone()), + context, + ), Variable::Dynamic(d) => { let date = d.as_date()?; let source = d @@ -280,18 +277,18 @@ mod helper { } } - pub(crate) fn parse_str(str: &str, tz: Tz) -> Option> { - parse_text(str, tz).or_else(|| zone_now(str)) + pub(crate) fn parse_str( + str: &str, + tz: Tz, + context: &EvaluationContext, + ) -> Option> { + parse_text(str, tz).or_else(|| zone_now(str, context)) } #[cold] #[inline(never)] - fn zone_now(str: &str) -> Option> { - Tz::from_str(str).ok().map(now_tz) - } - - pub(crate) fn from_text(str: &str) -> Option> { - parse_text(str, tz()) + fn zone_now(str: &str, context: &EvaluationContext) -> Option> { + Tz::from_str(str).ok().map(|tz| now_tz(context, tz)) } #[inline] @@ -445,7 +442,7 @@ mod helper { } } - pub(crate) trait Clock: Datelike + Timelike + Sized { + pub(crate) trait Wall: Datelike + Timelike + Sized { fn add_days(self, days: Days) -> Option; fn sub_days(self, days: Days) -> Option; fn plus(self, delta: TimeDelta) -> Option; @@ -453,7 +450,7 @@ mod helper { fn sub_months(self, months: Months) -> Option; } - impl Clock for DateTime { + impl Wall for DateTime { fn add_days(self, days: Days) -> Option { self.checked_add_days(days) } @@ -475,7 +472,7 @@ mod helper { } } - impl Clock for NaiveDateTime { + impl Wall for NaiveDateTime { fn add_days(self, days: Days) -> Option { self.checked_add_days(days) } @@ -500,7 +497,7 @@ mod helper { pub(crate) struct Calendar; impl Calendar { - pub(crate) fn shift(mut date_time: T, duration: Duration) -> Option { + pub(crate) fn shift(mut date_time: T, duration: Duration) -> Option { date_time = date_time.plus(TimeDelta::try_seconds(duration.seconds)?)?; date_time = match duration.months < 0 { true => date_time.sub_months(Months::new(duration.months.unsigned_abs()))?, @@ -525,7 +522,7 @@ mod helper { ) } - pub(crate) fn start_of(date_time: T, unit: DurationUnit) -> Option { + pub(crate) fn start_of(date_time: T, unit: DurationUnit) -> Option { Some(match unit { DurationUnit::Second => date_time.with_nanosecond(0)?, DurationUnit::Minute => date_time.with_second(0)?.with_nanosecond(0)?, @@ -571,7 +568,7 @@ mod helper { }) } - pub(crate) fn end_of(mut date_time: T, unit: DurationUnit) -> Option { + pub(crate) fn end_of(mut date_time: T, unit: DurationUnit) -> Option { date_time = date_time.with_nanosecond(999_999_999)?; Some(match unit { @@ -769,24 +766,31 @@ impl Date { Variable::Dynamic(Rc::new(crate::vm::VmDate::from(self.0))) } - pub(crate) fn coerce(v: &Variable) -> Option { + pub(crate) fn coerce(v: &Variable, tz: Tz) -> Option { match v { Variable::Dynamic(d) => d.as_date(), - Variable::String(text) => Some(Self::from_text(text)), + Variable::String(text) => Some(Self::from_text(text, tz)), _ => None, } } - pub(crate) fn parses(text: &str) -> bool { - helper::parse_text(text, helper::tz()).is_some() + pub(crate) fn from_text(text: &str, tz: Tz) -> Date { + Date(helper::parse_text(text, tz)) } - pub(crate) fn from_text(text: &str) -> Date { - Date(helper::from_text(text)) + pub(crate) fn never(text: &str) -> bool { + !Self::from_text(text, Tz::UTC).is_valid() + && !Self::from_text(text, Tz::Etc__GMTMinus14).is_valid() } - pub(crate) fn matches(&self, other: &Variable) -> bool { - self.0.is_some() && Self::coerce(other).is_some_and(|other| other == *self) + pub(crate) fn fixed(text: &str) -> Option { + let utc = Self::from_text(text, Tz::UTC); + let east = Self::from_text(text, Tz::Etc__GMTMinus14); + (utc.is_valid() && utc == east).then_some(utc) + } + + pub(crate) fn matches(&self, other: &Variable, tz: Tz) -> bool { + self.0.is_some() && Self::coerce(other, tz).is_some_and(|other| other == *self) } pub(crate) fn rendered(&self) -> Option { @@ -817,17 +821,6 @@ impl Date { } } -pub(crate) fn utc_now() -> DateTime { - static CURRENT_DATE_VALUE: OnceLock>> = OnceLock::new(); - - CURRENT_DATE_VALUE - .get_or_init(|| match std::env::var("__ZEN_MOCK_UTC_TIME") { - Ok(v) => v.parse::>().ok(), - Err(_) => None, - }) - .unwrap_or_else(Utc::now) -} - #[cfg(test)] mod format_tests { use super::Date; @@ -856,7 +849,11 @@ mod format_tests { "2025-10-26 02:30:00", ]; for date in dates { - let vm = Date::new(Variable::String(date.into()), None); + let vm = Date::new( + Variable::String(date.into()), + None, + &crate::context::EvaluationContext::default(), + ); let Some(dt) = vm.0 else { continue }; for format in formats { for _ in 0..2 { diff --git a/core/expression/src/lane/effect.rs b/core/expression/src/lane/effect.rs index 04a997ac..59c9a3a8 100644 --- a/core/expression/src/lane/effect.rs +++ b/core/expression/src/lane/effect.rs @@ -45,12 +45,10 @@ impl Effect { ) -> Self { match kind { FunctionKind::Internal(InternalFunction::Date) => match literals.next() { - None | Some(Literal::Computed) => Effect::Clock, - Some(Literal::Constant) => Effect::Pure, - Some(Literal::Text(text)) if Date::parses(text) || Tz::from_str(text).is_err() => { + Some(Literal::Text(text)) if Date::never(text) && Tz::from_str(text).is_err() => { Effect::Pure } - Some(Literal::Text(_)) => Effect::Clock, + _ => Effect::Clock, }, FunctionKind::Deprecated(DeprecatedFunction::Duration) => Effect::Pure, FunctionKind::Deprecated(_) => { diff --git a/core/expression/src/lane/exec/closure.rs b/core/expression/src/lane/exec/closure.rs index 1c649d4f..a1859fc3 100644 --- a/core/expression/src/lane/exec/closure.rs +++ b/core/expression/src/lane/exec/closure.rs @@ -166,7 +166,11 @@ impl Executor { rest: &mut [Frame], ctx: &mut Context, ) -> bool { - if c.sequential || matches!(c.kind, ClosureFunction::FlatMap) || active.is_empty() { + if c.sequential + || c.body.draws + || matches!(c.kind, ClosureFunction::FlatMap) + || active.is_empty() + { return false; } let source = match Self::selection(c, f, ctx) { @@ -755,10 +759,15 @@ impl Executor { bits.clear(); bits.resize(words, 0); } - let mut start = 0; - while start < total { - let end = (start + chunk).min(total); - let width = end - start; + let parent_of = |j: usize| match column { + Some(_) => slots[j].0, + None => items[j].0, + }; + let blocks = Executor::blocks(total, chunk, c.body.draws, ctx.context, |j| { + ctx.drawn_row(f.rows[parent_of(j) as usize]) + }); + for (start, width) in blocks { + let end = start + width; rows.clear(); parents.clear(); for j in start..end { @@ -823,7 +832,6 @@ impl Executor { _ => child.take(out, lane), }); } - start = end; } } @@ -852,14 +860,15 @@ impl Executor { rest: &mut [Frame], ctx: &mut Context, ) { - if active.count() == 1 { - let lane = active.first().unwrap_or_default(); - let r = match Self::list_of(c, lane, f, ctx) { - Ok(list @ Variable::Array(_)) => Self::single(c, lane, &list, f, rest, ctx), - Ok(_) => Err(Ops::error("Begin", "Unsupported type")), - Err(e) => Err(e), - }; - f.put(c.dst, lane, r); + if active.count() == 1 || c.body.draws { + for lane in Lanes::of(active) { + let r = match Self::list_of(c, lane, f, ctx) { + Ok(list @ Variable::Array(_)) => Self::single(c, lane, &list, f, rest, ctx), + Ok(_) => Err(Ops::error("Begin", "Unsupported type")), + Err(e) => Err(e), + }; + f.put(c.dst, lane, r); + } return; } let mut scratch = std::mem::take(&mut f.scratch); diff --git a/core/expression/src/lane/exec/context.rs b/core/expression/src/lane/exec/context.rs index 12b62e2a..92510e0b 100644 --- a/core/expression/src/lane/exec/context.rs +++ b/core/expression/src/lane/exec/context.rs @@ -1,6 +1,9 @@ +use crate::context::EvaluationContext; +use crate::lane::builtins::RowContext; use crate::lane::columns::{Column, Columns, Values}; use crate::lane::program::{Binding, Program, Reg}; use crate::scope::Scope; +use chrono_tz::Tz; pub enum Envs<'a> { Shared(&'a [Scope]), @@ -25,17 +28,19 @@ impl Envs<'_> { } pub struct Context<'a> { + pub context: &'a EvaluationContext, pub roots: Envs<'a>, pub envs: Envs<'a>, pub columns: Option<&'a Columns<'a>>, pub bound: &'a [Binding], pub base: usize, + pub first: usize, pub(super) views: Vec<(u64, Reg, Column<'a>)>, pub(super) texts: Vec<(*const u8, Option<&'a str>)>, } impl<'a> Context<'a> { - pub fn new(program: &Program, roots: &'a [Scope]) -> Self { + pub fn new(program: &Program, roots: &'a [Scope], context: &'a EvaluationContext) -> Self { let envs = match program.writes_env { true => Envs::Owned(roots.to_vec()), false => Envs::Shared(roots), @@ -45,11 +50,13 @@ impl<'a> Context<'a> { false => Envs::Shared(roots), }; Self { + context, roots, envs, columns: None, bound: &[], base: 0, + first: 0, views: Vec::new(), texts: Vec::new(), } @@ -61,14 +68,36 @@ impl<'a> Context<'a> { columns: &'a Columns<'a>, bound: &'a [Binding], base: usize, + context: &'a EvaluationContext, ) -> Self { - let mut ctx = Self::new(program, roots); + let mut ctx = Self::new(program, roots, context); ctx.columns = Some(columns); ctx.bound = bound; ctx.base = base; + ctx.first = base; ctx } + #[inline] + pub(super) fn drawn_row(&self, row: u32) -> usize { + self.first + row as usize + } + + #[inline] + pub(crate) fn at(&self, row: u32) -> RowContext<'a> { + RowContext::new(self.context, self.drawn_row(row)) + } + + #[inline] + pub(crate) fn here(&self) -> RowContext<'a> { + RowContext::new(self.context, self.first) + } + + #[inline] + pub(crate) fn tz(&self) -> Tz { + self.context.timezone() + } + pub(super) fn view(&self, program: u64, reg: Reg) -> Option> { self.views .iter() diff --git a/core/expression/src/lane/exec/date.rs b/core/expression/src/lane/exec/date.rs index 0eac42d4..94a11046 100644 --- a/core/expression/src/lane/exec/date.rs +++ b/core/expression/src/lane/exec/date.rs @@ -1,7 +1,7 @@ use super::frame::Frame; use super::Executor; use crate::functions::{FunctionKind, InternalFunction, MethodKind}; -use crate::lane::builtins::{Arg, Dates}; +use crate::lane::builtins::{Arg, Dates, RowContext}; use crate::lane::date::Date; use crate::lane::mask::{LaneSet, Lanes}; use crate::lane::program::{Input, Kind, Reg}; @@ -14,6 +14,7 @@ impl Executor { args: &[Input], active: M, f: &mut Frame, + ctx: RowContext, ) -> M { let mut done = f.none(); let zone = match (kind, args) { @@ -45,7 +46,7 @@ impl Executor { { *date } - _ => Date::text(text, zone), + _ => Date::text(text, zone, ctx.context()), }; let at = f.at(dst, lane); f.dates[at] = date; diff --git a/core/expression/src/lane/exec/load.rs b/core/expression/src/lane/exec/load.rs index 6589d834..be5b4501 100644 --- a/core/expression/src/lane/exec/load.rs +++ b/core/expression/src/lane/exec/load.rs @@ -3,7 +3,7 @@ use super::frame::{Fault, Frame, SEGMENTS}; use super::Executor; use crate::compiler::FetchFastTarget; use crate::functions::{FunctionKind, InternalFunction}; -use crate::lane::builtins::{Arg, Builtins, ListView, Out, Text, TextKernel}; +use crate::lane::builtins::{Arg, Builtins, ListView, Out, RowContext, Text, TextKernel}; use crate::lane::columns::{Column, Dictionary, Values}; use crate::lane::effect::Effect; use crate::lane::mask::{LaneSet, Lanes}; @@ -42,11 +42,19 @@ impl Executor { .map(|id| f.consts[*id as usize].clone()) .collect(); let mut hint = 0usize; + let context = ctx.context; + let drawn = std::cell::Cell::new(ctx.first); let mut call = |first: Arg| -> Result { let mut args: smallvec::SmallVec<[Arg; 4]> = smallvec::SmallVec::new(); args.push(first); args.extend(consts.iter().map(Arg::of)); - Builtins::call_hinted(builtin, &c.kind, &args, &mut hint) + Builtins::call_hinted( + builtin, + &c.kind, + &args, + &mut hint, + &RowContext::new(context, drawn.get()), + ) }; let column = ctx.column(c.site); if let Some(Some(col)) = column { @@ -194,6 +202,9 @@ impl Executor { let pure = Effect::function(&c.kind) != Effect::Random; for lane in Lanes::of(active & !done) { let mut share = None; + if !pure { + drawn.set(ctx.drawn_row(f.rows[lane])); + } let r = match column { Some(Some(col)) => { let row = ctx.base + f.rows[lane] as usize; @@ -649,6 +660,7 @@ impl Executor { ctx: &mut Context, ) { let k = f.consts[*id as usize].clone(); + let tz = ctx.tz(); let d = *dst as usize; let mut word = f.none(); match ctx.column(*site) { @@ -657,7 +669,7 @@ impl Executor { let mut matched = [0u64; 4]; if let Values::Dict { values, .. } = column.values { for code in 0..values.len() { - matched[code / 64] |= (values.equals(code, &k) as u64) << (code % 64); + matched[code / 64] |= (values.equals(code, &k, tz) as u64) << (code % 64); } } let null = matches!(k, Variable::Null); @@ -715,7 +727,7 @@ impl Executor { _ => { for lane in Lanes::of(active) { let row = ctx.base + f.rows[lane] as usize; - word.put(lane, column.equals(row, &k)); + word.put(lane, column.equals(row, &k, tz)); } } } @@ -732,18 +744,19 @@ impl Executor { let env = ctx.envs.get(row); let hit = match load { Load::Env(key) => Self::lookup(key, *site, row, f, ctx, |_, r| { - r.map(|v| Ops::equal(v, &k)) + r.map(|v| Ops::equal(v, &k, tz)) }), Load::Path(path) => match Self::simple(path) && env.locals().is_empty() { true => Ok(Self::path_with( env.base(), &path[1..], &mut f.hints[slot..], - |v| Ops::equal(v, &k), + |v| Ops::equal(v, &k, tz), )), false => Ok(Ops::equal( &Ops::fetch_fast(path, ctx.roots.get(row), env), &k, + tz, )), }, }; @@ -798,7 +811,7 @@ impl Executor { Some(None) => Ok(Variable::Null), None => Self::row_value(load, *site, lane, f, ctx), }; - haystack.and_then(|h| Ops::membership(f.take(*a, lane), &h)) + haystack.and_then(|h| Ops::membership(f.take(*a, lane), &h, ctx.tz())) } }; f.put(*dst, lane, result.map(Variable::Bool)); diff --git a/core/expression/src/lane/exec/mod.rs b/core/expression/src/lane/exec/mod.rs index 2dffa08e..9add1807 100644 --- a/core/expression/src/lane/exec/mod.rs +++ b/core/expression/src/lane/exec/mod.rs @@ -9,6 +9,7 @@ mod number; mod switch; mod text; +use crate::context::EvaluationContext; use crate::functions::{FunctionKind, InternalFunction}; use crate::lane::builtins::{Arg, Builtins, Out}; use crate::lane::interval::{Interval, IntervalData}; @@ -20,6 +21,7 @@ use crate::lane::program::{ }; use crate::lane::scaled::Scaled; use crate::variable::Variable; +use chrono_tz::Tz; use rust_decimal::Decimal; use zen_types::symbol::Symbol; @@ -155,7 +157,7 @@ impl Executor { } #[inline] - fn equal_lane(f: &Frame, a: Reg, b: Reg, lane: usize) -> Option { + fn equal_lane(f: &Frame, a: Reg, b: Reg, lane: usize, tz: Tz) -> Option { let typed = |reg: Reg, value: &Variable| match (f.kind(reg), value) { (Kind::List, _) => Some(false), (Kind::Str, Variable::String(s)) => Some(f.text_at(reg, lane) == s.as_str()), @@ -168,7 +170,11 @@ impl Executor { _ => None, }; match (f.generic(a, lane), f.generic(b, lane)) { - (true, true) => Some(Ops::equal(&f.regs[f.at(a, lane)], &f.regs[f.at(b, lane)])), + (true, true) => Some(Ops::equal( + &f.regs[f.at(a, lane)], + &f.regs[f.at(b, lane)], + tz, + )), (false, true) => typed(a, &f.regs[f.at(b, lane)]), (true, false) => typed(b, &f.regs[f.at(a, lane)]), (false, false) => match (f.kind(a), f.kind(b)) { @@ -222,6 +228,46 @@ impl Executor { word } + pub fn blocks( + total: usize, + width: usize, + draws: bool, + context: &EvaluationContext, + row: impl Fn(usize) -> usize, + ) -> smallvec::SmallVec<[(usize, usize); 4]> { + let mut out = smallvec::SmallVec::new(); + if !draws { + let mut start = 0; + while start < total { + let n = (total - start).min(width); + out.push((start, n)); + start += n; + } + return out; + } + let key = |i: usize| context.stream(row(i)); + let cap = crate::lane::Word::LANES.min(width); + let (mut start, mut n, mut i) = (0usize, 0usize, 0usize); + while i < total { + let k = key(i); + let mut j = i + 1; + while j < total && j - i < cap && key(j) == k { + j += 1; + } + if n + (j - i) > cap { + out.push((start, n)); + start = i; + n = 0; + } + n += j - i; + i = j; + } + if n > 0 { + out.push((start, n)); + } + out + } + pub fn run( program: &Program, frames: &mut [Frame], @@ -344,7 +390,7 @@ impl Executor { } Op::Stage { index } => f.stage = *index, Op::Num { dst, op, a, b } => Self::num(*op, *dst, *a, *b, active, f), - Op::Cmp { dst, op, a, b } => Self::cmp(*op, *dst, *a, *b, active, f), + Op::Cmp { dst, op, a, b } => Self::cmp(*op, *dst, *a, *b, active, f, ctx.tz()), Op::Env { site, dst, .. } | Op::Path { site, dst, .. } if ctx.column(*site).is_some() => { @@ -691,8 +737,9 @@ impl Executor { } if slow.any() { let k = f.consts[*id as usize].clone(); + let tz = ctx.tz(); for lane in Lanes::of(slow) { - if f.with(*a, lane, |v| Ops::equal(v, &k)) { + if f.with(*a, lane, |v| Ops::equal(v, &k, tz)) { word.set(lane); } } @@ -744,7 +791,7 @@ impl Executor { *right, ) }) { - Ok(range) => Ops::membership(x, range), + Ok(range) => Ops::membership(x, range, ctx.tz()), Err(e) => Err(e.clone()), }, }; @@ -761,8 +808,9 @@ impl Executor { let (done, mut word) = Self::any_number(*a, *id, active, f); if let Variable::Array(list) = &f.consts[*id as usize] { let list = list.borrow(); + let tz = ctx.tz(); for lane in Lanes::of(active & !done) { - let hit = f.with(*a, lane, |x| list.iter().any(|k| Ops::equal(x, k))); + let hit = f.with(*a, lane, |x| list.iter().any(|k| Ops::equal(x, k, tz))); word.put(lane, hit); } } @@ -776,7 +824,8 @@ impl Executor { f.boxed[d] &= !done; for lane in Lanes::of(active & !done) { let x = f.take(*a, lane); - let r = Ops::membership(x, &f.consts[*id as usize]).map(Variable::Bool); + let r = + Ops::membership(x, &f.consts[*id as usize], ctx.tz()).map(Variable::Bool); f.put(*dst, lane, r); } } @@ -801,7 +850,7 @@ impl Executor { } => { for lane in Lanes::of(active) { let (x, y) = (f.take(*a, lane), f.take(*b, lane)); - match Ops::compared(&x, &y, *c) { + match Ops::compared(&x, &y, *c, ctx.tz()) { Some(hit) => f.set(*dst, lane, Variable::Bool(hit)), None => f.fault(lane, Fault::Unsupported("Compare")), } @@ -815,7 +864,7 @@ impl Executor { } => { let (mut word, mut done) = (f.none(), f.none()); for lane in Lanes::of(active) { - if let Some(hit) = Self::equal_lane(f, *a, *b, lane) { + if let Some(hit) = Self::equal_lane(f, *a, *b, lane, ctx.tz()) { word.put(lane, hit); done.set(lane); } @@ -834,7 +883,7 @@ impl Executor { } for lane in Lanes::of(active & !done) { let (x, y) = (f.take(*a, lane), f.take(*b, lane)); - f.put(*dst, lane, Ok(Variable::Bool(Ops::equal(&x, &y)))); + f.put(*dst, lane, Ok(Variable::Bool(Ops::equal(&x, &y, ctx.tz())))); } } Op::Binary { dst, op, a, b } => { @@ -861,9 +910,11 @@ impl Executor { Binary::Divide => Ops::divide(x, y), Binary::Modulo => Ops::modulo(x, y), Binary::Exponent => Ops::exponent(x, y), - Binary::Equal => Ok(Variable::Bool(Ops::equal(&x, &y))), - Binary::In => Ops::membership(x, &y).map(Variable::Bool), - Binary::Compare(c) => Ops::compare(&x, &y, *c).map(Variable::Bool), + Binary::Equal => Ok(Variable::Bool(Ops::equal(&x, &y, ctx.tz()))), + Binary::In => Ops::membership(x, &y, ctx.tz()).map(Variable::Bool), + Binary::Compare(c) => { + Ops::compare(&x, &y, *c, ctx.tz()).map(Variable::Bool) + } }; f.put(*dst, lane, r); } @@ -888,7 +939,8 @@ impl Executor { } Op::Len { dst, a } => { for lane in Lanes::of(active) { - let r = f.with(*a, lane, Ops::len); + let row_ctx = ctx.here(); + let r = f.with(*a, lane, |v| Ops::len(v, &row_ctx)); f.put(*dst, lane, r); } } @@ -929,7 +981,7 @@ impl Executor { dst, items, largest, - } => Self::extreme(*dst, items, *largest, active, f), + } => Self::extreme(*dst, items, *largest, active, f, ctx.here()), Op::Concat { dst, a, b } => { let typed = match f.kind(*dst) { Kind::Str => active & !f.boxed[*a as usize] & !f.boxed[*b as usize], @@ -963,6 +1015,7 @@ impl Executor { dst, kind: FunctionKind::Internal(InternalFunction::String), args, + .. } if matches!(**args, [Input::Reg(a)] if matches!(f.kind(a), Kind::Str | Kind::Num)) && f.kind(*dst) == Kind::Str => { @@ -993,19 +1046,54 @@ impl Executor { for lane in Lanes::of(active & !typed) { if f.with(a, lane, |value| matches!(value, Variable::Null)) { let r = null - .get_or_insert_with(|| Builtins::call(builtin, &kind, &[Arg::Null])) + .get_or_insert_with(|| { + Builtins::call(builtin, &kind, &[Arg::Null], &ctx.here()) + }) .clone(); f.write(*dst, lane, r); continue; } let r = { let value = f.arg_view(a, lane); - Builtins::call(builtin, &kind, &[value]) + Builtins::call(builtin, &kind, &[value], &ctx.here()) }; f.write(*dst, lane, r); } } - Op::Call { dst, kind, args } => { + Op::Call { + dst, + kind: kind @ FunctionKind::Internal(InternalFunction::Rand), + args, + draw, + } => { + let Some(builtin) = Builtins::of(kind) else { + return; + }; + f.box_lists(args, active); + let mut hint = 0usize; + for lane in Lanes::of(active) { + let result = { + let values: smallvec::SmallVec<[Arg; 4]> = args + .iter() + .map(|a| match *a { + Input::Const(id) => Arg::of(&f.consts[id as usize]), + Input::Reg(r) => f.arg_view(r, lane), + }) + .collect(); + Builtins::call_hinted( + builtin, + kind, + &values, + &mut hint, + &ctx.at(f.rows[lane]).with_site(*draw), + ) + }; + f.write_call(*dst, lane, result); + } + } + Op::Call { + dst, kind, args, .. + } => { let Some(builtin) = Builtins::of(kind) else { let e = Ops::error("CallFunction", format!("Function `{kind}` not found")); for lane in Lanes::of(active) { @@ -1017,7 +1105,7 @@ impl Executor { if done.is_empty() { done = Self::number_call(*dst, kind, args, active, f) | Self::list_call(*dst, kind, args, active, f) - | Self::date_call(*dst, kind, args, active, f); + | Self::date_call(*dst, kind, args, active, f, ctx.here()); } done |= Self::member_call(*dst, kind, args, active & !done, f); done |= Self::length_call(*dst, kind, args, active & !done, f); @@ -1034,7 +1122,7 @@ impl Executor { Input::Reg(_) => None, }) .collect(); - Builtins::call_hinted(builtin, kind, &values, &mut hint) + Builtins::call_hinted(builtin, kind, &values, &mut hint, &ctx.here()) }; for lane in Lanes::of(rest) { let copy = match &result { @@ -1057,7 +1145,7 @@ impl Executor { Input::Reg(r) => f.arg_view(r, lane), }) .collect(); - Builtins::call_hinted(builtin, kind, &values, &mut hint) + Builtins::call_hinted(builtin, kind, &values, &mut hint, &ctx.here()) }; f.write_call(*dst, lane, result); } @@ -1075,7 +1163,7 @@ impl Executor { Input::Reg(r) => f.arg_view(r, lane), }) .collect(); - Builtins::call_method(builtin, kind, &values) + Builtins::call_method(builtin, kind, &values, &ctx.here()) }; f.write(*dst, lane, result); } diff --git a/core/expression/src/lane/exec/number.rs b/core/expression/src/lane/exec/number.rs index e69ba5e9..27e020b1 100644 --- a/core/expression/src/lane/exec/number.rs +++ b/core/expression/src/lane/exec/number.rs @@ -3,7 +3,7 @@ use super::frame::{Buffers, Frame}; use super::Executor; use crate::compiler::Compare; use crate::functions::{FunctionKind, InternalFunction}; -use crate::lane::builtins::{Arg, Builtins, Out}; +use crate::lane::builtins::{Arg, Builtins, Out, RowContext}; use crate::lane::columns::{Column, Values}; use crate::lane::mask::{LaneSet, Lanes}; use crate::lane::ops::Ops; @@ -11,6 +11,7 @@ use crate::lane::program::{Input, Kind, NumCmp, NumOp, Operand, Reg}; use crate::lane::scaled::{Kernel, Scaled}; use crate::lexer::Bracket; use crate::variable::Variable; +use chrono_tz::Tz; use rust_decimal::prelude::ToPrimitive; use rust_decimal::Decimal; @@ -293,6 +294,7 @@ impl Executor { largest: bool, active: M, f: &mut Frame, + ctx: RowContext, ) { let mut slow = f.none(); for lane in Lanes::of(active) { @@ -343,7 +345,7 @@ impl Executor { }) .collect(); let array = Variable::from_array(values); - let r = Builtins::call(builtin, &kind, &[Arg::of(&array)]); + let r = Builtins::call(builtin, &kind, &[Arg::of(&array)], &ctx); f.write(dst, lane, r); } } @@ -530,7 +532,7 @@ impl Executor { let scale = Frame::::uniform(f.scales.get(base..base + f.width)?, ok)?; let (k, s) = Scaled::parts(&n)?; match Threshold::of(op, scale, k, s)? { - Threshold::At(op, k) => Some(Kernel::threshold::(values, k, |o| op.test(o))), + Threshold::RowContext(op, k) => Some(Kernel::threshold::(values, k, |o| op.test(o))), Threshold::Never => Some(f.none()), } } @@ -691,6 +693,7 @@ impl Executor { b: Operand, active: M, f: &mut Frame, + tz: Tz, ) { let slow = active & (f.operand_boxed(a) | f.operand_boxed(b)); let fast = active & !slow; @@ -711,11 +714,11 @@ impl Executor { for lane in Lanes::of(slow) { let (x, y) = (f.operand_value(a, lane), f.operand_value(b, lane)); match op { - NumCmp::Order(c) => match Ops::compared(&x, &y, c) { + NumCmp::Order(c) => match Ops::compared(&x, &y, c, tz) { Some(hit) => f.set(dst, lane, Variable::Bool(hit)), None => f.fault(lane, Fault::Unsupported("Compare")), }, - NumCmp::Equal => f.set(dst, lane, Variable::Bool(Ops::equal(&x, &y))), + NumCmp::Equal => f.set(dst, lane, Variable::Bool(Ops::equal(&x, &y, tz))), } } } @@ -758,7 +761,7 @@ impl NumCmp { } pub(super) enum Threshold { - At(NumCmp, i64), + RowContext(NumCmp, i64), Never, } @@ -766,16 +769,16 @@ impl Threshold { pub(super) fn of(op: NumCmp, scale: u8, k: i64, s: u8) -> Option { if s <= scale { let k = k.checked_mul(*Scaled::POW10.get((scale - s) as usize)?)?; - return Some(Threshold::At(op, k)); + return Some(Threshold::RowContext(op, k)); } let p = *Scaled::POW10.get((s - scale) as usize)?; let floor = k.div_euclid(p); let exact = k.rem_euclid(p) == 0; let ceil = floor + (!exact) as i64; Some(match op { - NumCmp::Order(Compare::More | Compare::LessOrEqual) => Threshold::At(op, floor), - NumCmp::Order(Compare::MoreOrEqual | Compare::Less) => Threshold::At(op, ceil), - NumCmp::Equal if exact => Threshold::At(op, floor), + NumCmp::Order(Compare::More | Compare::LessOrEqual) => Threshold::RowContext(op, floor), + NumCmp::Order(Compare::MoreOrEqual | Compare::Less) => Threshold::RowContext(op, ceil), + NumCmp::Equal if exact => Threshold::RowContext(op, floor), NumCmp::Equal => Threshold::Never, }) } diff --git a/core/expression/src/lane/exec/switch.rs b/core/expression/src/lane/exec/switch.rs index a62451f6..56126edf 100644 --- a/core/expression/src/lane/exec/switch.rs +++ b/core/expression/src/lane/exec/switch.rs @@ -8,6 +8,7 @@ use crate::lane::program::{Kind, Subject, SwitchOp}; use crate::lane::scaled::Scaled; use crate::lane::ShortKey; use crate::variable::Variable; +use chrono_tz::Tz; use zen_types::symbol::Symbol; impl Executor { @@ -17,7 +18,7 @@ impl Executor { picks.resize(f.width, 0); let done = match op.subject { Subject::Site(site) => Self::switch_column(op, site, active, f, ctx, &mut picks), - Subject::Reg(reg) => Self::switch_register(op, reg, active, f, &mut picks), + Subject::Reg(reg) => Self::switch_register(op, reg, active, f, &mut picks, ctx.tz()), }; if done.any() { Self::switch_write(op, done, f, &picks); @@ -99,7 +100,11 @@ impl Executor { op.cases .iter() .position(|case| { - values.equals(code, &Variable::String(Symbol::from(case.as_ref()))) + values.equals( + code, + &Variable::String(Symbol::from(case.as_ref())), + ctx.tz(), + ) }) .map_or(fallback, |at| at as u8) }) @@ -126,6 +131,7 @@ impl Executor { active: M, f: &mut Frame, picks: &mut [u8], + tz: Tz, ) -> M { let fallback = op.cases.len() as u8; let typed = match f.kind(reg) { @@ -159,7 +165,7 @@ impl Executor { for lane in Lanes::of(active & !typed) { picks[lane] = f .with(reg, lane, |value| { - cases.iter().position(|case| Ops::equal(value, case)) + cases.iter().position(|case| Ops::equal(value, case, tz)) }) .map_or(fallback, |at| at as u8); } diff --git a/core/expression/src/lane/kernel.rs b/core/expression/src/lane/kernel.rs index 2ce67749..f7cee119 100644 --- a/core/expression/src/lane/kernel.rs +++ b/core/expression/src/lane/kernel.rs @@ -1,9 +1,10 @@ use crate::compiler::Compare; +use crate::context::EvaluationContext; use crate::functions::registry::FunctionRegistry; use crate::functions::{ ClosureFunction, DateMethod, FunctionKind, InternalFunction, MethodKind, MethodRegistry, }; -use crate::lane::builtins::{Arg, Builtins, Dates, Out}; +use crate::lane::builtins::{Arg, Builtins, Dates, Out, RowContext}; use crate::lane::columns::Columns; use crate::lane::compile::{Hints, LaneCompiler}; use crate::lane::date::Date; @@ -76,6 +77,7 @@ enum Step { } pub(crate) struct Env<'a> { + context: &'a EvaluationContext, row: usize, columns: Option<&'a Columns<'a>>, bound: &'a [Binding], @@ -84,17 +86,6 @@ pub(crate) struct Env<'a> { roots: Option<&'a RefCell>, } -impl Env<'_> { - const EMPTY: Env<'static> = Env { - row: 0, - columns: None, - bound: &[], - outs: &[], - current: None, - roots: None, - }; -} - pub(crate) struct Cx<'a> { scope: &'a Scope, env: &'a Env<'a>, @@ -103,6 +94,21 @@ pub(crate) struct Cx<'a> { } impl<'a> Cx<'a> { + #[inline] + fn at(&self) -> RowContext<'a> { + RowContext::new(self.env.context, self.env.row) + } + + #[inline] + fn tz(&self) -> chrono_tz::Tz { + self.env.context.timezone() + } + + #[inline] + fn context(&self) -> &'a EvaluationContext { + self.env.context + } + #[inline] fn pointer(&self, depth: u32) -> Option<&'a Variable> { let mut cx = self; @@ -576,15 +582,23 @@ impl Kernel { } #[inline(always)] - pub(crate) fn run(&self, scope: &Scope) -> Option { + pub(crate) fn run(&self, scope: &Scope, context: &EvaluationContext) -> Option { match (self.entries.as_slice(), &self.mode) { ([entry], Mode::Plain) => entry(&Cx { scope, - env: &Env::EMPTY, + env: &Env { + context, + row: 0, + columns: None, + bound: &[], + outs: &[], + current: None, + roots: None, + }, element: None, up: None, }), - _ => self.run_all(scope, 0, None, &[])?.pop(), + _ => self.run_all(scope, 0, None, &[], context)?.pop(), } } @@ -595,6 +609,7 @@ impl Kernel { row: usize, columns: Option<&Columns>, bound: &[Binding], + context: &EvaluationContext, ) -> Option { let mut values = Values::new(); let (current, roots, bound) = match &self.mode { @@ -613,6 +628,7 @@ impl Kernel { *current.borrow_mut() = roots.borrow().clone(); } let env = Env { + context, row, columns, bound, @@ -793,8 +809,11 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { let a = a(s)?; let to = match &to { Some(t) => t(s)?, - None => Ops::subtract(Ops::len(&a).ok()?, Variable::Number(Decimal::ONE)) - .ok()?, + None => Ops::subtract( + Ops::len(&a, &s.at()).ok()?, + Variable::Number(Decimal::ONE), + ) + .ok()?, }; let from = match &from { Some(f) => f(s)?, @@ -942,7 +961,9 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { Key::Static(k) => Symbol::from(k.as_ref()), Key::Dynamic(f) => { let k = f(s)?; - let text = Builtins::raw(string, &[Arg::of(&k)]).ok()?.variable(); + let text = Builtins::raw(string, &[Arg::of(&k)], &s.at()) + .ok()? + .variable(); Ops::object_key(text).ok()? } }; @@ -1243,7 +1264,10 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { let (m, sc) = Scaled::parts(&n)?; Scaled::write(m, sc, &mut out); } - v => match Builtins::raw(string, &[Arg::of(&v)]).ok()?.variable() { + v => match Builtins::raw(string, &[Arg::of(&v)], &s.at()) + .ok()? + .variable() + { Variable::String(t) => out.push_str(t.as_str()), _ => return None, }, @@ -1284,6 +1308,9 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { } fn call(&mut self, kind: &FunctionKind, arguments: &'a [&'a Node<'a>]) -> Option { + if crate::lane::effect::Effect::function(kind) == crate::lane::effect::Effect::Random { + return None; + } let function = match kind { FunctionKind::Internal(function) => function, FunctionKind::Closure(closure) => return self.closure(*closure, arguments), @@ -1350,7 +1377,9 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { builtin: &'static crate::lane::builtins::Builtin, codes: Vec, ) -> Result> { - let call = move |views: &[Arg]| Builtins::raw(builtin, views).ok().map(Out::variable); + let call = move |views: &[Arg], ctx: RowContext| { + Builtins::raw(builtin, views, &ctx).ok().map(Out::variable) + }; let mut codes = codes; match codes.as_slice() { [Code::Load(_)] => { @@ -1358,7 +1387,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { return Err(codes); }; Ok(Code::Val(Box::new(move |s| { - l.with(s, |v| call(&[Arg::of(v)])) + l.with(s, |v| call(&[Arg::of(v)], s.at())) }))) } [Code::Load(_), Code::Const(c)] if Self::const_arg(c).is_some() => { @@ -1366,7 +1395,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { return Err(codes); }; Ok(Code::Val(Box::new(move |s| { - l.with(s, |v| call(&[Arg::of(v), Self::const_arg(&c)?])) + l.with(s, |v| call(&[Arg::of(v), Self::const_arg(&c)?], s.at())) }))) } [Code::Load(_), Code::Load(_)] => { @@ -1374,7 +1403,9 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { return Err(codes); }; Ok(Code::Val(Box::new(move |s| { - a.with(s, |x| b.with(s, |y| call(&[Arg::of(x), Arg::of(y)]))) + a.with(s, |x| { + b.with(s, |y| call(&[Arg::of(x), Arg::of(y)], s.at())) + }) }))) } _ => Err(codes), @@ -1427,7 +1458,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { Variable::Array(a) => { Some(Variable::Number(Decimal::from(a.borrow().len()))) } - other => Builtins::raw(builtin, &[Arg::of(other)]) + other => Builtins::raw(builtin, &[Arg::of(other)], &s.at()) .ok() .map(Out::variable), }) @@ -1455,9 +1486,11 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { Ok(Code::Val(Box::new(move |s| { l.with(s, |v| match v { Variable::String(t) => Some(Variable::Bool(test(t.as_str(), &needle))), - other => Builtins::raw(builtin, &[Arg::of(other), Arg::Str(&needle)]) - .ok() - .map(Out::variable), + other => { + Builtins::raw(builtin, &[Arg::of(other), Arg::Str(&needle)], &s.at()) + .ok() + .map(Out::variable) + } }) }))) } @@ -1480,7 +1513,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { .map(|f| f(s)) .collect::>>()?; let views: SmallVec<[Arg; 4]> = values.iter().map(Held::arg).collect(); - Builtins::raw(builtin, &views).ok() + Builtins::raw(builtin, &views, &s.at()).ok() }), )) } @@ -1494,15 +1527,15 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { let builtin = Builtins::of(kind)?; let zone_text: Option> = zone.map(|(_, z)| Box::from(z)); let zone = zone.map(|(z, _)| z); - Some(Code::Date(self.node(text)?.view(move |_, v| match v { - Variable::String(t) => Some(Date::text(t.as_str(), zone)), + Some(Code::Date(self.node(text)?.view(move |s, v| match v { + Variable::String(t) => Some(Date::text(t.as_str(), zone, s.context())), other => { let mut views: SmallVec<[Arg; 2]> = SmallVec::new(); views.push(Arg::of(other)); if let Some(z) = &zone_text { views.push(Arg::Str(z)); } - match Builtins::raw(builtin, &views).ok()? { + match Builtins::raw(builtin, &views, &s.at()).ok()? { Out::Date(d) => Some(d), Out::Var(v) => Date::of(&v).filter(|_| !Date::sourced(&v)), _ => None, @@ -1553,7 +1586,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { return Some(Variable::Number(Scaled::decimal(m, sc))); } let array = Variable::from_array(values.into_vec()); - Builtins::raw(builtin, &[Arg::of(&array)]) + Builtins::raw(builtin, &[Arg::of(&array)], &s.at()) .ok() .map(Out::variable) }))) @@ -1653,7 +1686,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { values.push(f(s)?); } let views: SmallVec<[Arg; 4]> = values.iter().map(Held::arg).collect(); - Builtins::call_method(builtin, &kind, &views).ok() + Builtins::call_method(builtin, &kind, &views, &s.at()).ok() }), )) } @@ -1765,7 +1798,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { let y = y.val(); x.view(move |s, a| { let b = y(s)?; - Some(Ops::equal(a, &b)) + Some(Ops::equal(a, &b, s.tz())) }) } }; @@ -1791,11 +1824,11 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { }, Const::String(t) => { let t = t.clone(); - x.view(move |_, v| { + x.view(move |cx, v| { Some(match v { Variable::String(s) => s.as_str() == t.as_ref(), Variable::Dynamic(_) => { - Ops::equal(v, &Variable::String(Symbol::from(t.as_ref()))) + Ops::equal(v, &Variable::String(Symbol::from(t.as_ref())), cx.tz()) } _ => false, }) @@ -1812,7 +1845,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { } } Const::Null => x.view(|_, v| Some(matches!(v, Variable::Null))), - _ => x.view(move |_, v| Some(Ops::equal(v, &c.variable()))), + _ => x.view(move |s, v| Some(Ops::equal(v, &c.variable(), s.tz()))), } } @@ -1844,19 +1877,19 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { return Some(Code::Bool(f)); } let f: BoolFn = match (a, b) { - (x, Code::Const(Const::Number(k))) => x.view(move |_, v| match v { + (x, Code::Const(Const::Number(k))) => x.view(move |s, v| match v { Variable::Number(n) => Some(Ops::ordered_number(n, &k, order)), - other => Ops::compare(other, &Variable::Number(k), order).ok(), + other => Ops::compare(other, &Variable::Number(k), order, s.tz()).ok(), }), - (Code::Const(Const::Number(k)), y) => y.view(move |_, v| match v { + (Code::Const(Const::Number(k)), y) => y.view(move |s, v| match v { Variable::Number(n) => Some(Ops::ordered_number(&k, n, order)), - other => Ops::compare(&Variable::Number(k), other, order).ok(), + other => Ops::compare(&Variable::Number(k), other, order, s.tz()).ok(), }), (x, y) => { let y = y.val(); x.view(move |s, a| { let b = y(s)?; - Ops::compare(a, &b, order).ok() + Ops::compare(a, &b, order, s.tz()).ok() }) } }; @@ -1929,7 +1962,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> { let (a, b) = (self.node(left)?, self.node(right)?.val()); let test = a.view(move |s, x| { let y = b(s)?; - Ops::membership(x.clone(), &y).ok() + Ops::membership(x.clone(), &y, s.tz()).ok() }); Some(Self::negated(test, not)) } diff --git a/core/expression/src/lane/mod.rs b/core/expression/src/lane/mod.rs index 09c22a8c..830318be 100644 --- a/core/expression/src/lane/mod.rs +++ b/core/expression/src/lane/mod.rs @@ -42,6 +42,7 @@ pub use session::{Programs, Session}; #[doc(hidden)] pub use source::SourceInfo; +use crate::context::EvaluationContext; use crate::lexer::Lexer; use crate::parser::{Node, Parser}; use crate::scope::Scope; @@ -84,6 +85,7 @@ pub struct LaneProgram { constant: Option, hints: Option>, kernel: OnceLock>>, + labels: Arc<[u64]>, } impl LaneProgram { @@ -91,18 +93,27 @@ impl LaneProgram { Self::compile_with(source, kind, None) } + pub fn located(source: &str, kind: ExpressionKind, label: u64) -> Result { + Self::single(source, kind, None, label) + } + pub fn compile_with( source: &str, kind: ExpressionKind, hints: Option<&Hints>, ) -> Result { - Self::single(source, kind, hints) + Self::single(source, kind, hints, 0) + } + + pub fn labels(&self) -> &[u64] { + &self.labels } fn single( source: &str, kind: ExpressionKind, hints: Option<&Hints>, + label: u64, ) -> Result { let bump = Bump::new(); let mut lexer = Lexer::new(); @@ -113,7 +124,7 @@ impl LaneProgram { ExpressionKind::Unary => parser.unary().parse(), }; parsed.error()?; - let program = LaneCompiler::compile_with(parsed.root, hints)?; + let program = LaneCompiler::compile_located(parsed.root, hints, label)?; let constant = match kind { ExpressionKind::Standard => Const::of(parsed.root), ExpressionKind::Unary => None, @@ -125,18 +136,27 @@ impl LaneProgram { constant, hints: hints.map(|h| Arc::new(h.clone())), kernel: OnceLock::new(), + labels: match label { + 0 => Arc::from([]), + label => Arc::from([label]), + }, }) } fn recompile(&self, hints: &Hints) -> Result { match &self.source { - Source::Single(source) => Self::compile_with(source, self.kind.clone(), Some(hints)), + Source::Single(source) => Self::single( + source, + self.kind.clone(), + Some(hints), + self.labels.first().copied().unwrap_or(0), + ), Source::Many(entries, chain) => { let refs: Vec<(&str, &str)> = entries .iter() .map(|(k, s)| (k.as_str(), s.as_str())) .collect(); - Self::compile_many_with(&refs, *chain, Some(hints)) + Self::compile_many_with(&refs, *chain, Some(hints), &self.labels) } Source::Cells(cells) => { let refs: Vec<(&str, Option<&str>)> = cells @@ -190,6 +210,9 @@ impl LaneProgram { roots.push((key, root)); } let program = LaneCompiler::compile_isolated(&roots, hints)?; + if program.draws { + return Err(Self::unsupported("a draw")); + } let owned: Vec<(String, Option)> = cells .iter() .map(|(s, f)| (s.to_string(), f.map(str::to_string))) @@ -201,6 +224,7 @@ impl LaneProgram { constant: None, hints: None, kernel: OnceLock::from(None), + labels: Arc::from([]), }) } @@ -340,6 +364,7 @@ impl LaneProgram { constant: None, hints: None, kernel: OnceLock::new(), + labels: Arc::from([]), }) } @@ -424,6 +449,9 @@ impl LaneProgram { roots.push((key, root, output)); } let program = LaneCompiler::compile_named(&roots, hints)?; + if program.draws { + return Err(Self::unsupported("a draw")); + } Ok(Self { program, kind: ExpressionKind::Standard, @@ -431,17 +459,27 @@ impl LaneProgram { constant: None, hints: hints.map(|h| Arc::new(h.clone())), kernel: OnceLock::from(None), + labels: Arc::from([]), }) } pub fn compile_many(entries: &[(&str, &str)], chain: bool) -> Result { - Self::compile_many_with(entries, chain, None) + Self::compile_many_with(entries, chain, None, &[]) + } + + pub fn compile_many_located( + entries: &[(&str, &str)], + chain: bool, + labels: &[u64], + ) -> Result { + Self::compile_many_with(entries, chain, None, labels) } fn compile_many_with( entries: &[(&str, &str)], chain: bool, hints: Option<&Hints>, + labels: &[u64], ) -> Result { let bump = Bump::new(); let mut lexer = Lexer::new(); @@ -452,7 +490,7 @@ impl LaneProgram { parsed.error()?; roots.push((*key, parsed.root)); } - let program = LaneCompiler::compile_many(&roots, chain, hints)?; + let program = LaneCompiler::compile_many_located(&roots, chain, hints, labels)?; let owned: Vec<(String, String)> = entries .iter() .map(|(k, s)| (k.to_string(), s.to_string())) @@ -464,6 +502,10 @@ impl LaneProgram { constant: None, hints: hints.map(|h| Arc::new(h.clone())), kernel: OnceLock::new(), + labels: match labels.iter().any(|&label| label != 0) { + true => Arc::from(labels), + false => Arc::from([]), + }, }) } @@ -711,8 +753,8 @@ impl LaneProgram { program } - pub fn try_kernel(&self, scope: &Scope) -> Option { - self.kernel()?.run(scope) + pub fn try_kernel(&self, scope: &Scope, context: &EvaluationContext) -> Option { + self.kernel()?.run(scope, context) } pub fn has_kernel(&self) -> bool { @@ -791,7 +833,8 @@ impl LaneRunner { frames.resize_with(program.frames, Frame::default); } let roots = [Scope::default()]; - let mut ctx = Context::new(program, &roots); + let context = EvaluationContext::default(); + let mut ctx = Context::new(program, &roots, &context); Executor::run(program, frames, &mut ctx, &[0]); frames.first_mut()?.take_result(program, 0).ok() }) @@ -800,15 +843,16 @@ impl LaneRunner { pub fn evaluate_one( &mut self, program: &LaneProgram, + context: &EvaluationContext, scope: &Scope, ) -> Result { - if let Some(value) = program.kernel().and_then(|k| k.run(scope)) { + if let Some(value) = program.kernel().and_then(|k| k.run(scope, context)) { return Ok(value); } let p = &program.program; self.frames(p); let roots = std::slice::from_ref(scope); - let mut ctx = Context::new(p, roots); + let mut ctx = Context::new(p, roots, context); Executor::run(p, &mut self.frames, &mut ctx, &[0]); self.frames[0] .take_result(p, 0) @@ -818,35 +862,39 @@ impl LaneRunner { pub fn evaluate( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], ) -> Vec> { let mut out = Vec::with_capacity(scopes.len()); - self.evaluate_with(program, scopes, |_, r| out.push(r)); + self.evaluate_with(program, context, scopes, |_, r| out.push(r)); out } pub fn evaluate_with( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], mut sink: impl FnMut(usize, Result), ) { if let Some(kernel) = program.kernel() { - return self.evaluate_kernel(program, kernel, scopes, sink); + return self.evaluate_kernel(program, context, kernel, scopes, sink); } let p = &program.program; self.frames(p); - for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() { + for (start, n) in Executor::blocks(scopes.len(), Word::LANES, p.draws, context, |i| i) { + let roots = &scopes[start..start + n]; self.rows.clear(); - self.rows.extend(0..roots.len() as u32); - let mut ctx = Context::new(p, roots); + self.rows.extend(0..n as u32); + let mut ctx = Context::new(p, roots, context); + ctx.first = start; Executor::run(p, &mut self.frames, &mut ctx, &self.rows); let frame = &mut self.frames[0]; - for lane in 0..roots.len() { + for lane in 0..n { let result = frame .take_result(p, lane) .map_err(|source| IsolateError::VMError { source }); - sink(chunk * Word::LANES + lane, result); + sink(start + lane, result); } } } @@ -854,6 +902,7 @@ impl LaneRunner { fn evaluate_kernel( &mut self, program: &LaneProgram, + context: &EvaluationContext, kernel: &Kernel, scopes: &[Scope], mut sink: impl FnMut(usize, Result), @@ -869,7 +918,7 @@ impl LaneRunner { true => self.rows.extend(0..roots.len() as u32), false => { for (lane, scope) in roots.iter().enumerate() { - let value = kernel.run(scope); + let value = kernel.run(scope, context); if value.is_none() { self.rows.push(lane as u32); } @@ -886,7 +935,8 @@ impl LaneRunner { } values.resize(roots.len(), None); self.frames(p); - let mut ctx = Context::new(p, roots); + let mut ctx = Context::new(p, roots, context); + ctx.first = start; Executor::run(p, &mut self.frames, &mut ctx, &self.rows); let frame = &mut self.frames[0]; let mut slow = 0usize; @@ -910,12 +960,13 @@ impl LaneRunner { pub fn evaluate_many( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], mask: Option<&[bool]>, mut sink: impl FnMut(usize, Option, (usize, IsolateError)>>), ) { let Some(kernel) = program.kernel() else { - return self.evaluate_many_lane(program, scopes, mask, sink); + return self.evaluate_many_lane(program, context, scopes, mask, sink); }; let wanted = |row: usize| mask.is_none_or(|m| m.get(row).copied().unwrap_or(false)); let mut values: Vec> = Vec::with_capacity(scopes.len()); @@ -930,7 +981,7 @@ impl LaneRunner { true => None, false => { tried += 1; - kernel.run_all(scope, row, None, &[]) + kernel.run_all(scope, row, None, &[], context) } }; if value.is_none() { @@ -942,7 +993,7 @@ impl LaneRunner { let mut lane: Vec, (usize, IsolateError)>>> = Vec::new(); if slow.iter().any(|s| *s) { lane.resize_with(scopes.len(), || None); - self.evaluate_many_lane(program, scopes, Some(&slow), |row, result| { + self.evaluate_many_lane(program, context, scopes, Some(&slow), |row, result| { if let Some(slot) = lane.get_mut(row) { *slot = result; } @@ -959,6 +1010,7 @@ impl LaneRunner { fn kernel_rows( kernel: &Kernel, + context: &EvaluationContext, scopes: &[Scope], columns: &Columns, bound: &[Binding], @@ -970,7 +1022,7 @@ impl LaneRunner { let row = subset.map_or(at, |list| list[at]); let scope = scopes.get(row)?; kernel - .run_all(scope, row, Some(columns), bound) + .run_all(scope, row, Some(columns), bound, context) .map(|values| (row, values)) }) .collect() @@ -979,17 +1031,19 @@ impl LaneRunner { fn evaluate_many_lane( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], mask: Option<&[bool]>, mut sink: impl FnMut(usize, Option, (usize, IsolateError)>>), ) { let p = &program.program; self.frames(p); - for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() { - let start = chunk * Word::LANES; + for (start, n) in Executor::blocks(scopes.len(), Word::LANES, p.draws, context, |i| i) { + let roots = &scopes[start..start + n]; self.rows.clear(); self.rows.extend(0..roots.len() as u32); - let mut ctx = Context::new(p, roots); + let mut ctx = Context::new(p, roots, context); + ctx.first = start; let Some((frame, _)) = self.frames.split_first_mut() else { return; }; @@ -1021,9 +1075,11 @@ impl LaneRunner { } } + #[allow(clippy::too_many_arguments)] pub fn evaluate_bound( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], columns: &Columns, bind: &dyn Fn(&str) -> Binding, @@ -1034,7 +1090,8 @@ impl LaneRunner { let total = subset.map_or(scopes.len(), <[usize]>::len); if let (true, Some(kernel)) = (total <= Self::SMALL, program.kernel()) { let bound = kernel.bind(bind); - if let Some(rows) = Self::kernel_rows(kernel, scopes, columns, &bound, subset) { + if let Some(rows) = Self::kernel_rows(kernel, context, scopes, columns, &bound, subset) + { let many = !p.outputs.is_empty(); for (row, mut values) in rows { let values = match many { @@ -1062,6 +1119,7 @@ impl LaneRunner { let (frames, rows) = (&mut self.frames, &mut self.rows); Self::bound_blocks( p, + context, frames, rows, scopes, @@ -1077,7 +1135,7 @@ impl LaneRunner { self.wide.iter_mut().for_each(Frame::forget); let (frames, rows) = (&mut self.wide, &mut self.rows); Self::bound_blocks( - p, frames, rows, scopes, columns, &bound, subset, LANES, &mut sink, + p, context, frames, rows, scopes, columns, &bound, subset, LANES, &mut sink, ); } } @@ -1087,6 +1145,7 @@ impl LaneRunner { pub fn evaluate_bound_into( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], columns: &Columns, bind: &dyn Fn(&str) -> Binding, @@ -1103,13 +1162,16 @@ impl LaneRunner { (false, Some(k)) => bind(k), }) .collect(); - self.evaluate_sites(program, scopes, columns, &bound, subset, outs, failure) + self.evaluate_sites( + program, context, scopes, columns, &bound, subset, outs, failure, + ) } #[allow(clippy::too_many_arguments)] pub fn evaluate_sites( &mut self, program: &LaneProgram, + context: &EvaluationContext, scopes: &[Scope], columns: &Columns, bound: &[Binding], @@ -1126,7 +1188,8 @@ impl LaneRunner { let listed = p.layout.is_some() || regs.iter().any(|r| p.kinds[*r as usize] == Kind::List); if let (true, false, Some(kernel)) = (total <= Self::SMALL, listed, program.kernel()) { let kbound = kernel.bind_sites(bound); - if let Some(rows) = Self::kernel_rows(kernel, scopes, columns, &kbound, subset) { + if let Some(rows) = Self::kernel_rows(kernel, context, scopes, columns, &kbound, subset) + { outs.resize_with(regs.len(), Output::new); for (reg, out) in regs.iter().zip(outs.iter_mut()) { out.reset(p.kinds[*reg as usize], total); @@ -1155,6 +1218,7 @@ impl LaneRunner { let (frames, rows) = (&mut self.frames, &mut self.rows); Self::export_blocks( p, + context, frames, rows, scopes, @@ -1171,7 +1235,8 @@ impl LaneRunner { self.wide.iter_mut().for_each(Frame::forget); let (frames, rows) = (&mut self.wide, &mut self.rows); Self::export_blocks( - p, frames, rows, scopes, columns, bound, subset, LANES, outs, &mut sink, + p, context, frames, rows, scopes, columns, bound, subset, LANES, outs, + &mut sink, ); } } @@ -1180,6 +1245,7 @@ impl LaneRunner { #[allow(clippy::too_many_arguments)] fn export_blocks( p: &Program, + context: &EvaluationContext, frames: &mut [Frame], rows: &mut Vec, scopes: &[Scope], @@ -1191,9 +1257,11 @@ impl LaneRunner { sink: &mut dyn FnMut(usize, usize, Fault), ) { let total = subset.map_or(scopes.len(), <[usize]>::len); - let mut start = 0; - while start < total { - let n = (total - start).min(width); + let blocks = Executor::blocks(total, width, p.draws, context, |i| match subset { + None => i, + Some(list) => list[i], + }); + for (start, n) in blocks { rows.clear(); let (roots, base) = match subset { None => { @@ -1205,19 +1273,19 @@ impl LaneRunner { (scopes, 0) } }; - let mut ctx = Context::columnar(p, roots, columns, bound, base); + let mut ctx = Context::columnar(p, roots, columns, bound, base, context); Executor::run(p, frames, &mut ctx, rows); let Some(frame) = frames.first_mut() else { return; }; frame.export_outputs(p, outs, start, n, &mut *sink); - start += n; } } #[allow(clippy::too_many_arguments)] fn bound_blocks( p: &Program, + context: &EvaluationContext, frames: &mut [Frame], rows: &mut Vec, scopes: &[Scope], @@ -1229,9 +1297,11 @@ impl LaneRunner { ) { let many = !p.outputs.is_empty(); let total = subset.map_or(scopes.len(), <[usize]>::len); - let mut start = 0; - while start < total { - let n = (total - start).min(width); + let blocks = Executor::blocks(total, width, p.draws, context, |i| match subset { + None => i, + Some(list) => list[i], + }); + for (start, n) in blocks { rows.clear(); let (roots, base) = match subset { None => { @@ -1243,7 +1313,7 @@ impl LaneRunner { (scopes, 0) } }; - let mut ctx = Context::columnar(p, roots, columns, bound, base); + let mut ctx = Context::columnar(p, roots, columns, bound, base, context); Executor::run(p, frames, &mut ctx, rows); let Some(frame) = frames.first_mut() else { return; @@ -1265,18 +1335,18 @@ impl LaneRunner { }; sink(row, result); } - start += n; } } pub fn evaluate_columns( &mut self, program: &LaneProgram, + context: &EvaluationContext, columns: &Columns, mut sink: impl FnMut(usize, Result), ) { let p = &program.program; - self.columnar(p, columns, |frame, start, n| { + self.columnar(p, context, columns, |frame, start, n| { for lane in 0..n { let result = frame .take_result(p, lane) @@ -1289,6 +1359,7 @@ impl LaneRunner { pub fn evaluate_columns_into( &mut self, program: &LaneProgram, + context: &EvaluationContext, columns: &Columns, out: &mut Output, ) { @@ -1297,12 +1368,15 @@ impl LaneRunner { Some(layout) => out.reset_layout(layout, &p.kinds, columns.rows), None => out.reset(p.kinds[p.out as usize], columns.rows), } - self.columnar(p, columns, |frame, start, n| frame.export(p, out, start, n)); + self.columnar(p, context, columns, |frame, start, n| { + frame.export(p, out, start, n) + }); } pub fn evaluate_columns_many( &mut self, program: &LaneProgram, + context: &EvaluationContext, columns: &Columns, outs: &mut Vec, mut failure: impl FnMut(usize, usize, Fault), @@ -1319,7 +1393,7 @@ impl LaneRunner { _ => out.reset(p.kinds[*reg as usize], columns.rows), } } - self.columnar(p, columns, |frame, start, n| { + self.columnar(p, context, columns, |frame, start, n| { frame.export_outputs(p, outs, start, n, &mut failure) }); } @@ -1327,6 +1401,7 @@ impl LaneRunner { fn columnar( &mut self, p: &Program, + context: &EvaluationContext, columns: &Columns, mut chunk: impl FnMut(&mut Frame, usize, usize), ) { @@ -1345,9 +1420,7 @@ impl LaneRunner { false => None, }; self.wide.iter_mut().for_each(Frame::forget); - let mut start = 0; - while start < columns.rows { - let n = (columns.rows - start).min(LANES); + for (start, n) in Executor::blocks(columns.rows, LANES, p.draws, context, |i| i) { self.rows.clear(); self.rows.extend(0..n as u32); self.scopes.clear(); @@ -1359,10 +1432,9 @@ impl LaneRunner { }) })); } - let mut ctx = Context::columnar(p, &self.scopes, columns, &bound, start); + let mut ctx = Context::columnar(p, &self.scopes, columns, &bound, start, context); Executor::run(p, &mut self.wide, &mut ctx, &self.rows); chunk(&mut self.wide[0], start, n); - start += n; } } } @@ -1394,7 +1466,7 @@ impl Backend { } let program = &programs[source]; let mut runner = Self::RUNNER.take(); - let result = runner.evaluate_one(program, scope); + let result = runner.evaluate_one(program, &EvaluationContext::default(), scope); Self::RUNNER.set(runner); result } diff --git a/core/expression/src/lane/ops.rs b/core/expression/src/lane/ops.rs index 9a4b5fe4..99767da9 100644 --- a/core/expression/src/lane/ops.rs +++ b/core/expression/src/lane/ops.rs @@ -1,5 +1,5 @@ use crate::compiler::{Compare, FetchFastTarget}; -use crate::lane::builtins::{Arg, Builtins, Out, Text}; +use crate::lane::builtins::{Arg, Builtins, Out, RowContext, Text}; use crate::lane::date::{Date, DynamicVariableExt}; use crate::lane::interval::{Interval, IntervalData}; use crate::lexer::Bracket; @@ -8,6 +8,7 @@ use crate::variable::Variable; use crate::variable::Variable::*; use crate::vm::VMError; use crate::vm::VMError::*; +use chrono_tz::Tz; use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; use rust_decimal::{Decimal, MathematicalOps}; use std::rc::Rc; @@ -107,7 +108,7 @@ impl Ops { } } - pub(crate) fn equal(a: &Variable, b: &Variable) -> bool { + pub(crate) fn equal(a: &Variable, b: &Variable, tz: Tz) -> bool { match (a, b) { (Number(a), Number(b)) => Self::same_number(a, b), (Bool(a), Bool(b)) => a == b, @@ -118,7 +119,7 @@ impl Ops { a.is_some() && b.is_some() && a == b } (Dynamic(a), b @ String(_)) | (b @ String(_), Dynamic(a)) => { - a.as_date().is_some_and(|a| a.matches(b)) + a.as_date().is_some_and(|a| a.matches(b, tz)) } _ => false, } @@ -131,7 +132,7 @@ impl Ops { } } - pub(crate) fn membership(a: Variable, b: &Variable) -> VMResult { + pub(crate) fn membership(a: Variable, b: &Variable, tz: Tz) -> VMResult { let a = match b { Object(_) => Date::textual(a), _ => a, @@ -162,13 +163,13 @@ impl Ops { let Some(a) = a.as_date() else { return Err(Self::unsupported("In")); }; - Ok(arr.borrow().iter().any(|b| a.matches(b))) + Ok(arr.borrow().iter().any(|b| a.matches(b, tz))) } (String(a), Array(b)) => { let text = String(a.clone()); Ok(b.borrow().iter().any(|b| match b { String(b) => &a == b, - Dynamic(d) => d.as_date().is_some_and(|d| d.matches(&text)), + Dynamic(d) => d.as_date().is_some_and(|d| d.matches(&text, tz)), _ => false, })) } @@ -212,15 +213,25 @@ impl Ops { } } - pub(crate) fn compared(a: &Variable, b: &Variable, comparison: Compare) -> Option { + pub(crate) fn compared( + a: &Variable, + b: &Variable, + comparison: Compare, + tz: Tz, + ) -> Option { match (a, b) { (Number(a), Number(b)) => Some(Self::ordered_number(a, b, comparison)), - (Dynamic(_), _) | (_, Dynamic(_)) => Self::compare(a, b, comparison).ok(), + (Dynamic(_), _) | (_, Dynamic(_)) => Self::compare(a, b, comparison, tz).ok(), _ => None, } } - pub(crate) fn compare(a: &Variable, b: &Variable, comparison: Compare) -> VMResult { + pub(crate) fn compare( + a: &Variable, + b: &Variable, + comparison: Compare, + tz: Tz, + ) -> VMResult { match (a, b) { (Number(a), Number(b)) => Ok(Self::ordered_number(a, b, comparison)), (Dynamic(a), Dynamic(b)) => match (a.as_date(), b.as_date()) { @@ -229,7 +240,10 @@ impl Ops { }, (Dynamic(_), String(_)) | (String(_), Dynamic(_)) => { let valid = |date: &Date| date.is_valid(); - match (Date::coerce(a).filter(valid), Date::coerce(b).filter(valid)) { + match ( + Date::coerce(a, tz).filter(valid), + Date::coerce(b, tz).filter(valid), + ) { (Some(a), Some(b)) => Ok(Self::ordered(&a, &b, comparison)), _ => Err(Self::unsupported("Compare")), } @@ -399,8 +413,8 @@ impl Ops { Ok(()) } - pub(crate) fn len(current: &Variable) -> VMResult { - Builtins::raw(&Text::LEN, &[Arg::of(current)]) + pub(crate) fn len(current: &Variable, ctx: &RowContext) -> VMResult { + Builtins::raw(&Text::LEN, &[Arg::of(current)], ctx) .map(Out::variable) .map_err(|message| Self::error("Len", message)) } diff --git a/core/expression/src/lane/program.rs b/core/expression/src/lane/program.rs index 9b57f47f..356af3b8 100644 --- a/core/expression/src/lane/program.rs +++ b/core/expression/src/lane/program.rs @@ -1,4 +1,5 @@ use crate::compiler::{Compare, FetchFastTarget}; +use crate::context::Site; use crate::functions::{ClosureFunction, FunctionKind, MethodKind}; use crate::lane::effect::Effect; use crate::lexer::Bracket; @@ -259,6 +260,7 @@ pub enum Op { dst: Reg, kind: FunctionKind, args: Box<[Input]>, + draw: Site, }, Method { dst: Reg, @@ -510,6 +512,7 @@ pub struct Program { pub memos: u32, pub layout: Option, pub isolated: bool, + pub draws: bool, } #[derive(Debug, Clone)] @@ -657,6 +660,7 @@ impl Program { } } self.frames = self.depth() + 1; + self.draws = !self.stable(); } fn fields_only(&self, at: usize, reg: Reg) -> bool { @@ -700,22 +704,23 @@ impl Program { } pub fn pure(&self) -> bool { - self.steps.iter().all(|step| { - !matches!( - step.op, - Op::Env { .. } - | Op::Path { .. } - | Op::RootEnv { .. } - | Op::LoadEq { .. } - | Op::LoadIn { .. } - | Op::LoadCall(_) - | Op::AssignBegin { .. } - | Op::AssignStep { .. } - | Op::Closure(_) - | Op::Rewind - | Op::DollarInsert { .. } - ) - }) + !self.draws + && self.steps.iter().all(|step| { + !matches!( + step.op, + Op::Env { .. } + | Op::Path { .. } + | Op::RootEnv { .. } + | Op::LoadEq { .. } + | Op::LoadIn { .. } + | Op::LoadCall(_) + | Op::AssignBegin { .. } + | Op::AssignStep { .. } + | Op::Closure(_) + | Op::Rewind + | Op::DollarInsert { .. } + ) + }) } pub fn opaque(&self) -> bool { diff --git a/core/expression/src/lane/session.rs b/core/expression/src/lane/session.rs index 50a919cf..3297cdd0 100644 --- a/core/expression/src/lane/session.rs +++ b/core/expression/src/lane/session.rs @@ -1,3 +1,4 @@ +use crate::context::EvaluationContext; use crate::lane::{LaneProgram, LaneRunner}; use crate::scope::Scope; use crate::variable::Variable; @@ -18,6 +19,13 @@ impl Programs { Self::default() } + pub fn sources(&self) -> impl Iterator { + self.standard + .keys() + .chain(self.unary.keys()) + .map(|k| k.as_ref()) + } + pub fn compile<'s>(sources: impl IntoIterator) -> Self { let mut programs = Self::new(); for (source, kind) in sources { @@ -57,6 +65,7 @@ impl Programs { #[derive(Debug, Default)] pub struct Session { + context: Option, scope: Scope, references: HashMap, programs: Option>, @@ -78,6 +87,20 @@ impl Session { session } + pub fn with_context(mut self, context: EvaluationContext) -> Self { + self.context = Some(context); + self + } + + pub fn set_context(&mut self, context: EvaluationContext) { + self.context = Some(context); + } + + pub fn locate(&mut self, label: u64) { + let context = self.context.get_or_insert_with(EvaluationContext::default); + *context = context.located(label); + } + pub fn with_programs(mut self, programs: Option>) -> Self { self.programs = programs; self @@ -149,19 +172,24 @@ impl Session { } fn run(&mut self, source: &str, kind: ExpressionKind) -> Result { + let context = self.context.get_or_insert_with(EvaluationContext::default); let program = match self.programs.as_deref().and_then(|p| p.get(source, &kind)) { Some(program) => program, None => self.fallback.insert(source, kind.clone()), }; match program { - Some(program) => Self::evaluate(program, &self.scope), - None => Self::evaluate(&LaneProgram::compile(source, kind)?, &self.scope), + Some(program) => Self::evaluate(program, context, &self.scope), + None => Self::evaluate(&LaneProgram::compile(source, kind)?, context, &self.scope), } } - fn evaluate(program: &LaneProgram, scope: &Scope) -> Result { + fn evaluate( + program: &LaneProgram, + context: &EvaluationContext, + scope: &Scope, + ) -> Result { let mut runner = Self::RUNNER.take(); - let result = runner.evaluate_one(program, scope); + let result = runner.evaluate_one(program, context, scope); Self::RUNNER.set(runner); result } diff --git a/core/expression/src/lane/source.rs b/core/expression/src/lane/source.rs index 9be540c9..bb635a95 100644 --- a/core/expression/src/lane/source.rs +++ b/core/expression/src/lane/source.rs @@ -1,3 +1,4 @@ +use crate::functions::{FunctionKind, InternalFunction}; use crate::lexer::Lexer; use crate::parser::{Node, Parser}; use bumpalo::Bump; @@ -39,6 +40,20 @@ impl SourceInfo { found.get() } + pub fn draws(source: &str) -> bool { + let test = |node: &Node| { + matches!( + node, + Node::FunctionCall { + kind: FunctionKind::Internal(InternalFunction::Rand), + .. + } + ) + }; + source.contains("rand") + && (Self::scan(source, false, test) || Self::scan(source, true, test)) + } + pub fn reads_dollar(source: &str) -> bool { Self::any(source, |node| matches!(node, Node::Identifier("$"))) } diff --git a/core/expression/src/lib.rs b/core/expression/src/lib.rs index 9c1ec8f5..f98d720b 100644 --- a/core/expression/src/lib.rs +++ b/core/expression/src/lib.rs @@ -58,6 +58,7 @@ #![forbid(unsafe_code)] mod config; +pub mod context; mod isolate; pub mod compiler; diff --git a/core/expression/src/typed/batch.rs b/core/expression/src/typed/batch.rs index 9fd7d986..0dd54e1b 100644 --- a/core/expression/src/typed/batch.rs +++ b/core/expression/src/typed/batch.rs @@ -1,3 +1,4 @@ +use crate::context::EvaluationContext; use crate::lane::date::Date; use crate::lane::Bits; use crate::lane::ShortKey; @@ -85,6 +86,7 @@ pub(crate) struct Feeds<'x> { pub(crate) lists: Vec, pub(crate) parents: Vec>, pub(crate) now: Date, + pub(crate) context: EvaluationContext, } #[derive(Clone, Debug)] @@ -645,6 +647,7 @@ impl<'x> Feeds<'x> { hir: &Hir, classes: &[(Origin, u16)], batch: &Batch<'x>, + context: &EvaluationContext, ) -> Result { let schema = &hir.schema; if batch.columns.len() != schema.columns.len() || batch.lists.len() != schema.lists.len() { @@ -745,6 +748,7 @@ impl<'x> Feeds<'x> { lists, parents, now: Date(None), + context: context.clone(), }; for (origin, dict) in classes { let class = { diff --git a/core/expression/src/typed/date.rs b/core/expression/src/typed/date.rs index 23c86553..f9606ba1 100644 --- a/core/expression/src/typed/date.rs +++ b/core/expression/src/typed/date.rs @@ -1,5 +1,5 @@ use crate::functions::{DateMethod, FunctionKind, InternalFunction, MethodKind}; -use crate::lane::builtins::{Arg as Given, Builtin, Builtins, Dates, Out}; +use crate::lane::builtins::{Arg as Given, Builtin, Builtins, Dates, Out, RowContext}; use crate::lane::date::Date; use crate::lane::Bits; use crate::typed::exec::{Buf, Exec, Others, Reg}; @@ -160,9 +160,9 @@ impl<'e, 'x> Exec<'e, 'x> { let bytes = text.get(start, i); let date = match (bytes, last) { (Some(b), Some((prev, date))) if prev == b => Some(date), - (Some(b), _) => { - std::str::from_utf8(b).ok().map(|t| Date::text(t, None)) - } + (Some(b), _) => std::str::from_utf8(b) + .ok() + .map(|t| Date::text(t, None, &self.feeds.context)), (None, _) => Some(Date(None)), }; match date { @@ -182,6 +182,7 @@ impl<'e, 'x> Exec<'e, 'x> { return; } } + let ctx = RowContext::new(&self.feeds.context, start); let mut given: SmallVec<[Given; 4]> = SmallVec::new(); let mut seen: SmallVec<[Given; 4]> = SmallVec::new(); let mut last: Option> = None; @@ -200,7 +201,7 @@ impl<'e, 'x> Exec<'e, 'x> { && seen.len() == given.len() && seen.iter().zip(&given).all(|(a, b)| Self::same(a, b)); if !repeated { - last = Some(Builtins::raw(builtin, &given).ok()); + last = Some(Builtins::raw(builtin, &given, &ctx).ok()); seen.clear(); seen.extend(given.iter().copied()); } @@ -215,6 +216,7 @@ impl<'e, 'x> Exec<'e, 'x> { Self::broken(d, broken); }), Ins::Clock { clock, dst, args } => Self::def(regs, *dst, |d, regs| { + let tz = self.feeds.context.timezone(); let views: SmallVec<[DV; 2]> = args.iter().map(|(a, r)| self.dated(a, *r, regs)).collect(); for w in 0..words { @@ -228,7 +230,7 @@ impl<'e, 'x> Exec<'e, 'x> { (Clock::Coerce, [text]) => { d.stamps(); self.each(act, &skip, |i| match text.given(start, i) { - Some(Given::Str(t)) => match Date::from_text(t) { + Some(Given::Str(t)) => match Date::from_text(t, tz) { date if date.is_valid() => d.dates[i] = date, _ => broken.push(i), }, @@ -263,7 +265,7 @@ impl<'e, 'x> Exec<'e, 'x> { self.bools(act, &mut d.bits, |i| { match (date.given(start, i), text.given(start, i)) { (Some(Given::Date(x)), Some(Given::Str(t))) => { - x.is_valid() && Date::from_text(t) == x + x.is_valid() && Date::from_text(t, tz) == x } (Some(Given::Date(x)), Some(Given::Date(y))) => { x.is_valid() && x == y diff --git a/core/expression/src/typed/lower.rs b/core/expression/src/typed/lower.rs index 8bc90944..bbdbcaa2 100644 --- a/core/expression/src/typed/lower.rs +++ b/core/expression/src/typed/lower.rs @@ -1,9 +1,10 @@ +use crate::context::EvaluationContext; use crate::functions::defs::FunctionDefinition; use crate::functions::{ ClosureFunction, DateMethod, DeprecatedFunction, FunctionKind, FunctionRegistry, InternalFunction, MethodKind, MethodRegistry, }; -use crate::lane::builtins::{Arg as Given, Builtins, Out}; +use crate::lane::builtins::{Arg as Given, Builtins, Out, RowContext}; use crate::lane::date::Date; use crate::lane::effect::{Effect, Literal}; use crate::lane::Fusion; @@ -2563,7 +2564,8 @@ impl Lowering { Lit::Code(..) => None, }) .collect::>>()?; - match Builtins::raw(host.builtin()?, &given).ok()? { + let context = EvaluationContext::default(); + match Builtins::raw(host.builtin()?, &given, &RowContext::new(&context, 0)).ok()? { Out::Num(n) => Dec::from_decimal(&n).map(Lit::Num), Out::Bool(b) => Some(Lit::Bool(b)), Out::Str(s) => Some(Lit::Text(s.to_string())), @@ -2608,8 +2610,7 @@ impl Lowering { fn coerced(&mut self, id: NodeId) -> NodeId { if let Some(Lit::Text(text)) = self.lit(id) { - let date = Date::from_text(text); - if date.is_valid() { + if let Some(date) = Date::fixed(text) { return self.konst(Lit::Date(Stamp::of(date))); } } @@ -2638,18 +2639,16 @@ impl Lowering { let (scope, ids) = self.scoped(&[x, y])?; return Ok(self.add(Op::Cmp(op, ids[0], ids[1]), Ty::boolean(), scope)); } - let hit = match self.lit(text) { - Some(Lit::Text(t)) => { - let parsed = Date::from_text(t); - match parsed.is_valid() { - true => { - let other = self.konst(Lit::Date(Stamp::of(parsed))); - self.dated(Cmp::Eq, date, other)? - } - false => self.konst(Lit::Bool(false)), - } + let fixed = match self.lit(text) { + Some(Lit::Text(t)) => Date::fixed(t), + _ => None, + }; + let hit = match fixed { + Some(parsed) => { + let other = self.konst(Lit::Date(Stamp::of(parsed))); + self.dated(Cmp::Eq, date, other)? } - _ => { + None => { let (scope, ids) = self.scoped(&[date, text])?; self.add(Op::Clock(Clock::Matches, ids), Ty::boolean(), scope) } @@ -2696,20 +2695,26 @@ impl Lowering { fn dates_in(&mut self, a: NodeId, items: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { let mut set: Vec = Vec::new(); + let mut zoned: Vec = Vec::new(); for item in items { let id = self.expr(item, ctx, r)?; - let lit = match self - .lit(id) - .cloned() - .ok_or_else(|| Unsupported::new("in: non-literal set item"))? - { - Lit::Null => Some(Lit::Null), - Lit::Date(d) => d.is_valid().then_some(Lit::Date(d)), - Lit::Text(t) => { - let date = Date::from_text(&t); - date.is_valid().then(|| Lit::Date(Stamp::of(date))) + let lit = match self.lit(id).cloned() { + Some(Lit::Null) => Some(Lit::Null), + Some(Lit::Date(d)) => d.is_valid().then_some(Lit::Date(d)), + Some(Lit::Text(t)) => match Date::fixed(&t) { + Some(date) => Some(Lit::Date(Stamp::of(date))), + None if Date::never(&t) => None, + None => { + zoned.push(id); + None + } + }, + Some(_) => None, + None if self.constructed(id) => { + zoned.push(id); + None } - _ => None, + None => return Err(Unsupported::new("in: non-literal set item")), }; if let Some(lit) = lit { if !set.contains(&lit) { @@ -2718,7 +2723,21 @@ impl Lowering { } } let scope = self.nodes[a as usize].scope; - Ok(self.add(Op::InSet(a, set), Ty::boolean(), scope)) + let mut hit = self.add(Op::InSet(a, set), Ty::boolean(), scope); + for id in zoned { + let one = self.belongs(a, id)?; + hit = self.logic(false, hit, one)?; + } + Ok(hit) + } + + fn constructed(&self, id: NodeId) -> bool { + match &self.nodes[id as usize].op { + Op::Host(Host::Construct, args) => args + .iter() + .all(|arg| matches!(self.lit(*arg), Some(Lit::Text(_) | Lit::Num(_)))), + _ => false, + } } fn date_range( diff --git a/core/expression/src/typed/program.rs b/core/expression/src/typed/program.rs index 1bf763d4..613ab007 100644 --- a/core/expression/src/typed/program.rs +++ b/core/expression/src/typed/program.rs @@ -1,3 +1,4 @@ +use crate::context::EvaluationContext; use crate::lane::date::Date; use crate::typed::batch::{Batch, Feeds, Origin}; use crate::typed::build::{Build, Built, Passes, Stage}; @@ -152,10 +153,11 @@ impl Program { batch: &Batch, out: &mut Outputs, select: Option<&[u64]>, + context: &EvaluationContext, ) -> Result<(), Unsupported> { - let mut feeds = Feeds::new(&self.hir, &self.classes, batch)?; + let mut feeds = Feeds::new(&self.hir, &self.classes, batch, context)?; if self.clock { - feeds.now = Date::now(); + feeds.now = Date::now(context); } if out.slots().len() != self.hir.outputs.len() { *out = Outputs::new(&self.hir)?; @@ -204,7 +206,12 @@ impl Program { #[cfg(test)] pub(crate) fn dump(&self, batch: &Batch) -> Result { - let feeds = Feeds::new(&self.hir, &self.classes, batch)?; + let feeds = Feeds::new( + &self.hir, + &self.classes, + batch, + &EvaluationContext::default(), + )?; let mut sig = Vec::new(); feeds.sig(&self.hir, &mut sig); Ok(self.plan(&sig).dump()) diff --git a/core/expression/src/typed/tests/exact.rs b/core/expression/src/typed/tests/exact.rs index f6d3439b..2e602151 100644 --- a/core/expression/src/typed/tests/exact.rs +++ b/core/expression/src/typed/tests/exact.rs @@ -114,10 +114,11 @@ impl Lab { let shift = if size == 7 { 3 } else { 0 }; let frame = Frame::new(&self.hir, &self.workload.spec, chunk, shift); let batch = frame.batch(); - program.run(&batch, &mut out, None).expect("run"); + let context = Workload::context(); + program.run(&batch, &mut out, None, &context).expect("run"); let typed = Self::rows_of(&out, &self.hir, &frame); - let mut feeds = Feeds::new(&self.hir, &[], &batch).expect("feeds"); - feeds.now = crate::lane::date::Date::now(); + let mut feeds = Feeds::new(&self.hir, &[], &batch, &context).expect("feeds"); + feeds.now = crate::lane::date::Date::now(&context); let interp = Interp::run(&self.hir, &feeds); for (i, (t, r)) in typed.iter().zip(&interp).enumerate() { let row = start + i; @@ -210,12 +211,26 @@ impl Bench { let batch = frame.batch(); let program = Program::new(hir).expect("program"); let mut out = program.outputs(); - program.run(&batch, &mut out, None).expect("run"); + program + .run( + &batch, + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) + .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).expect("run"); + program + .run( + &batch, + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) + .expect("run"); } best = best.min(t.elapsed().as_nanos() as f64 / 50.0 / size as f64); } diff --git a/core/expression/src/typed/tests/interp.rs b/core/expression/src/typed/tests/interp.rs index d533e9f6..8f9d145a 100644 --- a/core/expression/src/typed/tests/interp.rs +++ b/core/expression/src/typed/tests/interp.rs @@ -541,7 +541,10 @@ impl<'a, 'x> Interp<'a, 'x> { V::Code(_) => return Err(Fault), }); } - match Builtins::raw(host.builtin().ok_or(Fault)?, &given).map_err(|_| Fault)? { + let ctx = crate::lane::builtins::RowContext::new(&self.feeds.context, 0); + match Builtins::raw(host.builtin().ok_or(Fault)?, &given, &ctx) + .map_err(|_| Fault)? + { Out::Num(n) => Ok(V::Num(n)), Out::Bool(b) => Ok(V::Bool(b)), Out::Str(s) => Ok(V::Text(Cow::Owned(s.as_bytes().to_vec()))), @@ -558,7 +561,7 @@ impl<'a, 'x> Interp<'a, 'x> { } let parsed = |t: &[u8]| { std::str::from_utf8(t) - .map(Date::from_text) + .map(|t| Date::from_text(t, self.feeds.context.timezone())) .map_err(|_| Fault) }; match (clock, vals.as_slice()) { diff --git a/core/expression/src/typed/tests/lower.rs b/core/expression/src/typed/tests/lower.rs index ae4db76e..462a3c5f 100644 --- a/core/expression/src/typed/tests/lower.rs +++ b/core/expression/src/typed/tests/lower.rs @@ -617,9 +617,11 @@ fn date_shapes() { op => format!("{op:?}"), }) .collect(); - assert_eq!(consts[..3], ["2024-02-29", "1704067200", "false"], "{hir}"); - assert!( - matches!(hir.node(hir.outputs[3].node).op, Op::Host(..)), - "{hir}" - ); + assert_eq!(consts[1..3], ["1704067200", "false"], "{hir}"); + for zoned in [0, 3] { + assert!( + matches!(hir.node(hir.outputs[zoned].node).op, Op::Host(..)), + "{hir}" + ); + } } diff --git a/core/expression/src/typed/tests/scale.rs b/core/expression/src/typed/tests/scale.rs index 75773f4f..9131ca37 100644 --- a/core/expression/src/typed/tests/scale.rs +++ b/core/expression/src/typed/tests/scale.rs @@ -59,7 +59,12 @@ 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) + .run( + &frame.batch(), + &mut out, + select, + &crate::context::EvaluationContext::default(), + ) .expect("run"); (0..rows.len()) .map(|r| { @@ -426,7 +431,14 @@ fn member_outputs_with_offset_lists() { for shift in [0, 5, 64, 70] { let frame = Frame::new(&hir, &workload.spec, &rows, shift); let mut out = program.outputs(); - program.run(&frame.batch(), &mut out, None).expect("run"); + program + .run( + &frame.batch(), + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) + .expect("run"); for (r, row) in rows.iter().enumerate() { if out.faults().get(r) { continue; @@ -466,7 +478,12 @@ fn outputs_move_out() { ); let mut out = case.program.outputs(); case.program - .run(&frame.batch(), &mut out, None) + .run( + &frame.batch(), + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) .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)); @@ -474,7 +491,12 @@ 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) + .run( + &frame.batch(), + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) .expect("rerun"); assert_eq!(out.slots()[0].num(0), Some(Dec::int(2))); } @@ -532,7 +554,14 @@ fn rules_fault_strictly() { ] { let frame = Frame::new(&hir, &spec, &rows, 0); let mut out = program.outputs(); - program.run(&frame.batch(), &mut out, None).expect("run"); + program + .run( + &frame.batch(), + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) + .expect("run"); let got: Vec = (0..rows.len()) .map(|r| { if out.faults().get(r) { @@ -583,7 +612,14 @@ fn programs_share_across_threads() { for (c, chunk) in rows.chunks(size).enumerate() { let frame = Frame::new(hir, spec, chunk, 0); let mut out = program.outputs(); - program.run(&frame.batch(), &mut out, None).expect("run"); + program + .run( + &frame.batch(), + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) + .expect("run"); for r in (0..chunk.len()).filter(|r| !out.faults().get(*r)) { let got: Vec = out .slots() @@ -667,7 +703,12 @@ 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) + .run( + &frame.batch(), + &mut out, + None, + &crate::context::EvaluationContext::default(), + ) .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 c3ad39b2..b701fa7f 100644 --- a/core/expression/src/typed/tests/workload.rs +++ b/core/expression/src/typed/tests/workload.rs @@ -1102,9 +1102,18 @@ 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", "2025-03-20T10:15:30Z")); + MOCK.call_once(|| std::env::set_var("__ZEN_MOCK_UTC_TIME", Self::CLOCK)); + } + + pub(crate) fn context() -> crate::context::EvaluationContext { + crate::context::EvaluationContext::new(crate::context::Pinned { + now: crate::context::parse_instant(Self::CLOCK), + ..Default::default() + }) } fn w14_spec() -> Spec { diff --git a/core/expression/tests/draws.rs b/core/expression/tests/draws.rs new file mode 100644 index 00000000..345a8a5e --- /dev/null +++ b/core/expression/tests/draws.rs @@ -0,0 +1,232 @@ +use serde_json::{json, Value}; +use zen_expression::context::{row_seed, unrowed_draws, EvaluationContext, Pinned}; +use zen_expression::lane::{LaneProgram, LaneRunner}; +use zen_expression::{ExpressionKind, Scope, Variable}; + +fn scope(n: usize) -> Scope { + let xs: Vec = (0..n).collect(); + Scope::new(Variable::from(json!({"xs": xs, "n": n}))) +} + +fn single(program: &LaneProgram, n: usize, seed: u64) -> Value { + let context = EvaluationContext::new(Pinned { + seed: Some(seed), + ..Pinned::default() + }); + let value = LaneRunner::new() + .evaluate_one(program, &context, &scope(n)) + .unwrap(); + serde_json::to_value(value).unwrap() +} + +fn compile(source: &str) -> LaneProgram { + LaneProgram::compile(source, ExpressionKind::Standard).unwrap() +} + +#[test] +fn items_of_a_closure_draw_independently() { + let program = compile("map(xs, rand(1000000))"); + let value = single(&program, 40, 3); + let mut items: Vec = value + .as_array() + .unwrap() + .iter() + .map(|v| v.to_string()) + .collect(); + items.sort(); + items.dedup(); + assert!(items.len() > 30, "{value}"); + assert_eq!(single(&program, 40, 3), value); + assert_ne!(single(&program, 40, 4), value); +} + +#[test] +fn constant_arguments_draw_per_call() { + let program = compile("[rand(1000000), rand(1000000), map([1, 2, 3], rand(1000000))]"); + let value = single(&program, 0, 9); + let flat: Vec = value + .as_array() + .unwrap() + .iter() + .flat_map(|v| match v { + Value::Array(items) => items.clone(), + other => vec![other.clone()], + }) + .map(|v| v.to_string()) + .collect(); + let mut distinct = flat.clone(); + distinct.sort(); + distinct.dedup(); + assert_eq!(distinct.len(), flat.len(), "{value}"); +} + +#[test] +fn batched_rows_match_single_rows() { + for source in [ + "rand(1000000) + n", + "map(xs, rand(1000) * 1000 + rand(1000))", + "filter(xs, rand(10) > 4)", + "some(xs, rand(100) > 90)", + "map(xs, map([1, 2], rand(100)))", + ] { + let program = compile(source); + let sizes: Vec = (0..150).map(|row| row * 7 % 97).collect(); + let scopes: Vec = sizes.iter().map(|&n| scope(n)).collect(); + let batch = EvaluationContext::batch(Pinned { + seed: Some(77), + ..Pinned::default() + }); + let results = LaneRunner::new().evaluate(&program, &batch, &scopes); + for (row, result) in results.into_iter().enumerate() { + let got = serde_json::to_value(result.unwrap()).unwrap(); + assert_eq!( + got, + single(&program, sizes[row], row_seed(77, row)), + "{source}: row {row}" + ); + } + } + assert_eq!(unrowed_draws(), 0); +} + +#[test] +fn interleaved_contexts_keep_their_own_clock_and_stream() { + use zen_expression::context::parse_instant; + let program = compile("[rand(1000000), d().timestamp(), d().offsetName()]"); + let pinned = |now: &str, zone: &str, seed: u64| { + EvaluationContext::new(Pinned { + now: parse_instant(now), + timezone: zen_expression::context::parse_timezone(zone), + seed: Some(seed), + }) + }; + let pins = [ + ("2026-11-04T09:30:00.125Z", "Europe/Berlin", 1), + ("2031-02-17T23:15:42.500Z", "America/New_York", 2), + ]; + let mut runner = LaneRunner::new(); + let alone: Vec> = pins + .iter() + .map(|&(now, zone, seed)| { + let context = pinned(now, zone, seed); + (0..4) + .map(|_| { + let value = runner.evaluate_one(&program, &context, &scope(0)).unwrap(); + serde_json::to_value(value).unwrap() + }) + .collect() + }) + .collect(); + let contexts: Vec = pins + .iter() + .map(|&(now, zone, seed)| pinned(now, zone, seed)) + .collect(); + let mut seen: Vec> = vec![Vec::new(); contexts.len()]; + for _ in 0..4 { + for (which, context) in contexts.iter().enumerate() { + let value = runner.evaluate_one(&program, context, &scope(0)).unwrap(); + seen[which].push(serde_json::to_value(value).unwrap()); + } + } + assert_eq!(seen, alone); + assert_ne!(alone[0][0][0], alone[1][0][0]); + assert_eq!(alone[1][0][2], json!("America/New_York")); +} + +fn seeded(seed: u64) -> EvaluationContext { + EvaluationContext::new(Pinned { + seed: Some(seed), + ..Pinned::default() + }) +} + +fn run(program: &LaneProgram, context: &EvaluationContext) -> Value { + let value = LaneRunner::new() + .evaluate_one(program, context, &scope(4)) + .unwrap(); + serde_json::to_value(value).unwrap() +} + +#[test] +fn draws_are_addressed_by_their_site() { + let first = compile("[rand(1000000), rand(1000000)]"); + let pair = run(&first, &seeded(21)); + assert_ne!(pair[0], pair[1]); + let skipped = compile("n > 100 ? rand(5) : rand(1000000)"); + assert_eq!(run(&skipped, &seeded(21)), pair[1]); + let alone = compile("rand(1000000)"); + assert_eq!(run(&alone, &seeded(21)), pair[0]); + let nested = compile("rand(rand(1) + 1000000)"); + assert_eq!(run(&nested, &seeded(21)), run(&nested, &seeded(21))); +} + +#[test] +fn located_programs_draw_independently_of_each_other() { + use zen_expression::context::location; + let a = location(&["expression", "node", "a"]); + let b = location(&["expression", "node", "b"]); + let left = LaneProgram::located("rand(1000000)", ExpressionKind::Standard, a).unwrap(); + let right = LaneProgram::located("rand(1000000)", ExpressionKind::Standard, b).unwrap(); + let context = seeded(5); + let alone = run(&left, &context); + let shared = seeded(5); + let other = run(&right, &shared); + assert_eq!(run(&left, &shared), alone); + assert_ne!(other, alone); + let runtime = seeded(5).located(a); + assert_eq!(run(&compile("rand(1000000)"), &runtime), alone); + let many = LaneProgram::compile_many_located( + &[("b", "rand(1000000)"), ("a", "rand(1000000)")], + true, + &[b, a], + ) + .unwrap(); + let mut both = Vec::new(); + LaneRunner::new().evaluate_many(&many, &seeded(5), &[scope(4)], None, |_, values| { + both = values.unwrap().unwrap(); + }); + let both: Vec = both + .into_iter() + .map(|v| serde_json::to_value(v).unwrap()) + .collect(); + assert_eq!(both, vec![other, alone]); +} + +#[test] +fn nested_scopes_draw_differently() { + use zen_expression::context::location; + let program = compile("rand(1000000)"); + let root = run(&program, &seeded(8)); + let one = run( + &program, + &seeded(8).nested(location(&["decision", "one", "child"])), + ); + let two = run( + &program, + &seeded(8).nested(location(&["decision", "two", "child"])), + ); + assert_ne!(one, two); + assert_ne!(root, one); + assert_eq!( + one, + run( + &program, + &seeded(8).nested(location(&["decision", "one", "child"])) + ) + ); +} + +#[test] +fn sessions_locate_each_evaluation() { + use zen_expression::context::location; + use zen_expression::lane::Session; + let mut session = Session::new().with_context(seeded(3)); + session.locate(location(&["x"])); + let x = session.run_standard("rand(1000000)").unwrap(); + session.locate(location(&["y"])); + let y = session.run_standard("rand(1000000)").unwrap(); + let mut alone = Session::new().with_context(seeded(3)); + alone.locate(location(&["y"])); + assert_eq!(alone.run_standard("rand(1000000)").unwrap(), y); + assert_ne!(x, y); +} diff --git a/core/expression/tests/lane.rs b/core/expression/tests/lane.rs index c048f7e4..c8ddc662 100644 --- a/core/expression/tests/lane.rs +++ b/core/expression/tests/lane.rs @@ -4,6 +4,7 @@ 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}; @@ -135,7 +136,9 @@ impl Differential { &VariableType::from(first), ) .expect("typed compile"); - let batch = self.runner.evaluate(&typed, &scopes); + let batch = self + .runner + .evaluate(&typed, &EvaluationContext::default(), &scopes); for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { self.compared += 1; let got = self.lane(got); @@ -148,7 +151,11 @@ impl Differential { } let specialized = program.specialize(&scopes).expect("specialize"); for (input, exp) in inputs.iter().zip(&expected) { - let got = self.runner.evaluate_one(&specialized, &Self::scope(input)); + let got = self.runner.evaluate_one( + &specialized, + &EvaluationContext::default(), + &Self::scope(input), + ); let got = self.lane(got); self.compared += 1; if &got != exp { @@ -157,7 +164,9 @@ impl Differential { )); } } - let batch = self.runner.evaluate(&specialized, &scopes); + let batch = self + .runner + .evaluate(&specialized, &EvaluationContext::default(), &scopes); for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { self.compared += 1; let got = self.lane(got); @@ -167,7 +176,9 @@ impl Differential { )); } } - let batch = self.runner.evaluate(&program, &scopes); + let batch = self + .runner + .evaluate(&program, &EvaluationContext::default(), &scopes); for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { self.compared += 1; let got = self.lane(got); @@ -180,7 +191,11 @@ impl Differential { } for (input, exp) in inputs.iter().zip(&expected) { - let got = self.runner.evaluate_one(&program, &Self::scope(input)); + let got = self.runner.evaluate_one( + &program, + &EvaluationContext::default(), + &Self::scope(input), + ); let got = self.lane(got); self.compared += 1; if &got != exp { @@ -221,8 +236,12 @@ impl Differential { program.specialize_columns(&columns).expect("specialize"), ] { let mut raw = Vec::new(); - self.runner - .evaluate_columns(&program, &columns, |i, r| raw.push((i, r))); + self.runner.evaluate_columns( + &program, + &EvaluationContext::default(), + &columns, + |i, r| raw.push((i, r)), + ); let mut got = vec![Err(String::new()); inputs.len()]; for (i, r) in raw { got[i] = self.lane_of(r); @@ -236,8 +255,12 @@ impl Differential { } } let mut out = Output::new(); - self.runner - .evaluate_columns_into(&program, &columns, &mut out); + self.runner.evaluate_columns_into( + &program, + &EvaluationContext::default(), + &columns, + &mut out, + ); for (i, (row, exp)) in rows.iter().zip(&expected).enumerate() { self.compared += 1; let got = match out.variable(i) { @@ -584,7 +607,7 @@ fn lane_struct_outputs_stay_typed() { .expect("specialize"); let mut runner = LaneRunner::new(); let mut out = Output::new(); - runner.evaluate_columns_into(&program, &columns, &mut out); + runner.evaluate_columns_into(&program, &EvaluationContext::default(), &columns, &mut out); let fields = out.fields(); assert_eq!( fields.iter().map(|(k, _)| k.as_ref()).collect::>(), @@ -1290,7 +1313,13 @@ fn lane_cell_sets_match_unary_evaluation() { .map(|_| Scope::new(json!({"limit": rng.below(15)}).into())) .collect(); let mut out = Vec::new(); - set.evaluate(&mut runner, &values, &envs, &mut out); + set.evaluate( + &mut runner, + &values, + &envs, + &mut out, + &EvaluationContext::default(), + ); let words = set.words(); for (row, value) in values.iter().enumerate() { let mut isolate = Isolate::new(); @@ -1410,12 +1439,18 @@ fn lane_many_matches_expression_node_semantics() { false => program, }; let mut got: Vec> = vec![None; inputs.len()]; - runner.evaluate_many(&program, &scopes, Some(&mask), |row, r| { - got[row] = r.map(|r| { - r.map(|v| v.into_iter().map(|x| x.to_value()).collect()) - .map_err(|(s, e)| (s, conformance::Spec::describe(&e))) - }); - }); + runner.evaluate_many( + &program, + &EvaluationContext::default(), + &scopes, + Some(&mask), + |row, r| { + got[row] = r.map(|r| { + r.map(|v| v.into_iter().map(|x| x.to_value()).collect()) + .map_err(|(s, e)| (s, conformance::Spec::describe(&e))) + }); + }, + ); for (row, input) in inputs.iter().enumerate() { compared += 1; if !mask[row] { @@ -2450,16 +2485,17 @@ impl SpecLane { let scopes = || cases.iter().map(|c| Self::scope(c)).collect::>(); let plain = program.without_kernel(); self.compiled += 1; - match program.has_kernel() { - true => self.kernels += 1, - false => self + match (program.has_kernel(), program.program().draws) { + (true, _) => self.kernels += 1, + (false, true) => {} + (false, false) => self .failures .push(format!("{expression} | compiled without a kernel")), } for case in cases.iter() { self.rows += 1; if self - .guarded(|_| program.try_kernel(&Self::scope(case))) + .guarded(|_| program.try_kernel(&Self::scope(case), &EvaluationContext::default())) .flatten() .is_some() { @@ -2468,7 +2504,7 @@ impl SpecLane { } for (case, want) in cases.iter().zip(&want) { let got = match self.guarded(|r| { - r.evaluate_one(&plain, &Self::scope(case)) + r.evaluate_one(&plain, &EvaluationContext::default(), &Self::scope(case)) .map(conformance::Spec::settle) }) { Some(got) => Self::normalize(&kind, got), @@ -2487,7 +2523,7 @@ impl SpecLane { } for (case, want) in cases.iter().zip(&want) { let got = match self.guarded(|r| { - r.evaluate_one(&program, &Self::scope(case)) + r.evaluate_one(&program, &EvaluationContext::default(), &Self::scope(case)) .map(conformance::Spec::settle) }) { Some(got) => Self::normalize(&kind, got), @@ -2512,13 +2548,13 @@ impl SpecLane { } let n = cases.len(); let batch = self - .guarded(|r| r.evaluate(&program, &scopes())) + .guarded(|r| r.evaluate(&program, &EvaluationContext::default(), &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, &scopes())) + .guarded(|r| r.evaluate(&plain, &EvaluationContext::default(), &scopes())) .unwrap_or_else(|| Self::panicked(n)); for ((case, want), got) in cases.iter().zip(&want).zip(batch) { self.compare( @@ -2531,8 +2567,12 @@ impl SpecLane { if let Ok(specialized) = program.specialize(&scopes()) { for (case, want) in cases.iter().zip(&want) { let got = match self.guarded(|r| { - r.evaluate_one(&specialized, &Self::scope(case)) - .map(conformance::Spec::settle) + r.evaluate_one( + &specialized, + &EvaluationContext::default(), + &Self::scope(case), + ) + .map(conformance::Spec::settle) }) { Some(got) => Self::normalize(&kind, got), None => Err(format!("{}: lane", conformance::Spec::PANIC)), @@ -2540,7 +2580,7 @@ impl SpecLane { self.compare("specialized", case, want, got); } let batch = self - .guarded(|r| r.evaluate(&specialized, &scopes())) + .guarded(|r| r.evaluate(&specialized, &EvaluationContext::default(), &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)); @@ -2551,7 +2591,7 @@ impl SpecLane { LaneProgram::compile_typed(expression, kind.clone(), &VariableType::from(&shape)) { let batch = self - .guarded(|r| r.evaluate(&typed, &scopes())) + .guarded(|r| r.evaluate(&typed, &EvaluationContext::default(), &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)); @@ -2641,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, &scope); + let _ = runner.evaluate_one(&first, &EvaluationContext::default(), &scope); let second = first.clone(); drop(first); let mut current = second.clone(); for _ in 0..50 { let got = runner - .evaluate_one(¤t, &scope) + .evaluate_one(¤t, &EvaluationContext::default(), &scope) .expect("lane") .to_value() .to_string(); @@ -2683,6 +2723,7 @@ fn lane_regression_many_entries_do_not_share_assignments() { let mut got = None; runner.evaluate_many( &program, + &EvaluationContext::default(), &[Scope::new(input.clone().into())], None, |_, r| { @@ -2702,11 +2743,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, &scope); - runner.evaluate_many(&program, std::slice::from_ref(&scope), None, |_, _| {}); + let _ = runner.evaluate_one(&program, &EvaluationContext::default(), &scope); + runner.evaluate_many( + &program, + &EvaluationContext::default(), + std::slice::from_ref(&scope), + None, + |_, _| {}, + ); let columns = Columns::new(3); let mut out = Output::new(); - runner.evaluate_columns_into(&program, &columns, &mut out); + runner.evaluate_columns_into(&program, &EvaluationContext::default(), &columns, &mut out); conformance::Spec::no_fallbacks(); } @@ -2728,6 +2775,7 @@ fn lane_regression_dates_cross_between_engines() { let lane_date = runner .evaluate_one( &LaneProgram::standard("d('2024-03-15 10:00:00')").expect("compile"), + &EvaluationContext::default(), &Scope::default(), ) .expect("lane"); @@ -2741,12 +2789,20 @@ fn lane_regression_dates_cross_between_engines() { .map_err(|e| conformance::Spec::describe(&e)); let program = LaneProgram::standard(e).expect("compile"); let got = runner - .evaluate_one(&program, &Scope::new(input.depth_clone(64))) + .evaluate_one( + &program, + &EvaluationContext::default(), + &Scope::new(input.depth_clone(64)), + ) .map(|v| v.to_value()) .map_err(|e| conformance::Spec::describe(&e)); assert_eq!(got, want, "{e}"); let again = runner - .evaluate_one(&program, &Scope::new(input.depth_clone(64))) + .evaluate_one( + &program, + &EvaluationContext::default(), + &Scope::new(input.depth_clone(64)), + ) .expect("lane"); let back = Variable::from(json!({"y": null})); back.dot_insert("y", again); @@ -2772,7 +2828,12 @@ impl Rows { program.specialize_columns(columns).expect("specialize"), ] { let mut out = Output::new(); - runner.evaluate_columns_into(&program, columns, &mut out); + runner.evaluate_columns_into( + &program, + &EvaluationContext::default(), + columns, + &mut out, + ); for r in 0..columns.rows { let want = Isolate::with_environment(columns.row(r)) .run_standard(e) @@ -2845,6 +2906,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(), &columns, &mut out, ); @@ -2878,7 +2940,13 @@ fn lane_regression_cells_near_decimal_max() { .collect(); let envs: Vec = values.iter().map(|_| Scope::default()).collect(); let mut out = Vec::new(); - set.evaluate(&mut LaneRunner::new(), &values, &envs, &mut out); + set.evaluate( + &mut LaneRunner::new(), + &values, + &envs, + &mut out, + &EvaluationContext::default(), + ); for (row, value) in values.iter().enumerate() { for (rule, cell) in cells.iter().enumerate() { let mut isolate = Isolate::new(); @@ -2986,13 +3054,19 @@ fn lane_regression_chained_dollar_matches_isolate() { .expect("specialize"), ] { let mut got = None; - runner.evaluate_many(&program, std::slice::from_ref(&scope), None, |_, r| { - got = r.and_then(|r| r.ok()).map(|v| { - v.into_iter() - .map(|x| Some(x.to_value())) - .collect::>() - }) - }); + runner.evaluate_many( + &program, + &EvaluationContext::default(), + std::slice::from_ref(&scope), + None, + |_, r| { + got = r.and_then(|r| r.ok()).map(|v| { + v.into_iter() + .map(|x| Some(x.to_value())) + .collect::>() + }) + }, + ); assert_eq!(got, Some(expected.clone()), "{entries:?}"); } } @@ -3019,7 +3093,13 @@ fn lane_regression_cells_survive_invalid_neighbours() { .map(|_| Scope::new(json!({"limit": 2}).into())) .collect(); let mut out = Vec::new(); - set.evaluate(&mut LaneRunner::new(), &values, &envs, &mut out); + set.evaluate( + &mut LaneRunner::new(), + &values, + &envs, + &mut out, + &EvaluationContext::default(), + ); for (row, value) in values.iter().enumerate() { for (rule, cell) in cells.iter().enumerate() { let mut isolate = Isolate::with_environment(json!({"limit": 2}).into()); @@ -3053,7 +3133,13 @@ fn lane_regression_cells_probe_between_close_bounds() { .collect(); let envs: Vec = values.iter().map(|_| Scope::default()).collect(); let mut out = Vec::new(); - set.evaluate(&mut LaneRunner::new(), &values, &envs, &mut out); + set.evaluate( + &mut LaneRunner::new(), + &values, + &envs, + &mut out, + &EvaluationContext::default(), + ); for (row, value) in values.iter().enumerate() { for (rule, cell) in cells.iter().enumerate() { let mut isolate = Isolate::new(); @@ -3193,7 +3279,7 @@ fn lane_regression_date_inputs_keep_their_text() { ]; for program in &programs { let got: Vec<_> = runner - .evaluate(program, &scopes) + .evaluate(program, &EvaluationContext::default(), &scopes) .into_iter() .map(|r| r.map(|v| v.to_value()).ok()) .collect(); @@ -3202,7 +3288,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, &columns, &mut out); + runner.evaluate_columns_into(&plain, &EvaluationContext::default(), &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()), @@ -3255,7 +3341,7 @@ fn lane_regression_constant_folding_keeps_runtime_semantics() { let program = LaneProgram::standard(e).expect("compile"); for _ in 0..2 { let got = runner - .evaluate_one(&program, &scope) + .evaluate_one(&program, &EvaluationContext::default(), &scope) .map(|v| v.to_value()) .ok(); assert_eq!(got, want, "{e}"); @@ -3263,7 +3349,11 @@ fn lane_regression_constant_folding_keeps_runtime_semantics() { } let rand = LaneProgram::standard("rand(1000000)").expect("compile"); let values: std::collections::BTreeSet = (0..20) - .filter_map(|_| runner.evaluate_one(&rand, &scope).ok()) + .filter_map(|_| { + runner + .evaluate_one(&rand, &EvaluationContext::default(), &scope) + .ok() + }) .map(|v| v.to_value().to_string()) .collect(); assert!(values.len() > 1); @@ -3298,7 +3388,7 @@ fn lane_regression_long_strings_and_list_membership() { program.specialize(&rows).expect("specialize"), ] { let got: Vec<_> = runner - .evaluate(&program, &rows) + .evaluate(&program, &EvaluationContext::default(), &rows) .into_iter() .map(|r| r.map(|v| v.to_value()).ok()) .collect(); @@ -3394,13 +3484,19 @@ fn lane_regression_chained_dotted_keys_resolve() { let program = LaneProgram::compile_many(entries, true).expect("compile"); let scope = Scope::new(input.clone().into()); let mut got = None; - runner.evaluate_many(&program, std::slice::from_ref(&scope), None, |_, r| { - got = r.and_then(|r| r.ok()).map(|v| { - v.into_iter() - .map(|x| Some(x.to_value())) - .collect::>() - }) - }); + runner.evaluate_many( + &program, + &EvaluationContext::default(), + std::slice::from_ref(&scope), + None, + |_, r| { + got = r.and_then(|r| r.ok()).map(|v| { + v.into_iter() + .map(|x| Some(x.to_value())) + .collect::>() + }) + }, + ); assert_eq!(got, Some(expected), "{entries:?}"); } conformance::Spec::no_fallbacks(); @@ -3433,7 +3529,11 @@ fn lane_builtin_failures_keep_messages() { continue; }; let lane = runner - .evaluate(&program, std::slice::from_ref(&scope)) + .evaluate( + &program, + &EvaluationContext::default(), + std::slice::from_ref(&scope), + ) .remove(0) .map(|v| v.to_value()) .map_err(|e| conformance::Spec::describe(&e)); @@ -3488,6 +3588,7 @@ fn lane_isolated_cells_keep_evaluating_after_a_fault() { let mut failures = Vec::new(); runner.evaluate_bound_into( &program, + &EvaluationContext::default(), &scopes, &columns, &bind, @@ -3753,11 +3854,19 @@ impl StructLists { program.specialize_columns(&columns).expect("specialize"), ] { let mut out = Output::new(); - runner.evaluate_columns_into(&program, &columns, &mut out); + runner.evaluate_columns_into( + &program, + &EvaluationContext::default(), + &columns, + &mut out, + ); let mut values = Vec::new(); - runner.evaluate_columns(&program, &columns, |_, r| { - values.push(r.map(|v| v.to_value()).ok()) - }); + runner.evaluate_columns( + &program, + &EvaluationContext::default(), + &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)) .run_standard(e) @@ -4075,9 +4184,13 @@ impl Fused { ] { let mut outs: Vec = Vec::new(); let mut failed = vec![false; rows.len()]; - runner.evaluate_columns_many(&program, &columns, &mut outs, |row, _, _| { - failed[row] = true - }); + runner.evaluate_columns_many( + &program, + &EvaluationContext::default(), + &columns, + &mut outs, + |row, _, _| failed[row] = true, + ); for (r, row) in rows.iter().enumerate() { let want = Self::expected(columns.row(r), entries); let got = match failed[r] { diff --git a/core/expression/tests/spec/standard/00-harness.csv b/core/expression/tests/spec/standard/00-harness.csv index cf0dd84d..2048c206 100644 --- a/core/expression/tests/spec/standard/00-harness.csv +++ b/core/expression/tests/spec/standard/00-harness.csv @@ -11,4 +11,4 @@ keys({'': 1});;[''] "x = 1; x + 1";{};2 "x = 1; x + 1";;!error;question: assignments need an object environment; with no input they fail d('2024-01-01');;'2024-01-01T00:00:00Z' -rand(-1);;!error;bug: panics inside fastrand (empty range) instead of returning an error +rand(-1);;!error diff --git a/core/expression/tests/spec/standard/10-03-math.csv b/core/expression/tests/spec/standard/10-03-math.csv index 9b512d37..a112672b 100644 --- a/core/expression/tests/spec/standard/10-03-math.csv +++ b/core/expression/tests/spec/standard/10-03-math.csv @@ -365,7 +365,7 @@ type(rand(null));;!error type(rand(true));;!error type(rand(false));;!error type(rand(0));;'number' -type(rand(-1));;!error;bug: panics (empty range in fastrand) on a negative upper bound instead of raising an error +type(rand(-1));;!error type(rand(1.5));;'number' type(rand(79228162514264337593543950335));;!error;question: an upper bound beyond i64 is rejected type(rand(''));;!error @@ -385,7 +385,7 @@ type(rand(x));{x: null};!error type(rand(x));{x: true};!error type(rand(x));{x: false};!error type(rand(x));{x: 0};'number' -type(rand(x));{x: -1};!error;bug: panics (empty range in fastrand) on a negative upper bound instead of raising an error +type(rand(x));{x: -1};!error type(rand(x));{x: 1.5};'number' type(rand(x));{x: 79228162514264337593543950335};!error;question: an upper bound beyond i64 is rejected type(rand(x));{x: ''};!error diff --git a/core/expression/tests/typed.rs b/core/expression/tests/typed.rs index fa9f0b59..96597d9a 100644 --- a/core/expression/tests/typed.rs +++ b/core/expression/tests/typed.rs @@ -3,6 +3,7 @@ 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, @@ -342,7 +343,7 @@ impl Report { } let mut out = program.outputs(); let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - program.run(&batch, &mut out, None) + program.run(&batch, &mut out, None, &EvaluationContext::default()) })); match ran { Ok(Ok(())) => {}