diff --git a/Cargo.lock b/Cargo.lock index cc57864d3..9411781ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6045,11 +6045,14 @@ dependencies = [ name = "zen-benchmark" version = "0.0.23" dependencies = [ + "mimalloc", + "rust_decimal", "serde", "serde_json", "tokio", "zen-engine", "zen-expression", + "zstd", ] [[package]] @@ -6069,6 +6072,7 @@ dependencies = [ "flate2", "http", "insta", + "itoa", "json_dotpath", "jsonschema", "mimalloc", @@ -6076,6 +6080,7 @@ dependencies = [ "once_cell", "petgraph", "recursive", + "regex", "reqsign", "reqwest 0.12.28", "rquickjs", @@ -6085,6 +6090,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "sha2 0.10.9", + "smallvec", "strum 0.27.2", "swc_common", "swc_ecma_ast", @@ -6336,3 +6342,31 @@ name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zstd" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb02c3132d251ab1606e9fc913a7da6c6ed08cc263df15edf082e1dc497d157" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index eb357666d..2c9062f49 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,9 @@ nohash-hasher = "0.2" anyhow = "1" thiserror = "1" +[profile.test] +opt-level = 1 + [profile.release] lto = true codegen-units = 1 diff --git a/benchmark/rust/Cargo.toml b/benchmark/rust/Cargo.toml index ec6f3fc05..6ca6fb90b 100644 --- a/benchmark/rust/Cargo.toml +++ b/benchmark/rust/Cargo.toml @@ -10,3 +10,10 @@ zen-expression = { path = "../../core/expression" } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } +rust_decimal = { workspace = true } +zstd = "0.13" +mimalloc = { version = "0.1.52", optional = true } + +[features] +base = [] +mimalloc = ["dep:mimalloc"] diff --git a/benchmark/rust/src/bin/trace.rs b/benchmark/rust/src/bin/trace.rs new file mode 100644 index 000000000..404e17878 --- /dev/null +++ b/benchmark/rust/src/bin/trace.rs @@ -0,0 +1,831 @@ +use serde::Deserialize; +use serde_json::{json, Value}; +use std::alloc::{GlobalAlloc, Layout, System}; +use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Instant; +use zen_engine::columns::{Column, Columns, Values}; +use zen_engine::loader::{FilesystemLoader, FilesystemLoaderOptions, MemoryLoader}; +use zen_engine::model::DecisionContent; +use zen_engine::{DecisionEngine, EvaluationOptions, ZEN_CONFIG}; +use zen_expression::Variable; + +struct Counting; + +static CURRENT: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +static CALLS: AtomicUsize = AtomicUsize::new(0); + +#[cfg(feature = "mimalloc")] +static INNER: mimalloc::MiMalloc = mimalloc::MiMalloc; +#[cfg(not(feature = "mimalloc"))] +static INNER: System = System; + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let p = INNER.alloc(layout); + CALLS.fetch_add(1, Ordering::Relaxed); + if !p.is_null() { + let now = CURRENT.fetch_add(layout.size(), Ordering::Relaxed) + layout.size(); + PEAK.fetch_max(now, Ordering::Relaxed); + } + p + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + INNER.dealloc(ptr, layout); + CURRENT.fetch_sub(layout.size(), Ordering::Relaxed); + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + let p = INNER.realloc(ptr, layout, new_size); + if !p.is_null() { + if new_size >= layout.size() { + let now = CURRENT.fetch_add(new_size - layout.size(), Ordering::Relaxed) + new_size + - layout.size(); + PEAK.fetch_max(now, Ordering::Relaxed); + } else { + CURRENT.fetch_sub(layout.size() - new_size, Ordering::Relaxed); + } + } + p + } +} + +#[global_allocator] +static ALLOC: Counting = Counting; + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Off, + Legacy, + #[cfg(not(feature = "base"))] + V1, +} + +impl Mode { + fn all() -> Vec { + #[cfg(feature = "base")] + return vec![Mode::Off, Mode::Legacy]; + #[cfg(not(feature = "base"))] + return vec![Mode::Off, Mode::V1, Mode::Legacy]; + } + + fn name(self) -> &'static str { + match self { + Mode::Off => "off", + #[cfg(feature = "base")] + Mode::Legacy => "legacy (base)", + #[cfg(not(feature = "base"))] + Mode::Legacy => "legacy via restore", + #[cfg(not(feature = "base"))] + Mode::V1 => "v1", + } + } + + #[cfg(feature = "base")] + fn options(self) -> EvaluationOptions { + EvaluationOptions { + trace: (self != Mode::Off).into(), + max_depth: 10, + ..Default::default() + } + } + + #[cfg(not(feature = "base"))] + fn options(self) -> EvaluationOptions { + use zen_engine::trace::TraceFormat; + EvaluationOptions { + trace: match self { + Mode::Off => TraceFormat::Off, + Mode::Legacy => TraceFormat::Legacy, + Mode::V1 => TraceFormat::V1, + }, + max_depth: 10, + ..Default::default() + } + } +} + +const CATEGORIES: [&str; 6] = [ + "electronics", + "grocery", + "apparel", + "home", + "toys", + "garden", +]; +const SEGMENTS: [&str; 4] = ["gold", "silver", "bronze", "new"]; +const COUNTRIES: [&str; 5] = ["GB", "US", "DE", "NG", "BR"]; + +fn payload(seed: usize, items: usize) -> Value { + let rows: Vec = (0..items) + .map(|k| { + let h = (seed * 7919 + k * 104_729) % 1_000_003; + json!({ + "sku": format!("sku-{:06}", h % 1_000_000), + "title": format!("Product {h} in a reasonably descriptive catalogue title, size {}", h % 13), + "category": CATEGORIES[h % 6], + "qty": h % 5 + 1, + "price": (h % 90_000) as f64 / 100.0 + 0.99, + "warehouse": format!("wh-{}", h % 17), + "tags": ["catalog", if h.is_multiple_of(3) { "promo" } else { "regular" }, "season-26"], + "attrs": {"color": (["red", "blue", "black", "white"][h % 4]), "weightKg": (h % 300) as f64 / 10.0, "fragile": h.is_multiple_of(7)} + }) + }) + .collect(); + let total: f64 = rows + .iter() + .map(|r| r["price"].as_f64().unwrap() * r["qty"].as_f64().unwrap()) + .sum(); + json!({ + "customer": {"id": format!("cus_{}", seed * 31 % 99_991), "segment": SEGMENTS[seed % 4], "country": COUNTRIES[seed % 5], + "history": {"orders": seed * 13 % 400, "returns": seed % 9, "lifetimeValue": (seed * 977 % 50_000) as f64 + 0.5}}, + "order": {"id": format!("ord_{seed:08}"), "channel": (["web", "app", "store"][seed % 3]), "currency": "EUR", "total": (total * 100.0).round() / 100.0, "items": rows}, + "device": {"ip": format!("203.0.113.{}", seed % 250), "fingerprint": format!("{:016x}", seed * 0x9e37_79b9_7f4a_7c15usize)} + }) +} + +fn node(id: &str, kind: &str, content: Value) -> Value { + json!({"id": id, "name": id, "type": kind, "content": content}) +} + +fn table(i: usize, loop_items: bool) -> Value { + if loop_items { + return json!({ + "hitPolicy": "first", "passThrough": false, "inputField": "order.items", "outputPath": format!("lines.n{i}"), "executionMode": "loop", + "inputs": [{"id": "i0", "name": "category", "field": "category"}, {"id": "i1", "name": "price", "field": "price"}, {"id": "i2", "name": "qty", "field": "qty"}], + "outputs": [{"id": "o0", "name": "band", "field": "band"}], + "rules": [ + {"_id": "r0", "i0": "'electronics'", "i1": "> 500", "i2": "", "o0": "'review'"}, + {"_id": "r1", "i0": "", "i1": "> 800", "i2": "> 2", "o0": "'hold'"}, + {"_id": "r2", "i0": "'toys', 'garden'", "i1": "", "i2": "", "o0": "'light'"}, + {"_id": "r3", "i0": "", "i1": "", "i2": "", "o0": "'ok'"} + ] + }); + } + let big_input = i.is_multiple_of(5); + let mut inputs = vec![ + json!({"id": "i0", "name": "segment", "field": "customer.segment"}), + json!({"id": "i1", "name": "total", "field": "order.total"}), + json!({"id": "i2", "name": "country", "field": "customer.country"}), + ]; + if big_input { + inputs.push(json!({"id": "i3", "name": "items", "field": "order.items"})); + } + let rules: Vec = (0..6) + .map(|r| { + let mut rule = json!({"_id": format!("r{r}"), "i0": "", "i1": "", "i2": "", "o0": format!("'{}'", ["block", "review", "step-up", "fast", "watch", "ok"][r])}); + match r { + 0 => rule["i2"] = json!("'NG'"), + 1 => rule["i1"] = json!(format!("> {}", 900_000 + i * 1_000)), + 2 => rule["i0"] = json!("'new'"), + 3 => rule["i0"] = json!("'gold'"), + 4 => rule["i1"] = json!(format!("> {}", 400_000 + i * 5_000)), + _ => {} + } + if big_input { + rule["i3"] = json!(if r == 1 { "count($) > 1500" } else { "" }); + } + rule + }) + .collect(); + json!({"hitPolicy": "first", "passThrough": true, "inputField": null, "outputPath": null, "executionMode": "single", + "inputs": inputs, "outputs": [{"id": "o0", "name": "flag", "field": format!("checks.n{i}")}], "rules": rules}) +} + +fn expression(i: usize, pass: bool) -> Value { + json!({"passThrough": pass, "inputField": null, "outputPath": null, "executionMode": "single", "expressions": [ + {"id": "x0", "key": format!("scores.n{i}"), "value": format!("order.total / {} + customer.history.orders", i + 1)}, + {"id": "x1", "key": format!("seen.n{i}"), "value": "customer.history.returns > 3 or order.channel == 'store'"} + ]}) +} + +fn rewrite(i: usize) -> Value { + json!({"source": format!( + "export const handler = async (input) => ({{...input, order: {{...input.order, items: input.order.items.map((it) => ({{...it, step{i}: Math.round(it.price * it.qty * {k}) / 100}}))}}}});", + k = i + 1 + )}) +} + +fn graph(nodes: Vec, fan_out: bool) -> Value { + let side: Vec = nodes + .iter() + .filter(|n| n["content"]["executionMode"] == "loop") + .map(|n| n["id"].as_str().unwrap().to_string()) + .collect(); + let mut all = vec![node("request", "inputNode", json!({}))]; + let ids: Vec = nodes + .iter() + .map(|n| n["id"].as_str().unwrap().to_string()) + .collect(); + all.extend(nodes); + all.push(node("response", "outputNode", json!({}))); + let mut edges = Vec::new(); + let mut edge = |a: &str, b: &str| { + edges.push(json!({"id": format!("{a}-{b}"), "type": "edge", "sourceId": a, "targetId": b})) + }; + if fan_out { + for id in &ids { + edge("request", id); + edge(id, "response"); + } + } else { + let mut prev = "request".to_string(); + let mut before = String::new(); + for id in &ids { + edge(&prev, id); + if side.contains(&prev) { + edge(&before, id); + } + before = prev; + prev = id.clone(); + } + edge(&prev, "response"); + } + json!({"contentType": "application/vnd.gorules.decision", "nodes": all, "edges": edges}) +} + +fn big_graphs() -> Vec<(&'static str, Value)> { + let mixed = |loops: bool| -> Vec { + (0..20) + .map(|i| { + let id = format!("n{i:02}"); + if loops && i % 5 == 2 { + node(&id, "decisionTableNode", table(i, true)) + } else if i % 2 == 0 { + node(&id, "decisionTableNode", table(i, false)) + } else { + node(&id, "expressionNode", expression(i, true)) + } + }) + .collect() + }; + let fan = (0..20) + .map(|i| { + let id = format!("n{i:02}"); + if i % 2 == 0 { + let mut t = table(i, false); + t["passThrough"] = json!(false); + node(&id, "decisionTableNode", t) + } else { + node(&id, "expressionNode", expression(i, false)) + } + }) + .collect(); + vec![ + ("ride", graph(mixed(false), false)), + ("fan", graph(fan, true)), + ("loops", graph(mixed(true), false)), + ( + "rewrite", + graph( + (0..20) + .map(|i| node(&format!("n{i:02}"), "functionNode", rewrite(i))) + .collect(), + false, + ), + ), + ] +} + +#[derive(Deserialize)] +struct Entry { + name: String, + file: String, + input: Value, +} + +struct Scenario { + name: String, + engine: DecisionEngine, + key: String, + input: Value, + iters: usize, + policy: bool, +} + +struct Sample { + eval_peak: usize, + eval_ns: f64, + json_ns: f64, + peak: usize, + bytes: usize, +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(|a, b| a.partial_cmp(b).unwrap()); + v[v.len() / 2] +} + +async fn measure(s: &Scenario, mode: Mode) -> Sample { + let options = mode.options(); + let input: Variable = s.input.clone().into(); + for _ in 0..s.iters.min(3) { + let r = s + .engine + .evaluate_with_opts(&s.key, input.depth_clone(64), options) + .await; + let _ = r + .map(|r| serde_json::to_string(&r).unwrap()) + .map_err(|e| e.to_string()) + .unwrap(); + } + let (mut eval, mut json, mut peaks) = (Vec::new(), Vec::new(), Vec::new()); + let mut eval_peaks = Vec::new(); + let mut bytes = 0; + for _ in 0..s.iters { + let context = input.depth_clone(64); + let base = CURRENT.load(Ordering::Relaxed); + PEAK.store(base, Ordering::Relaxed); + let t0 = Instant::now(); + let response = s + .engine + .evaluate_with_opts(&s.key, context, options) + .await + .unwrap(); + let t1 = Instant::now(); + eval_peaks.push(PEAK.load(Ordering::Relaxed).saturating_sub(base) as f64); + let text = serde_json::to_string(&response).unwrap(); + let t2 = Instant::now(); + peaks.push(PEAK.load(Ordering::Relaxed).saturating_sub(base) as f64); + bytes = text.len(); + drop(text); + drop(response); + eval.push((t1 - t0).as_nanos() as f64); + json.push((t2 - t1).as_nanos() as f64); + } + Sample { + eval_ns: median(eval), + json_ns: median(json), + peak: median(peaks) as usize, + eval_peak: median(eval_peaks) as usize, + bytes, + } +} + +fn fmt_ns(ns: f64) -> String { + if ns >= 1e9 { + format!("{:.2} s", ns / 1e9) + } else if ns >= 1e6 { + format!("{:.2} ms", ns / 1e6) + } else { + format!("{:.2} µs", ns / 1e3) + } +} + +fn fmt_bytes(b: usize) -> String { + let b = b as f64; + if b >= 1e6 { + format!("{:.1} MB", b / 1e6) + } else if b >= 1e3 { + format!("{:.1} KB", b / 1e3) + } else { + format!("{b:.0} B") + } +} + +fn rows_of(s: &Scenario, rows: usize) -> Vec { + (0..rows).map(|_| Variable::from(s.input.clone())).collect() +} + +enum Owned { + Dec(Vec), + Strs(Vec<&'static str>), + Any(Vec), +} + +fn leaves(prefix: &str, v: &Value, out: &mut Vec<(String, Value)>) { + match v { + Value::Object(map) if !map.is_empty() => { + for (k, x) in map { + let path = match prefix.is_empty() { + true => k.clone(), + false => format!("{prefix}.{k}"), + }; + leaves(&path, x, out); + } + } + other => out.push((prefix.to_string(), other.clone())), + } +} + +fn owned_columns(input: &Value, rows: usize) -> Vec<(&'static str, Owned)> { + let mut flat = Vec::new(); + leaves("", input, &mut flat); + flat.into_iter() + .map(|(path, value)| { + let path: &'static str = Box::leak(path.into_boxed_str()); + let owned = match &value { + Value::Number(n) => { + Owned::Dec(vec![ + rust_decimal::Decimal::from_str_exact(&n.to_string()) + .unwrap_or_default(); + rows + ]) + } + Value::String(t) => { + let t: &'static str = Box::leak(t.clone().into_boxed_str()); + Owned::Strs(vec![t; rows]) + } + other => Owned::Any((0..rows).map(|_| Variable::from(other.clone())).collect()), + }; + (path, owned) + }) + .collect() +} + +fn columns_of<'a>(owned: &'a [(&'static str, Owned)], rows: usize) -> Columns<'a> { + let mut columns = Columns::new(rows); + for (path, values) in owned { + let values = match values { + Owned::Dec(d) => Values::Dec(d), + Owned::Strs(s) => Values::Strs(s), + Owned::Any(a) => Values::Any(a), + }; + columns = columns.column(path, Column::new(values)); + } + columns +} + +struct BatchSample { + ns: f64, + json_ns: f64, + peak: usize, + bytes: usize, +} + +async fn batch(s: &Scenario, mode: Mode, rows: usize, reps: usize) -> BatchSample { + let options = mode.options(); + let (mut times, mut json, mut peaks) = (Vec::new(), Vec::new(), Vec::new()); + let mut last = 0usize; + for rep in 0..reps + 1 { + let contexts = rows_of(s, rows); + let base = CURRENT.load(Ordering::Relaxed); + PEAK.store(base, Ordering::Relaxed); + let t0 = Instant::now(); + let results = s.engine.evaluate_batch(&s.key, &contexts, options).await; + let t1 = Instant::now(); + if let (Ok(dir), 0, Some(Ok(first))) = (std::env::var("TRACE_DUMP"), rep, results.first()) { + let slug: String = format!("{} {}", s.name, mode.name()) + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + std::fs::create_dir_all(&dir).unwrap(); + let value = serde_json::to_value(first).unwrap(); + let text = serde_json::to_string(&value["trace"]).unwrap(); + std::fs::write(Path::new(&dir).join(format!("{slug}-batch.json")), text).unwrap(); + } + let mut bytes = 0usize; + for r in &results { + bytes += match r { + Ok(r) => serde_json::to_string(r).unwrap().len(), + Err(e) => e.to_string().len(), + }; + } + std::hint::black_box(bytes); + let t2 = Instant::now(); + let peak = PEAK.load(Ordering::Relaxed).saturating_sub(base); + last = bytes; + drop(results); + if rep > 0 { + times.push((t1 - t0).as_nanos() as f64); + json.push((t2 - t1).as_nanos() as f64); + peaks.push(peak as f64); + } + } + BatchSample { + ns: median(times), + json_ns: median(json), + peak: median(peaks) as usize, + bytes: last / rows.max(1), + } +} + +async fn columnar(s: &Scenario, mode: Mode, rows: usize, reps: usize) -> Option { + let decision = s.engine.get_decision(&s.key).await.ok()?.ok()?; + let owned = owned_columns(&s.input, rows); + let columns = columns_of(&owned, rows); + let options = mode.options(); + let (mut times, mut json, mut peaks) = (Vec::new(), Vec::new(), Vec::new()); + let mut last = 0usize; + for rep in 0..reps + 1 { + let base = CURRENT.load(Ordering::Relaxed); + PEAK.store(base, Ordering::Relaxed); + let t0 = Instant::now(); + let output = decision.evaluate_columns(&columns, options).await; + let t1 = Instant::now(); + let bytes = columnar_json(&output, mode); + std::hint::black_box(bytes); + let t2 = Instant::now(); + let peak = PEAK.load(Ordering::Relaxed).saturating_sub(base); + last = bytes; + drop(output); + if rep > 0 { + times.push((t1 - t0).as_nanos() as f64); + json.push((t2 - t1).as_nanos() as f64); + peaks.push(peak as f64); + } + } + Some(BatchSample { + ns: median(times), + json_ns: median(json), + peak: median(peaks) as usize, + bytes: last / rows.max(1), + }) +} + +#[cfg(feature = "base")] +fn columnar_json(output: &zen_engine::ColumnarOutput, _mode: Mode) -> usize { + (0..output.rows) + .map(|row| serde_json::to_string(&output.row(row)).unwrap().len()) + .sum() +} + +#[cfg(not(feature = "base"))] +fn columnar_json(output: &zen_engine::ColumnarOutput, _mode: Mode) -> usize { + if std::env::var("TRACE_ALL").is_ok() { + let mut rows = String::new(); + output.write_rows(&mut rows); + let results = rows.len().saturating_sub(output.rows); + let mut out = String::new(); + let rows = output + .traces() + .map_or(0, |traces| traces.write_all(&mut out).len()); + return results + out.len().saturating_sub(rows); + } + (0..output.rows) + .map(|row| { + serde_json::to_string(&output.row(row)).unwrap().len() + + output.trace_json(row).map_or(0, |t| t.len()) + }) + .sum() +} + +#[cfg(feature = "base")] +fn reevaluations() -> Vec<(&'static str, usize)> { + Vec::new() +} + +#[cfg(not(feature = "base"))] +fn reevaluations() -> Vec<(&'static str, usize)> { + zen_engine::trace::testing::reevaluations() +} + +fn report_reevaluated(label: &str, before: &[(&'static str, usize)], runs: usize) { + let after = reevaluations(); + let moved: Vec = after + .iter() + .filter_map(|(k, v)| { + let was = before.iter().find(|(b, _)| b == k).map_or(0, |(_, n)| *n); + (*v > was).then(|| format!("{k}: {} rows", (v - was) / runs.max(1))) + }) + .collect(); + if !moved.is_empty() { + eprintln!("{label}: re-evaluated {}", moved.join(", ")); + } +} + +async fn batches(scenarios: &[Scenario], filter: Option<&str>, rows: usize) { + println!("| scenario | rows | path | mode | batch | rows/s | + JSON per row | peak memory | JSON bytes per row |"); + println!("|---|---:|---|---|---:|---:|---:|---:|---:|"); + for s in scenarios { + if s.policy || filter.is_some_and(|f| !s.name.contains(f)) { + continue; + } + let rows = match s.iters < 100 { + true => (rows / 100).max(4), + false => rows, + }; + let reps = std::env::var("TRACE_REPS") + .ok() + .and_then(|r| r.parse().ok()) + .unwrap_or(match s.iters < 100 { + true => 3, + false => 10, + }); + let wanted = |mode: Mode| { + std::env::var("TRACE_MODE").map_or(true, |m| mode.name().contains(m.as_str())) + }; + let paths = std::env::var("TRACE_PATH").unwrap_or_default(); + for mode in Mode::all() { + if !wanted(mode) || paths == "columnar" { + continue; + } + let before = reevaluations(); + let r = batch(s, mode, rows, reps).await; + report_reevaluated( + &format!("{} batch {}", s.name, mode.name()), + &before, + reps + 1, + ); + println!( + "| {} | {rows} | batch | {} | {} | {:.0} | {} | {} | {} |", + s.name, + mode.name(), + fmt_ns(r.ns), + rows as f64 / (r.ns / 1e9), + fmt_ns(r.json_ns / rows as f64), + fmt_bytes(r.peak), + r.bytes + ); + } + for mode in Mode::all() { + #[cfg(feature = "base")] + if mode != Mode::Off { + continue; + } + if !wanted(mode) || paths == "batch" { + continue; + } + let before = reevaluations(); + let Some(r) = columnar(s, mode, rows, reps).await else { + continue; + }; + report_reevaluated( + &format!("{} columnar {}", s.name, mode.name()), + &before, + reps + 1, + ); + println!( + "| {} | {rows} | columnar | {} | {} | {:.0} | {} | {} | {} |", + s.name, + mode.name(), + fmt_ns(r.ns), + rows as f64 / (r.ns / 1e9), + fmt_ns(r.json_ns / rows as f64), + fmt_bytes(r.peak), + r.bytes + ); + } + } +} + +#[tokio::main(flavor = "current_thread")] +async fn main() { + let manifest_path = std::env::args() + .nth(1) + .unwrap_or_else(|| "../manifest.json".to_string()); + ZEN_CONFIG.compiled.store( + std::env::var("BENCH_ENGINE").map_or(true, |e| e != "interpreted"), + Ordering::Relaxed, + ); + let filter = std::env::var("TRACE_BENCH").ok(); + let small_iters: usize = std::env::var("SMALL_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2000); + let big_iters: usize = std::env::var("BIG_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10); + let items: usize = std::env::var("BIG_ITEMS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4000); + let manifest_path = Path::new(&manifest_path); + let fixtures = manifest_path + .parent() + .unwrap_or(Path::new(".")) + .join("fixtures"); + let manifest: Vec = + serde_json::from_str(&std::fs::read_to_string(manifest_path).expect("manifest")) + .expect("manifest json"); + let files = match std::env::var("BENCH_LOADER").is_ok_and(|l| l == "filesystem") { + true => DecisionEngine::default().with_loader(Arc::new(FilesystemLoader::new( + FilesystemLoaderOptions { + root: fixtures.to_string_lossy().to_string(), + }, + ))), + false => { + let memory = Arc::new(MemoryLoader::default()); + for e in &manifest { + let text = std::fs::read_to_string(fixtures.join(&e.file)).expect("fixture"); + memory.add( + e.file.as_str(), + serde_json::from_str::(&text).expect("fixture json"), + ); + } + DecisionEngine::default().with_loader(memory) + } + }; + let mut scenarios: Vec = manifest + .iter() + .filter(|e| e.file.starts_with("graphs/") || e.file.starts_with("policies/")) + .map(|e| Scenario { + name: format!( + "{} {}", + if e.file.starts_with("graphs/") { + "small" + } else { + "policy" + }, + e.name + ), + engine: files.clone(), + key: e.file.clone(), + input: e.input.clone(), + iters: small_iters, + policy: e.file.starts_with("policies/"), + }) + .collect(); + let loader = Arc::new(MemoryLoader::default()); + for (key, graph) in big_graphs() { + loader.add( + key, + serde_json::from_value::(graph).unwrap(), + ); + } + let big = DecisionEngine::default().with_loader(loader); + scenarios.push(Scenario { + name: "loops, 50 items".to_string(), + engine: big.clone(), + key: "loops".to_string(), + input: payload(1, 50), + iters: small_iters / 10, + policy: false, + }); + for key in ["ride", "fan", "loops", "rewrite"] { + scenarios.push(Scenario { + name: format!("{key}, {items} items"), + engine: big.clone(), + key: key.to_string(), + input: payload(1, items), + iters: big_iters, + policy: false, + }); + } + if let Ok(rows) = std::env::var("TRACE_BATCH") { + batches(&scenarios, filter.as_deref(), rows.parse().unwrap_or(1000)).await; + return; + } + if let Ok(dir) = std::env::var("TRACE_SIZES") { + sizes(&scenarios, filter.as_deref(), &dir).await; + return; + } + println!("| scenario | mode | evaluate | + JSON | peak memory | peak during evaluate | response JSON |"); + println!("|---|---|---:|---:|---:|---:|---:|"); + for s in &scenarios { + if filter + .as_ref() + .is_some_and(|f| !s.name.contains(f.as_str())) + { + continue; + } + for mode in Mode::all() { + if std::env::var("TRACE_MODE").is_ok_and(|m| !mode.name().contains(m.as_str())) { + continue; + } + let r = measure(s, mode).await; + println!( + "| {} | {} | {} | {} | {} | {} | {} |", + s.name, + mode.name(), + fmt_ns(r.eval_ns), + fmt_ns(r.json_ns), + fmt_bytes(r.peak), + fmt_bytes(r.eval_peak), + fmt_bytes(r.bytes) + ); + } + } +} + +async fn sizes(scenarios: &[Scenario], filter: Option<&str>, dir: &str) { + std::fs::create_dir_all(dir).unwrap(); + println!("| scenario | mode | trace JSON | zstd |"); + println!("|---|---|---:|---:|"); + for s in scenarios { + if filter.is_some_and(|f| !s.name.contains(f)) { + continue; + } + for mode in Mode::all() { + if mode == Mode::Off { + continue; + } + let options = mode.options(); + let input: Variable = s.input.clone().into(); + let response = s + .engine + .evaluate_with_opts(&s.key, input, options) + .await + .unwrap(); + let value = serde_json::to_value(&response).unwrap(); + let text = serde_json::to_string(&value["trace"]).unwrap(); + let packed = zstd::encode_all(text.as_bytes(), 3).unwrap(); + let slug: String = format!("{} {}", s.name, mode.name()) + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + std::fs::write(Path::new(dir).join(format!("{slug}.json")), &text).unwrap(); + println!( + "| {} | {} | {} | {} |", + s.name, + mode.name(), + text.len(), + packed.len() + ); + } + } +} diff --git a/benchmark/rust/src/main.rs b/benchmark/rust/src/main.rs index a3e5cbb63..6836ed1d0 100644 --- a/benchmark/rust/src/main.rs +++ b/benchmark/rust/src/main.rs @@ -55,7 +55,7 @@ async fn main() { let input: Variable = e.input.clone().into(); for trace in [false, true] { let opts = || EvaluationOptions { - trace, + trace: trace.into(), max_depth: 10, ..Default::default() }; diff --git a/bindings/c/src/engine.rs b/bindings/c/src/engine.rs index ba16def88..f7c0d8024 100644 --- a/bindings/c/src/engine.rs +++ b/bindings/c/src/engine.rs @@ -80,7 +80,7 @@ impl Into for ZenEngineEvaluationOptions { fn into(self) -> EvaluationOptions { use zen_engine::context::{parse_instant, parse_timezone}; EvaluationOptions { - trace: self.trace, + trace: self.trace.into(), 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), diff --git a/bindings/nodejs/dts-header.d.ts b/bindings/nodejs/dts-header.d.ts index efaf65854..f2cea29bb 100644 --- a/bindings/nodejs/dts-header.d.ts +++ b/bindings/nodejs/dts-header.d.ts @@ -339,7 +339,12 @@ export interface PolicyEvaluationResult { output?: unknown; /** Evaluation duration in microseconds. */ duration?: number; - trace?: PolicyTrace; + /** + * Version 1 trace document by default on the compiled engine; today's shape with `trace: 'legacy'` and always on the + * interpreted engine. Tell them apart with `version`: `1` for {@link ZenPolicyTraceV1}, absent for {@link PolicyTrace}. + * `null` when the engine could not write the version 1 document. + */ + trace?: ZenPolicyTraceV1 | PolicyTrace | null; /** Present when a block failed mid-evaluation; `trace` then holds the partial trace up to the failure. */ error?: PolicyEvaluationFailure; } @@ -351,7 +356,1159 @@ export interface PolicyEvaluationFailure { message: string; } +/** + * A Zen trace document, format version 1: the stored form of a graph run (`kind: "graph"`) or a + * policy run (`kind: "policy"`). + * + * Narrow it with `kind`: + * + * ```ts + * if (trace.kind === 'graph') trace.nodes; else trace.executions; + * ``` + * + * The document is compact rather than self-explanatory: much is left out because a reader can + * derive it (a node's input, a table's `reference_map`, an expression node's output, a policy + * block's reads), and repeated lists may be packed (`$runs`, `$pick`). The engine restores the + * full legacy trace from it. Readers ignore fields they don't know, refuse tags (`$…` keys) they + * don't know, and refuse `requires` entries they don't know. + */ +export type ZenTraceV1 = ZenGraphTraceV1 | ZenPolicyTraceV1; + +/** + * @deprecated Use {@link ZenTraceV1}, or {@link ZenGraphTraceV1} / {@link ZenPolicyTraceV1}. + */ +export type ZenTraceDocument = ZenTraceV1; + +/** + * Today's graph trace: one {@link ZenEngineTrace} per node, keyed by node id. It has no `version` + * field, so `trace.version === 1` tells a version 1 document apart from it. (A node whose id is + * `version` would show up under that key; its record is an object, never `1`, so the check still + * holds.) + */ +export type ZenLegacyGraphTrace = Record & { version?: undefined }; + +/** + * The `trace` of a {@link ZenEngineResponse}, by the `trace` evaluation option and the decision: + * + * | option | graph decision | policy decision | + * |---|---|---| + * | `true` or `'v1'`, compiled engine | {@link ZenGraphTraceV1} | {@link ZenPolicyTraceV1} | + * | `'legacy'`, compiled engine | {@link ZenLegacyGraphTrace} | {@link PolicyTrace} | + * | `true`, `'v1'` or `'legacy'`, interpreted engine | {@link ZenLegacyGraphTrace} | {@link PolicyTrace} | + * | `false` or absent | no `trace` | no `trace` | + * + * The field is `null` instead when the engine wrote a document that it then failed to read into a + * JavaScript value, an internal error. + * + * Narrow it with `version`, then with `kind`: + * + * ```ts + * if (trace?.version === 1) { + * if (trace.kind === 'graph') trace.nodes; else trace.executions; + * } else if (trace) { + * // a legacy graph trace (graph decision) or a legacy policy trace (policy decision) + * } + * ``` + */ +export type ZenEngineResponseTrace = ZenTraceV1 | ZenLegacyGraphTrace | PolicyTrace; + +/** + * An RFC 6901 JSON Pointer: `""` is the whole value, `/a/b/0` is key `a`, then `b`, then `0`. + * Inside a segment `~` is written `~0` and `/` is written `~1`. Segments are strings: `0` is an + * index when the value there is an array and a key when it is an object. + * + * Policy pointers keep Zen's dotted-path meaning: `/order/items/0` is `order.items.0`, and a + * path in a record is relative to the record's `member`. + */ +export type ZenJsonPointer = '' | `/${string}`; + +/** An object keyed by JSON Pointers (`""` or `/…`), such as the keys of `$set`. */ +export interface ZenJsonPointerMap { + ''?: T; + [pointer: `/${string}`]: T; +} + +/** + * Optional features a document uses. A reader must understand every entry to read the document + * correctly. + * + * - `steps`: the graph body has {@link ZenGraphTraceV1Body.steps | steps}. + * - `documents`: policy `reads` are derived from the policy documents; restoring needs them. + * - `absent-default`: the policy body has {@link ZenPolicyTraceV1Body.absent | absent}. + * - `result-rows`: some expression node stores its `results` as {@link ZenGraphResultRow | rows}. + * - `redacted`: some value is a {@link ZenTraceRedacted} marker. + * - `truncated`: the document is incomplete (`truncated: true`) and may hold `$omitted` markers. + * - `derived`, `ref-nodes`: draft documents only (T2/T3); Zen refuses `derived`. + */ +export type ZenTraceKnownFeature = + | 'steps' + | 'documents' + | 'absent-default' + | 'result-rows' + | 'redacted' + | 'truncated' + | 'derived' + | 'ref-nodes'; + +/** + * A `requires` entry: a {@link ZenTraceKnownFeature}, or a feature added by a later writer. + * Readers must refuse a document with an entry they don't know, instead of misreading it. + */ +export type ZenTraceFeature = ZenTraceKnownFeature | (string & {}); + +/** + * Free-form data the caller attached to the evaluation. It is plain data: keys starting with `$` + * are not tags here, and no reader derives anything from it. + */ +export interface ZenTraceContext { + /** The caller's id for this evaluation. */ + evaluationId?: string; + /** The evaluation this one ran for (a batch, or a decision that called a service that evaluated this one). */ + parentEvaluationId?: string; + /** A request or trace id from the caller's system. */ + correlationId?: string; + /** The variant of an experiment the evaluation ran under. */ + variant?: string; + [key: string]: unknown; +} + +/** Fields shared by graph and policy documents. */ +export interface ZenTraceEnvelope { + /** Always `1`. A reader rejects any other value. */ + version: 1; + /** Selects the body: {@link ZenGraphTraceV1} or {@link ZenPolicyTraceV1}. */ + kind: 'graph' | 'policy'; + /** + * The engine version that produced the trace. Informational for graphs; for policies it is + * the legacy trace's `engineVersion` and is restored. Absent when unknown. + */ + engine?: string; + /** + * The optional features this document uses, which a reader must understand to read it. + * Absent means none. Readers must refuse unknown entries. + */ + requires?: ZenTraceFeature[]; + /** + * The evaluation's pinned clock: the one instant every "now" in the evaluation used. RFC 3339 + * in UTC with a `Z` suffix and 3, 6 or 9 fraction digits, e.g. `"2026-11-04T09:30:00.125Z"`. + * Always written by the engine; absent from converted documents. + */ + evaluatedAt?: string; + /** + * The IANA time zone the evaluation ran in (`"UTC"`, `"Europe/Berlin"`). Always written by the + * engine; absent from converted documents. + */ + timezone?: string; + /** + * The seed of the evaluation's random stream, an integer from 0 to 2^64 − 1. Written only when + * the evaluation drew a random number. Seeds the engine draws are below 2^53, so they are exact + * as JavaScript numbers; a larger seed supplied by the caller loses digits when parsed as one. + */ + seed?: number; + /** Caller data, passed through untouched. */ + context?: ZenTraceContext; + /** + * `true`: the document does not hold the whole evaluation; `$omitted` markers show where data is + * missing. Requires the `truncated` feature. Absent means `false`. + */ + truncated?: boolean; + /** Only set on derived display views, never on stored documents; readers reject it. */ + view?: never; +} + +/** A JSON scalar. */ +export type ZenTraceScalar = null | boolean | number | string; + +/** + * Plain data: `x` is taken as it is, and nothing inside is read as a tag. User data with an + * object key starting with `$` is always written this way. + * + * @example { "$literal": { "$price": 10 } } + */ +export interface ZenTraceLiteral { + $literal: unknown; +} + +/** + * A value that was removed on purpose. It restores as the string `"[redacted]"`. Requires the + * `redacted` feature. It may only stand for user data (a value position: node inputs and outputs, + * results, rule cells and references, logs, details, step values, writes, stored operands); a + * reader refuses it in a structural position such as a whole rule entry, an `id` or a `$merge`. + * + * @example { "$redacted": true, "reason": "pii" } + */ +export interface ZenTraceRedacted { + $redacted: true; + /** Why the value was removed. Free text. */ + reason?: string; +} + +/** + * A value the writer did not store. It restores as the string `"[omitted]"`. Requires the + * `truncated` feature. + * + * @example { "$omitted": { "bytes": 12345 } } + */ +export interface ZenTraceOmittedValue { + $omitted: { + /** The size of the omitted value, when the writer knows it. */ + bytes?: number; + }; +} + +/** + * Omitted loop items: stands for `iterations` items of a sub-decision `loop` list or of a + * loop-mode expression node's `results`. Each restores as `null`. + */ +export interface ZenTraceOmittedIterations { + $omitted: { iterations: number }; +} + +/** The last `nodes` of a trace level that the writer did not store. They are not restored. */ +export interface ZenTraceOmittedNodes { + $omitted: { nodes: number }; +} + +/** + * A step of a `$runs` entry: a number added per element, or a tree of per-field steps for + * objects and arrays (keys are field names or array indexes). + */ +export type ZenTraceRunStep = number | { [field: string]: ZenTraceRunStep }; + +/** + * A packed list of runs. Each entry is `[v]` (`v` once), `[v, n]` (`v` repeated `n` times) or + * `[v, n, step]` (`n` values starting at `v`, adding `step` each time, computed exactly). + * + * @example { "$runs": [[0, 5, 1], ["x", 3]] } // [0, 1, 2, 3, 4, "x", "x", "x"] + */ +export interface ZenTraceRuns { + $runs: Array<[T] | [T, number] | [T, number, ZenTraceRunStep]>; +} + +/** + * A packed list of repeated values: element `k` is `$pick[at[k]]`. + * + * @example { "$pick": ["a", "b"], "at": [0, 0, 1, 0] } // ["a", "a", "b", "a"] + */ +export interface ZenTracePick { + $pick: T[]; + at: number[]; +} + +/** + * A list. Any list of 4 or more elements may be written packed, as {@link ZenTraceRuns} or + * {@link ZenTracePick}, when that is at least 20% shorter. Expand packing before reading. + */ +export type ZenTraceList = T[] | ZenTraceRuns | ZenTracePick; + +/** + * User data as stored: JSON, where an object with a `$` key is wrapped in `$literal`, any list + * may be packed, and any value may be replaced by a `$redacted` or `$omitted` marker. Used where + * data is kept verbatim: `details`, function logs, rule cells, step values, policy writes. + */ +export type ZenTraceData = + | ZenTraceScalar + | ZenTraceData[] + | ZenTraceRuns + | ZenTracePick + | ZenTraceDataObject + | ZenTraceLiteral + | ZenTraceRedacted + | ZenTraceOmittedValue; + +/** A plain object of user data. Keys starting with `$` are tags, so they never appear here. */ +export interface ZenTraceDataObject { + [key: string]: ZenTraceData; + [tag: `$${string}`]: never; +} + +/** + * Where a graph `$ref` points, as ``: + * - `request…`: the request of the current trace level (a sub-decision's own request inside it); + * - `nodes//output…`: the output of a node that ran earlier at the same level; + * - `self…`: another place in the same value. + */ +export type ZenGraphRefTarget = + | 'request' + | `request/${string}` + | `nodes/${string}` + | 'self' + | `self/${string}`; + +/** + * A value equal to the one at another place. Used instead of repeating a large value. + * With `items`, the value is the list of those 0-based elements of the referenced array. + * + * @example { "$ref": "nodes/score/output/risk" } + */ +export interface ZenGraphRef { + $ref: ZenGraphRefTarget; + items?: ZenTraceList; +} + +/** + * A graph value: {@link ZenTraceData} where a {@link ZenGraphRef} may also stand in for any value + * at any depth. Used for node inputs and outputs, edit values and expression results. + */ +export type ZenGraphValue = + | ZenTraceScalar + | ZenGraphValue[] + | ZenTraceRuns + | ZenTracePick + | ZenGraphValueObject + | ZenTraceLiteral + | ZenTraceRedacted + | ZenTraceOmittedValue + | ZenGraphRef; + +/** A plain object of graph values. Keys starting with `$` are tags, so they never appear here. */ +export interface ZenGraphValueObject { + [key: string]: ZenGraphValue; + [tag: `$${string}`]: never; +} + +/** + * An array splice `[at, deleteCount, ...insert]`, as in `Array.prototype.splice`. + * Like any list it may be packed. + */ +export type ZenTraceSplice = [number, number, ...ZenGraphValue[]] | ZenTraceRuns | ZenTracePick; + +/** + * Edits applied to a base value. They touch disjoint paths, so their order carries nothing. + */ +export interface ZenTraceEdits { + /** Set the value at each pointer. */ + $set?: ZenJsonPointerMap; + /** Delete these paths. */ + $delete?: ZenTraceList; + /** Splice the array at each pointer. */ + $splice?: ZenJsonPointerMap; + /** + * The same edit on every item of the array at each pointer: `$set` maps a pointer inside the + * item to one value per item. + * + * @example { "$each": { "/lines": { "$set": { "/total": [10, 20, 30] } } } } + */ + $each?: ZenJsonPointerMap<{ $set: ZenJsonPointerMap> }>; +} + +/** + * A node input written as edits against a base: + * - `$merge`: the merge of these earlier nodes' outputs at the same level, in order (objects + * merge key by key; anything else is replaced by the later value); + * - `$from: "request"` / `"null"`: the level's request, or `null`; + * - neither: the default input (see {@link ZenGraphNodeBase.input}). + * + * @example { "$merge": ["a", "b"], "$set": { "/flag": true } } + */ +export type ZenGraphInputBag = ZenTraceEdits & + ( + | { $merge: ZenTraceList; $from?: never } + | { $from: 'request' | 'null'; $merge?: never } + | { $merge?: never; $from?: never } + ); + +/** A node input: an operator bag, or the input itself as a value. */ +export type ZenGraphInput = ZenGraphInputBag | ZenGraphValue; + +/** + * Output bases every node offers: `input` (the node's input), `empty` (`{}`) and `null`. + */ +export type ZenGraphOutputBase = 'input' | 'empty' | 'null'; + +/** + * Output bases of an expression node, built from its `results` (keys sorted, dotted keys nested, + * placed at `resultsAt`): + * - `results`: the results alone; + * - `input+results`: the results merged over the node input; + * - `items+results`, `input+items+results` (loop mode): each item's results merged over its item. + */ +export type ZenGraphResultsBase = 'results' | 'input+results' | 'items+results' | 'input+items+results'; + +/** + * A node output written as edits against a base. Without `$from` the base is the node's + * default output (see each node type's `output`). + */ +export type ZenGraphOutputBag = ZenTraceEdits & { + /** The base, when it is not the node's default. */ + $from?: Base; +}; + +/** A node output: an operator bag, or the output itself as a value. */ +export type ZenGraphOutput = ZenGraphOutputBag | ZenGraphValue; + +/** + * A timing. An integer is nanoseconds and prints back the way the engine prints a `Duration` + * (`333` → `"333.0ns"`, `47200` → `"47.2µs"`). A string is a timing kept verbatim, and + * `{ value }` is a non-string timing kept verbatim. + */ +export type ZenTracePerf = number | string | { value: ZenTraceData }; + +/** The node kinds a `type` names. */ +export type ZenGraphNodeType = 'input' | 'output' | 'table' | 'expression' | 'switch' | 'function' | 'decision' | 'custom'; + +/** Fields every graph node record has. */ +export interface ZenGraphNodeBase { + /** The node's id (its key in the legacy trace). */ + id: string; + /** The node's name, when it differs from `id`. Absent: the name is the id. */ + name?: string; + /** + * The node kind. It selects the default output. The engine always writes it; a converted + * document leaves it out where the legacy trace does not tell (see {@link ZenGraphUntypedNode}). + */ + type?: ZenGraphNodeType; + /** Timing (see {@link ZenTracePerf}). Only absent in path shapes ({@link ZenGraphShapeNode}). */ + perf: ZenTracePerf; + /** + * The evaluation failed at this node, at every trace level the failure bubbled through. + * Its output is `null` unless `output` says otherwise. + */ + failed?: true; + /** The evaluation's error message, on the top-level failed node. */ + error?: string; + /** + * The node's input. Absent: the default. The first node of a level has input `null`; any other + * node merges the outputs of the open nodes (earlier nodes at this level whose output no later + * node has merged yet), in execution order, or takes the level's request when there are none. + */ + input?: ZenGraphInput; + /** + * The legacy trace's `traceData`, verbatim, for anything the record fields don't cover. When + * present it replaces the type-specific fields. + */ + details?: ZenTraceData; +} + +/** The input node. Its default output is the request. */ +export interface ZenGraphInputNode extends ZenGraphNodeBase { + type: 'input'; + /** Absent: the request (`$from: "request"`). */ + output?: ZenGraphOutput; + /** The node ran over an empty list. */ + loop?: []; +} + +/** An output node. Its default output is `null`. */ +export interface ZenGraphOutputNode extends ZenGraphNodeBase { + type: 'output'; + /** Absent: `null`. */ + output?: ZenGraphOutput; + /** The node ran over an empty list. */ + loop?: []; +} + +/** + * What one expression key evaluated to, as an id/key/value row. Rows are used instead of a map + * when a key repeats (requires `result-rows`); restoring reads them in order, the later row + * winning. + * + * @example { "id": "x1", "key": "v", "value": 2 } + */ +export interface ZenGraphResultRow { + /** The expression's id in the node content. */ + id: string; + /** The expression's key. */ + key: string; + /** What it evaluated to. */ + value: ZenGraphValue; +} + +/** What each expression key evaluated to. Keys are expression keys, not tags. */ +export interface ZenGraphResultMap { + [key: string]: ZenGraphValue; +} + +/** One run's results: a map, or rows (in evaluation order) when a key repeats. */ +export type ZenGraphRunResults = ZenGraphResultMap | ZenGraphResultRow[]; + +/** + * An expression node's results: + * - one run: a {@link ZenGraphResultMap}, or a list of {@link ZenGraphResultRow} (requires + * `result-rows`); + * - loop mode: one entry per item, each a map or a row list; omitted items appear as + * {@link ZenTraceOmittedIterations}. + */ +export type ZenGraphResults = + | ZenGraphRunResults + | ZenTraceList; + +/** + * An expression node. Its default output is built from `results` (base `results`); the + * expression values themselves are always stored, in `results`. + */ +export interface ZenGraphExpressionNode extends ZenGraphNodeBase { + type: 'expression'; + /** Absent: the results (`$from: "results"`), or `null` when the node failed. */ + output?: ZenGraphOutput; + /** What each expression evaluated to. */ + results?: ZenGraphResults; + /** + * Loop mode, in place of `results`, when the loop has at least two items and every item + * evaluated the same keys: `{ "": [value per item] }`. Item *k*'s results are + * `{ key: column[k] }` over the keys in this order. + * + * @example { "total": [10, 20, 30], "premium": [false, false, true] } + */ + resultColumns?: Record>; + /** The key that was being evaluated when the node failed. */ + failedKey?: string; + /** Where the results are placed in the output. Absent: at the root. */ + resultsAt?: ZenJsonPointer; + /** Loop mode: the list the node looped over, as a pointer into its input. */ + items?: ZenJsonPointer; + /** The node looped over an empty list. */ + loop?: []; +} + +/** + * A map keyed by user strings (rule cells, references), escaped as a whole: when any key starts + * with `$`, the map is written as `{ "$literal": map }`. + */ +export type ZenTraceKeyedData = ZenTraceDataObject | ZenTraceLiteral | ZenTraceRedacted | ZenTraceOmittedValue; + +/** + * A matched decision table row of a policy: its 0-based position, or the position with the + * rule's `_id` when the rule has one. + * + * @example { "index": 3, "id": "r3" } + */ +export type ZenPolicyRow = number | { index: number; id: string }; + +/** + * A matched table rule, as the legacy trace logged it. Its `reference_map` is derived from the + * scope (the input, `scope`, or the loop item) at each cell's field, then corrected by + * `references` and `referencesAbsent`. + * + * @example { "id": "r0", "cells": { "i0": ">= 18" }, "index": 0 } + */ +export interface ZenGraphRuleEntry { + /** The rule's `_id`, when the logged rule has a string `_id`. */ + id?: string; + /** + * The logged rule without its string `_id`. When the node has `inputs`, a key that is listed + * there is an input column id and stands for the logged key `"[]"`; any other + * key is the logged key as it is. + */ + cells: ZenTraceKeyedData; + /** The rule's position, as logged. */ + index: number; + /** In a loop: the 0-based item this entry belongs to, when it is not the next item. */ + item?: number; + /** `reference_map` entries whose value differs from the one read from the scope. */ + references?: ZenTraceKeyedData; + /** Fields a reader would derive that are missing from `reference_map`. */ + referencesAbsent?: ZenTraceList; + verbatim?: never; +} + +/** A logged table entry that does not have the usual `rule` / `reference_map` / `index` shape. */ +export interface ZenGraphVerbatimRuleEntry { + verbatim: ZenTraceData; +} + +/** A table entry. */ +export type ZenGraphTableEntry = ZenGraphRuleEntry | ZenGraphVerbatimRuleEntry; + +/** A decision table node. Its default output is its input; what it produced is in `output`. */ +export interface ZenGraphTableNode extends ZenGraphNodeBase { + type: 'table'; + /** Absent: the input. */ + output?: ZenGraphOutput; + /** The matched rule, when one entry was logged; `null` when the logged entry was `null`. */ + rule?: ZenGraphTableEntry | null; + /** + * A list of entries: with `items`, one per matched loop item; without, the matched rules of a + * collect table. + */ + rules?: ZenTraceList; + /** Loop-mode collect table: one list of entries per item. */ + rulesPerItem?: ZenTraceList>; + /** The part of the input the table worked on, as a pointer into the input. Absent: the whole input. */ + scope?: ZenJsonPointer; + /** Loop mode: the list the table looped over, as a pointer into the input. */ + items?: ZenJsonPointer; + /** + * The input columns of the rules listed in this record: `{ "": "" }`. Absent: + * rule cells are keyed by the logged `"[]"`. + * + * @example { "i0": "customer.age", "i1": "upper(customer.country)" } + */ + inputs?: ZenTraceKeyedData; + /** The table looped over an empty list. */ + loop?: []; +} + +/** A switch node. Its default output is its input. */ +export interface ZenGraphSwitchNode extends ZenGraphNodeBase { + type: 'switch'; + /** Absent: the input. */ + output?: ZenGraphOutput; + /** The ids of the statements taken, in order. */ + branches?: ZenTraceList; +} + +/** A function node. Its default output is `{}`; what it produced is in `output`. */ +export interface ZenGraphFunctionNode extends ZenGraphNodeBase { + type: 'function'; + /** Absent: `{}` (`$from: "empty"`). */ + output?: ZenGraphOutput; + /** Console output, when not empty. Absent: `[]`. */ + log?: ZenTraceList | ZenTraceRedacted | ZenTraceOmittedValue; +} + +/** + * A sub-decision node. It runs a nested trace on its own request: the input at `scope` (one run) + * or item `i` of the list at `items` (loop mode). Inside, `request` refers to that value. + */ +export interface ZenGraphDecisionNode extends ZenGraphNodeBase { + type: 'decision'; + /** Absent: the input. */ + output?: ZenGraphOutput; + /** One run: an inline trace, or a reference to a shared path shape. */ + sub?: ZenGraphSub; + /** Loop mode: one trace per item, in one of the {@link ZenGraphLoop} forms. */ + loop?: ZenGraphLoop; + /** The part of the input the sub-decision ran on. Absent: the whole input. */ + scope?: ZenJsonPointer; + /** Loop mode: the list it looped over, as a pointer into the input. */ + items?: ZenJsonPointer; +} + +/** A custom node. Its default output is its input; its trace data, if any, is in `details`. */ +export interface ZenGraphCustomNode extends ZenGraphNodeBase { + type: 'custom'; + /** Absent: the input. */ + output?: ZenGraphOutput; + /** The node ran over an empty list. */ + loop?: []; +} + +/** + * A node whose kind the document does not name. Converted documents leave `type` out for custom + * nodes, tables that matched nothing, failed nodes without trace data, and loops over an empty + * list. Its default output is its input, or `null` when it failed. + */ +export interface ZenGraphUntypedNode extends ZenGraphNodeBase { + type?: undefined; + /** Absent: the input. */ + output?: ZenGraphOutput; + /** The node ran over an empty list. */ + loop?: []; +} + +/** A graph node record, discriminated by `type`. */ +export type ZenGraphNode = + | ZenGraphInputNode + | ZenGraphOutputNode + | ZenGraphExpressionNode + | ZenGraphTableNode + | ZenGraphSwitchNode + | ZenGraphFunctionNode + | ZenGraphDecisionNode + | ZenGraphCustomNode + | ZenGraphUntypedNode; + +/** + * The records of one trace level, in execution order (a record's position is its `order`). + * In a truncated document the last element may be a {@link ZenTraceOmittedNodes} marker. + */ +export type ZenGraphNodeList = ZenGraphNode[] | [...ZenGraphNode[], ZenTraceOmittedNodes]; + +/** + * One trace level: the top-level graph, an inline sub-decision, or one loop iteration. + * `{ verbatim }` is a level kept as the legacy trace because it does not fit the record model. + */ +export type ZenGraphTrace = { nodes: ZenGraphNodeList; verbatim?: never } | ZenGraphVerbatimTrace; + +/** A trace level kept as the legacy trace (escaped). */ +export interface ZenGraphVerbatimTrace { + verbatim: ZenTraceData; + nodes?: never; +} + +/** + * A sub-decision node inside a path shape. Besides the usual forms, its `sub` and `loop` may + * refer to further shapes without timings of their own: their timings continue the enclosing + * row. + */ +export interface ZenGraphShapeDecisionNode extends Omit { + perf?: ZenTracePerf; + sub?: ZenGraphSub | ZenGraphNestedSub; + loop?: ZenGraphLoop | ZenGraphNestedLoop; +} + +/** + * A node record inside a path shape: like {@link ZenGraphNode}, but `perf` may be left out, in + * which case it is the next value of the enclosing timings row (depth-first node order). + */ +export type ZenGraphShapeNode = + | (Exclude extends infer N + ? N extends ZenGraphNode + ? Omit & { perf?: ZenTracePerf } + : never + : never) + | ZenGraphShapeDecisionNode; + +/** A path shape: a trace level without (some of) its timings, shared between iterations. */ +export type ZenGraphShape = { nodes: ZenGraphShapeNode[]; verbatim?: never } | ZenGraphVerbatimTrace; + +/** A path shape: an index into the body's `paths`, or the shape inline. */ +export type ZenGraphShapeRef = number | ZenGraphShape; + +/** One iteration's timings, in depth-first node order. */ +export type ZenGraphTimingRow = ZenTraceList; + +/** + * Loop timings, either form: + * - `timings`: one row per iteration; + * - `timingColumns`: the same table grouped by shape (iterations whose shape entries are equal + * as written), in order of first use, each group column-major: `[[col0, col1, …], …]`. + * Used when some group has at least 16 iterations. + */ +export type ZenGraphLoopTimings = + | { timings: ZenTraceList; timingColumns?: never } + | { timingColumns: ZenTraceList>>; timings?: never }; + +/** + * A packed loop with its own shapes: iteration `i` is `paths[iterationPaths[i]]` (or `paths[0]` + * for each of `iterations` iterations) with its timings filled in. + */ +export type ZenGraphLocalLoop = { paths: ZenTraceList; path?: never } & ( + | { iterations: number; iterationPaths?: never } + | { iterationPaths: ZenTraceList; iterations?: never } +) & + ZenGraphLoopTimings; + +/** + * The iterations of a loop over shared shapes: `path` for each of `iterations` iterations, or one + * shape per iteration in `iterationPaths`. Shape numbers index the body's `paths`. + */ +export type ZenGraphLoopShapes = { paths?: never } & ( + | { path: ZenGraphShapeRef; iterations: number; iterationPaths?: never } + | { iterationPaths: ZenTraceList; path?: never; iterations?: never } +); + +/** A loop over shared shapes (the deep form), with its timings. */ +export type ZenGraphDeepLoop = ZenGraphLoopShapes & ZenGraphLoopTimings; + +/** A loop over shared shapes inside a shape: its timings continue the enclosing row. */ +export type ZenGraphNestedLoop = ZenGraphLoopShapes & { timings?: never; timingColumns?: never }; + +/** + * A sub-decision in loop mode: one trace per item. + * - a list of iteration traces (omitted items as {@link ZenTraceOmittedIterations}); + * - {@link ZenGraphLocalLoop}: packed with the loop's own shapes; + * - {@link ZenGraphDeepLoop}: packed with the body's shared shapes. + * + * `[]` is a loop over an empty list. + */ +export type ZenGraphLoop = ZenTraceList | ZenGraphLocalLoop | ZenGraphDeepLoop; + +/** A one-run sub-decision written as a shared shape and its single timings row. */ +export interface ZenGraphDeepSub { + path: ZenGraphShapeRef; + timings: [ZenGraphTimingRow]; + nodes?: never; + verbatim?: never; +} + +/** A one-run sub-decision inside a shape: its timings continue the enclosing row. */ +export interface ZenGraphNestedSub { + path: ZenGraphShapeRef; + timings?: never; + nodes?: never; + verbatim?: never; +} + +/** A one-run sub-decision: an inline trace, or {@link ZenGraphDeepSub}. */ +export type ZenGraphSub = ZenGraphTrace | ZenGraphDeepSub; + +/** + * One intermediate expression value. + * - `{ expr, value }`: a sub-expression and its value; + * - `{ expr, values, at?, count? }`: a closure body, one value per item (capped; `count` is the + * full count, `at` the item positions when they are not 0, 1, 2, …); + * - `{ expr, error, errorAt? }`: the sub-expression failed. + */ +export interface ZenGraphStep { + /** The sub-expression's text. */ + expr: string; + value?: ZenTraceData; + values?: ZenTraceList; + at?: ZenTraceList; + count?: number; + error?: ZenTraceData; + errorAt?: number | number[]; + /** Documents written before steps dropped the whole expression: readers drop such a first step. */ + final?: true; +} + +/** The steps of one expression key, in source pre-order. */ +export type ZenGraphStepList = ZenTraceList; + +/** The steps of a key that produced no result (the node failed there; see `failedKey`). */ +export interface ZenGraphNoResultSteps { + steps: ZenGraphStepList; + noResult: true; +} + +/** + * The recorded intermediate values of one expression node. Keys of `keys`, `perItem` and + * `columns` are expression keys, or the rows' expression ids when the node's results are rows. + */ +export interface ZenGraphSteps { + /** The expression node's id. */ + node: string; + /** + * Where the node is: node ids, each followed by an iteration index when that node's trace data + * is a list, as a pointer. Absent: the top level. + */ + in?: ZenJsonPointer; + /** Single-run node: steps per expression key. */ + keys?: { [key: string]: ZenGraphStepList | ZenGraphNoResultSteps }; + /** Loop-mode node: per key, one step list (or `null`) per item. */ + perItem?: { [key: string]: ZenTraceList }; + /** Loop-mode node whose items all ran the same plain steps: per key, one value per item for each step. */ + columns?: { [key: string]: ZenTraceList<{ expr: string; values: ZenTraceList }> }; +} + +/** The body of a graph document. */ +export interface ZenGraphTraceV1Body { + /** The top-level node records, in execution order. */ + nodes: ZenGraphNodeList; + /** Shared path shapes, referenced by number from `path` and `iterationPaths`. */ + paths?: ZenTraceList; + /** Intermediate expression values. Requires `steps`. */ + steps?: ZenTraceList; + verbatim?: never; +} + +/** A graph document whose whole trace was kept verbatim (a fallback that does not occur in practice). */ +export interface ZenGraphTraceV1Verbatim extends ZenTraceEnvelope { + kind: 'graph'; + /** The legacy trace, escaped. */ + verbatim: ZenTraceData; + nodes?: never; +} + +/** A graph document with node records. */ +export interface ZenGraphTraceV1Records extends ZenTraceEnvelope, ZenGraphTraceV1Body { + kind: 'graph'; +} + +/** + * A version 1 graph trace. + * + * @example + * {"version":1,"kind":"graph","nodes":[ + * {"id":"input","type":"input","perf":333}, + * {"id":"plans","type":"table","perf":11700,"output":{"$set":{"/plan":{"feePct":0}}}, + * "rule":{"id":"r0","cells":{"risk.band[i0]":"'A', 'B'"},"index":0}}, + * {"id":"offer","type":"expression","perf":52600,"results":{"approved":true}}, + * {"id":"output","type":"output","perf":833}]} + */ +export type ZenGraphTraceV1 = ZenGraphTraceV1Records | ZenGraphTraceV1Verbatim; + +/** A policy block kind. */ +export type ZenPolicyBlockKind = 'expression' | 'match' | 'assertion' | 'decisionTable'; + +/** A field a policy body's `absent` can list. */ +export type ZenPolicyAbsentField = 'writes' | 'reads' | 'operands'; + +/** + * A policy `$ref`: the elements `items` of the list at a path in the running document (the + * request plus every earlier write) just before the block ran. A write stored this way holds + * live references to those elements. + * + * @example { "$ref": "current/shipment/vehicles", "items": [0, 1, 2] } + */ +export interface ZenPolicyRef { + $ref: 'current' | `current/${string}`; + items: ZenTraceList; +} + +/** A written value: user data, or a {@link ZenPolicyRef}. */ +export type ZenPolicyWriteValue = ZenTraceData | ZenPolicyRef; + +/** One write in a multi-write list. */ +export interface ZenPolicyWrite { + path: ZenJsonPointer; + value: ZenPolicyWriteValue; +} + +/** + * What a block wrote, every value explicit: `{ pointer: value }` for one write, a list in write + * order for several. + * + * @example { "/order/total": 250 } + */ +export type ZenPolicyWrites = ZenJsonPointerMap | ZenTraceList; + +/** A correction to a derived list of pointers. */ +export interface ZenPolicyListCorrection { + add?: ZenTraceList; + remove?: ZenTraceList; +} + +/** + * The paths a block read. + * - With `requires: ["documents"]`: absent means the reads derived from the documents; + * `{ add, remove }` corrects them; a list is the reads in full. + * - Without: a list, or `"previous"` when it equals the previous reads of the same block (and + * policy); absent means `[]`. + */ +export type ZenPolicyReads = ZenTraceList | 'previous' | ZenPolicyListCorrection; + +/** Decision table: per rule position (`"0"`, `"1"`, …), the input positions whose cells did not pass. */ +export interface ZenPolicyFailedCells { + [rule: `${number}`]: ZenTraceList; +} + +/** + * Legacy execution fields kept verbatim, under their legacy names, when the record fields can't + * express them. + */ +export interface ZenPolicyDetails { + /** The legacy block trace, whole. */ + trace?: ZenTraceData; + writes?: ZenTraceData; + operandValues?: ZenTraceData; + reads?: ZenTraceData; + matchedRows?: ZenTraceData; + extras?: ZenTraceData; + evaluations?: ZenTraceData; + /** Expression: the written property, when it is not the first write's path. */ + property?: string; + /** The block's value (an assertion's result), when it is not the first write's value. */ + value?: ZenTraceData; + /** Match: the matched arm's id, when it is not the first true arm. */ + matchedArm?: string | null; + /** Arm or condition ids, when they are not `:`. */ + ids?: ZenTraceList; + /** The whole legacy execution, when its paths can't be written as pointers. */ + execution?: ZenTraceData; +} + +/** Fields of an execution record that are not tied to the block kind. */ +export interface ZenPolicyExecutionFields { + /** + * What the block wrote, in write order. Absent: nothing (`[]`), unless `writesAbsent` (or the + * body's `absent`) says the legacy execution had no `writes` field at all. + */ + writes?: ZenPolicyWrites; + /** + * `true`: the legacy execution had no `writes`. `false`: it had them, though the body's + * `absent` lists `writes`. Absent: the body's default. + */ + writesAbsent?: boolean; + /** See {@link ZenPolicyReads}. */ + reads?: ZenPolicyReads; + /** + * `true`: the legacy execution had no `reads`. `false`: it had them, though the body's + * `absent` lists `reads`. Absent: the body's default. + */ + readsAbsent?: boolean; + /** Operand values that differ from the running document, by pointer. */ + storedOperands?: ZenJsonPointerMap; + /** Corrections to the derived operand names (the reads that have a value). */ + operandKeys?: ZenPolicyListCorrection; + /** + * `true`: the legacy execution had no `operandValues`. `false`: it had them, though the body's + * `absent` lists `operands`. Absent: the body's default. + */ + operandsAbsent?: boolean; + /** These operands (or all, `true`) are read from the document after the block's own write. */ + operandsAfterWrite?: true | ZenTraceList; + /** Execution fields the legacy format doesn't define, verbatim. */ + extraFields?: ZenTraceDataObject | ZenTraceLiteral; + /** Legacy fields kept verbatim. */ + details?: ZenPolicyDetails; +} + +/** Fields that place an execution: which block, where, from which policy. */ +export interface ZenPolicyExecutionHead { + /** The block id. */ + block?: string; + /** The policy that holds the block (legacy `policyPath`). */ + policy?: string; +} + +/** An expression block execution. Its trace (property and value) is its first write. */ +export interface ZenPolicyExpressionFields { + kind: 'expression'; +} + +/** A match block execution. Arm `n`'s id is `:`; the matched arm is the first true one. */ +export interface ZenPolicyMatchFields { + kind: 'match'; + /** Each arm's result, in order. */ + arms?: ZenTraceList; +} + +/** An assertion block execution. Condition `n`'s id is `:`. */ +export interface ZenPolicyAssertionFields { + kind: 'assertion'; + /** Each condition's result, in order. */ + conditions?: ZenTraceList; +} + +/** + * A decision table execution. `inputPass` is rebuilt from `ruleCount`, `inputCount` and + * `failedCells`; `evaluations` default to one map of every write when one row matched, `[]` when + * none did. + */ +export interface ZenPolicyDecisionTableFields { + kind: 'decisionTable'; + /** The matched rows (0-based rule positions). */ + rows?: ZenTraceList; + /** The number of rules. */ + ruleCount?: number; + /** The number of input columns. */ + inputCount?: number; + /** The input cells that did not pass. Absent: every cell passed. */ + failedCells?: ZenPolicyFailedCells; + /** The fields each matched row produced, one list per row, when it is not the default. */ + evaluations?: ZenTraceList>; + /** The fields whose value in `evaluations` is the next element of the written list. */ + collected?: ZenTraceList; +} + +/** An execution whose legacy trace did not fit the model: it is in `details.trace` (or `details.execution`). */ +export interface ZenPolicyUnknownKindFields { + kind?: undefined; +} + +/** The kind-specific fields of an execution, discriminated by `kind`. */ +export type ZenPolicyKindFields = + | ZenPolicyExpressionFields + | ZenPolicyMatchFields + | ZenPolicyAssertionFields + | ZenPolicyDecisionTableFields + | ZenPolicyUnknownKindFields; + +/** + * One block execution. + * + * @example {"block":"b3","kind":"match","arms":[false,false,true],"writes":{"/order/couponOff":0}} + */ +export type ZenPolicyExecution = ZenPolicyExecutionHead & + ZenPolicyExecutionFields & + ZenPolicyKindFields & { + /** The entity the block ran on (legacy `instancePath`). Absent: the root. */ + member?: ZenJsonPointer; + members?: never; + }; + +/** A member's fields in a run that could not be shared or put in a column. */ +export type ZenPolicyMemberFields = ZenPolicyExecutionFields & { + kind?: ZenPolicyBlockKind; + arms?: ZenTraceList; + conditions?: ZenTraceList; + rows?: ZenTraceList; + ruleCount?: number; + inputCount?: number; + failedCells?: ZenPolicyFailedCells; + evaluations?: ZenTraceList>; + collected?: ZenTraceList; +}; + +/** A column: one entry per member, `null` where a member has none. */ +export type ZenPolicyColumn = ZenTraceList; + +/** + * A run of one block over every member of a list: member `k` is `/`. Column fields + * hold one entry per member; any other field is shared by every member, and `perMember` holds + * what is neither. + * + * @example + * {"block":"band","kind":"decisionTable","members":"/customer/companies","rows":[[0],[1]], + * "ruleCount":2,"inputCount":1,"failedCells":[{"1":[0]},{"0":[0]}],"writes":{"/company/band":["low","high"]}} + */ +export interface ZenPolicyRun extends ZenPolicyExecutionHead, Omit { + /** The list the block ran over. */ + members: ZenJsonPointer; + member?: never; + /** The number of members, when it differs from the list's length at that moment. */ + count?: number; + /** The block kind, when it is the same for every member. */ + kind?: ZenPolicyBlockKind; + /** + * What each member wrote: `{ pointer: [value per member] }` for one write each, or one + * `{ path, values }` per write when every member wrote the same paths. + */ + writes?: + | ZenJsonPointerMap> + | ZenTraceList<{ path: ZenJsonPointer; values: ZenTraceList }>; + arms?: ZenPolicyColumn>; + conditions?: ZenPolicyColumn>; + rows?: ZenPolicyColumn>; + ruleCount?: number; + inputCount?: number; + failedCells?: ZenPolicyColumn; + evaluations?: ZenPolicyColumn>>; + collected?: ZenPolicyColumn>; + /** One object per member with that member's own fields. */ + perMember?: ZenTraceList; +} + +/** An execution record: one block execution, or a {@link ZenPolicyRun} over a list. */ +export type ZenPolicyExecutionRecord = ZenPolicyExecution | ZenPolicyRun; + +/** + * The legacy `properties`. Absent: derived from the top-level writes. + * - `{ set, remove }`: corrections to the derived properties, by pointer; + * - `{ verbatim }`: the legacy value; + * - `{ absent: true }`: the legacy trace had no `properties`. + */ +export type ZenPolicyProperties = + | { set?: ZenJsonPointerMap; remove?: ZenTraceList; verbatim?: never; absent?: never } + | { verbatim: ZenTraceData; set?: never; remove?: never; absent?: never } + | { absent: true; set?: never; remove?: never; verbatim?: never }; + +/** The body of a policy document. */ +export interface ZenPolicyTraceV1Body { + /** + * The fields most executions lack, in this order. Each listed field is absent in every record + * unless the record says `Absent: false`. Requires `absent-default`. Absent: no default. + */ + absent?: ZenPolicyAbsentField[]; + /** The execution records, in execution order. */ + executions: ZenTraceList; + /** See {@link ZenPolicyProperties}. */ + properties?: ZenPolicyProperties; + /** Top-level legacy trace fields other than `engineVersion`, `executions` and `properties`. */ + extraFields?: ZenTraceDataObject | ZenTraceLiteral; + verbatim?: never; +} + +/** A policy document whose whole trace was kept verbatim (a fallback that does not occur in practice). */ +export interface ZenPolicyTraceV1Verbatim extends ZenTraceEnvelope { + kind: 'policy'; + /** The legacy trace, escaped. */ + verbatim: ZenTraceData; + executions?: never; +} + +/** A policy document with execution records. */ +export interface ZenPolicyTraceV1Records extends ZenTraceEnvelope, ZenPolicyTraceV1Body { + kind: 'policy'; +} + +/** + * A version 1 policy trace. + * + * @example + * {"version":1,"kind":"policy","engine":"2.1.2","requires":["documents"],"executions":[ + * {"block":"b0","kind":"expression","member":"/order/items/0","writes":{"/item/lineTotal":200}}, + * {"block":"discount","kind":"decisionTable","rows":[3],"ruleCount":4,"inputCount":2, + * "failedCells":{"0":[0,1]},"writes":{"/order/discountRate":0}}]} + */ +export type ZenPolicyTraceV1 = ZenPolicyTraceV1Records | ZenPolicyTraceV1Verbatim; + export interface PolicyTrace { + /** Absent in the legacy shape; a version 1 document has `version: 1`. */ + version?: undefined; engineVersion: string; properties: Record; executions: PolicyBlockExecution[]; diff --git a/bindings/nodejs/src/convert.rs b/bindings/nodejs/src/convert.rs index f002e0bc2..8391a32e4 100644 --- a/bindings/nodejs/src/convert.rs +++ b/bindings/nodejs/src/convert.rs @@ -6,7 +6,7 @@ use napi::bindgen_prelude::ToNapiValue; use napi::sys; use napi::sys::{napi_env, napi_value}; use serde_json::Value; -use zen_engine::{DecisionGraphResponse, EvaluationTrace, EvaluationTraceKind}; +use zen_engine::{DecisionGraphResponse, EvaluationTrace}; use zen_expression::variable::{RcCell, ToVariable}; use zen_expression::Variable; @@ -95,7 +95,7 @@ pub struct NodeEvalResponse { } impl NodeEvalResponse { - pub fn build(response: DecisionGraphResponse, mode: EvaluationTraceKind) -> Self { + pub fn build(response: DecisionGraphResponse) -> Self { let mut arena = PortableArena::new(); let mut memo = HashMap::new(); @@ -104,23 +104,13 @@ impl NodeEvalResponse { let trace = match response.trace { None => TraceField::None, Some(EvaluationTrace::Graph(graph)) => { - let variable = graph.to_variable(); - match mode { - EvaluationTraceKind::Default => { - TraceField::Arena(arena.add(&variable, &mut memo)) - } - other => TraceField::Json(other.serialize_trace(&variable)), - } + TraceField::Arena(arena.add(&graph.to_variable(), &mut memo)) } Some(EvaluationTrace::Policy(policy)) => { - let value = match mode { - EvaluationTraceKind::String | EvaluationTraceKind::ReferenceString => { - Value::String(serde_json::to_string(&policy).unwrap_or_default()) - } - _ => serde_json::to_value(&policy).unwrap_or_default(), - }; - - TraceField::Json(value) + TraceField::Json(serde_json::to_value(&policy).unwrap_or_default()) + } + Some(EvaluationTrace::V1(document)) => { + TraceField::Arena(arena.add(&document.to_variable(), &mut memo)) } }; diff --git a/bindings/nodejs/src/decision.rs b/bindings/nodejs/src/decision.rs index 12edc8661..7b161afa7 100644 --- a/bindings/nodejs/src/decision.rs +++ b/bindings/nodejs/src/decision.rs @@ -30,8 +30,7 @@ impl ZenDecision { opts: Option, ) -> napi::Result { let decision = self.0.clone(); - let options: zen_engine::EvaluationSerializedOptions = - opts.unwrap_or_default().try_into()?; + let options: zen_engine::EvaluationOptions = opts.unwrap_or_default().try_into()?; let result = spawn_worker(move || async move { let context = zen_engine::Variable::try_from_value(context).map_err( |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), diff --git a/bindings/nodejs/src/engine.rs b/bindings/nodejs/src/engine.rs index 659a6454b..603d5b93c 100644 --- a/bindings/nodejs/src/engine.rs +++ b/bindings/nodejs/src/engine.rs @@ -24,9 +24,8 @@ use crate::safe_result::SafeResult; use crate::types::{ZenEngineHandlerRequest, ZenEngineHandlerResponse}; use zen_engine::loader::{DynamicLoader, LoaderConfig}; use zen_engine::model::DecisionContent; -use zen_engine::{ - DecisionEngine, EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind, -}; +use zen_engine::trace::TraceFormat; +use zen_engine::{DecisionEngine, EvaluationOptions, EvaluationSerializedOptions}; #[napi] pub struct ZenEngine { @@ -38,45 +37,32 @@ pub struct ZenEngine { } #[derive(Debug, Default)] -pub struct JsEvaluationTraceKind(pub EvaluationTraceKind); +pub struct JsTraceFormat(pub TraceFormat); -impl FromNapiValue for JsEvaluationTraceKind { +impl FromNapiValue for JsTraceFormat { unsafe fn from_napi_value(env: napi_env, napi_val: napi_value) -> napi::Result { let js_value = Unknown::from_napi_value(env, napi_val)?; match js_value.get_type()? { - ValueType::Undefined | ValueType::Null => Ok(JsEvaluationTraceKind::default()), - ValueType::Boolean => { - let enabled = js_value.coerce_to_bool()?; - let kind = match enabled { - true => EvaluationTraceKind::Default, - false => EvaluationTraceKind::None, - }; - - Ok(JsEvaluationTraceKind(kind)) - } + ValueType::Undefined | ValueType::Null => Ok(JsTraceFormat::default()), + ValueType::Boolean => Ok(JsTraceFormat(TraceFormat::from(js_value.coerce_to_bool()?))), ValueType::String => { - let kind_utf8 = js_value.coerce_to_string()?.into_utf8()?; - let kind_str = kind_utf8.as_str()?; - let kind = - EvaluationTraceKind::from_str(kind_str).context("invalid evaluation mode")?; - - Ok(JsEvaluationTraceKind(kind)) + let utf8 = js_value.coerce_to_string()?.into_utf8()?; + let format = + TraceFormat::from_str(utf8.as_str()?).context("invalid trace format")?; + Ok(JsTraceFormat(format)) } _ => Err(anyhow!("Invalid trace setting").into()), } } } -impl ToNapiValue for JsEvaluationTraceKind { +impl ToNapiValue for JsTraceFormat { unsafe fn to_napi_value(env: napi_env, val: Self) -> napi::Result { match val.0 { - EvaluationTraceKind::None => ToNapiValue::to_napi_value(env, false), - EvaluationTraceKind::Default => ToNapiValue::to_napi_value(env, true), - _ => { - let mode_str: &'static str = val.0.into(); - ToNapiValue::to_napi_value(env, mode_str) - } + TraceFormat::Off => ToNapiValue::to_napi_value(env, false), + TraceFormat::V1 => ToNapiValue::to_napi_value(env, true), + TraceFormat::Legacy => ToNapiValue::to_napi_value(env, "legacy"), } } } @@ -85,8 +71,8 @@ impl ToNapiValue for JsEvaluationTraceKind { #[napi(object)] pub struct ZenEvaluateOptions { pub max_depth: Option, - #[napi(ts_type = "boolean | 'string' | 'reference' | 'referenceString'")] - pub trace: Option, + #[napi(ts_type = "boolean | 'v1' | 'legacy'")] + pub trace: Option, #[napi(ts_type = "string | number")] pub now: Option>, pub timezone: Option, @@ -98,7 +84,7 @@ impl Default for ZenEvaluateOptions { fn default() -> Self { Self { max_depth: Some(5), - trace: Some(JsEvaluationTraceKind::default()), + trace: Some(JsTraceFormat::default()), now: None, timezone: None, seed: None, @@ -159,16 +145,6 @@ impl TryFrom for EvaluationSerializedOptions { } } -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, - } -} - #[napi(object)] pub struct EvaluateBatchRequest { pub key: String, @@ -313,24 +289,16 @@ impl ZenEngine { opts: Option, ) -> napi::Result { let graph = self.graph.clone(); - let serialized: EvaluationSerializedOptions = opts.unwrap_or_default().try_into()?; - let result = spawn_worker(move || { - let mode = serialized.trace; - let options = unserialized(&serialized); - - async move { - let context = zen_engine::Variable::try_from_value(context).map_err( - |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), - )?; - graph - .evaluate_with_opts(key, context, options) - .await - .map(|response| NodeEvalResponse::build(response, mode)) - .map_err(|e| { - e.serialize_with_mode(serde_json::value::Serializer, mode) - .unwrap_or_default() - }) - } + let options: EvaluationOptions = opts.unwrap_or_default().try_into()?; + let result = spawn_worker(move || async move { + let context = zen_engine::Variable::try_from_value(context).map_err( + |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), + )?; + graph + .evaluate_with_opts(key, context, options) + .await + .map(NodeEvalResponse::build) + .map_err(|e| serde_json::to_value(&*e).unwrap_or_default()) }) .await .map_err(|_| anyhow!("Hook timed out"))? @@ -402,14 +370,13 @@ impl ZenEngine { opts: Option, ) -> napi::Result> { let options: EvaluationSerializedOptions = opts.unwrap_or_default().try_into()?; - let mode = options.trace; 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 = unserialized(&options); + let eval_opts = options; let context = zen_engine::Variable::try_from_value(context).map_err( |e| serde_json::json!({ "type": "ContextError", "source": e.to_string() }), @@ -417,11 +384,8 @@ impl ZenEngine { engine .evaluate_with_opts(key, context, eval_opts) .await - .map(|response| NodeEvalResponse::build(response, mode)) - .map_err(|e| { - e.serialize_with_mode(serde_json::value::Serializer, mode) - .unwrap_or_default() - }) + .map(NodeEvalResponse::build) + .map_err(|e| serde_json::to_value(&*e).unwrap_or_default()) })); } diff --git a/bindings/nodejs/src/policy.rs b/bindings/nodejs/src/policy.rs index 5d3dc1564..0a9429c13 100644 --- a/bindings/nodejs/src/policy.rs +++ b/bindings/nodejs/src/policy.rs @@ -323,7 +323,8 @@ pub struct PolicyEvaluateRequest { #[napi(ts_type = "unknown")] pub input: Value, pub goals: Option>, - pub trace: Option, + #[napi(ts_type = "boolean | 'v1' | 'legacy'")] + pub trace: Option, } #[napi(object)] @@ -964,7 +965,7 @@ impl Workspace { policy_path: req.policy_path.into(), input: req.input.into(), goals: goals_to_arc(req.goals), - trace: req.trace.unwrap_or(false), + trace: req.trace.unwrap_or_default().0, }; Self::eval_to_value(self.inner.evaluate(&inner_req)) } @@ -975,7 +976,10 @@ impl Workspace { policy_path: req.policy_path.into(), input: req.input.into(), goals: goals_to_arc(req.goals), - trace: true, + trace: match req.trace.map(|t| t.0) { + Some(zen_engine::trace::TraceFormat::V1) => zen_engine::trace::TraceFormat::V1, + _ => zen_engine::trace::TraceFormat::Legacy, + }, }; Self::eval_to_value(self.inner.enhance_trace(&inner_req)) } diff --git a/bindings/nodejs/src/types.rs b/bindings/nodejs/src/types.rs index db05f420a..d5b72f0c3 100644 --- a/bindings/nodejs/src/types.rs +++ b/bindings/nodejs/src/types.rs @@ -40,6 +40,7 @@ impl From for ZenEngineTrace { pub struct ZenEngineResponse { pub performance: String, pub result: Value, + #[napi(ts_type = "ZenEngineResponseTrace | null")] pub trace: Option, ZenEngineTrace>>, } diff --git a/bindings/python/src/convert.rs b/bindings/python/src/convert.rs index acd844b9d..5efca143b 100644 --- a/bindings/python/src/convert.rs +++ b/bindings/python/src/convert.rs @@ -135,6 +135,9 @@ impl PortableResponse { Some(EvaluationTrace::Policy(policy)) => { PortableTrace::Json(serde_json::to_value(&policy).unwrap_or_default()) } + Some(EvaluationTrace::V1(document)) => { + PortableTrace::Arena(Self::add(&mut nodes, &mut memo, &document.to_variable())) + } }; Self { @@ -285,6 +288,7 @@ pub fn response_to_py(py: Python<'_>, response: DecisionGraphResponse) -> PyResu let value = serde_json::to_value(&policy).unwrap_or_default(); value_to_object(py, &value)? } + EvaluationTrace::V1(document) => converter.convert(&document.to_variable())?, }; dict.set_item("trace", trace_obj)?; diff --git a/bindings/python/src/engine.rs b/bindings/python/src/engine.rs index d1d8521fb..a6b347182 100644 --- a/bindings/python/src/engine.rs +++ b/bindings/python/src/engine.rs @@ -1,3 +1,4 @@ +use std::str::FromStr; use std::sync::Arc; use crate::content::PyZenDecisionContentJson; @@ -16,6 +17,7 @@ use pyo3_async_runtimes::{tokio, TaskLocals}; use pythonize::{depythonize, pythonize}; use serde_json::Value; use zen_engine::loader::{DynamicLoader, LoaderConfig}; +use zen_engine::trace::TraceFormat; use zen_engine::{DecisionEngine, EvaluationOptions}; #[pyclass] @@ -26,7 +28,7 @@ pub struct PyZenEngine { #[derive(Default)] pub struct PyZenEvaluateOptions { - pub trace: Option, + pub trace: Option, pub max_depth: Option, pub now: Option, pub timezone: Option, @@ -105,10 +107,21 @@ impl<'py> FromPyObject<'py> for PyZenEvaluateOptions { fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult { let dict = ob.downcast::()?; - let trace = dict - .get_item("trace")? - .map(|v| v.extract::()) - .transpose()?; + let trace = match dict.get_item("trace")? { + None => None, + Some(v) if v.is_none() => None, + Some(v) => match v.extract::() { + Ok(flag) => Some(TraceFormat::from(flag)), + Err(_) => { + let name = v.extract::()?; + Some(TraceFormat::from_str(&name).map_err(|_| { + pyo3::exceptions::PyValueError::new_err(format!( + "invalid trace format '{name}', expected true, false, 'v1' or 'legacy'" + )) + })?) + } + }, + }; let max_depth = dict .get_item("max_depth")? diff --git a/bindings/python/zen.pyi b/bindings/python/zen.pyi index e9251432d..b0f76cdd5 100644 --- a/bindings/python/zen.pyi +++ b/bindings/python/zen.pyi @@ -5,7 +5,7 @@ from typing import Any, Optional, TypedDict, Literal, TypeAlias, Union class DecisionEvaluateOptions(TypedDict, total=False): max_depth: int - trace: bool + trace: Union[bool, Literal["v1", "legacy"]] now: Union[int, str, datetime] timezone: str seed: Union[int, str] diff --git a/bindings/uniffi/src/engine.rs b/bindings/uniffi/src/engine.rs index 3bfefe832..00a6d58f2 100644 --- a/bindings/uniffi/src/engine.rs +++ b/bindings/uniffi/src/engine.rs @@ -46,7 +46,10 @@ impl From for EvaluationOptions { use zen_engine::context::{parse_instant, parse_timezone}; Self { max_depth: value.max_depth.unwrap_or(5), - trace: value.trace.unwrap_or(false), + trace: match value.trace.unwrap_or(false) { + true => zen_engine::trace::TraceFormat::Legacy, + false => zen_engine::trace::TraceFormat::Off, + }, now: value.now.as_deref().and_then(parse_instant), timezone: value.timezone.as_deref().and_then(parse_timezone), seed: value.seed, diff --git a/core/engine/Cargo.toml b/core/engine/Cargo.toml index a0b7372e1..c19292e3f 100644 --- a/core/engine/Cargo.toml +++ b/core/engine/Cargo.toml @@ -16,9 +16,11 @@ chrono = { workspace = true } ahash = { workspace = true } anyhow = { workspace = true } base64 = "0.22" +itoa = "1" +regex = { workspace = true } thiserror = { workspace = true } petgraph = { workspace = true } -serde_json = { workspace = true, features = [] } +serde_json = { workspace = true, features = ["raw_value"] } serde = { workspace = true, features = ["derive", "rc"] } serde_path_to_error = "0.1" strum = { workspace = true, features = ["derive"] } @@ -31,6 +33,7 @@ rquickjs = { version = "0.10", features = ["macro", "loader", "rust-alloc", "fut zen-types = { path = "../types", version = "2.1.6" } zen-expression = { path = "../expression", version = "2.1.6" } zen-tmpl = { path = "../template", version = "2.1.6" } +smallvec = { version = "1", features = ["union"] } nohash-hasher = { workspace = true } downcast-rs = { version = "2.0", features = ["std", "sync"] } arc-swap = "1" @@ -44,6 +47,7 @@ typed-arena = "2" self_cell = "1" [dev-dependencies] +serde_json = { workspace = true, features = ["unbounded_depth"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } criterion = { workspace = true, features = ["async_tokio"] } insta = { version = "1.43", features = ["yaml", "redactions"] } diff --git a/core/engine/examples/trace_corpus.rs b/core/engine/examples/trace_corpus.rs new file mode 100644 index 000000000..41636d796 --- /dev/null +++ b/core/engine/examples/trace_corpus.rs @@ -0,0 +1,481 @@ +use mimalloc::MiMalloc; +use std::collections::BTreeMap; +use std::io::{BufRead, BufReader, BufWriter, Write}; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::Instant; +use zen_engine::trace::testing::{convert_val_with, first_diff, parse, restore_val, Val}; +use zen_engine::trace::Status; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +struct Args { + corpus: PathBuf, + segment: String, + source: PathBuf, + poc: Option, + poc_nodocs: Option, + out: Option, + limit: usize, + no_docs: bool, + batch_mb: usize, +} + +fn args() -> Args { + let mut m: BTreeMap = BTreeMap::new(); + for a in std::env::args().skip(1) { + let a = a.trim_start_matches("--").to_string(); + match a.split_once('=') { + Some((k, v)) => m.insert(k.to_string(), v.to_string()), + None => m.insert(a, "1".to_string()), + }; + } + let corpus = PathBuf::from( + m.get("corpus") + .cloned() + .or_else(|| std::env::var("ZEN_TRACE_CORPUS").ok()) + .expect("--corpus or ZEN_TRACE_CORPUS"), + ); + let segment = m.get("segment").cloned().expect("--segment"); + let source = m + .get("legacy") + .map(PathBuf::from) + .unwrap_or_else(|| corpus.join(format!("{segment}.jsonl"))); + Args { + corpus, + segment, + source, + poc: m.get("poc").map(PathBuf::from), + poc_nodocs: m.get("poc-nodocs").map(PathBuf::from), + out: m.get("out").map(PathBuf::from), + limit: m + .get("limit") + .and_then(|t| t.parse().ok()) + .unwrap_or(usize::MAX), + no_docs: m.contains_key("no-docs"), + batch_mb: m + .get("batch-mb") + .and_then(|t| t.parse().ok()) + .unwrap_or(256), + } +} + +#[derive(Default, Clone)] +struct One { + id: String, + skipped: bool, + poc_precision_only: bool, + converted: bool, + reason: String, + round_trip: bool, + poc_restore: Option, + identical: Option, + rust_raw: usize, + poc_raw: usize, + today_raw: usize, + encode_ns: u128, + convert_ns: u128, + restore_ns: u128, + v1: String, + nd: Option, + failure: Option, +} + +#[derive(Default, Clone)] +struct NoDocs { + poc_precision_only: bool, + converted: bool, + round_trip: bool, + poc_restore: Option, + identical: Option, + rust_raw: usize, + poc_raw: usize, + v1: String, +} + +fn release_text( + corpus: &std::path::Path, + id: &str, + cache: &Mutex>>, +) -> std::sync::Arc { + if let Some(t) = cache.lock().unwrap().get(id) { + return t.clone(); + } + let t = std::sync::Arc::new( + std::fs::read_to_string(corpus.join("releases").join(format!("{id}.json"))) + .expect("release"), + ); + cache.lock().unwrap().insert(id.to_string(), t.clone()); + t +} + +fn poc_text(line: &str) -> (String, String) { + let v = parse(line).expect("poc line"); + ( + v.get("id") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(), + v.get("v1") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(), + ) +} + +fn f64_of(d: &rust_decimal::Decimal) -> f64 { + d.to_string().parse().unwrap_or(f64::NAN) +} + +fn eq_f64(a: &Val, b: &Val) -> bool { + match (a, b) { + (Val::Num(x), Val::Num(y)) => f64_of(x) == f64_of(y), + (Val::Arr(x), Val::Arr(y)) => { + x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| eq_f64(p, q)) + } + (Val::Obj(x), Val::Obj(y)) => { + x.len() == y.len() + && x.iter() + .all(|(k, v)| y.get(k).is_some_and(|w| eq_f64(v, w))) + } + _ => zen_engine::trace::testing::eq(a, b), + } +} + +fn check( + a: &Args, + line: &str, + poc: Option<&str>, + poc_nd: Option<&str>, + cache: &Mutex>>, +) -> One { + let rec = match parse(line) { + Ok(r) => r, + Err(e) => { + let id = line + .split("\"id\":\"") + .nth(1) + .and_then(|r| r.split('"').next()) + .unwrap_or("?") + .to_string(); + return One { + id: id.clone(), + skipped: true, + failure: Some(format!("{id}: not readable as Zen numbers: {e}")), + ..Default::default() + }; + } + }; + let id = rec + .get("id") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(); + let request = rec.get("request").cloned().unwrap_or(Val::Null); + let trace = rec.get("trace").cloned().unwrap_or(Val::Null); + let error = rec.get("error").filter(|e| e.is_obj()).map(|e| { + ( + e.get("node") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(), + e.get("message") + .and_then(|x| x.as_str()) + .map(|x| x.to_string()), + ) + }); + let err = error.as_ref().map(|(n, m)| (n.as_str(), m.as_deref())); + let is_policy = trace.get("executions").is_some_and(|e| e.is_arr()); + let docs = if is_policy { + rec.get("release") + .and_then(|r| r.as_str()) + .map(|r| parse(&release_text(&a.corpus, r, cache)).expect("release json")) + } else { + None + }; + let mut one = One { + id: id.clone(), + ..Default::default() + }; + one.today_raw = line.len(); + let t0 = Instant::now(); + let _ = convert_val_with(&trace, &request, err, None, docs.as_ref(), false); + one.encode_ns = t0.elapsed().as_nanos(); + let t0 = Instant::now(); + let (text, status) = convert_val_with(&trace, &request, err, None, docs.as_ref(), true); + one.convert_ns = t0.elapsed().as_nanos(); + one.converted = status == Status::Converted; + if let Status::Verbatim { reason } = &status { + one.reason = reason.clone(); + one.failure = Some(format!("{id}: verbatim: {reason}")); + } + let t0 = Instant::now(); + let back = restore_val(&text, &request, docs.as_ref()); + one.restore_ns = t0.elapsed().as_nanos(); + match back { + Ok(b) => match first_diff(&trace, &b) { + None => one.round_trip = true, + Some(d) => one.failure = Some(format!("{id}: rust restore differs at {d}")), + }, + Err(e) => one.failure = Some(format!("{id}: rust restore failed: {e}")), + } + one.rust_raw = text.len(); + if let Some(p) = poc { + let (pid, ptext) = poc_text(p); + assert_eq!(pid, id, "poc file out of order"); + one.poc_raw = ptext.len(); + one.identical = Some(ptext == text); + match restore_val(&ptext, &request, docs.as_ref()) { + Ok(b) => match first_diff(&trace, &b) { + None => one.poc_restore = Some(true), + Some(d) => { + one.poc_restore = Some(false); + one.poc_precision_only = eq_f64(&trace, &b); + if !one.poc_precision_only { + one.failure + .get_or_insert(format!("{id}: restore of poc text differs at {d}")); + } + } + }, + Err(e) => { + one.poc_restore = Some(false); + one.failure + .get_or_insert(format!("{id}: restore of poc text failed: {e}")); + } + } + } + if a.no_docs && is_policy { + let (t2, s2) = convert_val_with(&trace, &request, err, None, None, true); + let mut nd = NoDocs { + converted: s2 == Status::Converted, + ..Default::default() + }; + nd.round_trip = + restore_val(&t2, &request, None).is_ok_and(|b| first_diff(&trace, &b).is_none()); + nd.rust_raw = t2.len(); + if let Some(p) = poc_nd { + let (pid, ptext) = poc_text(p); + assert_eq!(pid, id, "poc no-docs file out of order"); + nd.poc_raw = ptext.len(); + nd.identical = Some(ptext == t2); + let back = restore_val(&ptext, &request, None); + nd.poc_restore = Some(back.as_ref().is_ok_and(|b| first_diff(&trace, b).is_none())); + nd.poc_precision_only = + nd.poc_restore == Some(false) && back.as_ref().is_ok_and(|b| eq_f64(&trace, b)); + } + if !(nd.converted + && nd.round_trip + && (nd.poc_restore != Some(false) || nd.poc_precision_only)) + { + one.failure.get_or_insert(format!( + "{id}: without documents: converted {} round trip {} poc {:?}", + nd.converted, nd.round_trip, nd.poc_restore + )); + } + nd.v1 = t2; + one.nd = Some(nd); + } + one.v1 = text; + one +} + +#[derive(Default)] +struct Sum { + traces: usize, + skipped: usize, + poc_precision_only: usize, + converted: usize, + round_trip: usize, + poc_checked: usize, + poc_restore: usize, + identical: usize, + rust_raw: usize, + poc_raw: usize, + today_raw: usize, + encode_ns: u128, + convert_ns: u128, + restore_ns: u128, + max_convert_ns: u128, + max_convert_id: String, + nd_traces: usize, + nd_precision_only: usize, + nd_ok: usize, + nd_poc_restore: usize, + nd_identical: usize, + nd_rust_raw: usize, + nd_poc_raw: usize, + failures: Vec, + verbatim: BTreeMap, +} + +fn main() { + let a = args(); + let src = BufReader::with_capacity(1 << 24, std::fs::File::open(&a.source).expect("source")); + let mut poc = a + .poc + .as_ref() + .map(|p| BufReader::with_capacity(1 << 22, std::fs::File::open(p).expect("poc")).lines()); + let mut poc_nd = a.poc_nodocs.as_ref().map(|p| { + BufReader::with_capacity(1 << 22, std::fs::File::open(p).expect("poc nodocs")).lines() + }); + let mut out = a + .out + .as_ref() + .map(|p| BufWriter::new(std::fs::File::create(p).expect("out"))); + let cache = Mutex::new(BTreeMap::new()); + let mut sum = Sum::default(); + let wall = Instant::now(); + let mut lines = src.lines(); + let mut n = 0usize; + loop { + let mut batch: Vec<(String, Option, Option)> = Vec::new(); + let mut bytes = 0usize; + while batch.len() < 256 && bytes < (a.batch_mb << 20) && n < a.limit { + let Some(l) = lines.next() else { break }; + let l = l.expect("line"); + if l.is_empty() { + continue; + } + n += 1; + bytes += l.len(); + let p = poc + .as_mut() + .and_then(|p| p.next()) + .map(|x| x.expect("poc line")); + let pn = poc_nd + .as_mut() + .and_then(|p| p.next()) + .map(|x| x.expect("poc line")); + batch.push((l, p, pn)); + } + if batch.is_empty() { + break; + } + let results: Vec = batch + .iter() + .map(|(l, p, pn)| check(&a, l, p.as_deref(), pn.as_deref(), &cache)) + .collect(); + for r in results { + if r.skipped { + sum.skipped += 1; + if let Some(f) = &r.failure { + sum.failures.push(f.clone()); + } + continue; + } + sum.traces += 1; + sum.poc_precision_only += r.poc_precision_only as usize; + sum.converted += r.converted as usize; + sum.round_trip += r.round_trip as usize; + if let Some(ok) = r.poc_restore { + sum.poc_checked += 1; + sum.poc_restore += ok as usize; + } + sum.identical += r.identical.unwrap_or(false) as usize; + sum.rust_raw += r.rust_raw; + sum.poc_raw += r.poc_raw; + sum.today_raw += r.today_raw; + sum.encode_ns += r.encode_ns; + sum.convert_ns += r.convert_ns; + sum.restore_ns += r.restore_ns; + if r.convert_ns > sum.max_convert_ns { + sum.max_convert_ns = r.convert_ns; + sum.max_convert_id = r.id.clone(); + } + if !r.converted { + *sum.verbatim + .entry(r.reason.chars().take(80).collect()) + .or_default() += 1; + } + if let Some(f) = &r.failure { + if sum.failures.len() < 20 { + sum.failures.push(f.chars().take(400).collect()); + } + } + if let Some(nd) = &r.nd { + sum.nd_traces += 1; + sum.nd_precision_only += nd.poc_precision_only as usize; + sum.nd_ok += (nd.converted && nd.round_trip) as usize; + sum.nd_poc_restore += nd.poc_restore.unwrap_or(false) as usize; + sum.nd_identical += nd.identical.unwrap_or(false) as usize; + sum.nd_rust_raw += nd.rust_raw; + sum.nd_poc_raw += nd.poc_raw; + } + if let Some(o) = out.as_mut() { + let mut line = format!( + "{{\"id\":{},\"v1\":{}", + Val::str(&r.id).to_json(), + Val::str(&r.v1).to_json() + ); + if let Some(nd) = &r.nd { + line.push_str(&format!(",\"v1NoDocs\":{}", Val::str(&nd.v1).to_json())); + } + line.push('}'); + writeln!(o, "{line}").unwrap(); + } + } + } + let t = sum.traces.max(1) as f64; + let ms = |ns: u128| ns as f64 / 1e6 / t; + let pct = |a: usize, b: usize| { + if b == 0 { + 0.0 + } else { + (a as f64 / b as f64 - 1.0) * 100.0 + } + }; + let mut report = format!( + "{{\"segment\":\"{}\",\"skipped\":{},\"pocDiffersOnlyBeyondDoublePrecision\":{},\"traces\":{},\"converted\":{},\"verbatim\":{},\"roundTrip\":{},\"pocChecked\":{},\"restoreOfPocText\":{},\"byteIdentical\":{},\ +\"bytesPerTrace\":{{\"rustRaw\":{:.1},\"pocRaw\":{:.1},\"todayRaw\":{:.1},\"rawVsPocPct\":{:.3}}},\ +\"msPerTrace\":{{\"encode\":{:.4},\"convertWithVerify\":{:.4},\"restore\":{:.4},\"maxConvert\":{:.1},\"maxConvertId\":\"{}\"}},\"wallSeconds\":{:.1}", + a.segment, + sum.skipped, + sum.poc_precision_only, + sum.traces, + sum.converted, + sum.traces - sum.converted, + sum.round_trip, + sum.poc_checked, + sum.poc_restore, + sum.identical, + sum.rust_raw as f64 / t, + sum.poc_raw as f64 / t, + sum.today_raw as f64 / t, + pct(sum.rust_raw, sum.poc_raw), + ms(sum.encode_ns), + ms(sum.convert_ns), + ms(sum.restore_ns), + sum.max_convert_ns as f64 / 1e6, + sum.max_convert_id, + wall.elapsed().as_secs_f64() + ); + if sum.nd_traces > 0 { + let tn = sum.nd_traces as f64; + report.push_str(&format!( + ",\"withoutDocuments\":{{\"traces\":{},\"ok\":{},\"pocDiffersOnlyBeyondDoublePrecision\":{},\"restoreOfPocText\":{},\"byteIdentical\":{},\"rustRaw\":{:.1},\"pocRaw\":{:.1}}}", + sum.nd_traces, + sum.nd_ok, + sum.nd_precision_only, + sum.nd_poc_restore, + sum.nd_identical, + sum.nd_rust_raw as f64 / tn, + sum.nd_poc_raw as f64 / tn + )); + } + let fails: Vec = sum.failures.iter().map(|f| Val::str(f).to_json()).collect(); + let verb: Vec = sum + .verbatim + .iter() + .map(|(k, v)| format!("{}:{}", Val::str(k).to_json(), v)) + .collect(); + report.push_str(&format!( + ",\"verbatimReasons\":{{{}}},\"failures\":[{}]}}", + verb.join(","), + fails.join(",") + )); + println!("{report}"); + if let Some(o) = out.as_mut() { + o.flush().unwrap(); + } +} diff --git a/core/engine/src/compiled/bound.rs b/core/engine/src/compiled/bound.rs index 5dc607823..2b7a7b876 100644 --- a/core/engine/src/compiled/bound.rs +++ b/core/engine/src/compiled/bound.rs @@ -1,4 +1,5 @@ use crate::compiled::core::special::Specialized; +use crate::compiled::trace::record::Probe; use std::cell::RefCell; use std::rc::Rc; use zen_expression::context::EvaluationContext; @@ -24,6 +25,7 @@ pub(crate) struct Bound<'a> { pub scopes: Scopes, pub columns: Columns<'a>, pub bind: Box Binding + 'a>, + pub probe: Option>, } pub(crate) struct Outs(Vec); @@ -100,6 +102,14 @@ impl<'a> Bound<'a> { scopes: Scopes::Owned(scopes), columns: Columns::new(rows), bind: Box::new(|_| Binding::Row), + probe: None, + } + } + + pub fn probed(self, probe: Option<&Rc>) -> Self { + Self { + probe: probe.cloned(), + ..self } } diff --git a/core/engine/src/compiled/decision.rs b/core/engine/src/compiled/decision.rs index 10e55079b..2ae233fde 100644 --- a/core/engine/src/compiled/decision.rs +++ b/core/engine/src/compiled/decision.rs @@ -60,7 +60,7 @@ impl CompiledDecision { input: Variable, options: EvaluationOptions, ) -> Result> { - let context = pinning::single(options.pinned()); + let context = pinning::single(&options); self.evaluate_with_opts(input, options, &context).await } @@ -69,7 +69,7 @@ impl CompiledDecision { contexts: &[Variable], options: EvaluationOptions, ) -> Vec>> { - let context = pinning::batch(options.pinned()); + let context = pinning::batch(&options); self.evaluate_batch(contexts, options, &context).await } @@ -78,17 +78,32 @@ impl CompiledDecision { columns: &'a Columns<'a>, options: EvaluationOptions, ) -> ColumnarOutput<'a> { - let context = pinning::batch(options.pinned()); + let context = pinning::batch(&options); self.evaluate_columns(columns, options, &context).await } + pub(crate) async fn trace_pair_pinned( + &self, + input: Variable, + ) -> Option<( + crate::compiled::trace::TraceDocument, + crate::compiled::trace::TraceDocument, + )> { + let options = EvaluationOptions { + trace: crate::compiled::trace::TraceFormat::V1, + ..Default::default() + }; + let context = pinning::single(&options); + self.trace_pair(input, &context).await + } + pub(crate) async fn evaluate_with_opts( &self, input: Variable, options: EvaluationOptions, context: &EvaluationContext, ) -> Result> { - if options.trace { + if options.trace.is_on() { return self.traced(input, options, context).await; } @@ -109,16 +124,25 @@ impl CompiledDecision { contexts: &[Variable], options: EvaluationOptions, context: &EvaluationContext, + ) -> Vec>> { + self.evaluate_batched(contexts, options, context).await + } + + async fn evaluate_batched( + &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 (row, input) in owned.into_iter().enumerate() { - responses.push( - Box::pin(self.evaluate_with_opts(input, options, &context.at(row))).await, - ); - } - return responses; + if options.trace.is_on() { + let start = std::time::Instant::now(); + return match self.traced_batch(&owned, contexts, options, context).await { + Ok((results, batch)) => { + batch.responses(results, &format!("{:.1?}", start.elapsed())) + } + Err(invalid) => owned.iter().map(|_| Err(invalid.evaluation())).collect(), + }; } match Self::compiled(self.prepared()) { @@ -143,6 +167,55 @@ impl CompiledDecision { options: EvaluationOptions, context: &EvaluationContext, ) -> ColumnarOutput<'a> { + self.evaluate_columned(columns, options, context).await + } + + async fn evaluate_columned<'a>( + &self, + columns: &'a Columns<'a>, + options: EvaluationOptions, + context: &EvaluationContext, + ) -> ColumnarOutput<'a> { + if options.trace.is_on() { + if let Ok((compiled, content)) = Self::compiled(self.prepared()) { + let content = compiled.schemas(content, &self.loader).await; + if let Some(output) = compiled + .evaluate_columns_traced( + &content, + &self.extensions(&content, context), + options.max_depth, + columns, + options.trace, + ) + .await + { + crate::compiled::trace::count_columnar(true, columns.rows); + return output; + } + } + crate::compiled::trace::count_columnar(false, columns.rows); + context.reset(); + let contexts: Vec = (0..columns.rows).map(|row| columns.row(row)).collect(); + let owned: Vec = contexts.iter().map(Variable::deep_clone).collect(); + return match self.traced_batch(&owned, &contexts, options, context).await { + Ok((results, batch)) => { + let results = results + .into_iter() + .map(|result| { + result.map(|result| DecisionGraphResponse { + performance: String::new(), + result, + trace: None, + }) + }) + .collect(); + ColumnarOutput::from_results(results).traced_rows(batch) + } + Err(invalid) => ColumnarOutput::from_results( + owned.iter().map(|_| Err(invalid.evaluation())).collect(), + ), + }; + } match Self::compiled(self.prepared()) { Ok((compiled, content)) => { let content = compiled.schemas(content, &self.loader).await; @@ -159,21 +232,69 @@ impl CompiledDecision { let contexts: Vec = (0..columns.rows).map(|row| columns.row(row)).collect(); let options = EvaluationOptions { - trace: false, + trace: crate::compiled::trace::TraceFormat::Off, ..options }; - let results = Box::pin(self.evaluate_batch(&contexts, options, context)).await; + let results = Box::pin(self.evaluate_batched(&contexts, options, context)).await; ColumnarOutput::from_results(results) } } } + pub(crate) async fn traced_batch( + &self, + owned: &[Variable], + requests: &[Variable], + options: EvaluationOptions, + context: &EvaluationContext, + ) -> Result< + ( + Vec>>, + crate::compiled::trace::TraceBatch<'static>, + ), + &Invalid, + > { + let (compiled, content) = Self::compiled(self.prepared())?; + let content = compiled.schemas(content, &self.loader).await; + let (results, traces) = compiled + .traced_batch( + &content, + &self.extensions(&content, context), + options.max_depth, + owned, + requests, + ) + .await; + let batch = crate::compiled::trace::TraceBatch::new( + traces, + requests.to_vec(), + owned.to_vec(), + &results, + options.trace, + context, + ); + Ok((results, batch)) + } + async fn traced( &self, input: Variable, options: EvaluationOptions, context: &EvaluationContext, ) -> Result> { + let start = std::time::Instant::now(); + let request = crate::compiled::trace::Request::wanted(options.trace, &input); + let run = self.run(input, options.max_depth, context).await?; + let evaluation = pinning::evaluation(context); + crate::compiled::trace::collected(options.trace, request, run, start, Some(&evaluation)) + } + + async fn run( + &self, + input: Variable, + max_depth: u8, + 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, context); @@ -181,11 +302,25 @@ impl CompiledDecision { graph: compiled, content: &content, extensions: &extensions, - max_depth: options.max_depth, + max_depth, iteration: 0, parent: None, }; - traced.evaluate(input).await + Ok(traced.run(input).await) + } + + pub(crate) async fn trace_pair( + &self, + input: Variable, + context: &EvaluationContext, + ) -> Option<( + crate::compiled::trace::TraceDocument, + crate::compiled::trace::TraceDocument, + )> { + let request = crate::compiled::trace::Request::take(&input); + let run = self.run(input, 10, context).await.ok()?; + let evaluation = pinning::evaluation(context); + crate::compiled::trace::pair(request, run, Some(&evaluation)) } fn prepared(&self) -> (&Arc, &CompiledPlan) { diff --git a/core/engine/src/compiled/engine.rs b/core/engine/src/compiled/engine.rs index faf3d0394..bbd4b3b9d 100644 --- a/core/engine/src/compiled/engine.rs +++ b/core/engine/src/compiled/engine.rs @@ -2,7 +2,6 @@ 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}; @@ -12,9 +11,7 @@ use crate::nodes::custom::DynamicCustomNode; use crate::nodes::function::http_handler::DynamicHttpHandler; use crate::policy::raw::PolicyDocument; use crate::workspace::db::Db; -use crate::workspace::types::{ - EvaluateRequest, EvaluationError as PolicyEvaluationError, Severity, -}; +use crate::workspace::{EvaluateRequest, EvaluationError as PolicyEvaluationError, Severity}; use crate::EvaluationError; use ahash::{HashMap, HashSet, HashSetExt}; use arc_swap::ArcSwapOption; @@ -80,7 +77,7 @@ impl Caches { .into_iter() .any(|d| d.severity == Severity::Error); if !blocked { - let artifact = Artifact::new(db.eval_artifact(key), InputSchema::of(&db, key)); + let artifact = Artifact::new(&db, key, db.eval_artifact(key)); entries.insert(key.clone(), Entry::Policy(Arc::new(artifact))); } } @@ -117,7 +114,7 @@ impl Caches { input: Variable, options: EvaluationOptions, ) -> LoaderResult>> { - let context = pinning::single(options.pinned()); + let context = pinning::single(&options); self.evaluate(parts, key, input, options, &context).await } @@ -128,7 +125,7 @@ impl Caches { input: Variable, options: EvaluationSerializedOptions, ) -> Result { - let context = pinning::single(options.pinned()); + let context = pinning::single(&options); self.evaluate_serialized(parts, key, input, options, &context) .await } @@ -140,7 +137,7 @@ impl Caches { contexts: &[Variable], options: EvaluationOptions, ) -> Vec>> { - let context = pinning::batch(options.pinned()); + let context = pinning::batch(&options); self.evaluate_batch(parts, key, contexts, options, &context) .await } @@ -188,11 +185,8 @@ impl Caches { options: EvaluationSerializedOptions, context: &EvaluationContext, ) -> Result { - match self - .evaluate(parts, key, input, options.unserialized(), context) - .await - { - Ok(response) => Responses::serialized(response, options.trace), + match self.evaluate(parts, key, input, options, context).await { + Ok(response) => Responses::serialized(response), Err(err) => Err(Value::String(err.to_string())), } } @@ -285,8 +279,9 @@ impl Caches { .any(|d| d.severity == Severity::Error); (!blocked).then(|| { Arc::new(Artifact::new( + &db, + &entry_path, db.eval_artifact(&entry_path), - InputSchema::of(&db, &entry_path), )) }) }); diff --git a/core/engine/src/compiled/exact/graph/expression.rs b/core/engine/src/compiled/exact/graph/expression.rs index f370450fc..a54ccbd5b 100644 --- a/core/engine/src/compiled/exact/graph/expression.rs +++ b/core/engine/src/compiled/exact/graph/expression.rs @@ -1,50 +1,49 @@ -use super::{Ctx, Row}; -use crate::compiled::host::expression::ExpressionNodeTrace; -use crate::compiled::host::graph::tracer::ExpressionNodeTraceItem; +use super::Row; use crate::compiled::host::NodeResult; use crate::compiled::pinning::Located; -use std::rc::Rc; +use std::sync::Arc; use zen_expression::variable::Variable; use zen_types::decision::ExpressionNodeContent; impl Row<'_> { pub(crate) fn expression(self, content: &ExpressionNodeContent) -> NodeResult { - let mut ctx = Ctx::::new(self); let result = Variable::empty_object(); - let mut session = ctx.row.session(); + let mut session = self.session(); + let mut results: Option, Variable)>> = self.traced().then(Vec::new); for expression in content.expressions.iter() { if expression.key.is_empty() || expression.value.is_empty() { continue; } - session.locate(Located::expression(ctx.row.id, &expression.key)); + session.locate(Located::expression(self.id, &expression.key)); let value = match session.run_standard(&expression.value) { Ok(value) => value, Err(_) => { - return Err(ctx.error(crate::compiled::exact::Failure::expression( + if let Some(results) = results { + self.record(|recorder| recorder.expression(results)); + } + return Err(self.error(crate::compiled::exact::Failure::expression( &expression.value, - ))) + ))); } }; let value = match expression.value.contains('$') { true => value.deep_clone(), false => value, }; - ctx.trace(|trace| { - trace.insert( - Rc::from(&*expression.key), - ExpressionNodeTraceItem { - result: value.clone(), - }, - ); - }); + if let Some(results) = results.as_mut() { + results.push((expression.key.clone(), value.clone())); + } session.insert_dollar(&expression.key, value.clone()); result.dot_insert(&expression.key, value); } - ctx.success(result) + if let Some(results) = results { + self.record(|recorder| recorder.expression(results)); + } + self.success(result) } } diff --git a/core/engine/src/compiled/exact/graph/mod.rs b/core/engine/src/compiled/exact/graph/mod.rs index c52af82e9..44bb43427 100644 --- a/core/engine/src/compiled/exact/graph/mod.rs +++ b/core/engine/src/compiled/exact/graph/mod.rs @@ -9,24 +9,21 @@ 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_expression::variable::Variable; use zen_types::decision::{DecisionNode, DecisionNodeKind, TransformAttributes}; +pub(crate) use crate::compiled::trace::record::NodeRecorder; + #[derive(Clone)] pub(crate) struct Row<'a> { pub(crate) id: &'a Arc, pub(crate) input: Variable, pub(crate) nodes: Option, pub(crate) programs: Option<&'a Arc>, - pub(crate) trace: bool, + pub(crate) recorder: Option<&'a NodeRecorder>, pub(crate) context: EvaluationContext, } -pub(crate) struct Ctx<'a, T> { - pub(crate) row: Row<'a>, - pub(crate) trace: Option, -} - impl<'a> Row<'a> { pub(crate) fn session(&self) -> Session { let mut session = Session::with_environment(self.input.clone()) @@ -102,32 +99,25 @@ impl<'a> Row<'a> { } } -impl<'a, T: Default + ToVariable> Ctx<'a, T> { - pub(crate) fn new(row: Row<'a>) -> Self { - Self { - trace: row.trace.then(T::default), - row, - } +impl Row<'_> { + pub(crate) fn traced(&self) -> bool { + self.recorder.is_some() } - pub(crate) fn trace(&mut self, mutator: impl FnOnce(&mut T)) { - if let Some(trace) = &mut self.trace { - mutator(trace); + pub(crate) fn record(&self, record: impl FnOnce(&NodeRecorder)) { + if let Some(recorder) = self.recorder { + record(recorder); } } pub(crate) fn error(&self, source: impl Into>) -> NodeError { - NodeError::traced( - self.row.id.clone(), - self.trace.as_ref().map(ToVariable::to_variable), - source, - ) + NodeError::new(self.id.clone(), source) } pub(crate) fn success(&self, output: Variable) -> NodeResult { Ok(NodeResponse { output, - trace_data: self.trace.as_ref().map(ToVariable::to_variable), + trace_data: None, }) } } diff --git a/core/engine/src/compiled/exact/graph/transform.rs b/core/engine/src/compiled/exact/graph/transform.rs index db6092ec4..c64703341 100644 --- a/core/engine/src/compiled/exact/graph/transform.rs +++ b/core/engine/src/compiled/exact/graph/transform.rs @@ -1,6 +1,7 @@ use super::Row; -use crate::compiled::host::{NodeError, NodeResponse, NodeResult}; +use crate::compiled::host::{NodeResponse, NodeResult}; use crate::compiled::pinning::Located; +use crate::compiled::trace::collect::Fact; use std::future::Future; use std::ops::Deref; use zen_expression::context::EvaluationContext; @@ -17,15 +18,14 @@ impl Row<'_> { F: Fn(Variable, bool, EvaluationContext) -> Fut, Fut: Future, { - let mut trace = self.trace.then_some(Variable::Null); let input = match &attributes.input_field { 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)) - })? + session + .run_standard(input_field.deref()) + .map_err(|err| self.error(crate::compiled::exact::Failure::input(err)))? } }; @@ -33,9 +33,7 @@ impl Row<'_> { TransformExecutionMode::Single => { let response = evaluate(input, false, self.context.clone()).await?; if let Some(td) = response.trace_data { - if let Some(t) = &mut trace { - *t = td; - } + self.record(|recorder| recorder.data(td)); } response.output @@ -43,20 +41,20 @@ impl Row<'_> { TransformExecutionMode::Loop => { let input_array_ref = input .as_array() - .ok_or_else(|| self.fault(&trace, "Expected an array".to_string()))?; + .ok_or_else(|| self.error("Expected an array".to_string()))?; let input_array = input_array_ref.borrow().clone(); - if let Some(t) = &mut trace { - *t = Variable::from_array(Vec::with_capacity(input_array.len())); - } + let mut items: Option> = + self.traced().then(|| Vec::with_capacity(input_array.len())); 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, self.context.item(index)).await?; - if let Some(td) = response.trace_data { - if let Some(Variable::Array(arr)) = &trace { - arr.borrow_mut().push(td); + Box::pin(evaluate(input.clone(), has_more, self.context.item(index))) + .await?; + if let Some(items) = items.as_mut() { + if let Some(recorder) = self.recorder { + items.push(recorder.item(response.trace_data)); } } @@ -67,6 +65,9 @@ impl Row<'_> { )); } + if let Some(items) = items { + self.record(|recorder| recorder.items(items)); + } Variable::from_array(output_array) } }; @@ -80,11 +81,7 @@ impl Row<'_> { Ok(NodeResponse { output, - trace_data: trace, + trace_data: None, }) } - - fn fault(&self, trace: &Option, message: String) -> NodeError { - NodeError::traced(self.id.clone(), trace.clone(), message) - } } diff --git a/core/engine/src/compiled/exact/table.rs b/core/engine/src/compiled/exact/table.rs index 67e0aa9de..47ffcbf0e 100644 --- a/core/engine/src/compiled/exact/table.rs +++ b/core/engine/src/compiled/exact/table.rs @@ -1,16 +1,15 @@ -use crate::compiled::exact::graph::{Ctx, Row}; +use crate::compiled::exact::graph::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::compiled::trace::collect::{Hit, Refs}; use crate::policy::blocks::{DecisionTableIr, ExecutionError}; use crate::workspace::types::{BlockTrace, DecisionTableExtras}; use ahash::{HashMap, HashSet}; use base64::Engine as _; use fixedbitset::FixedBitSet; -use std::rc::Rc; use std::sync::Arc; use zen_expression::lane::Session; use zen_expression::IsolateError; @@ -275,33 +274,19 @@ impl RowTable<'_, '_> { Some((object, lists)) } - fn trace(&mut self, index: usize, rule: &Rule) -> DecisionTableRowTrace { - let mut expressions: HashMap, Rc> = HashMap::default(); - let mut reference_map: HashMap, Variable> = HashMap::default(); - expressions.insert( - Rc::from("_id"), - rule.get("_id") - .map_or_else(|| Rc::from(""), |id| Rc::from(id.as_ref())), - ); - if let Some(description) = rule.get("_description") { - expressions.insert(Rc::from("_description"), Rc::from(description.as_ref())); - } + fn hit(&mut self, index: usize, rule: &Rule) -> Hit { + let mut refs = Refs::new(); for (col, input) in self.inputs.iter().enumerate() { - let (Some(cell), Some(field)) = (rule.get(&input.id), &input.field) else { + let (Some(_), Some(field)) = (rule.get(&input.id), &input.field) else { continue; }; if let Ok(Some(reference)) = self.reference(col) { - reference_map.insert(Rc::from(field.as_ref()), reference); + refs.push((field.clone(), reference)); } - expressions.insert( - Rc::from(format!("{field}[{}]", input.id).as_str()), - Rc::from(cell.as_ref()), - ); } - DecisionTableRowTrace { - index, - reference_map, - rule: expressions, + Hit { + rule: index as u32, + refs: Some(refs), } } @@ -310,10 +295,9 @@ impl RowTable<'_, '_> { content: &DecisionTableContent, index: Option<&TableIndex>, ) -> NodeResult { - 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 session = row.session(); + let traced = row.traced(); + let owner = row.id.clone(); let mut table = RowTable::new( &mut session, &content.inputs, @@ -346,17 +330,12 @@ impl RowTable<'_, '_> { continue; }; if traced { - traces.push(table.trace(at, rule)); + traces.push(table.hit(at, rule)); } match (first, split, object) { (true, false, Some(object)) => { - ctx.trace(|t| { - *t = traces.pop().map_or_else( - DecisionTableNodeTrace::default, - DecisionTableNodeTrace::FirstHit, - ) - }); - return ctx.success(object); + row.record(|recorder| recorder.table_hit(traces.pop())); + return row.success(object); } (false, _, Some(object)) => items.push(object), (_, _, object) => { @@ -375,7 +354,9 @@ impl RowTable<'_, '_> { trace_data: None, }); } - ctx.trace(|t| *t = DecisionTableNodeTrace::Collect(traces)); + if traced { + row.record(|recorder| recorder.table_hits(traces)); + } let output = match split { false => Variable::from_array(items), true => { @@ -392,7 +373,7 @@ impl RowTable<'_, '_> { output } }; - ctx.success(output) + row.success(output) } pub(crate) fn select( @@ -519,6 +500,17 @@ impl RowTable<'_, '_> { } } Ok(BlockTrace::DecisionTable { + matched_ids: selection + .matched_rows + .iter() + .map(|row| { + ir.rules + .get(*row as usize) + .and_then(|rule| rule.get("_id")) + .filter(|id| !id.is_empty()) + .cloned() + }) + .collect(), matched_rows: selection.matched_rows.clone(), evaluations, extras: selection diff --git a/core/engine/src/compiled/graph/batched.rs b/core/engine/src/compiled/graph/batched.rs index 359d91773..56e581816 100644 --- a/core/engine/src/compiled/graph/batched.rs +++ b/core/engine/src/compiled/graph/batched.rs @@ -181,6 +181,7 @@ impl CompiledGraph { parents: Some(&parents), iteration: iteration + 1, completed: None, + traced: false, }; let state = Box::pin(compiled.run( Host { diff --git a/core/engine/src/compiled/graph/call.rs b/core/engine/src/compiled/graph/call.rs index f8965d9ab..95492c6db 100644 --- a/core/engine/src/compiled/graph/call.rs +++ b/core/engine/src/compiled/graph/call.rs @@ -1,17 +1,16 @@ -use super::traced::Traced; +use super::traced::{Run, Traced}; 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; @@ -28,8 +27,6 @@ pub(crate) enum Load { Kind(&'static str), } -pub(crate) type TracedRun = Result>; - impl Call<'_> { pub(crate) async fn load(&self) -> Result { let loader = self.extensions.loader(); @@ -93,6 +90,7 @@ impl Call<'_> { parents: Some(&parents), iteration: self.iteration + 1, completed: None, + traced: false, }; let state = Box::pin(compiled.run( Host { @@ -118,7 +116,7 @@ impl Call<'_> { input: Variable, parent: Option, context: &EvaluationContext, - ) -> Result> { + ) -> Result> { let compiled = Self::compiled(graph)?; let content = compiled.schemas(graph, self.extensions.loader()).await; let extensions = self.sub_extensions(&content, context); @@ -130,7 +128,7 @@ impl Call<'_> { iteration: self.iteration + 1, parent, }; - Ok(Box::pin(traced.evaluate(input)).await) + Ok(Box::pin(traced.run(input)).await) } pub(crate) async fn node(&self, row: Row<'_>, attributes: &TransformAttributes) -> NodeResult { @@ -138,18 +136,16 @@ impl Call<'_> { let loaded = &loaded; let id = row.id; let nodes = &row.nodes; - let traced = row.trace; + let traced = row.traced(); + let sink = &row; row.transform(attributes, |input, _, context| async move { - let fault = |source: Box, trace: Option| { - NodeError::traced(id.clone(), trace, source) - }; - let blank = traced.then_some(Variable::Null); + let fault = |source: Box| NodeError::new(id.clone(), source); let cached = loaded.borrow().clone(); let graph = match cached { Some(graph) => graph, None => match self.load().await { - Err(error) => return Err(fault(error.into(), blank)), - Ok(Load::Kind(kind)) => return Err(fault(Self::kind(self.key, kind), blank)), + Err(error) => return Err(fault(error.into())), + Ok(Load::Kind(kind)) => return Err(fault(Self::kind(self.key, kind))), Ok(Load::Graph(graph)) => { *loaded.borrow_mut() = Some(graph.clone()); graph @@ -160,31 +156,26 @@ impl Call<'_> { let output = self .run(&graph, input, nodes.clone(), &context) .await - .map_err(|e| fault(e, None))?; + .map_err(fault)?; return Ok(NodeResponse { output, trace_data: None, }); } match self.traced(&graph, input, nodes.clone(), &context).await { - Err(source) => Err(fault(source, blank)), - Ok(Ok(response)) => Ok(NodeResponse { - output: response.result, - trace_data: Some( - response - .trace - .and_then(|trace| trace.into_graph()) - .as_ref() - .map(ToVariable::to_variable) - .unwrap_or(Variable::Null), - ), - }), - Ok(Err(error)) => { - let trace = match error.as_ref() { - EvaluationError::NodeError { trace, .. } => trace.to_variable(), - _ => Variable::Null, - }; - Err(fault(error.to_string().into(), Some(trace))) + Err(source) => Err(fault(source)), + Ok(run) => { + let failed = matches!(&run.result, Err(e) if !matches!(**e, EvaluationError::NodeError { .. })); + if !failed { + sink.record(|recorder| recorder.sub_decision(run.recording)); + } + match run.result { + Ok(output) => Ok(NodeResponse { + output, + trace_data: None, + }), + Err(error) => Err(fault(error.to_string().into())), + } } } }) diff --git a/core/engine/src/compiled/graph/columnar.rs b/core/engine/src/compiled/graph/columnar.rs index 8a5be8af2..b5e9ace4c 100644 --- a/core/engine/src/compiled/graph/columnar.rs +++ b/core/engine/src/compiled/graph/columnar.rs @@ -28,6 +28,60 @@ pub struct ColumnarOutput<'a> { pub columns: Vec<(Arc, OutputColumn<'a>)>, pub errors: Vec>>, pub(crate) paths: Paths, + pub(crate) traces: Option>, +} + +#[derive(Clone)] +pub(crate) enum Traced<'a> { + Columns(Rc>), + Rows(Rc>), +} + +pub struct ColumnarTraces<'o, 'a>(&'o Traced<'a>); + +impl ColumnarTraces<'_, '_> { + pub fn len(&self) -> usize { + match self.0 { + Traced::Columns(batch) => batch.len(), + Traced::Rows(batch) => batch.len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn json(&self, row: usize) -> Option { + match self.0 { + Traced::Columns(batch) => batch.json(row), + Traced::Rows(batch) => batch.json(row), + } + } + + pub fn document(&self, row: usize) -> Option { + match self.0 { + Traced::Columns(batch) => batch.document(row), + Traced::Rows(batch) => batch.document(row), + } + } + + pub fn write_all(&self, out: &mut String) -> Vec { + match self.0 { + Traced::Columns(batch) => batch.write_all(out), + Traced::Rows(batch) => batch.write_all(out), + } + } +} + +impl<'a> ColumnarOutput<'a> { + pub fn traces(&self) -> Option> { + self.traces.as_ref().map(ColumnarTraces) + } + + pub(crate) fn traced(mut self, traces: crate::compiled::trace::TraceBatch<'a>) -> Self { + self.traces = Some(Traced::Columns(Rc::new(traces))); + self + } } impl ColumnarOutput<'_> { @@ -50,6 +104,7 @@ impl ColumnarOutput<'_> { hosted: rows, ..Paths::default() }, + traces: None, } } @@ -57,6 +112,40 @@ impl ColumnarOutput<'_> { OutputColumn::row(&self.columns, row) } + pub fn write_rows(&self, out: &mut String) -> Vec { + let layout = crate::compiled::output::Layout::new(&self.columns); + let cells = crate::compiled::output::Layout::cells(&self.columns); + let mut bytes = std::mem::take(out).into_bytes(); + let mut ends = Vec::with_capacity(self.rows); + let start = bytes.len(); + for row in 0..self.rows { + match self.errors.get(row).is_some_and(Option::is_some) { + true => bytes.extend_from_slice(b"null"), + false => layout.write(&self.columns, &cells, row, &mut bytes), + } + if row == 0 { + let first = bytes.len() - start; + bytes.reserve((first + first / 16 + 16).saturating_mul(self.rows - 1)); + } + ends.push(bytes.len()); + bytes.push(b'\n'); + } + *out = String::from_utf8(bytes).unwrap_or_default(); + ends + } + + pub fn trace_json(&self, row: usize) -> Option { + self.traces().and_then(|traces| traces.json(row)) + } + + pub(crate) fn traced_rows( + mut self, + traces: crate::compiled::trace::TraceBatch<'static>, + ) -> Self { + self.traces = Some(Traced::Rows(Rc::new(traces))); + self + } + #[doc(hidden)] pub fn paths(&self) -> Paths { self.paths @@ -87,12 +176,13 @@ impl ColumnarOutput<'_> { hosted: self.paths.hosted + rows.len(), ..self.paths }, + traces: self.traces, } } } impl CompiledGraph { - fn input_data<'a>(columns: &Columns<'a>) -> Data<'a> { + pub(in crate::compiled::graph) fn input_data<'a>(columns: &Columns<'a>) -> Data<'a> { let rows = columns.rows; let mut paths: Vec> = Vec::with_capacity(columns.columns.len()); let mut leaves: Vec> = Vec::with_capacity(columns.columns.len()); @@ -225,6 +315,51 @@ impl CompiledGraph { Leaf::Any(values.into()) } + pub(crate) async fn evaluate_columns_traced<'a>( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + columns: &'a Columns<'a>, + format: crate::compiled::trace::TraceFormat, + ) -> Option> { + if max_depth == 0 { + return None; + } + let admitted = self.planned_input(content, extensions, columns).await?; + match self + .plan() + .evaluate( + self, + content, + extensions, + max_depth, + columns, + admitted, + Some(format), + ) + .await + { + PlanOutcome::Skipped | PlanOutcome::Untraced => None, + PlanOutcome::Done(output) => Some(output), + PlanOutcome::Partial { + output, + rows, + completed, + } => { + let inputs = Self::input_data(columns).materialized(); + let inputs: Vec = rows.iter().map(|&row| inputs[row].clone()).collect(); + let completed = completed.subset(&rows); + 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; + Some(output.splice(&rows, results)) + } + } + } + pub(crate) async fn evaluate_columns<'a>( &self, content: &Arc, @@ -236,10 +371,12 @@ impl CompiledGraph { if let Some(admitted) = self.planned_input(content, extensions, columns).await { match self .plan() - .evaluate(self, content, extensions, max_depth, columns, admitted) + .evaluate( + self, content, extensions, max_depth, columns, admitted, None, + ) .await { - PlanOutcome::Skipped => {} + PlanOutcome::Skipped | PlanOutcome::Untraced => {} PlanOutcome::Done(output) => return output, PlanOutcome::Partial { output, diff --git a/core/engine/src/compiled/graph/data.rs b/core/engine/src/compiled/graph/data.rs index a28c6f12d..1d08f25c2 100644 --- a/core/engine/src/compiled/graph/data.rs +++ b/core/engine/src/compiled/graph/data.rs @@ -1,5 +1,6 @@ use crate::compiled::host::graph::walker::GraphWalker; use crate::compiled::leaf::{Bits, ColumnBuilder, Leaf, Mask}; +use smallvec::SmallVec; use std::cell::{OnceCell, RefCell}; use std::rc::Rc; use std::sync::Arc; @@ -12,8 +13,46 @@ use zen_types::variable::VariableMap; pub(crate) type Col = Rc<[Variable]>; type Parts<'a> = (Option, Vec>, Vec<(Arc, Leaf<'a>)>); +enum Nest { + Leaf(Symbol, usize), + Branch(Symbol, Vec), +} + +impl Nest { + fn of(segments: &[Box<[Symbol]>], items: &[usize], depth: usize) -> Option> { + let mut nodes: Vec = Vec::new(); + let mut seen: Vec<&Symbol> = Vec::new(); + let mut start = 0; + while start < items.len() { + let key = segments[items[start]].get(depth)?; + let end = (start..items.len()) + .find(|&at| segments[items[at]].get(depth) != Some(key)) + .unwrap_or(items.len()); + if seen.contains(&key) { + return None; + } + seen.push(key); + let group = &items[start..end]; + let leaf = group + .iter() + .any(|&index| segments[index].len() == depth + 1); + match (leaf, group) { + (true, [index]) => nodes.push(Nest::Leaf(key.clone(), *index)), + (true, _) => return None, + (false, _) => nodes.push(Nest::Branch( + key.clone(), + Self::of(segments, group, depth + 1)?, + )), + } + start = end; + } + Some(nodes) + } +} + #[derive(Clone)] pub(crate) struct Layer<'a> { + nest: Option>, pub paths: Arc<[Arc]>, keys: Rc<[Symbol]>, segments: Rc<[Box<[Symbol]>]>, @@ -30,11 +69,19 @@ impl<'a> Layer<'a> { ) -> Layer<'a> { let flat = paths.iter().all(|p| !p.contains('.')); let keys = paths.iter().map(|p| Symbol::from(p.as_ref())).collect(); - let segments = paths + let segments: Rc<[Box<[Symbol]>]> = paths .iter() .map(|p| p.split('.').map(Symbol::from).collect()) .collect(); + let nest = match flat { + true => None, + false => { + let segments: &[Box<[Symbol]>] = &segments; + Nest::of(segments, &(0..segments.len()).collect::>(), 0).map(Rc::from) + } + }; Layer { + nest, paths, keys, segments, @@ -54,18 +101,24 @@ impl<'a> Layer<'a> { let mut map = VariableMap::with_capacity(self.keys.len()); for (i, (key, column)) in self.keys.iter().zip(self.columns.iter()).enumerate() { if self.has(i, row) { - map.insert(key.clone(), column.get(row)); + map.insert(key.clone(), column.shared(row)); } } Variable::from_object(map) } false => { + if let Some(nest) = &self.nest { + return Variable::from_object( + self.nested(nest, row) + .unwrap_or_else(|| VariableMap::with_capacity(0)), + ); + } let object = Variable::empty_object(); for (i, (segments, column)) in self.segments.iter().zip(self.columns.iter()).enumerate() { if self.has(i, row) { - Self::insert(&object, segments, column.get(row)); + Self::insert(&object, segments, column.shared(row)); } } object @@ -73,6 +126,29 @@ impl<'a> Layer<'a> { } } + fn nested(&self, nodes: &[Nest], row: usize) -> Option { + let mut map: Option = None; + let mut put = |key: &Symbol, value: Variable| { + map.get_or_insert_with(|| VariableMap::with_capacity(nodes.len())) + .insert(key.clone(), value); + }; + for node in nodes { + match node { + Nest::Leaf(key, index) => { + if self.has(*index, row) { + put(key, self.columns[*index].shared(row)); + } + } + Nest::Branch(key, children) => { + if let Some(child) = self.nested(children, row) { + put(key, Variable::from_object(child)); + } + } + } + } + map + } + fn insert(target: &Variable, segments: &[Symbol], value: Variable) { let Some((last, head)) = segments.split_last() else { return; @@ -82,17 +158,11 @@ impl<'a> Layer<'a> { let Variable::Object(object) = ¤t else { return; }; - let existing = object.borrow().get(part).map(Variable::shallow_clone); - let next = match existing { - Some(existing) => existing, - None => { - let created = Variable::empty_object(); - object - .borrow_mut() - .insert(part.clone(), created.shallow_clone()); - created - } - }; + let existing = object.borrow().get(part).map(|found| found.depth_clone(1)); + let next = existing.unwrap_or_else(Variable::empty_object); + object + .borrow_mut() + .insert(part.clone(), next.shallow_clone()); current = next; } if let Variable::Object(object) = current { @@ -130,14 +200,25 @@ impl<'a> Layer<'a> { fn object_key(&self, row: usize, top: &str, under: &[usize]) -> Option { if let [index] = under { if self.paths[*index].as_ref() == top { - return self.has(*index, row).then(|| self.columns[*index].get(row)); + return self + .has(*index, row) + .then(|| self.columns[*index].shared(row)); + } + } + if let Some(nest) = &self.nest { + let found = nest.iter().find_map(|node| match node { + Nest::Branch(key, children) if key.as_str() == top => Some(children), + _ => None, + }); + if let Some(children) = found { + return self.nested(children, row).map(Variable::from_object); } } let object = Variable::empty_object(); let mut any = false; for &i in under { if self.has(i, row) { - Self::insert(&object, &self.segments[i], self.columns[i].get(row)); + Self::insert(&object, &self.segments[i], self.columns[i].shared(row)); any = true; } } @@ -154,7 +235,7 @@ impl<'a> Layer<'a> { true => { for (i, (key, column)) in self.keys.iter().zip(self.columns.iter()).enumerate() { if self.has(i, row) { - Self::put(current, key, &column.get(row)); + Self::put(current, key, &column.shared(row)); } } } @@ -171,6 +252,7 @@ impl<'a> Layer<'a> { fn gather(&self, positions: &Rc<[usize]>) -> Layer<'a> { Layer { paths: self.paths.clone(), + nest: self.nest.clone(), keys: self.keys.clone(), segments: self.segments.clone(), columns: self.columns.iter().map(|c| c.pick(positions)).collect(), @@ -259,6 +341,19 @@ impl<'a> Data<'a> { } } + pub fn copied(&self) -> Data<'a> { + Data::with_shape(self.rows.clone(), self.shape.clone()) + } + + pub fn single(&self) -> bool { + match &self.shape { + Shape::Plain(values) => values + .iter() + .all(|v| matches!(v, Variable::Object(_) | Variable::Array(_))), + Shape::Patched { nulls, .. } => nulls.is_none(), + } + } + pub fn pick(column: &Col, positions: &[usize]) -> Col { positions.iter().map(|&i| column[i].clone()).collect() } @@ -432,6 +527,70 @@ impl<'a> Data<'a> { } } + pub fn object(&self, row: usize) -> bool { + match (self.whole.get(), &self.shape) { + (Some(whole), _) => matches!(whole[row], Variable::Object(_)), + (None, Shape::Plain(values)) => matches!(values[row], Variable::Object(_)), + (None, Shape::Patched { .. }) => !self.nulled(row), + } + } + + pub fn container(&self, row: usize) -> bool { + match &self.shape { + _ if self.whole.get().is_some() => self.whole.get().is_some_and(|whole| { + matches!(whole[row], Variable::Object(_) | Variable::Array(_)) + }), + Shape::Plain(values) => matches!(values[row], Variable::Object(_) | Variable::Array(_)), + Shape::Patched { .. } => !self.nulled(row), + } + } + + pub fn extends(&self, input: &Data<'a>) -> Option<&Layer<'a>> { + let Shape::Patched { + base, + layers, + nulls: None, + .. + } = &self.shape + else { + return None; + }; + let (last, head) = layers.split_last()?; + let same = |a: &Layer<'a>, b: &Layer<'a>| { + Rc::ptr_eq(&a.columns, &b.columns) || a.paths.is_empty() && b.paths.is_empty() + }; + match &input.shape { + Shape::Plain(values) => { + let based = base.as_ref().is_some_and(|b| Rc::ptr_eq(b, values)); + (based && head.is_empty()).then_some(last) + } + Shape::Patched { + base: before, + layers: earlier, + .. + } => { + let based = match (base, before) { + (None, None) => true, + (Some(a), Some(b)) => Rc::ptr_eq(a, b), + _ => false, + }; + (based + && head.len() == earlier.len() + && head.iter().zip(earlier.iter()).all(|(a, b)| same(a, b))) + .then_some(last) + } + } + } + + pub fn apply(layer: &Layer<'a>, row: usize, before: &Variable) -> Option { + let Variable::Object(map) = before else { + return None; + }; + let mut current = map.borrow().clone(); + layer.apply(row, &mut current); + Some(Variable::from_object(current)) + } + pub fn partial(&self, path: &str) -> Leaf<'a> { Leaf::Any(self.subtree(path)) } @@ -548,7 +707,7 @@ impl<'a> Data<'a> { match &self.shape { Shape::Plain(values) => Self::lookup(&values[row], path).unwrap_or(Variable::Null), Shape::Patched { base, leaves, .. } => match Self::read(leaves, path) { - Read::Leaf(index) => leaves[index].1.get(row), + Read::Leaf(index) => leaves[index].1.shared(row), Read::Base => base .as_ref() .and_then(|b| Self::lookup(&b[row], path)) @@ -811,7 +970,7 @@ impl<'a> Data<'a> { (true, None) => { let leaf = Leaf::Any( (0..count) - .map(|row| match (has(row), column.get(row)) { + .map(|row| match (has(row), column.shared(row)) { (false, _) => self.resolve(path, row), (true, value @ Variable::Object(_)) => { match self.resolve(path, row) { @@ -971,3 +1130,693 @@ impl<'a> Data<'a> { } } } + +struct EditField<'a> { + name: Arc, + pointer: String, + index: usize, + column: Leaf<'a>, + before: Option, +} + +enum EditKind<'a> { + Dynamic, + Flat { + index: usize, + column: Leaf<'a>, + before: Option, + }, + Nested { + fields: Vec>, + exact: Option, + under: Vec, + }, +} + +struct EditGroup<'a> { + top: Arc, + pointer: String, + before: Vec>, + after: Vec>, + layer: Vec, + kind: EditKind<'a>, +} + +pub(crate) struct Edits<'a> { + groups: Vec>, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) enum Cell { + Absent, + Container, + Null, + Bool(bool), + Number(i128, u32), + Text(Symbol), +} + +impl Cell { + pub fn of(value: &Variable) -> Option { + match value { + Variable::Null => Some(Cell::Null), + Variable::Bool(b) => Some(Cell::Bool(*b)), + Variable::Number(d) => Some(Cell::Number(d.mantissa(), d.scale())), + Variable::String(s) => Some(Cell::Text(s.clone())), + Variable::Array(_) | Variable::Object(_) => Some(Cell::Container), + Variable::Dynamic(_) => None, + } + } + + fn scalar(value: &Variable) -> Option { + Self::of(value).filter(|cell| *cell != Cell::Container) + } + + fn earlier(value: Option<&Variable>) -> Option { + match value { + Some(value) => Self::of(value), + None => Some(Cell::Absent), + } + } +} + +#[derive(Default)] +pub(crate) struct Keys { + pub words: Vec, + cells: FastCells, +} + +type FastCells = + std::collections::HashMap>; + +impl Keys { + pub fn mark(&mut self, tag: u64) { + self.words.push(tag); + } + + fn cell(&mut self, cell: Cell) -> Option<()> { + let next = self.cells.len() as u32; + if next > 1 << 16 && !self.cells.contains_key(&cell) { + return None; + } + let id = *self.cells.entry(cell).or_insert(next); + self.words.extend_from_slice(&[4, id as u64]); + Some(()) + } + + pub fn value(&mut self, value: &Variable) -> Option<()> { + self.cell(Cell::scalar(value)?) + } + + fn scalar(&mut self, leaf: &Leaf, row: usize) -> Option { + if leaf.words(row, &mut self.words) { + return Some(true); + } + if leaf.listed(row).is_some() { + return None; + } + let cell = Cell::scalar(&leaf.get(row))?; + let valued = cell != Cell::Null; + self.cell(cell)?; + Some(valued) + } + + fn known(&mut self, leaf: &Leaf, row: usize) -> Option<()> { + if leaf.words(row, &mut self.words) { + return Some(()); + } + if let Some((records, at)) = leaf.listed(row) { + return match records.range(at) { + Some(_) => self.cell(Cell::Container), + None => None, + }; + } + match leaf.get(row) { + Variable::Null => None, + value => self.cell(Cell::of(&value)?), + } + } + + fn earlier(&mut self, value: Option<&Variable>) -> Option<()> { + self.cell(Cell::earlier(value)?) + } +} + +enum Earlier { + Absent, + Value(Variable), + Object, + Unknown, +} + +impl<'a> Data<'a> { + fn unders(&self, top: &str) -> Vec> { + match &self.shape { + Shape::Plain(_) => Vec::new(), + Shape::Patched { layers, .. } => layers.iter().map(|layer| layer.under(top)).collect(), + } + } + + fn based(&self, row: usize) -> Option<&Variable> { + match &self.shape { + Shape::Plain(values) => values.get(row), + Shape::Patched { base, .. } => base.as_ref().and_then(|base| base.get(row)), + } + } + + pub fn edits( + &self, + input: &Data<'a>, + keys: &[Arc], + escape: fn(&str, &mut String), + ) -> Option> { + let layer = self.extends(input)?; + if matches!(&input.shape, Shape::Patched { nulls: Some(_), .. }) { + return None; + } + let earlier = input.leaves(); + let groups = keys + .iter() + .map(|top| { + let own = layer.under(top); + let mut pointer = String::new(); + escape(top, &mut pointer); + let exact = earlier.iter().position(|(path, _)| path == top); + let under: Vec = earlier + .iter() + .enumerate() + .filter(|(_, (path, _))| DotPath::under(path, top)) + .map(|(index, _)| index) + .collect(); + let parts = |index: usize| { + layer.paths[index] + .split('.') + .collect::>() + }; + let reserved = own + .iter() + .any(|&index| parts(index).iter().any(|part| *part == "$nodes")); + let repeated = own.iter().enumerate().any(|(at, &index)| { + own[..at] + .iter() + .any(|&other| layer.paths[other] == layer.paths[index]) + }); + let deeper = own.iter().any(|&index| { + earlier + .iter() + .any(|(path, _)| DotPath::under(path, &layer.paths[index])) + }); + let kind = match own.as_slice() { + _ if reserved || repeated || deeper => EditKind::Dynamic, + [] => EditKind::Dynamic, + [index] if layer.paths[*index] == *top => match under.is_empty() { + true => EditKind::Flat { + index: *index, + column: layer.columns[*index].clone(), + before: exact, + }, + false => EditKind::Dynamic, + }, + all if all.iter().all(|&index| parts(index).len() == 2) + && (exact.is_none() || under.is_empty()) => + { + EditKind::Nested { + fields: all + .iter() + .map(|&index| { + let name = parts(index)[1]; + let mut at = pointer.clone(); + escape(name, &mut at); + EditField { + name: Arc::from(name), + pointer: at, + index, + column: layer.columns[index].clone(), + before: earlier + .iter() + .position(|(path, _)| *path == layer.paths[index]), + } + }) + .collect(), + exact, + under: under.clone(), + } + } + _ => EditKind::Dynamic, + }; + EditGroup { + top: top.clone(), + pointer, + before: input.unders(top), + after: self.unders(top), + layer: own, + kind, + } + }) + .collect(); + Some(Edits { groups }) + } + + pub fn key_columns(&self, input: &Data<'a>, edits: &Edits<'a>) -> Option, u32)>> { + let layer = self.extends(input)?; + if !matches!(&input.shape, Shape::Patched { base: None, .. }) { + return None; + } + let count = self.len(); + let earlier = input.leaves(); + let mut leaves: Vec<&Leaf<'a>> = Vec::new(); + let mut columns: Vec<(Vec, u32)> = Vec::new(); + for group in &edits.groups { + for &index in &group.layer { + leaves.push(&layer.columns[index]); + if layer.present.is_some() { + columns.push(( + (0..count) + .map(|row| u32::from(layer.has(index, row))) + .collect(), + 2, + )); + } + } + match &group.kind { + EditKind::Dynamic => return None, + EditKind::Flat { before, .. } => { + leaves.extend(before.iter().map(|&leaf| &earlier[leaf].1)); + } + EditKind::Nested { + fields, + exact, + under, + } => { + leaves.extend(exact.iter().map(|&leaf| &earlier[leaf].1)); + leaves.extend(under.iter().map(|&leaf| &earlier[leaf].1)); + leaves.extend( + fields + .iter() + .filter_map(|field| field.before) + .map(|leaf| &earlier[leaf].1), + ); + } + } + } + columns.extend(leaves.into_iter().map(|leaf| leaf.codes(count))); + Some(columns) + } + + pub fn scope_columns(&self, fields: &[Arc]) -> Option, u32)>> { + let Shape::Patched { + base: None, + leaves, + presence: Some(presence), + nulls: None, + .. + } = &self.shape + else { + return None; + }; + let count = self.len(); + let mut columns = Vec::new(); + for field in fields.iter().filter(|field| !field.is_empty()) { + let Read::Leaf(index) = Self::read(leaves, field) else { + return None; + }; + let leaf = &leaves[index].1; + columns.push(( + (0..count) + .map(|row| u32::from(presence[index].at(leaf, row))) + .collect(), + 2, + )); + columns.push(leaf.codes(count)); + } + Some(columns) + } + + pub fn scope_flat(&self, row: usize, fields: &[Arc]) -> bool { + let Shape::Patched { + base: None, + leaves, + presence: Some(presence), + nulls: None, + .. + } = &self.shape + else { + return false; + }; + fields + .iter() + .filter(|field| !field.is_empty()) + .all(|field| match Self::read(leaves, field) { + Read::Leaf(index) => { + !presence[index].at(&leaves[index].1, row) + || leaves[index].1.listed(row).is_none() + && Cell::scalar(&leaves[index].1.get(row)).is_some() + } + _ => false, + }) + } + + pub fn counts(&self, path: &str) -> Option>> { + let Shape::Patched { leaves, .. } = &self.shape else { + return None; + }; + let Read::Leaf(index) = Self::read(leaves, path) else { + return None; + }; + let leaf = &leaves[index].1; + Some( + (0..self.len()) + .map(|row| match leaf.listed(row) { + Some((records, at)) => { + records.range(at).map(|(start, end)| (end - start) as u32) + } + None => leaf + .get(row) + .as_array() + .map(|items| items.borrow().len() as u32), + }) + .collect(), + ) + } + + pub fn lists(&self, row: usize, id: usize, at: usize) -> Option> { + let Shape::Patched { + base: None, + leaves, + presence, + .. + } = &self.shape + else { + return None; + }; + Some( + leaves + .iter() + .enumerate() + .filter(|(_, (path, _))| !path.contains('.')) + .filter(|(index, (_, leaf))| { + leaf.listed(row) + .is_some_and(|(records, found)| records.id() == id && found == at) + && presence + .as_ref() + .is_none_or(|presence| presence[*index].at(leaf, row)) + }) + .map(|(_, (path, _))| &**path) + .collect(), + ) + } + + pub fn sparse(&self, row: usize, fields: &[Arc]) -> Option { + let Shape::Patched { + base: None, + leaves, + presence: Some(presence), + nulls: None, + .. + } = &self.shape + else { + return None; + }; + let object = Variable::empty_object(); + for field in fields.iter().filter(|field| !field.is_empty()) { + let Read::Leaf(index) = Self::read(leaves, field) else { + return None; + }; + if presence[index].at(&leaves[index].1, row) { + let segments: SmallVec<[Symbol; 4]> = field.split('.').map(Symbol::from).collect(); + Layer::insert(&object, &segments, leaves[index].1.shared(row)); + } + } + Some(object) + } + + pub fn edit_key( + &self, + input: &Data<'a>, + edits: &Edits<'a>, + row: usize, + key: &mut Keys, + ) -> bool { + self.edit_cells(input, edits, row, key).is_some() + } + + fn edit_cells( + &self, + input: &Data<'a>, + edits: &Edits<'a>, + row: usize, + key: &mut Keys, + ) -> Option<()> { + let layer = self.extends(input)?; + if !self.object(row) || !input.object(row) { + return None; + } + let earlier = input.leaves(); + for group in &edits.groups { + if !group.layer.iter().any(|&index| layer.has(index, row)) { + key.mark(5); + continue; + } + let based = || { + input + .based(row) + .and_then(|base| Self::lookup(base, &group.top)) + }; + match &group.kind { + EditKind::Dynamic => return None, + EditKind::Flat { column, before, .. } => { + match before { + Some(leaf) => key.known(&earlier[*leaf].1, row)?, + None => key.earlier(based().as_ref())?, + }; + key.scalar(column, row)?; + } + EditKind::Nested { + fields, + exact, + under, + } => { + let was = match (exact, under.is_empty()) { + (Some(leaf), _) => match earlier[*leaf].1.shared(row) { + Variable::Null => return None, + value => Some(value), + }, + (None, false) => match under.iter().any(|&leaf| !earlier[leaf].1.null(row)) + { + true => Some(Variable::empty_object()), + false => return None, + }, + (None, true) => based(), + }; + match &was { + Some(Variable::Object(map)) => { + key.mark(8); + let outer = match (exact, under.is_empty()) { + (None, false) => None, + _ => Some(map), + }; + for field in fields { + if !layer.has(field.index, row) { + key.mark(5); + continue; + } + if !key.scalar(&field.column, row)? { + return None; + } + match (field.before, outer) { + (Some(leaf), _) => key.known(&earlier[leaf].1, row)?, + (None, Some(map)) => { + key.earlier(map.borrow().get_str(&field.name))? + } + (None, None) => match based() { + Some(Variable::Object(map)) => { + key.earlier(map.borrow().get_str(&field.name))? + } + _ => key.mark(6), + }, + }; + } + } + was => { + key.mark(9); + key.earlier(was.as_ref())?; + for &index in &group.layer { + match layer.has(index, row) { + true => { + key.scalar(&layer.columns[index], row)?; + } + false => key.mark(5), + } + } + } + } + } + } + } + Some(()) + } + + pub fn edit( + &self, + input: &Data<'a>, + edits: &Edits<'a>, + row: usize, + emit: &mut dyn FnMut(&str, Option<&Variable>, Option<&Variable>), + list: &mut dyn FnMut(&str, &Leaf<'a>, usize) -> bool, + ) -> bool { + let Some(layer) = self.extends(input) else { + return false; + }; + if !self.object(row) || !input.object(row) { + return false; + } + let earlier = input.leaves(); + let known = |index: usize| match earlier[index].1.shared(row) { + Variable::Null => None, + value => Some(value), + }; + for group in &edits.groups { + if !group.layer.iter().any(|&index| layer.has(index, row)) { + continue; + } + let based = || { + input + .based(row) + .and_then(|base| Self::lookup(base, &group.top)) + }; + let settled = match &group.kind { + EditKind::Dynamic => false, + EditKind::Flat { + index, + column, + before, + } => { + let was = match before { + Some(leaf) => match known(*leaf) { + Some(value) => Earlier::Value(value), + None => Earlier::Unknown, + }, + None => match based() { + Some(value) => Earlier::Value(value), + None => Earlier::Absent, + }, + }; + if matches!(was, Earlier::Absent) + && column + .listed(row) + .is_some_and(|(records, at)| records.range(at).is_some()) + && list(&group.pointer, column, row) + { + let _ = index; + continue; + } + let now = column.shared(row); + match (&was, &now) { + (Earlier::Unknown, _) => false, + (Earlier::Value(Variable::Object(_)), Variable::Object(_)) => false, + (Earlier::Value(was), Variable::Null) => { + emit(&group.pointer, Some(was), None); + true + } + (Earlier::Value(was), now) => { + emit(&group.pointer, Some(was), Some(now)); + true + } + (_, Variable::Null) => true, + (_, now) => { + emit(&group.pointer, None, Some(now)); + let _ = index; + true + } + } + } + EditKind::Nested { + fields, + exact, + under, + } => { + let was = match (exact, under.is_empty()) { + (Some(leaf), _) => match known(*leaf) { + Some(value) => Earlier::Value(value), + None => Earlier::Unknown, + }, + (None, false) => match under.iter().any(|&leaf| known(leaf).is_some()) { + true => Earlier::Object, + false => Earlier::Unknown, + }, + (None, true) => match based() { + Some(value) => Earlier::Value(value), + None => Earlier::Absent, + }, + }; + match &was { + Earlier::Unknown => false, + Earlier::Absent | Earlier::Value(_) + if !matches!(&was, Earlier::Value(Variable::Object(_))) => + { + let whole = layer.object_key(row, &group.top, &group.layer); + let before = match &was { + Earlier::Value(value) => Some(value), + _ => None, + }; + emit(&group.pointer, before, whole.as_ref()); + true + } + _ => { + let mut found: SmallVec<[(usize, Option, Variable); 8]> = + SmallVec::new(); + let mut simple = true; + for (at, field) in fields.iter().enumerate() { + if !layer.has(field.index, row) { + continue; + } + let now = field.column.shared(row); + let before = match field.before { + Some(leaf) => match known(leaf) { + Some(value) => Some(value), + None => { + simple = false; + break; + } + }, + None => match &was { + Earlier::Value(Variable::Object(map)) => { + map.borrow().get_str(&field.name).cloned() + } + _ => based().and_then(|top| match top { + Variable::Object(map) => { + map.borrow().get_str(&field.name).cloned() + } + _ => None, + }), + }, + }; + let merges = matches!( + (&before, &now), + (Some(Variable::Object(_)), Variable::Object(_)) + ); + if matches!(now, Variable::Null) || merges { + simple = false; + break; + } + found.push((at, before, now)); + } + if simple { + for (at, before, now) in &found { + emit(&fields[*at].pointer, before.as_ref(), Some(now)); + } + } + simple + } + } + } + }; + if !settled { + let before = input.materialize_key(row, &group.top, &group.before); + let after = self.materialize_key(row, &group.top, &group.after); + emit(&group.pointer, before.as_ref(), after.as_ref()); + } + } + true + } +} diff --git a/core/engine/src/compiled/graph/mod.rs b/core/engine/src/compiled/graph/mod.rs index 923b35f04..261d71aad 100644 --- a/core/engine/src/compiled/graph/mod.rs +++ b/core/engine/src/compiled/graph/mod.rs @@ -6,7 +6,7 @@ mod step; pub(crate) mod traced; pub use columnar::ColumnarOutput; pub(super) mod columnar; -mod data; +pub(crate) mod data; pub(crate) mod errors; mod schedule; mod schema; @@ -36,6 +36,7 @@ pub struct CompiledGraph { root: Arc, dictionaries: bool, plan: OnceLock, + template: OnceLock>, census: usize, } @@ -142,6 +143,16 @@ impl CompiledGraph { self.plan.get_or_init(|| plan::Plan::analyze(self)) } + pub(crate) fn template(&self) -> &Arc { + self.template.get_or_init(|| { + Arc::new(crate::compiled::trace::collect::Template::new( + self.steps + .iter() + .map(|step| step.as_ref().map(|step| step.node.clone())), + )) + }) + } + pub(crate) fn plan_verdict(&self, columns: &Columns) -> Result<(), String> { self.plan() .verdict(self, columns) @@ -200,6 +211,70 @@ impl CompiledGraph { .collect() } + pub(crate) async fn traced_batch( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + inputs: &[Variable], + requests: &[Variable], + ) -> ( + Vec>>, + crate::compiled::trace::batch::Traces<'static>, + ) { + let nesting = Nesting { + traced: true, + ..Nesting::default() + }; + let mut state = self + .run( + Host { + content, + extensions, + max_depth, + }, + inputs, + nesting, + ) + .await; + let mut traces = state.traces.take().unwrap_or_else(|| { + crate::compiled::trace::batch::Traces::new(self.template().clone(), 0, inputs.len()) + }); + let errors = state.errors.into_vec(); + let mut results = Vec::with_capacity(inputs.len()); + for (row, (error, result)) in errors.into_iter().zip(state.results).enumerate() { + match error { + None => results.push(Ok(result.unwrap_or_else(Variable::empty_object))), + Some(error) => { + let Some(request) = requests.get(row) else { + results.push(Err(error)); + continue; + }; + extensions.context.restart(&[row]); + let fresh = NodeHandlerExtensions { + function_runtime: Default::default(), + context: extensions.context.at(row), + ..extensions.clone() + }; + let traced = traced::Traced { + graph: self, + content, + extensions: &fresh, + max_depth, + iteration: 0, + parent: None, + }; + let run = Box::pin(traced.run(request.deep_clone())).await; + if let Some(slot) = traces.replaced.get_mut(row) { + *slot = Some(run.recording); + } + results.push(Err(error)); + } + } + } + (results, traces) + } + pub(crate) async fn evaluate_one( &self, content: &Arc, diff --git a/core/engine/src/compiled/graph/plan/mod.rs b/core/engine/src/compiled/graph/plan/mod.rs index 688982099..d6c9ee876 100644 --- a/core/engine/src/compiled/graph/plan/mod.rs +++ b/core/engine/src/compiled/graph/plan/mod.rs @@ -225,6 +225,7 @@ pub(crate) struct SegPlan { pub end: SegEnd, pub hosted: Vec, views: Vec<(NodeIndex, Node)>, + results: Vec<(NodeIndex, Node)>, nested: Nested, } @@ -239,6 +240,7 @@ struct Builder<'g> { masks: Masks, catalog: Catalog, views: Vec<(NodeIndex, Node)>, + results: Vec<(NodeIndex, Node)>, objects: Vec<(Node, Ref)>, hosted: Vec, null: Option, @@ -703,6 +705,7 @@ impl<'g> Builder<'g> { op.sources = sources; self.catalog.ops.push(Op::Lane(Box::new(op))); } + self.results.push((node, out.clone())); match transform.pass_through { true => Node::merge(input, &out, &mut self.masks, &mut self.catalog), false => Ok(out), @@ -833,6 +836,7 @@ impl<'g> Builder<'g> { } } }; + self.results.push((node, out.clone())); match transform.pass_through { true => Node::merge(input, &out, &mut self.masks, &mut self.catalog), false => Ok(out), @@ -1231,16 +1235,18 @@ impl<'g> Builder<'g> { &mut self, f: impl FnOnce(&mut Self) -> Result, ) -> Result { - let (slots, ops, objects, masks) = ( + let (slots, ops, objects, results, masks) = ( self.catalog.slots.len(), self.catalog.ops.len(), self.objects.len(), + self.results.len(), self.masks.clone(), ); f(self).inspect_err(|_| { self.catalog.slots.truncate(slots); self.catalog.ops.truncate(ops); self.objects.truncate(objects); + self.results.truncate(results); self.masks = masks; }) } @@ -1292,6 +1298,7 @@ impl<'g> Builder<'g> { fields: Vec::new(), }; let output = Node::wrap(leaf, path); + self.results.push((node, output.clone())); match transform.pass_through { true => Node::merge(input, &output, &mut self.masks, &mut self.catalog), false => Ok(output), @@ -1517,6 +1524,7 @@ impl<'g> Builder<'g> { end, hosted: self.hosted, views: self.views, + results: self.results, nested: self.nested, }) } @@ -1569,6 +1577,7 @@ impl SegPlan { ops: Vec::new(), }, views: self.views.clone(), + results: self.results.clone(), objects: Vec::new(), hosted: Vec::new(), null: None, @@ -1755,6 +1764,7 @@ impl Plan { masks: Masks::default(), catalog: Catalog::default(), views: Vec::new(), + results: Vec::new(), objects: Vec::new(), hosted: Vec::new(), null: None, diff --git a/core/engine/src/compiled/graph/plan/run/assemble.rs b/core/engine/src/compiled/graph/plan/run/assemble.rs index f61b0d710..c1a6364be 100644 --- a/core/engine/src/compiled/graph/plan/run/assemble.rs +++ b/core/engine/src/compiled/graph/plan/run/assemble.rs @@ -182,10 +182,221 @@ impl<'a> Run<'_, 'a> { laned: store.counts.1, hosted: 0, }, + traces: None, } } } +impl CompiledGraph { + fn request_data<'a>(columns: &'a Columns<'a>) -> super::trace::Source<'a> { + use crate::compiled::graph::data::{Data, Layer}; + use crate::compiled::leaf::Mask; + use zen_expression::Variable; + let rows = columns.rows; + let scalars = |values: &[Variable]| { + values.iter().all(|value| { + !matches!( + value, + Variable::Array(_) | Variable::Object(_) | Variable::Dynamic(_) + ) + }) + }; + let scalar = |column: &Column<'a>| match column.values { + Values::List { .. } => false, + Values::Any(values) => scalars(values), + Values::Dict { + values: Dictionary::Any(values), + .. + } => scalars(values), + _ => true, + }; + let clean = columns + .columns + .iter() + .all(|(path, _)| !path.split('.').any(|part| part.starts_with('$'))); + let paths: Arc<[Arc]> = columns + .columns + .iter() + .map(|(path, _)| Arc::from(*path)) + .collect(); + let leaves: Vec> = columns + .columns + .iter() + .map(|(_, column)| match scalar(column) { + true => Leaf::input(*column, rows), + false => Leaf::Any((0..rows).map(|row| column.variable(row)).collect()), + }) + .collect(); + let present: Vec>> = columns + .columns + .iter() + .map(|(_, column)| match column.validity { + None => None, + Some(_) => { + let bits = Bits::of(rows, |row| { + column.valid(row) || !matches!(column.variable(row), Variable::Null) + }); + (0..rows).any(|row| !Bits::get(&bits, row)).then_some(bits) + } + }) + .collect(); + let masks = present.iter().any(Option::is_some).then(|| { + present + .into_iter() + .map(|bits| Mask::Bits(bits.unwrap_or_else(|| Bits::ones(rows)).into())) + .collect() + }); + let all: Rc<[usize]> = (0..rows).collect(); + let containers = columns + .columns + .iter() + .zip(&leaves) + .filter(|((_, column), _)| !scalar(column)) + .map(|(_, leaf)| leaf.clone()) + .collect(); + super::trace::Source::Derived { + data: Rc::new(Data::record(&all, Layer::new(paths, leaves, masks), None)), + reserved: crate::compiled::trace::batch::Reserved::new(clean, containers, rows), + } + } + + pub(super) fn shared_rows(columns: &Columns<'_>) -> Rc<[zen_expression::Variable]> { + use zen_expression::Variable; + use zen_types::symbol::Symbol; + let shapes: Vec<(Box<[Symbol]>, bool)> = columns + .columns + .iter() + .map(|(path, column)| { + let nested = matches!(column.values, Values::Any(_)) + && columns + .columns + .iter() + .any(|(other, _)| zen_types::path::DotPath::under(other, path)); + (path.split('.').map(Symbol::from).collect(), nested) + }) + .collect(); + (0..columns.rows) + .map(|row| { + let object = Variable::empty_object(); + for ((_, column), (segments, nested)) in columns.columns.iter().zip(&shapes) { + let value = match nested { + true => column.variable(row).depth_clone(usize::MAX), + false => column.variable(row), + }; + if !matches!(value, Variable::Null) || column.valid(row) { + Self::shared_insert(&object, segments, value); + } + } + object + }) + .collect() + } + + fn flat_scalars(columns: &Columns<'_>) -> bool { + columns + .columns + .iter() + .all(|(path, column)| !path.contains('.') && !matches!(column.values, Values::Any(_))) + } + + fn shared_insert( + target: &zen_expression::Variable, + segments: &[zen_types::symbol::Symbol], + value: zen_expression::Variable, + ) { + use zen_expression::Variable; + let Some((last, head)) = segments.split_last() else { + return; + }; + let mut current = target.shallow_clone(); + for part in head { + let Variable::Object(object) = ¤t else { + return; + }; + let existing = object.borrow().get(part).map(Variable::shallow_clone); + let next = match existing { + Some(existing) => existing, + None => { + let created = Variable::empty_object(); + object + .borrow_mut() + .insert(part.clone(), created.shallow_clone()); + created + } + }; + current = next; + } + if let Variable::Object(object) = current { + object.borrow_mut().insert(last.clone(), value); + } + } + + #[allow(clippy::too_many_arguments)] + async fn plan_traces<'a>( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + columns: &Columns<'_>, + trace: super::PlanTrace<'a>, + output: &ColumnarOutput<'_>, + deferred: &[usize], + format: crate::compiled::trace::TraceFormat, + ) -> crate::compiled::trace::TraceBatch<'a> { + let rows = columns.rows; + let mut traces = crate::compiled::trace::batch::Traces::new( + self.template().clone(), + self.steps.len(), + rows, + ); + traces.events = trace.events; + let requests = match trace.source { + super::trace::Source::Rows { requests, .. } => { + crate::compiled::trace::Requests::Owned(requests.to_vec()) + } + super::trace::Source::Derived { data, reserved } => { + traces.derived = Some(reserved); + crate::compiled::trace::Requests::derived(data) + } + }; + let mut failures: Vec, String)>> = vec![None; rows]; + for row in 0..rows { + let errored = output.errors.get(row).is_some_and(Option::is_some); + if !errored && !deferred.contains(&row) { + continue; + } + extensions.context.restart(&[row]); + let fresh = NodeHandlerExtensions { + function_runtime: Default::default(), + context: extensions.context.at(row), + ..extensions.clone() + }; + let traced = crate::compiled::traced::Traced { + graph: self, + content, + extensions: &fresh, + max_depth, + iteration: 0, + parent: None, + }; + let request = requests.get(row).unwrap_or(zen_expression::Variable::Null); + let run = Box::pin(traced.run(request.deep_clone())).await; + failures[row] = crate::compiled::trace::failure(&run.result); + if let Some(slot) = traces.replaced.get_mut(row) { + *slot = Some(run.recording); + } + } + crate::compiled::trace::TraceBatch::with_failures( + traces, + requests, + Vec::new(), + failures, + format, + &extensions.context, + ) + } +} + impl Plan { #[allow(clippy::too_many_arguments)] pub async fn evaluate<'a>( @@ -196,6 +407,7 @@ impl Plan { max_depth: u8, columns: &'a Columns<'a>, admitted: Admitted<'a>, + traced: Option, ) -> PlanOutcome<'a> { if let Some(resolved) = &content.resolved_schemas { let touched = graph.steps.iter().flatten().any(|step| { @@ -218,6 +430,44 @@ impl Plan { let Ok(root) = root.as_ref().as_ref() else { return PlanOutcome::Skipped; }; + if traced.is_some() { + let hosted = graph.steps.iter().flatten().any(|step| { + matches!(step.kind, Kind::Host(_) | Kind::Switch { .. }) || step.draws() + }) || root.ops.iter().any(|op| match op { + crate::compiled::graph::plan::Op::Child(_) => true, + crate::compiled::graph::plan::Op::Rows(rows) => graph + .step_at(rows.node) + .is_none_or(|step| matches!(step.kind, Kind::Host(_))), + _ => false, + }); + if hosted { + if std::env::var("ZEN_TRACE_COLUMNAR_DEBUG").is_ok_and(|v| v != "0") { + eprintln!("columnar plan not traced: hosted node"); + } + return PlanOutcome::Untraced; + } + } + crate::compiled::trace::count_run(); + let overlapping = graph.steps.iter().flatten().any(|step| { + matches!( + &step.kind, + Kind::Node { + body: crate::compiled::graph::Body::Expression { + overlapping: true, + .. + }, + .. + } + ) + }); + let hosted_rows = graph.steps.iter().flatten().any(|step| step.nodes) + || root.ops.iter().any(|op| { + matches!( + op, + crate::compiled::graph::plan::Op::Rows(_) + | crate::compiled::graph::plan::Op::Child(_) + ) + }); let mut store = Store::new(root, columns, dated); for (row, error) in failures { store.errors.set(row, error); @@ -238,17 +488,49 @@ impl Plan { completed: Completed::default(), iteration: 0, parents: None, + trace: traced.map(|_| { + let lazy = !overlapping && !hosted_rows; + let source = match (lazy && indexes.is_empty(), indexes.is_empty()) { + (true, _) => CompiledGraph::request_data(columns), + (false, plain) => super::trace::Source::Rows { + requests: CompiledGraph::shared_rows(columns), + shared: plain && CompiledGraph::flat_scalars(columns), + }, + }; + let mut trace = super::PlanTrace::new(graph.steps.len(), source, lazy); + trace.aliased = overlapping; + Box::new(trace) + }), }; run.walk(root.clone()).await; let Run { runner, store, completed, + trace, .. } = run; + if let Some(reason) = trace.as_ref().and_then(|t| t.refused) { + if std::env::var("ZEN_TRACE_COLUMNAR_DEBUG").is_ok_and(|v| v != "0") { + eprintln!("columnar plan not traced: {reason}"); + } + CompiledGraph::RUNNER.with_borrow_mut(|slot| *slot = runner); + return PlanOutcome::Untraced; + } CompiledGraph::RUNNER.with_borrow_mut(|slot| *slot = runner); let rows = store.errors.deferred(); let output = Run::assemble(store); + let output = match (traced, trace) { + (Some(format), Some(trace)) => { + let batch = graph + .plan_traces( + content, extensions, max_depth, columns, *trace, &output, &rows, format, + ) + .await; + output.traced(batch) + } + _ => output, + }; match rows.is_empty() { true => PlanOutcome::Done(output), false => PlanOutcome::Partial { @@ -262,6 +544,7 @@ impl Plan { pub(crate) enum PlanOutcome<'a> { Skipped, + Untraced, Done(ColumnarOutput<'a>), Partial { output: ColumnarOutput<'a>, diff --git a/core/engine/src/compiled/graph/plan/run/child.rs b/core/engine/src/compiled/graph/plan/run/child.rs index 56a61bf9d..927158b55 100644 --- a/core/engine/src/compiled/graph/plan/run/child.rs +++ b/core/engine/src/compiled/graph/plan/run/child.rs @@ -222,6 +222,7 @@ impl<'a> Run<'_, 'a> { completed: Completed::default(), iteration: self.iteration + 1, parents: Some(&parents), + trace: None, }; Box::pin(run.walk(op.root.clone())).await; let Run { diff --git a/core/engine/src/compiled/graph/plan/run/fanout.rs b/core/engine/src/compiled/graph/plan/run/fanout.rs index 720e622cc..4066a3fb4 100644 --- a/core/engine/src/compiled/graph/plan/run/fanout.rs +++ b/core/engine/src/compiled/graph/plan/run/fanout.rs @@ -11,8 +11,10 @@ impl<'a> Run<'_, 'a> { positions: Option<&Rc<[usize]>>, first: bool, conditions: &[Cond], + ids: &[std::sync::Arc], children: &mut Vec, ) { + let start = std::time::Instant::now(); let rows = self.store.rows; let truths: Vec>> = conditions .iter() @@ -166,6 +168,20 @@ impl<'a> Run<'_, 'a> { None => (0..rows).for_each(&mut visit), } } + if self.trace.is_some() { + let groups: Box = keys + .chunks_exact(words) + .zip(&sets) + .map(|(key, members)| { + ( + key.to_vec(), + (!members.is_empty()).then(|| Rc::from(members.as_slice())), + ) + }) + .collect(); + let ns = start.elapsed().as_nanos() as u64; + self.trace_switch(seg, positions, ids, &groups, ns); + } for (key, members) in keys.chunks_exact(words).zip(sets) { let child = seg.child(self.graph, self.layout, key); let Ok(child) = child.as_ref().as_ref() else { diff --git a/core/engine/src/compiled/graph/plan/run/loops.rs b/core/engine/src/compiled/graph/plan/run/loops.rs index 3f58c52cf..95f4a30f7 100644 --- a/core/engine/src/compiled/graph/plan/run/loops.rs +++ b/core/engine/src/compiled/graph/plan/run/loops.rs @@ -92,7 +92,16 @@ impl<'a> Run<'_, 'a> { 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 probe = self.probe(); + let produced = CompiledGraph::items( + &mut self.runner, + &context, + probe.as_ref(), + step, + body, + &items, + &[], + ); let mut values = vec![Variable::Null; rows]; for (row, start, end) in spans { let mut collected = Vec::with_capacity(end - start); @@ -245,9 +254,11 @@ 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 probe = self.probe(); let (output, failures) = CompiledGraph::item_run( &mut self.runner, &self.host.extensions.context, + probe.as_ref(), step, body, &data, diff --git a/core/engine/src/compiled/graph/plan/run/mod.rs b/core/engine/src/compiled/graph/plan/run/mod.rs index 156e07905..1c0e0c376 100644 --- a/core/engine/src/compiled/graph/plan/run/mod.rs +++ b/core/engine/src/compiled/graph/plan/run/mod.rs @@ -22,7 +22,9 @@ mod loops; mod rows; mod store; mod table; +mod trace; mod typed; +pub(crate) use trace::PlanTrace; type Parents<'r> = &'r dyn Fn(usize) -> Option; @@ -38,6 +40,7 @@ struct Run<'r, 'a> { completed: Completed, iteration: u8, parents: Option>, + trace: Option>>, } impl<'a> Run<'_, 'a> { @@ -88,6 +91,9 @@ impl<'a> Run<'_, 'a> { live = self.alive(live, &mut seen); positions = live.as_ref(); } + if self.trace.is_some() && self.traced_op(seg, op, positions) { + continue; + } match op { Op::Lane(lane) => { if matches!(lane.program, Program::Expression) { @@ -112,7 +118,9 @@ impl<'a> Run<'_, 'a> { Op::Deferred { op, units } => self.deferred(seg, op, units, positions), Op::Rows(op) => { Census::begin(); + let start = std::time::Instant::now(); self.rows(seg, op, positions).await; + self.timed_rows(op.node, start); if Census::on() { self.counted(op, positions); } @@ -232,6 +240,9 @@ impl<'a> Run<'_, 'a> { live = self.alive(live, &mut seen); positions = live.as_ref(); } + if self.trace.is_some() { + self.capture(seg, positions); + } match &seg.end { SegEnd::Finish(_) if self.iteration > 0 => {} SegEnd::Finish(refs) if matches!(refs.as_slice(), [(path, _)] if path.is_empty()) => { @@ -257,8 +268,11 @@ impl<'a> Run<'_, 'a> { }); } SegEnd::Switch { - first, conditions, .. - } => self.fan_out(seg, positions, *first, conditions, children), + first, + conditions, + ids, + .. + } => self.fan_out(seg, positions, *first, conditions, ids, children), } } diff --git a/core/engine/src/compiled/graph/plan/run/rows.rs b/core/engine/src/compiled/graph/plan/run/rows.rs index e91cd743e..0c981f65d 100644 --- a/core/engine/src/compiled/graph/plan/run/rows.rs +++ b/core/engine/src/compiled/graph/plan/run/rows.rs @@ -9,6 +9,7 @@ use crate::compiled::host::NodeError; use crate::compiled::leaf::Mask; use crate::compiled::leaf::{Bits, Leaf}; use crate::compiled::shred::Shredder; +use crate::compiled::trace::record::Probe; use crate::decision_graph::cleaner::VariableCleaner; use crate::model::DecisionNodeKind; use std::rc::Rc; @@ -320,9 +321,22 @@ impl<'a> Run<'_, 'a> { _ => { let data = data.unwrap_or_else(|| Data::plain((0..inputs.len()).collect(), inputs.into())); + let traced = self.trace.is_some(); + let mut walked = Vec::new(); + let probe = traced.then(|| Probe::new(CompiledGraph::wants_fields(step))); let context = self.host.extensions.context.rows(&at); - let (output, failures) = - graph.rowwise(&mut self.runner, &context, step, data, &nodes); + let (output, failures) = graph.rowwise( + &mut self.runner, + &context, + probe.as_ref(), + step, + data, + &nodes, + traced.then_some(&mut walked), + ); + if let Some(probe) = probe { + self.hosted_rows(op.node, &output, Some(probe.finish()), walked); + } for (i, message) in failures { self.store.errors.fail(at[i], &step.node, Rc::from(message)); } diff --git a/core/engine/src/compiled/graph/plan/run/store.rs b/core/engine/src/compiled/graph/plan/run/store.rs index 402649c52..4c7576f7d 100644 --- a/core/engine/src/compiled/graph/plan/run/store.rs +++ b/core/engine/src/compiled/graph/plan/run/store.rs @@ -520,7 +520,7 @@ impl<'a> Store<'a> { } } - fn object(shape: &Shaped<'a>, row: usize) -> Variable { + pub(super) fn object(shape: &Shaped<'a>, row: usize) -> Variable { if let Some((leaf, present)) = &shape.leaf { if Bits::get(present, row) { return leaf.get(row); @@ -564,3 +564,151 @@ impl<'a> Store<'a> { } } } + +pub(super) struct Columned<'a> { + pub paths: Vec>, + pub leaves: Vec>, + pub present: Vec>, + pub wanted: Vec, + pub nulls: bool, +} + +impl<'a> Columned<'a> { + pub fn full(&self) -> bool { + self.present.iter().all(|present| *present == self.wanted) + } + + pub fn at(&self, path: &str) -> Option { + self.paths.iter().position(|own| own.as_ref() == path) + } + + pub fn leaf(&self, index: usize) -> (Leaf<'a>, Option>) { + let present = &self.present[index]; + ( + self.leaves[index].clone(), + (*present != self.wanted).then(|| Rc::from(present.clone())), + ) + } + + pub fn layer( + &self, + rows: &Rc<[usize]>, + total: usize, + ) -> crate::compiled::graph::data::Layer<'a> { + use crate::compiled::leaf::Mask; + let whole = rows.len() == total; + let columns = self + .leaves + .iter() + .map(|leaf| match whole { + true => leaf.clone(), + false => leaf.pick(rows), + }) + .collect(); + let present = (!self.full()).then(|| { + self.present + .iter() + .map(|present| match whole { + true => Mask::Bits(Rc::from(present.clone())), + false => Mask::Picked(Rc::from(present.clone()), rows.clone()), + }) + .collect() + }); + crate::compiled::graph::data::Layer::new(self.paths.clone().into(), columns, present) + } +} + +impl<'a> Store<'a> { + pub(super) fn columned( + shape: &Shaped<'a>, + rows: &[usize], + total: usize, + ) -> Option> { + let words = total.div_ceil(64); + let wanted = match rows.len() == total { + true => Bits::ones(total), + false => { + let mut bits = vec![0u64; words]; + rows.iter().for_each(|&row| Bits::set(&mut bits, row, true)); + bits + } + }; + let word = |bits: &Rc<[u64]>, at: usize| bits.get(at).copied().unwrap_or(0); + if let Some((_, present)) = &shape.leaf { + if (0..words).any(|at| word(present, at) & wanted[at] != 0) { + return None; + } + } + let obj = shape.obj.as_ref()?; + if (0..words).any(|at| wanted[at] & !word(obj, at) != 0) { + return None; + } + let mut out = Columned { + paths: Vec::new(), + leaves: Vec::new(), + present: Vec::new(), + wanted: wanted.clone(), + nulls: false, + }; + Self::flatten(shape, "", &wanted, total, true, &mut out)?; + Some(out) + } + + fn flatten( + shape: &Shaped<'a>, + prefix: &str, + active: &[u64], + total: usize, + root: bool, + out: &mut Columned<'a>, + ) -> Option<()> { + let words = active.len(); + let word = |bits: &Rc<[u64]>, at: usize| bits.get(at).copied().unwrap_or(0); + let mut exists = vec![0u64; words]; + for (key, child) in &shape.fields { + if key.contains('.') { + return None; + } + let path: Arc = match prefix.is_empty() { + true => Arc::from(key.as_ref()), + false => Arc::from(format!("{prefix}.{key}")), + }; + let leaf: Vec = (0..words) + .map(|at| match &child.leaf { + Some((_, present)) => word(present, at) & active[at], + None => 0, + }) + .collect(); + let object: Vec = (0..words) + .map(|at| match &child.obj { + Some(obj) => word(obj, at) & active[at] & !leaf[at], + None => 0, + }) + .collect(); + if let Some((column, _)) = &child.leaf { + if !Bits::none(&leaf) { + let valued = column.valued(total); + out.nulls |= + (0..words).any(|at| leaf[at] & !valued.get(at).copied().unwrap_or(0) != 0); + out.paths.push(path.clone()); + out.leaves.push(column.clone()); + out.present.push(leaf.clone()); + } + } + if !Bits::none(&leaf) && !child.fields.is_empty() { + return None; + } + match child.fields.is_empty() { + true if !Bits::none(&object) => return None, + true => {} + false => Self::flatten(child, &path, &object, total, false, out)?, + } + Bits::or(&mut exists, &leaf); + Bits::or(&mut exists, &object); + } + if !root && (0..words).any(|at| active[at] & !exists[at] != 0) { + return None; + } + Some(()) + } +} diff --git a/core/engine/src/compiled/graph/plan/run/table.rs b/core/engine/src/compiled/graph/plan/run/table.rs index 4900e873a..6f2595c74 100644 --- a/core/engine/src/compiled/graph/plan/run/table.rs +++ b/core/engine/src/compiled/graph/plan/run/table.rs @@ -42,7 +42,7 @@ impl<'a> Run<'_, 'a> { }) }) .collect(); - let keyed = match (op.mode, table.stable) { + let keyed = match (op.mode, table.stable && self.trace.is_none()) { (TableMode::First, true) => { let present: Vec> = leaves.iter().flatten().cloned().collect(); match present.len() > 1 { @@ -108,6 +108,7 @@ impl<'a> Run<'_, 'a> { context, scopes: Bound::blank(evaluated), columns, + probe: self.probe(), bind: Box::new(move |key: &str| match key.starts_with('$') { true => Bind::Row, false => names diff --git a/core/engine/src/compiled/graph/plan/run/trace.rs b/core/engine/src/compiled/graph/plan/run/trace.rs new file mode 100644 index 000000000..43a64bc13 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/trace.rs @@ -0,0 +1,736 @@ +use super::store::{Columned, Shaped, Store}; +use super::Run; +use crate::compiled::graph::data::Data; +use crate::compiled::graph::plan::{Op, SegPlan}; +use crate::compiled::graph::schedule::End; +use crate::compiled::graph::{Body, CompiledGraph, Kind}; +use crate::compiled::leaf::{Bits, Leaf}; +use crate::compiled::trace::batch::{BatchEvent, Cols, Encoding, Facts, Value}; +use crate::compiled::trace::collect::{Fact, Slot}; +use crate::compiled::trace::record::{KernelFacts, NodeShape, Probe}; +use petgraph::prelude::NodeIndex; +use smallvec::SmallVec; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::Variable; + +fn trace_hosted( + trace: &mut Option>>, + node: NodeIndex, + rows: usize, +) -> Option { + let trace = trace.as_mut()?; + let at = trace.hosted.iter().position(|h| h.node == node)?; + let hosted = trace.hosted.swap_remove(at); + (hosted.values.len() == rows).then_some(hosted) +} + +struct Hosted { + node: NodeIndex, + values: Rc<[Variable]>, + kernel: Option, + walked: Vec, +} +pub(super) type Groups = [(Vec, Option>)]; + +enum Own<'o, 'a> { + Values(&'o Rc<[Variable]>), + Columns(&'o Columned<'a>), +} + +pub(crate) enum Source<'a> { + Rows { + requests: Rc<[Variable]>, + shared: bool, + }, + Derived { + data: Rc>, + reserved: crate::compiled::trace::batch::Reserved<'a>, + }, +} + +pub(crate) struct PlanTrace<'a> { + pub(crate) events: Vec>, + kernels: Vec<(NodeIndex, Option)>, + probe: Option>, + hosted: Vec, + times: Vec<(NodeIndex, u64)>, + values: Vec>>>, + pub(crate) source: Source<'a>, + lazy: bool, + pub(crate) aliased: bool, + pub(crate) refused: Option<&'static str>, +} + +impl<'a> PlanTrace<'a> { + pub(crate) fn new(slots: usize, source: Source<'a>, lazy: bool) -> Self { + Self { + events: Vec::new(), + kernels: Vec::new(), + probe: None, + hosted: Vec::new(), + times: Vec::new(), + values: vec![None; slots], + source, + lazy, + aliased: true, + refused: None, + } + } + + fn refuse(&mut self, reason: &'static str) { + self.refused.get_or_insert(reason); + } + + fn piece(&self, slot: Slot, rows: &Rc<[usize]>) -> Option>> { + let piece = self.values.get(slot as usize)?.as_ref()?; + match Rc::ptr_eq(&piece.rows, rows) || piece.rows == *rows { + true => Some(piece.clone()), + false => Some(Rc::new(Data::gather(std::slice::from_ref(piece), rows))), + } + } + + fn input(&self, parents: &[NodeIndex], rows: &Rc<[usize]>) -> Rc> { + let mut gathered: Vec>> = parents + .iter() + .filter_map(|parent| self.piece(parent.index() as Slot, rows)) + .collect(); + if let [single] = gathered.as_slice() { + if single.single() { + return gathered.swap_remove(0); + } + } + Rc::new(Data::merged( + rows, + gathered.iter().map(|piece| piece.copied()).collect(), + )) + } + + fn nodes( + &self, + graph: &CompiledGraph, + visible: &[NodeIndex], + rows: &Rc<[usize]>, + ) -> Vec { + let named: Vec<(&str, Rc<[Variable]>)> = visible + .iter() + .filter_map(|nid| { + let step = graph.step_at(*nid)?; + let piece = self.piece(nid.index() as Slot, rows)?; + Some((step.node.name.as_ref(), piece.materialized())) + }) + .collect(); + (0..rows.len()) + .map(|at| { + let object = Variable::empty_object(); + if let Variable::Object(map) = &object { + let mut map = map.borrow_mut(); + for (name, values) in &named { + if let Some(value) = values.get(at) { + map.insert((*name).into(), value.clone()); + } + } + } + object + }) + .collect() + } +} + +impl<'a> Run<'_, 'a> { + pub(super) fn traced_op( + &mut self, + seg: &SegPlan, + op: &Op, + positions: Option<&Rc<[usize]>>, + ) -> bool { + match op { + Op::Typed { units, .. } | Op::Deferred { units, .. } => { + let mut seen = self.store.errors.generation(); + let mut live = positions.cloned(); + for unit in units { + if self.store.errors.generation() != seen { + live = self.alive(live, &mut seen); + } + self.traced_unit(seg, unit, live.as_ref()); + } + true + } + Op::Rows(rows) + if self + .graph + .step_at(rows.node) + .is_none_or(|step| matches!(step.kind, Kind::Host(_))) => + { + self.refuse("hosted node"); + false + } + Op::Lane(_) | Op::Table(_) | Op::Loop { .. } => { + self.traced_unit(seg, op, positions); + true + } + Op::Child(_) => { + self.refuse("sub-decision"); + false + } + _ => false, + } + } + + fn refuse(&mut self, reason: &'static str) { + if let Some(trace) = self.trace.as_mut() { + trace.refuse(reason); + } + } + + pub(super) fn probe(&self) -> Option> { + self.trace.as_ref()?.probe.clone() + } + + pub(super) fn hosted_rows( + &mut self, + node: NodeIndex, + output: &Data<'_>, + kernel: Option, + walked: Vec, + ) { + if let Some(trace) = self.trace.as_mut() { + trace.hosted.push(Hosted { + node, + values: match trace.aliased { + true => output + .materialized() + .iter() + .map(Variable::deep_clone) + .collect(), + false => output.materialized(), + }, + kernel, + walked, + }); + } + } + + pub(super) fn timed_rows(&mut self, node: NodeIndex, start: Instant) { + if let Some(trace) = self.trace.as_mut() { + trace.times.push((node, start.elapsed().as_nanos() as u64)); + } + } + + fn traced_unit(&mut self, seg: &SegPlan, op: &Op, positions: Option<&Rc<[usize]>>) { + let node = match op { + Op::Lane(lane) => lane.node, + Op::Table(table) => table.node, + Op::Loop { node, .. } => *node, + _ => { + self.unit(seg, op, positions); + return; + } + }; + let start = Instant::now(); + let probe = Probe::new( + self.graph + .step_at(node) + .is_some_and(CompiledGraph::wants_fields), + ); + if let Some(trace) = self.trace.as_mut() { + trace.probe = Some(probe.clone()); + } + match op { + Op::Lane(lane) => self.lane(seg, lane, positions, true), + Op::Table(table) => self.table(seg, table, positions), + Op::Loop { node, list, out } => self.looped(seg, *node, *list, *out, positions), + _ => {} + } + let ns = start.elapsed().as_nanos() as u64; + if let Some(trace) = self.trace.as_mut() { + trace.probe = None; + trace.times.push((node, ns)); + trace.kernels.push((node, Some(probe.finish()))); + } + } + + fn captured(&self, shape: &Shaped<'a>, rows: &[usize]) -> Rc<[Variable]> { + match rows.len() == self.store.rows { + true => Store::objects(shape, self.store.rows).into(), + false => rows.iter().map(|&row| Store::object(shape, row)).collect(), + } + } + + pub(super) fn capture(&mut self, seg: &SegPlan, positions: Option<&Rc<[usize]>>) { + if self.trace.as_ref().is_none_or(|t| t.refused.is_some()) { + return; + } + let rows: Rc<[usize]> = match positions { + Some(positions) => positions.clone(), + None => (0..self.store.rows).collect(), + }; + let total = self.store.rows; + let graph = self.graph; + for event in seg.segment.events.iter() { + let Some(step) = graph.step_at(event.node) else { + continue; + }; + let slot = event.node.index() as Slot; + let Some(trace) = self.trace.as_mut() else { + return; + }; + let ns = trace + .times + .iter() + .filter(|(n, _)| *n == event.node) + .map(|(_, ns)| *ns) + .sum(); + let kernel = trace + .kernels + .iter() + .position(|(n, _)| *n == event.node) + .and_then(|at| trace.kernels.swap_remove(at).1); + let parents: Box<[Slot]> = event.parents.iter().map(|p| p.index() as Slot).collect(); + let (input, values, output, facts, encoding) = match &step.kind { + Kind::Input => { + let values = match &trace.source { + Source::Derived { data, .. } => match rows.len() == total { + true => data.clone(), + false => Rc::new(Data::gather(std::slice::from_ref(data), &rows)), + }, + Source::Rows { + requests, + shared: true, + } => Rc::new(Data::plain( + rows.clone(), + rows.iter() + .map(|&row| requests.get(row).cloned().unwrap_or(Variable::Null)) + .collect(), + )), + Source::Rows { shared: false, .. } => { + let Some(view) = seg + .views + .iter() + .rev() + .find(|(n, _)| *n == event.node) + .map(|(_, v)| v.clone()) + else { + self.refuse("node without a view"); + return; + }; + let shape = self.store.shape(seg, &view); + Rc::new(Data::plain(rows.clone(), self.captured(&shape, &rows))) + } + }; + ( + false, + values.clone(), + Value::Data(values), + Facts::None, + Encoding::Request, + ) + } + Kind::Output => { + let values = trace.input(&event.parents, &rows); + (true, values, Value::Null, Facts::None, Encoding::Null) + } + Kind::Node { transform, .. } + if !seg.results.iter().any(|(n, _)| *n == event.node) => + { + let nodes = match step.nodes + && crate::ZEN_CONFIG + .nodes_in_context + .load(std::sync::atomic::Ordering::Relaxed) + { + true => trace.nodes(graph, &event.visible, &rows), + false => Vec::new(), + }; + let inputs: Vec = + trace.input(&event.parents, &rows).materialized().to_vec(); + let hosted = trace_hosted(&mut self.trace, event.node, rows.len()); + let (facts, values): (Facts<'a>, Rc<[Variable]>) = match hosted { + Some(hosted) if hosted.walked.len() == rows.len() => { + (Facts::Rows(hosted.walked), hosted.values) + } + Some(hosted) => { + let data = Data::plain(rows.clone(), inputs.clone().into()); + let shape = CompiledGraph::node_shape(step, Some(&data)); + let facts = hosted + .kernel + .ok_or("evaluated outside the batch kernels") + .and_then(|kernel| { + kernel.facts(graph.template(), slot, shape, rows.len()) + }) + .unwrap_or_else(|reason| { + crate::compiled::trace::reevaluated(reason, rows.len()); + Facts::Rows(CompiledGraph::facts_of( + step, + &inputs, + &nodes, + &self.host.extensions.context.rows(&rows), + )) + }); + (facts, hosted.values) + } + None => { + crate::compiled::trace::reevaluated( + "plan hosts the node row by row", + rows.len(), + ); + let (facts, outputs) = CompiledGraph::evaluated( + step, + &inputs, + &nodes, + &self.host.extensions.context.rows(&rows), + ); + (Facts::Rows(facts), outputs.into()) + } + }; + let touched = graph.template().touched(slot).is_some(); + let encoding = match (transform.pass_through, touched) { + (false, _) => Encoding::Checked(false), + (true, true) => Encoding::Touched(None), + (true, false) => Encoding::Checked(true), + }; + let output = Rc::new(Data::plain(rows.clone(), values)); + (true, output.clone(), Value::Data(output), facts, encoding) + } + Kind::Node { transform, body } => { + let Some(own) = seg + .results + .iter() + .rev() + .find(|(n, _)| *n == event.node) + .map(|(_, v)| v.clone()) + else { + self.refuse("node without its own view"); + return; + }; + let shape = self.store.shape(seg, &own); + let Some(trace) = self.trace.as_ref() else { + return; + }; + let input = trace.input(&event.parents, &rows); + let columned = match trace.lazy { + true => Store::columned(&shape, &rows, total) + .filter(|columned| !(transform.pass_through && columned.nulls)), + false => None, + }; + let touched = graph.template().touched(slot).is_some(); + let keys = + |facts: &Facts| match (facts, transform.pass_through, transform.looped) { + (Facts::Results((keys, _)), false, false) => { + let prefix = transform.output_path.as_deref(); + Some( + keys.iter() + .map(|key| match prefix { + Some(prefix) => format!("{prefix}.{key}"), + None => key.to_string(), + }) + .collect::>(), + ) + } + _ => None, + }; + match columned { + Some(columned) => { + let layer = columned.layer(&rows, total); + let facts = match self.facts( + step, + event, + body, + transform.looped, + kernel, + &rows, + &input, + Own::Columns(&columned), + ) { + Some(facts) => facts, + None => { + self.refuse("node reads $nodes"); + return; + } + }; + let values = Rc::new(match transform.pass_through { + false => Data::record(&rows, layer, None), + true => input.layered(layer), + }); + let complete = keys(&facts).map(|paths| { + let exact: Vec> = + paths.iter().map(|path| columned.at(path)).collect(); + match exact.iter().all(Option::is_some) { + true => rows + .iter() + .map(|&row| { + exact.iter().flatten().all(|&index| { + Bits::get(&columned.present[index], row) + }) + }) + .collect::>(), + false => self + .captured(&shape, &rows) + .iter() + .map(|o| paths.iter().all(|p| o.dot(p).is_some())) + .collect(), + } + }); + let encoding = match (transform.pass_through, touched, complete) { + (false, _, Some(complete)) => Encoding::Results(complete), + (false, _, None) => Encoding::Checked(false), + (true, true, _) => Encoding::Touched(Some(input.clone())), + (true, false, _) => Encoding::Checked(true), + }; + (true, values.clone(), Value::Data(values), facts, encoding) + } + None => { + let own = self.captured(&shape, &rows); + let values: Rc<[Variable]> = match transform.pass_through { + false => own.clone(), + true => input + .materialized() + .iter() + .zip(own.iter()) + .map(|(before, own)| before.clone().merge_clone(own)) + .collect(), + }; + let facts = match self.facts( + step, + event, + body, + transform.looped, + kernel, + &rows, + &input, + Own::Values(&own), + ) { + Some(facts) => facts, + None => { + self.refuse("node reads $nodes"); + return; + } + }; + let complete = keys(&facts).map(|paths| { + own.iter() + .map(|o| paths.iter().all(|p| o.dot(p).is_some())) + .collect::>() + }); + let encoding = match (transform.pass_through, touched, complete) { + (false, _, Some(complete)) => Encoding::Results(complete), + (false, _, None) => Encoding::Checked(false), + (true, true, _) => Encoding::Touched(None), + (true, false, _) => Encoding::Checked(true), + }; + let output = Rc::new(Data::plain(rows.clone(), values)); + (true, output.clone(), Value::Data(output), facts, encoding) + } + } + } + Kind::Switch { .. } | Kind::Host(_) => { + self.refuse("hosted node"); + return; + } + }; + let Some(trace) = self.trace.as_mut() else { + return; + }; + trace.events.push(BatchEvent { + slot, + parents, + rows: rows.clone(), + input, + output: Some(output), + ns, + facts, + encoding, + }); + if let Some(entry) = trace.values.get_mut(slot as usize) { + *entry = Some(values); + } + } + if let Some(trace) = self.trace.as_mut() { + trace.kernels.clear(); + trace.hosted.clear(); + trace.times.clear(); + } + } + + #[allow(clippy::too_many_arguments)] + fn facts( + &self, + step: &crate::compiled::graph::Step, + event: &crate::compiled::graph::schedule::Execute, + body: &Body, + looped: bool, + kernel: Option, + rows: &Rc<[usize]>, + input: &Rc>, + own: Own<'_, 'a>, + ) -> Option> { + let count = rows.len(); + let reason = match (looped, body) { + (true, _) => match kernel { + Some(kernel) => { + let shape = CompiledGraph::node_shape(step, Some(input)); + let slot = event.node.index() as Slot; + match kernel.facts(self.graph.template(), slot, shape, count) { + Ok(facts) => return Some(facts), + Err(reason) => reason, + } + } + None => "evaluated outside the batch kernels", + }, + (false, Body::Expression { keys, .. }) if CompiledGraph::keyed_results(step) => { + let prefix = match &step.kind { + Kind::Node { transform, .. } => transform.output_path.clone(), + _ => None, + }; + let path = |key: &Arc| match &prefix { + Some(prefix) => format!("{prefix}.{key}"), + None => key.to_string(), + }; + fn dotted<'x>(values: &Rc<[Variable]>, path: &str) -> Leaf<'x> { + Leaf::Any( + values + .iter() + .map(|o| o.dot(path).unwrap_or(Variable::Null)) + .collect(), + ) + } + let leaves = match &own { + Own::Values(values) => { + Cols::Owned(keys.iter().map(|key| dotted(values, &path(key))).collect()) + } + Own::Columns(columned) => { + let total = self.store.rows; + let mut whole: Option> = None; + let exact: Vec> = + keys.iter().map(|key| columned.at(&path(key))).collect(); + match exact.iter().all(Option::is_some) { + true => Cols::Lazy( + exact + .iter() + .flatten() + .map(|&index| columned.leaf(index)) + .collect(), + (rows.len() != total).then(|| rows.clone()), + ), + false => Cols::Lazy( + keys.iter() + .zip(&exact) + .map(|(key, exact)| match exact { + Some(index) => { + let (leaf, present) = columned.leaf(*index); + let leaf = match rows.len() == total { + true => leaf, + false => leaf.pick(rows), + }; + let present = present.map(|present| { + Rc::from(Bits::gather(&present, rows)) + }); + (leaf, present) + } + None => ( + dotted( + whole.get_or_insert_with(|| { + Data::record( + rows, + columned.layer(rows, total), + None, + ) + .materialized() + }), + &path(key), + ), + None, + ), + }) + .collect(), + None, + ), + } + } + }; + return Some(Facts::Results((keys.clone(), leaves))); + } + (false, Body::Expression { .. }) => "expression without one result per key", + (false, Body::Table(table)) => { + let slot = event.node.index() as Slot; + let shape = NodeShape::Table { + first: table.first_hit(), + derived: CompiledGraph::derived_refs(step), + }; + match kernel.map(|kernel| kernel.facts(self.graph.template(), slot, shape, count)) { + Some(Ok(facts)) => return Some(facts), + Some(Err(reason)) => reason, + None => "evaluated outside the batch kernels", + } + } + }; + if step.nodes { + return None; + } + crate::compiled::trace::reevaluated(reason, count); + let inputs = input.materialized(); + Some(Facts::Rows(CompiledGraph::facts_of( + step, + &inputs, + &[], + &self.host.extensions.context.picked(rows.clone()), + ))) + } + + pub(super) fn trace_switch( + &mut self, + seg: &SegPlan, + positions: Option<&Rc<[usize]>>, + ids: &[std::sync::Arc], + groups: &Groups, + ns: u64, + ) { + if self.trace.as_ref().is_none_or(|t| t.refused.is_some()) { + return; + } + let End::Switch { node, parents, .. } = &seg.segment.end else { + return; + }; + let rows: Rc<[usize]> = match positions { + Some(positions) => positions.clone(), + None => (0..self.store.rows).collect(), + }; + let slot = node.index() as Slot; + let template = self.graph.template().clone(); + let statements: Vec> = + ids.iter().map(|id| template.statement(slot, id)).collect(); + let mut taken: Vec> = vec![SmallVec::new(); rows.len()]; + for (key, members) in groups { + let picked: SmallVec<[u32; 4]> = (0..ids.len()) + .filter(|i| key.get(i / 64).is_some_and(|w| w & (1 << (i % 64)) != 0)) + .filter_map(|i| statements[i]) + .collect(); + match members { + None => taken.iter_mut().for_each(|t| *t = picked.clone()), + Some(members) => { + for row in members.iter() { + if let Ok(at) = rows.binary_search(row) { + taken[at] = picked.clone(); + } + } + } + } + } + let Some(trace) = self.trace.as_mut() else { + return; + }; + let merged = trace.input(parents, &rows); + trace.events.push(BatchEvent { + slot, + parents: parents.iter().map(|p| p.index() as Slot).collect(), + rows: rows.clone(), + input: true, + output: None, + ns, + facts: Facts::Branches(taken), + encoding: Encoding::Passed, + }); + if let Some(entry) = trace.values.get_mut(slot as usize) { + *entry = Some(merged); + } + } +} diff --git a/core/engine/src/compiled/graph/state/exec.rs b/core/engine/src/compiled/graph/state/exec.rs index 8d5ae8d6f..2b7b20cc1 100644 --- a/core/engine/src/compiled/graph/state/exec.rs +++ b/core/engine/src/compiled/graph/state/exec.rs @@ -1,4 +1,5 @@ use crate::compiled::content::Content; +use crate::compiled::exact::graph::NodeRecorder; use crate::compiled::graph::data::{Col, Data}; use crate::compiled::graph::schedule::Execute; use crate::compiled::graph::{data, Body, CompiledGraph, Kind, NodeColumn, State, Step}; @@ -8,9 +9,12 @@ use crate::compiled::host::input::dates::DeclaredDates; use crate::compiled::host::variable_json::{Guards, VariableNode}; use crate::compiled::host::NodeError; use crate::compiled::host::{NodeContextConfig, NodeHandlerExtensions}; +use crate::compiled::trace::batch::{Encoding, Facts, Value}; +use crate::compiled::trace::record::Probe; use crate::model::DecisionNodeKind; use std::rc::Rc; use std::sync::Arc; +use std::time::Instant; use zen_expression::context::EvaluationContext; use zen_expression::lane::LaneRunner; use zen_expression::Variable; @@ -31,13 +35,14 @@ impl CompiledGraph { let Some(step) = self.step_at(event.node) else { return; }; - let data = match step.kind { + let start = Instant::now(); + let data = Rc::new(match step.kind { Kind::Input => Data::plain( rows.clone(), rows.iter().map(|&r| inputs[r].clone()).collect(), ), _ => Self::input_of(state, &event.parents, rows), - }; + }); let (nodes, extra) = self.node_inputs( step, state, @@ -47,15 +52,39 @@ impl CompiledGraph { ); if matches!(step.kind, Kind::Host(_)) { - let materialized = data.materialized(); + let materialized = match state.traces.is_some() { + true => Self::merged_rows(state, &event.parents, rows).into(), + false => data.materialized(), + }; let batched = state.errors.len() > 1; + let traced = state.traces.is_some(); 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 => { + let (results, facts) = match (replayed, traced) { + (_, true) => { + let nodes = match step.nodes && state.with_nodes && nodes.is_empty() { + true => self + .nodes_of(state, &event.visible, rows) + .into_iter() + .map(Some) + .collect(), + false => nodes, + }; + let (results, facts) = Box::pin(Self::hosted_traced( + step, + &materialized, + &nodes, + &scoped, + max_depth, + state.nesting.iteration, + )) + .await; + (results, Facts::Rows(facts)) + } + (None, false) => ( Box::pin(Self::hosted( step, &materialized, @@ -65,9 +94,10 @@ impl CompiledGraph { state.nesting.iteration, batched, )) - .await - } - Some(replayed) => { + .await, + Facts::None, + ), + (Some(replayed), false) => { let missing: Vec = (0..rows.len()).filter(|&i| replayed[i].is_none()).collect(); let inputs: Vec = @@ -94,13 +124,16 @@ impl CompiledGraph { } } .into_iter(); - replayed - .into_iter() - .map(|done| match done { - Some(value) => Ok(value), - None => fresh.next().unwrap_or(Ok(Variable::Null)), - }) - .collect() + ( + replayed + .into_iter() + .map(|done| match done { + Some(value) => Ok(value), + None => fresh.next().unwrap_or(Ok(Variable::Null)), + }) + .collect(), + Facts::None, + ) } }; let mut values = Vec::with_capacity(rows.len()); @@ -113,13 +146,24 @@ impl CompiledGraph { } } } - state.nodes[event.node.index()].push(Rc::new(Data::plain(rows.clone(), values.into()))); + let output = Rc::new(Data::plain(rows.clone(), values.into())); + state.nodes[event.node.index()].push(output.clone()); + Self::trace_event( + state, + event, + rows, + true, + Some(Value::Data(output)), + start, + facts, + Encoding::Generic, + ); return; } - let (output, failures): (Data<'a>, Vec<(usize, String)>) = match &step.kind { - Kind::Switch { .. } | Kind::Host(_) => (data, Vec::new()), - Kind::Output if !step.schema => (data, Vec::new()), + let (output, failures): (Rc>, Vec<(usize, String)>) = match &step.kind { + Kind::Switch { .. } | Kind::Host(_) => (data.clone(), Vec::new()), + Kind::Output if !step.schema => (data.clone(), Vec::new()), Kind::Input if !step.schema && Self::unresolved(content, &step.node) => { let values: Col = data .materialized() @@ -128,21 +172,43 @@ impl CompiledGraph { DeclaredDates::prepare(value, None).unwrap_or_else(|| value.clone()) }) .collect(); - (Data::plain(rows.clone(), values), Vec::new()) + (Rc::new(Data::plain(rows.clone(), values)), Vec::new()) } Kind::Input | Kind::Output => { let (values, failures) = self .bounded(step, &data.materialized(), &nodes, content, extensions) .await; - (Data::plain(rows.clone(), values.into()), failures) + (Rc::new(Data::plain(rows.clone(), values.into())), failures) + } + Kind::Node { .. } => { + let (output, failures) = + self.node(&state.context, None, step, rows, &data, &nodes, &extra); + (Rc::new(output), failures) } - Kind::Node { .. } => self.node(&state.context, step, rows, &data, &nodes, &extra), }; for (i, message) in failures { state.errors.fail(rows[i], &step.node, message); } - state.nodes[event.node.index()].push(Rc::new(output)); + state.nodes[event.node.index()].push(output.clone()); + if state.traces.is_some() { + let encoding = self.encoding(step, event, &data); + let (input, output) = match step.kind { + Kind::Input => (false, Some(Value::Data(output))), + Kind::Output => (true, Some(Value::Null)), + _ => (true, Some(Value::Data(output))), + }; + Self::trace_event( + state, + event, + rows, + input, + output, + start, + Facts::None, + encoding, + ); + } } pub(in crate::compiled::graph) async fn hosted( @@ -292,13 +358,16 @@ impl CompiledGraph { (values, failures) } + #[allow(clippy::too_many_arguments)] pub(in crate::compiled::graph) fn rowwise<'a>( &self, runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, data: Data<'a>, nodes: &[Option], + mut facts: Option<&mut Vec>, ) -> (Data<'a>, Vec<(usize, String)>) { let rows: Rc<[usize]> = (0..data.len()).collect(); if Self::foreign_input(step, &data) { @@ -310,7 +379,14 @@ impl CompiledGraph { .enumerate() .map(|(i, value)| { let node = nodes.get(i).cloned().flatten(); - match Self::walked(step, value.clone(), node, true, &context.at(i)) { + let at = context.at(i); + let recorder = facts.is_some().then(NodeRecorder::default); + let result = + Self::walked(step, value.clone(), node, true, &at, recorder.as_ref()); + if let (Some(facts), Some(recorder)) = (facts.as_deref_mut(), recorder) { + facts.push(recorder.finish(None)); + } + match result { Ok(output) => output, Err(message) => { failures.push((i, message)); @@ -321,12 +397,14 @@ impl CompiledGraph { .collect(); return (Data::plain(rows, values), failures); } - self.node_with(runner, context, step, &rows, &data, nodes, &[]) + self.node_with(runner, context, probe, step, &rows, &data, nodes, &[]) } + #[allow(clippy::too_many_arguments)] fn node<'a>( &self, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, rows: &Rc<[usize]>, data: &Data<'a>, @@ -334,7 +412,7 @@ impl CompiledGraph { extra: &[NodeColumn<'a>], ) -> (Data<'a>, Vec<(usize, String)>) { Self::RUNNER.with_borrow_mut(|runner| { - self.node_with(runner, context, step, rows, data, nodes, extra) + self.node_with(runner, context, probe, step, rows, data, nodes, extra) }) } @@ -343,6 +421,7 @@ impl CompiledGraph { &self, runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, rows: &Rc<[usize]>, data: &Data<'a>, @@ -371,13 +450,13 @@ impl CompiledGraph { match (rebase, &transform.output_path, wide) { (Some(rebase), None, true) if !overlapping => { crate::compiled::census::Census::mark("layered"); - Self::bound(context, step, data, nodes, extra, rebase, |bound| { + Self::bound(context, probe, 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(context, step, data, nodes, extra, rebase, |bound| { + Self::bound(context, probe, step, data, nodes, extra, rebase, |bound| { Self::layered( runner, body, @@ -390,7 +469,7 @@ impl CompiledGraph { } (Some(None), Some(path), true) if keyed => { crate::compiled::census::Census::mark("placed"); - Self::bound(context, step, data, nodes, extra, None, |bound| { + Self::bound(context, probe, step, data, nodes, extra, None, |bound| { Self::placed(runner, body, path, transform.pass_through, data, bound) }) } @@ -406,6 +485,7 @@ impl CompiledGraph { Self::looped( runner, &context.picked(rows.clone()), + probe, step, body, transform, @@ -419,6 +499,7 @@ impl CompiledGraph { let results = Self::transformed( runner, &context.picked(rows.clone()), + probe, step, body, transform, @@ -481,8 +562,13 @@ impl CompiledGraph { rows: &Rc<[usize]>, state: &mut State<'a>, ) { - let data = Self::input_of(state, &event.parents, rows); - let foreign = Self::foreign_input(step, &data); + let start = Instant::now(); + let traced = state.traces.is_some(); + let data = Rc::new(Self::input_of(state, &event.parents, rows)); + let foreign = Self::foreign_input(step, &data) + || (traced && matches!(step.kind, Kind::Node { .. }) && step.draws()); + let probe = traced.then(|| Probe::new(Self::wants_fields(step))); + let mut walked: Option> = None; let (output, failures) = match &step.kind { Kind::Node { .. } if foreign => { let values = data.materialized(); @@ -495,13 +581,21 @@ impl CompiledGraph { false => Vec::new(), }; let mut failures = Vec::new(); + let mut facts = traced.then(|| Vec::with_capacity(values.len())); let context = state.context.picked(rows.clone()); let outputs: Vec = values .iter() .enumerate() .map(|(i, value)| { let node = nodes.get(i).cloned().flatten(); - match Self::walked(step, value.clone(), node, true, &context.at(i)) { + let at = context.at(i); + let recorder = facts.is_some().then(NodeRecorder::default); + let result = + Self::walked(step, value.clone(), node, true, &at, recorder.as_ref()); + if let (Some(facts), Some(recorder)) = (facts.as_mut(), recorder) { + facts.push(recorder.finish(None)); + } + match result { Ok(output) => output, Err(message) => { failures.push((i, message)); @@ -510,7 +604,8 @@ impl CompiledGraph { } }) .collect(); - (Data::plain(rows.clone(), outputs.into()), failures) + walked = facts; + (Rc::new(Data::plain(rows.clone(), outputs.into())), failures) } Kind::Node { .. } => { let (nodes, extra) = self.node_inputs( @@ -520,13 +615,46 @@ impl CompiledGraph { rows, step.column_path(rows.len()), ); - self.node(&state.context, step, rows, &data, &nodes, &extra) + let (output, failures) = self.node( + &state.context, + probe.as_ref(), + step, + rows, + &data, + &nodes, + &extra, + ); + (Rc::new(output), failures) } - _ => (data, Vec::new()), + _ => (data.clone(), Vec::new()), }; for (i, message) in failures { state.errors.fail(rows[i], &step.node, message); } - state.nodes[event.node.index()].push(Rc::new(output)); + state.nodes[event.node.index()].push(output.clone()); + if traced && !matches!(step.kind, Kind::Switch { .. }) { + let facts = match (&step.kind, walked) { + (Kind::Node { .. }, Some(walked)) => Facts::Rows(walked), + (Kind::Node { .. }, None) => { + self.kernel_facts(step, probe, state, event, rows, &data) + } + _ => Facts::None, + }; + let encoding = self.encoding(step, event, &data); + let output = match step.kind { + Kind::Output => Value::Null, + _ => Value::Data(output), + }; + Self::trace_event( + state, + event, + rows, + true, + Some(output), + start, + facts, + encoding, + ); + } } } diff --git a/core/engine/src/compiled/graph/state/host.rs b/core/engine/src/compiled/graph/state/host.rs index e75974b7f..2a8b34824 100644 --- a/core/engine/src/compiled/graph/state/host.rs +++ b/core/engine/src/compiled/graph/state/host.rs @@ -1,6 +1,6 @@ use crate::compiled::bound::Bound; use crate::compiled::content::Content; -use crate::compiled::exact::graph::Row; +use crate::compiled::exact::graph::{NodeRecorder, Row}; use crate::compiled::graph::data::{Col, Data, Layer}; use crate::compiled::graph::{call, schema, Body, CompiledGraph, Step}; use crate::compiled::host::custom::CustomNodeHandler; @@ -19,6 +19,7 @@ use crate::compiled::table::TableOut; use crate::loader::DynamicLoader; use crate::model::DecisionNodeKind; use jsonschema::Validator; +use std::rc::Rc; use std::sync::Arc; use zen_expression::lane::{LaneRunner, Programs}; use zen_expression::Variable; @@ -134,11 +135,13 @@ impl CompiledGraph { .map(|out| table.value(out)) .collect(), }; - let layer = Layer::new( - Arc::from([path.clone()]), - vec![Leaf::Any(values.into())], - None, - ); + let values: Rc<[Variable]> = values.into(); + if let Body::Expression { keys, .. } = body { + if let Some(probe) = &bound.probe { + probe.record_objects(keys, &values); + } + } + let layer = Layer::new(Arc::from([path.clone()]), vec![Leaf::Any(values)], None); let data = match pass_through { true => input.layered(layer), false => Data::record(&input.rows, layer, None), @@ -183,13 +186,16 @@ impl CompiledGraph { .map(|key| Arc::from(format!("{prefix}.{key}"))) .collect(), }; - let layer = Layer::new( - keys, - outs.iter_mut() - .map(|out| Leaf::typed(Array::from_output(out))) - .collect(), - None, - ); + let leaves: Vec = outs + .iter_mut() + .map(|out| Leaf::typed(Array::from_output(out))) + .collect(); + if let Body::Expression { keys, .. } = body { + if let Some(probe) = &bound.probe { + probe.record_results(keys, &leaves); + } + } + let layer = Layer::new(keys, leaves, None); let data = match pass_through { true => input.layered(layer), false => Data::record(&rows, layer, None), @@ -311,7 +317,7 @@ impl CompiledGraph { | DecisionNodeKind::CustomNode { .. } | DecisionNodeKind::ExpressionNode { .. } | DecisionNodeKind::DecisionTableNode { .. } => { - Self::dispatch(step, base, step.shared_programs()) + Self::dispatch(step, base, step.shared_programs(), None) .await .map(|r| r.output) } @@ -323,9 +329,9 @@ impl CompiledGraph { step: &Step, base: NodeContextBase, programs: Option<&Arc>, + recorder: Option<&NodeRecorder>, ) -> NodeResult { let node = &step.node; - let trace = base.config.trace; match &node.kind { DecisionNodeKind::FunctionNode { content } => { DecisionGraph::handle(base, content.clone(), FunctionNodeHandler).await @@ -346,7 +352,7 @@ impl CompiledGraph { input: base.input.clone(), nodes: base.nodes.clone(), programs: None, - trace, + recorder, context: base.extensions.context.clone(), }; call.node(row, &content.transform_attributes).await @@ -363,7 +369,7 @@ impl CompiledGraph { input: base.input.clone(), nodes: base.nodes.clone(), programs, - trace, + recorder, 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 63cef68f5..98b59db25 100644 --- a/core/engine/src/compiled/graph/state/loops.rs +++ b/core/engine/src/compiled/graph/state/loops.rs @@ -1,10 +1,11 @@ use crate::compiled::bound::Bound; -use crate::compiled::exact::graph::Row; +use crate::compiled::exact::graph::{NodeRecorder, Row}; use crate::compiled::graph::data::{Data, Layer}; use crate::compiled::graph::{Body, CompiledGraph, Kind, Step, Transform}; use crate::compiled::leaf; use crate::compiled::leaf::Mask; use crate::compiled::leaf::{ColumnBuilder, Leaf}; +use crate::compiled::trace::record::Probe; use std::rc::Rc; use std::sync::Arc; use zen_expression::context::EvaluationContext; @@ -13,9 +14,11 @@ use zen_expression::{Scope, Variable}; use zen_types::path::DotPath; impl CompiledGraph { + #[allow(clippy::too_many_arguments)] pub(in crate::compiled::graph) fn transformed( runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, body: &Body, transform: &Transform, @@ -54,6 +57,7 @@ impl CompiledGraph { let mut produced = Self::items( runner, &context.rows(&rows), + probe, step, body, &body_inputs, @@ -92,7 +96,8 @@ impl CompiledGraph { false => context.clone(), }; let mut produced = - Self::items(runner, &looped, step, body, &items, &item_nodes).into_iter(); + Self::items(runner, &looped, probe, step, body, &items, &item_nodes) + .into_iter(); let mut item_inputs = items.into_iter(); shaped .into_iter() @@ -138,9 +143,11 @@ impl CompiledGraph { outputs } + #[allow(clippy::too_many_arguments)] pub(in crate::compiled::graph) fn looped<'a>( runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, body: &Body, transform: &Transform, @@ -178,7 +185,7 @@ impl CompiledGraph { true => context.items(&owners), false => context.clone(), }; - let produced = Self::items(runner, &looped, step, body, &items, &[]); + let produced = Self::items(runner, &looped, probe, 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 { @@ -223,6 +230,7 @@ impl CompiledGraph { pub(in crate::compiled::graph) fn items( runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, body: &Body, inputs: &[Variable], @@ -240,6 +248,7 @@ impl CompiledGraph { let mut produced = Self::items( runner, &context.rows(&kept), + probe, step, body, &kept_inputs, @@ -256,6 +265,7 @@ impl CompiledGraph { nodes.get(i).cloned().flatten(), false, &context.at(i), + None, ), false => produced.next().unwrap_or(Ok(Variable::Null)), }) @@ -263,7 +273,7 @@ impl CompiledGraph { } match Self::item_data(step, body, inputs, nodes) { Some(data) => { - let (output, failures) = Self::item_run(runner, context, step, body, &data); + let (output, failures) = Self::item_run(runner, context, probe, step, body, &data); let values = output.materialized(); let mut results: Vec> = values.iter().cloned().map(Ok).collect(); @@ -274,7 +284,7 @@ impl CompiledGraph { } results } - None => Self::body(runner, context, body, inputs, nodes), + None => Self::body(runner, context, probe, body, inputs, nodes), } } @@ -295,13 +305,17 @@ impl CompiledGraph { nodes: Option, transforms: bool, context: &EvaluationContext, + recorder: Option<&NodeRecorder>, ) -> Result { let row = Row { id: &step.node.id, input, nodes, - programs: step.shared_programs(), - trace: false, + programs: match recorder { + Some(_) => Some(step.programs()), + None => step.shared_programs(), + }, + recorder, context: context.clone(), }; row.now(&step.node, None, transforms) @@ -342,11 +356,12 @@ impl CompiledGraph { pub(in crate::compiled::graph) fn item_run<'a>( runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, body: &Body, data: &Data<'a>, ) -> (Data<'a>, Vec<(usize, String)>) { - Self::bound(context, step, data, &[], &[], None, |bound| { + Self::bound(context, probe, step, data, &[], &[], None, |bound| { Self::layered(runner, body, false, data, bound, None) }) } @@ -387,6 +402,7 @@ impl CompiledGraph { fn body( runner: &mut LaneRunner, context: &EvaluationContext, + probe: Option<&Rc>, body: &Body, inputs: &[Variable], nodes: &[Option], @@ -398,14 +414,25 @@ impl CompiledGraph { .collect(); match body { Body::Expression { - program, entries, .. + program, + entries, + keys, + .. } => { let mut out: Vec> = vec![Ok(Variable::Null); scopes.len()]; + let mut results: Option>> = probe + .filter(|_| entries.len() == keys.len()) + .map(|_| vec![Vec::new(); scopes.len()]); runner.evaluate_many(program, context, &scopes, None, |row, result| { out[row] = match result { Some(Ok(values)) => { let object = Variable::empty_object(); for ((key, _), value) in entries.iter().zip(values) { + if let Some(values) = + results.as_mut().and_then(|results| results.get_mut(row)) + { + values.push(value.clone()); + } object.dot_insert(key, value); } Ok(object) @@ -416,13 +443,19 @@ impl CompiledGraph { .map(|(_, v)| v.as_ref()) .unwrap_or_default(), )), - None => Ok(Variable::Null), + None => { + results = None; + Ok(Variable::Null) + } }; }); + if let (Some(probe), Some(results)) = (probe, results) { + probe.record_row_results(keys, results); + } out } Body::Table(table) => table - .evaluate(runner, &Bound::plain(scopes, context.clone())) + .evaluate(runner, &Bound::plain(scopes, context.clone()).probed(probe)) .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 feaab9345..e91037634 100644 --- a/core/engine/src/compiled/graph/state/mod.rs +++ b/core/engine/src/compiled/graph/state/mod.rs @@ -1,6 +1,7 @@ mod exec; mod host; mod loops; +mod trace; use crate::compiled::bound::{Bound, Scopes}; use crate::compiled::content::Content; @@ -13,6 +14,8 @@ use crate::compiled::host::graph::walker::GraphWalker; use crate::compiled::host::NodeError; use crate::compiled::host::NodeHandlerExtensions; use crate::compiled::leaf::{Array, Leaf}; +use crate::compiled::trace::batch::Traces; +use crate::compiled::trace::record::Probe; use crate::decision_graph::cleaner::VariableCleaner; use crate::{EvaluationError, ZEN_CONFIG}; use petgraph::prelude::NodeIndex; @@ -39,6 +42,7 @@ pub(crate) struct State<'a> { pub(in crate::compiled::graph) results: Vec>, nesting: Nesting<'a>, with_nodes: bool, + pub(in crate::compiled::graph) traces: Option>, } #[derive(Clone, Copy, Default)] @@ -46,6 +50,7 @@ pub(crate) struct Nesting<'a> { pub(in crate::compiled::graph) parents: Option<&'a [Option]>, pub(in crate::compiled::graph) iteration: u8, pub(in crate::compiled::graph) completed: Option<&'a Completed>, + pub(in crate::compiled::graph) traced: bool, } #[derive(Default)] @@ -233,6 +238,9 @@ impl CompiledGraph { max_depth, } = host; let count = inputs.len(); + if nesting.iteration == 0 && nesting.parents.is_none() { + crate::compiled::trace::count_run(); + } let mut state = State { context: extensions.context.clone(), nodes: vec![Vec::new(); self.steps.len()], @@ -240,6 +248,9 @@ impl CompiledGraph { results: vec![None; count], with_nodes: ZEN_CONFIG.nodes_in_context.load(Ordering::Relaxed), nesting, + traces: nesting + .traced + .then(|| Traces::new(self.template().clone(), self.steps.len(), count)), }; if nesting.iteration >= max_depth { state @@ -298,7 +309,11 @@ impl CompiledGraph { visible, .. } => { + let start = std::time::Instant::now(); let groups = self.switch(*node, parents, visible, &rows, &state); + if state.traces.is_some() { + self.trace_switch(*node, parents, &rows, &groups, start, &mut state); + } for (outcome, members) in groups.into_iter().rev() { let members: Rc<[usize]> = match members.len() == rows.len() { true => rows.clone(), @@ -380,8 +395,10 @@ impl CompiledGraph { out } + #[allow(clippy::too_many_arguments)] fn bound<'a, R>( context: &EvaluationContext, + probe: Option<&Rc>, step: &Step, data: &Data<'a>, nodes: &[Option], @@ -418,7 +435,7 @@ impl CompiledGraph { .enumerate() .map(|(row, v)| with_nodes(Scope::new(v.clone()), row)) .collect(); - return f(&Bound::plain(scopes, context)); + return f(&Bound::plain(scopes, context).probed(probe)); } let blank = nodes.iter().all(Option::is_none) && matches!(&data.shape, data::Shape::Patched { base: None, .. }); @@ -459,6 +476,7 @@ impl CompiledGraph { context, scopes, columns, + probe: probe.cloned(), bind: Box::new(move |key: &str| { let rebased = rebase.and_then(|base| Self::rebased(base, key)); let path = rebased.as_deref().unwrap_or(key); @@ -497,44 +515,53 @@ 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(&state.context, step, &data, &nodes, &extra, None, |bound| { - conditions - .iter() - .map(|(_, condition)| match condition { - Condition::Program(program) => { - let p = program.program(); - let rows = bound.rows(); - let uniform = rows > 1 - && !p.opaque() - && p.stable() - && p.site_keys.iter().all(|key| { - key.as_deref() - .is_some_and(|key| (bound.bind)(key) == Binding::Absent) - }); - let mut outs = Vec::new(); - let subset = [0usize]; - bound.export( - runner, - program, - uniform.then_some(&subset[..]), - &mut outs, - |_, _, _| {}, - ); - match ( - outs.first_mut() - .map(|out| Leaf::typed(Array::from_output(out))), - uniform, - ) { - (Some(column), true) => Hit::Uniform(column.truthy(0)), - (Some(column), false) => Hit::Rows(column.truths(rows)), - (None, _) => Hit::Uniform(false), + Self::bound( + &state.context, + None, + step, + &data, + &nodes, + &extra, + None, + |bound| { + conditions + .iter() + .map(|(_, condition)| match condition { + Condition::Program(program) => { + let p = program.program(); + let rows = bound.rows(); + let uniform = rows > 1 + && !p.opaque() + && p.stable() + && p.site_keys.iter().all(|key| { + key.as_deref() + .is_some_and(|key| (bound.bind)(key) == Binding::Absent) + }); + let mut outs = Vec::new(); + let subset = [0usize]; + bound.export( + runner, + program, + uniform.then_some(&subset[..]), + &mut outs, + |_, _, _| {}, + ); + match ( + outs.first_mut() + .map(|out| Leaf::typed(Array::from_output(out))), + uniform, + ) { + (Some(column), true) => Hit::Uniform(column.truthy(0)), + (Some(column), false) => Hit::Rows(column.truths(rows)), + (None, _) => Hit::Uniform(false), + } } - } - Condition::Always => Hit::Uniform(true), - Condition::Invalid(_) => Hit::Uniform(false), - }) - .collect() - }) + Condition::Always => Hit::Uniform(true), + Condition::Invalid(_) => Hit::Uniform(false), + }) + .collect() + }, + ) }); let words = conditions.len().div_ceil(64).max(1); let mut groups: Vec<(Vec, Vec)> = Vec::new(); diff --git a/core/engine/src/compiled/graph/state/trace.rs b/core/engine/src/compiled/graph/state/trace.rs new file mode 100644 index 000000000..906cf5321 --- /dev/null +++ b/core/engine/src/compiled/graph/state/trace.rs @@ -0,0 +1,385 @@ +use crate::compiled::exact::graph::NodeRecorder; +use crate::compiled::graph::data::Data; +use crate::compiled::graph::schedule::{Execute, Outcome}; +use crate::compiled::graph::{Body, CompiledGraph, Kind, State, Step, Transform}; +use crate::compiled::host::{ + NodeContextBase, NodeContextConfig, NodeError, NodeHandlerExtensions, Runtime, +}; +use crate::compiled::trace::batch::{BatchEvent, Encoding, Facts, Value}; +use crate::compiled::trace::collect::{Fact, Slot}; +use crate::compiled::trace::record::{LoopBody, NodeShape, Probe}; +use crate::model::DecisionNodeKind; +use petgraph::prelude::NodeIndex; +use smallvec::SmallVec; +use std::cell::RefCell; +use std::rc::Rc; +use std::time::Instant; +use zen_expression::context::EvaluationContext; +use zen_expression::Variable; + +impl CompiledGraph { + fn slots(parents: &[NodeIndex]) -> Box<[Slot]> { + parents.iter().map(|p| p.index() as Slot).collect() + } + + #[allow(clippy::too_many_arguments)] + pub(in crate::compiled::graph) fn trace_event<'a>( + state: &mut State<'a>, + event: &Execute, + rows: &Rc<[usize]>, + input: bool, + output: Option>, + start: Instant, + facts: Facts<'a>, + encoding: Encoding<'a>, + ) { + if let Some(traces) = state.traces.as_mut() { + traces.record_batch(BatchEvent { + slot: event.node.index() as Slot, + parents: Self::slots(&event.parents), + rows: rows.clone(), + input, + output, + ns: start.elapsed().as_nanos() as u64, + facts, + encoding, + }); + } + } + + pub(in crate::compiled::graph) fn encoding<'a>( + &self, + step: &Step, + event: &Execute, + data: &Rc>, + ) -> Encoding<'a> { + match &step.kind { + Kind::Input => Encoding::Request, + Kind::Output => Encoding::Null, + Kind::Switch { .. } => Encoding::Passed, + Kind::Host(_) => Encoding::Generic, + Kind::Node { transform, .. } => { + match ( + self.template() + .touched(event.node.index() as Slot) + .is_some(), + transform.pass_through, + ) { + (true, _) => Encoding::Touched(Some(data.clone())), + (false, false) => Encoding::Record, + (false, true) => Encoding::Generic, + } + } + } + } + + pub(in crate::compiled::graph) fn trace_switch( + &self, + node: NodeIndex, + parents: &[NodeIndex], + rows: &Rc<[usize]>, + groups: &[(Outcome, Vec)], + start: Instant, + state: &mut State<'_>, + ) { + let slot = node.index() as Slot; + let mut taken: Vec> = vec![SmallVec::new(); rows.len()]; + if let Some(traces) = state.traces.as_ref() { + for (outcome, members) in groups { + let positions: SmallVec<[u32; 4]> = outcome + .iter() + .filter_map(|id| traces.template.statement(slot, id)) + .collect(); + for row in members { + if let Ok(at) = rows.binary_search(row) { + taken[at] = positions.clone(); + } + } + } + } + let ns = start.elapsed().as_nanos() as u64; + if let Some(traces) = state.traces.as_mut() { + traces.record_batch(BatchEvent { + slot, + parents: Self::slots(parents), + rows: rows.clone(), + input: true, + output: None, + ns, + facts: Facts::Branches(taken), + encoding: Encoding::Passed, + }); + } + } + + pub(in crate::compiled::graph) fn keyed_results(step: &Step) -> bool { + let (Kind::Node { body, .. }, DecisionNodeKind::ExpressionNode { content }) = + (&step.kind, &step.node.kind) + else { + return false; + }; + let Body::Expression { + keys, overlapping, .. + } = body + else { + return false; + }; + let original: Vec<&std::sync::Arc> = content + .expressions + .iter() + .filter(|e| !e.key.is_empty() && !e.value.is_empty()) + .map(|e| &e.key) + .collect(); + !overlapping + && original.len() == keys.len() + && original.iter().zip(keys.iter()).all(|(a, b)| a == &b) + } + + pub(in crate::compiled::graph) fn derived_refs(step: &Step) -> bool { + let DecisionNodeKind::DecisionTableNode { content } = &step.node.kind else { + return false; + }; + let scoped = content + .transform_attributes + .input_field + .as_deref() + .is_none_or(crate::compiled::trace::plain_path); + scoped + && content.inputs.iter().all(|input| match &input.field { + None => true, + Some(field) if field.is_empty() => true, + Some(field) => { + crate::compiled::trace::plain_path(field) + && zen_expression::lane::LaneProgram::standard(field) + .is_ok_and(|program| program.path() == Some(field.as_ref())) + } + }) + } + + pub(in crate::compiled::graph) fn kernel_facts<'x>( + &self, + step: &Step, + probe: Option>, + state: &State<'_>, + event: &Execute, + rows: &Rc<[usize]>, + data: &Data<'_>, + ) -> Facts<'x> { + let slot = event.node.index() as Slot; + let shape = Self::node_shape(step, Some(data)); + let recorded = probe + .ok_or("evaluated outside the batch kernels") + .and_then(|probe| { + probe + .finish() + .facts(self.template(), slot, shape, rows.len()) + }); + match recorded { + Ok(facts) => facts, + Err(reason) => { + crate::compiled::trace::reevaluated(reason, rows.len()); + Facts::Rows(self.row_facts(step, state, event, rows, data)) + } + } + } + + pub(in crate::compiled::graph) fn node_shape( + step: &Step, + data: Option<&Data<'_>>, + ) -> NodeShape { + let Kind::Node { body, transform } = &step.kind else { + return NodeShape::Hosted; + }; + if transform.looped { + let spans = data.and_then(|data| Self::loop_spans(transform, data)); + let inner = match body { + Body::Expression { .. } if Self::keyed_results(step) => LoopBody::Results, + Body::Table(table) if table.first_hit() && Self::derived_refs(step) => { + LoopBody::FirstDerived + } + _ => LoopBody::Other, + }; + return NodeShape::Loop { spans, inner }; + } + match body { + Body::Expression { .. } => NodeShape::Expression { + keyed: Self::keyed_results(step), + }, + Body::Table(table) => NodeShape::Table { + first: table.first_hit(), + derived: Self::derived_refs(step), + }, + } + } + + pub(in crate::compiled::graph) fn wants_fields(step: &Step) -> bool { + matches!( + &step.kind, + Kind::Node { body: Body::Table(table), transform } + if !transform.looped && !(table.first_hit() && Self::derived_refs(step)) + ) + } + + fn loop_spans(transform: &Transform, data: &Data<'_>) -> Option> { + let source = transform + .input_field + .as_ref() + .and_then(|(program, _)| program.path())?; + let mut spans: Vec<(u32, u32)> = Vec::with_capacity(data.len()); + let mut total = 0u32; + if let Some(counts) = data.counts(source) { + for count in counts { + let count = count?; + spans.push((total, count)); + total += count; + } + return Some(spans.into()); + } + for list in data.subtree(source).iter() { + let count = list.as_array()?.borrow().len() as u32; + spans.push((total, count)); + total += count; + } + Some(spans.into()) + } + + pub(in crate::compiled::graph) fn merged_rows( + state: &State<'_>, + parents: &[NodeIndex], + rows: &Rc<[usize]>, + ) -> Vec { + let columns: Vec = parents + .iter() + .filter_map(|p| { + let pieces = state.nodes.get(p.index())?; + (!pieces.is_empty()).then(|| Data::gather(pieces, rows).materialized()) + }) + .collect(); + (0..rows.len()) + .map(|row| { + crate::compiled::host::graph::walker::GraphWalker::merge_values( + columns.iter().map(|c| &c[row]), + ) + }) + .collect() + } + + fn row_facts( + &self, + step: &Step, + state: &State<'_>, + event: &Execute, + rows: &Rc<[usize]>, + _data: &Data<'_>, + ) -> Vec { + let inputs = Self::merged_rows(state, &event.parents, rows); + let nodes: Vec = match step.nodes && state.with_nodes { + true => self.nodes_of(state, &event.visible, rows), + false => Vec::new(), + }; + Self::facts_of(step, &inputs, &nodes, &state.context.picked(rows.clone())) + } + + pub(in crate::compiled::graph) fn facts_of( + step: &Step, + inputs: &[Variable], + nodes: &[Variable], + context: &EvaluationContext, + ) -> Vec { + Self::evaluated(step, inputs, nodes, context).0 + } + + pub(in crate::compiled::graph) fn evaluated( + step: &Step, + inputs: &[Variable], + nodes: &[Variable], + context: &EvaluationContext, + ) -> (Vec, Vec) { + let mut outputs = Vec::with_capacity(inputs.len()); + let facts = inputs + .iter() + .enumerate() + .map(|(position, input)| { + let recorder = NodeRecorder::default(); + outputs.push( + Self::walked( + step, + input.clone(), + nodes.get(position).cloned(), + true, + &context.at(position), + Some(&recorder), + ) + .unwrap_or(Variable::Null), + ); + recorder.finish(None) + }) + .collect(); + (facts, outputs) + } + + pub(in crate::compiled::graph) async fn hosted_traced( + step: &Step, + inputs: &[Variable], + nodes: &[Option], + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + ) -> (Vec>, Vec) { + let shared: Option = match &step.node.kind { + DecisionNodeKind::FunctionNode { + content: zen_types::decision::FunctionNodeContent::Version2(content), + } => { + let source = extensions + .stripped_functions + .as_ref() + .and_then(|stripped| stripped.get(content.source.as_ref()).cloned()) + .unwrap_or_else(|| { + crate::compiled::host::function::v2::strip::TypeStripper::strip( + content.source.as_ref(), + ) + }); + crate::compiled::host::function::purity::Purity::module(&source) + .then(Runtime::default) + } + _ => None, + }; + let mut results = Vec::with_capacity(inputs.len()); + let mut facts = Vec::with_capacity(inputs.len()); + for (i, input) in inputs.iter().enumerate() { + let node = &step.node; + let recorder = NodeRecorder::default(); + let base = NodeContextBase { + id: node.id.clone(), + name: node.name.clone(), + input: input.clone(), + nodes: nodes.get(i).cloned().flatten(), + extensions: NodeHandlerExtensions { + function_runtime: shared.clone().unwrap_or_default(), + context: extensions.context.at(i), + ..extensions.clone() + }, + iteration, + trace: Some(RefCell::new(Variable::Null)), + config: NodeContextConfig { + max_depth, + trace: true, + ..Default::default() + }, + }; + let result = Box::pin(Self::dispatch( + step, + base, + Some(step.programs()), + Some(&recorder), + )) + .await; + facts.push(recorder.finish(match &result { + Ok(response) => response.trace_data.as_ref(), + Err(error) => error.trace.as_ref(), + })); + results.push(result.map(|response| response.output)); + } + (results, facts) + } +} diff --git a/core/engine/src/compiled/graph/step.rs b/core/engine/src/compiled/graph/step.rs index 163734a96..a341966ef 100644 --- a/core/engine/src/compiled/graph/step.rs +++ b/core/engine/src/compiled/graph/step.rs @@ -81,6 +81,22 @@ pub(super) struct StaticRead { } impl Step { + pub(super) fn draws(&self) -> bool { + match &self.kind { + Kind::Node { body, transform } => { + super::CompiledGraph::draws(body) + || transform + .input_field + .as_ref() + .is_some_and(|(program, _)| program.program().draws) + } + Kind::Switch { conditions, .. } => conditions.iter().any(|(_, condition)| { + matches!(condition, Condition::Program(program) if program.program().draws) + }), + _ => false, + } + } + pub(super) fn column_path(&self, rows: usize) -> bool { match &self.kind { Kind::Node { body, transform } => { @@ -206,6 +222,7 @@ impl CompiledGraph { root, dictionaries, plan: OnceLock::new(), + template: OnceLock::new(), census: crate::compiled::census::Census::id(), }) } diff --git a/core/engine/src/compiled/graph/traced.rs b/core/engine/src/compiled/graph/traced.rs index fea88b587..daf3d108a 100644 --- a/core/engine/src/compiled/graph/traced.rs +++ b/core/engine/src/compiled/graph/traced.rs @@ -1,26 +1,24 @@ use super::schedule::{End, Outcome}; use super::{CompiledGraph, Step}; use crate::compiled::content::Content; -use crate::compiled::host::graph::tracer::{ - NodeTracer, SwitchStatementTrace, SwitchStatementTraceRow, -}; +use crate::compiled::exact::graph::NodeRecorder; 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::compiled::trace::collect::Slot; +use crate::compiled::trace::record::{Recording, TraceEvent, Tracer}; use crate::model::DecisionNodeKind; -use crate::{DecisionGraphTrace, EvaluationError, ZEN_CONFIG}; -use ahash::HashMap; +use crate::{EvaluationError, ZEN_CONFIG}; use petgraph::prelude::NodeIndex; +use smallvec::SmallVec; use std::cell::RefCell; use std::sync::atomic::Ordering; use std::sync::Arc; use std::time::Instant; use zen_expression::lane::Session; -use zen_expression::variable::{ToVariable, Variable}; +use zen_expression::variable::Variable; use zen_types::decision::{SwitchNodeContent, SwitchStatement, SwitchStatementHitPolicy}; use zen_types::symbol::Symbol; @@ -33,26 +31,31 @@ pub(crate) struct Traced<'g> { pub(crate) parent: Option, } -struct Slot { +struct Held { data: Variable, view: Option, } -type Traces = HashMap, DecisionGraphTrace>; +pub(crate) struct Run { + pub(crate) result: Result>, + pub(crate) recording: Recording, +} impl Traced<'_> { - pub(crate) async fn evaluate( - &self, - context: Variable, - ) -> Result> { - let root_start = Instant::now(); + pub(crate) async fn run(&self, context: Variable) -> Run { + if self.iteration == 0 && self.parent.is_none() { + crate::compiled::trace::count_run(); + } + let mut tracer = Tracer::new(self.graph.template(), self.graph.steps.len()); if self.iteration >= self.max_depth { - return Err(Box::new(EvaluationError::DepthLimitExceeded)); + return Run { + result: Err(Box::new(EvaluationError::DepthLimitExceeded)), + recording: tracer.finish(), + }; } let with_nodes = ZEN_CONFIG.nodes_in_context.load(Ordering::Relaxed); - let mut slots: Vec> = (0..self.graph.steps.len()).map(|_| None).collect(); - let mut tracer = NodeTracer::new(true); + let mut slots: Vec> = (0..self.graph.steps.len()).map(|_| None).collect(); let mut segment = self.graph.root.clone(); let ending = loop { for event in segment.events.iter() { @@ -62,11 +65,45 @@ impl Traced<'_> { let start = Instant::now(); let input = Self::merged(&slots, &event.parents); let nodes = with_nodes.then(|| self.nodes(&slots, &event.visible)); - let result = self.node(step, &context, input.clone(), nodes).await; - tracer.record_execution(&step.node, input, &result, start.elapsed()); + let recorder = NodeRecorder::default(); + let result = self + .node(step, &context, input.clone(), nodes, &recorder) + .await; + let ns = start.elapsed().as_nanos() as u64; + let switch = matches!(step.node.kind, DecisionNodeKind::SwitchNode { .. }); + if !switch { + let (output, detail) = match &result { + Ok(response) => ( + match step.node.kind { + DecisionNodeKind::OutputNode { .. } => Variable::Null, + _ => response.output.clone(), + }, + recorder.finish(response.trace_data.as_ref()), + ), + Err(error) => (Variable::Null, recorder.finish(error.trace.as_ref())), + }; + tracer.record(TraceEvent::Node { + node: event.node.index() as Slot, + parents: Self::parents(&slots, &event.parents), + input: match step.node.kind { + DecisionNodeKind::InputNode { .. } => Variable::Null, + _ => input, + }, + output, + ns, + detail, + }); + } let output = match result { Ok(response) => response.output, - Err(error) => return Err(Self::failed(tracer.into_traces(), error)), + Err(error) => { + return Run { + result: Err(Box::new( + NodeError::new(error.node_id, error.source).failure(), + )), + recording: tracer.finish(), + } + } }; let view = match (&step.node.kind, &self.parent) { (DecisionNodeKind::InputNode { .. }, Some(parent)) => { @@ -77,7 +114,7 @@ impl Traced<'_> { _ => None, }; if let Some(slot) = slots.get_mut(event.node.index()) { - *slot = Some(Slot { data: output, view }); + *slot = Some(Held { data: output, view }); } } @@ -93,7 +130,17 @@ impl Traced<'_> { let input = Self::merged(&slots, parents); let nodes = with_nodes.then(|| self.nodes(&slots, visible)); let outcome = match self.graph.step_at(*node) { - Some(step) => self.switch(step, input, nodes, start, &mut tracer), + Some(step) => { + let (outcome, taken) = self.switch(step, &input, nodes); + tracer.record(TraceEvent::Switch { + node: node.index() as Slot, + parents: Self::parents(&slots, parents), + input, + ns: start.elapsed().as_nanos() as u64, + branches: taken, + }); + outcome + } None => Outcome::from(Vec::new()), }; segment = self.graph.child(&segment, outcome); @@ -106,23 +153,21 @@ impl Traced<'_> { .iter() .filter_map(|nid| slots.get(nid.index())?.as_ref().map(|slot| &slot.data)), ); - let traces = tracer.into_traces(); - if self.iteration == 0 { - let mut cleaner = VariableCleaner::new(); - cleaner.clean(&result); - if let Some(traces) = &traces { - Self::clean(&mut cleaner, traces); - } + Run { + result: Ok(result), + recording: tracer.finish(), } + } - Ok(DecisionGraphResponse { - performance: format!("{:.1?}", root_start.elapsed()), - result, - trace: traces.map(EvaluationTrace::Graph), - }) + fn parents(slots: &[Option], parents: &[NodeIndex]) -> SmallVec<[Slot; 4]> { + parents + .iter() + .filter(|nid| matches!(slots.get(nid.index()), Some(Some(_)))) + .map(|nid| nid.index() as Slot) + .collect() } - fn merged(slots: &[Option], parents: &[NodeIndex]) -> Variable { + fn merged(slots: &[Option], parents: &[NodeIndex]) -> Variable { GraphWalker::merge_values( parents .iter() @@ -130,7 +175,7 @@ impl Traced<'_> { ) } - fn nodes(&self, slots: &[Option], visible: &[NodeIndex]) -> Variable { + fn nodes(&self, slots: &[Option], visible: &[NodeIndex]) -> Variable { Variable::from_object( visible .iter() @@ -144,65 +189,22 @@ impl Traced<'_> { ) } - fn clean(cleaner: &mut VariableCleaner, traces: &Traces) { - traces.values().for_each(|trace| { - cleaner.clean(&trace.input); - cleaner.clean(&trace.output); - if let Some(data) = &trace.trace_data { - cleaner.clean(data); - } - }); - } - - fn failed(traces: Option, error: NodeError) -> Box { - if let Some(traces) = &traces { - Self::clean(&mut VariableCleaner::new(), traces); - } - - Box::new( - NodeError::traced( - error.node_id, - traces.map(|traces| traces.to_variable()), - error.source, - ) - .failure(), - ) - } - fn switch( &self, step: &Step, - input: Variable, + input: &Variable, nodes: Option, - start: Instant, - tracer: &mut NodeTracer, - ) -> Outcome { + ) -> (Outcome, SmallVec<[u32; 4]>) { let DecisionNodeKind::SwitchNode { content } = &step.node.kind else { - return Outcome::from(Vec::new()); + return (Outcome::from(Vec::new()), SmallVec::new()); }; - 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 { - id: step.node.id.clone(), - name: step.node.name.clone(), - input, - output, - order: 0, - performance: Some(Arc::from(format!("{:.1?}", start.elapsed()))), - trace_data: Some( - SwitchStatementTrace { - statements: statements.clone(), - } - .to_variable(), - ), - }); - } - - statements - .into_iter() - .map(|statement| statement.id) - .collect() + let taken = Self::statements(step, content, input, nodes, &self.extensions.context); + let outcome = taken + .iter() + .filter_map(|&at| content.statements.get(at as usize)) + .map(|statement| statement.id.clone()) + .collect(); + (outcome, taken) } fn statements( @@ -211,7 +213,7 @@ impl Traced<'_> { input: &Variable, nodes: Option, context: &zen_expression::context::EvaluationContext, - ) -> Vec { + ) -> SmallVec<[u32; 4]> { let mut session = Session::with_environment(input.clone()) .with_programs(Some(step.programs().clone())) .with_context(context.clone()); @@ -229,18 +231,16 @@ impl Traced<'_> { .run_standard(&statement.condition) .is_ok_and(|value| value.as_bool().unwrap_or(false)) }; - let mut statements = content.statements.iter(); + let mut statements = content.statements.iter().enumerate(); match content.hit_policy { SwitchStatementHitPolicy::First => statements - .find(|statement| passes(statement)) + .find(|(_, statement)| passes(statement)) + .map(|(at, _)| at as u32) .into_iter() - .cloned() - .map(SwitchStatementTraceRow::from) .collect(), SwitchStatementHitPolicy::Collect => statements - .filter(|statement| passes(statement)) - .cloned() - .map(SwitchStatementTraceRow::from) + .filter(|(_, statement)| passes(statement)) + .map(|(at, _)| at as u32) .collect(), } } @@ -251,6 +251,7 @@ impl Traced<'_> { context: &Variable, input: Variable, nodes: Option, + recorder: &NodeRecorder, ) -> NodeResult { let node = &step.node; let base = NodeContextBase { @@ -281,7 +282,7 @@ impl Traced<'_> { output: base.input, trace_data: None, }), - _ => CompiledGraph::dispatch(step, base, Some(step.programs())).await, + _ => CompiledGraph::dispatch(step, base, Some(step.programs()), Some(recorder)).await, } } } diff --git a/core/engine/src/compiled/host/expression.rs b/core/engine/src/compiled/host/expression.rs deleted file mode 100644 index 7bbf23bf1..000000000 --- a/core/engine/src/compiled/host/expression.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub(crate) use crate::compiled::host::graph::tracer::ExpressionNodeTraceItem; -use ahash::HashMap; -use std::rc::Rc; - -pub(crate) type ExpressionNodeTrace = HashMap, ExpressionNodeTraceItem>; diff --git a/core/engine/src/compiled/host/extensions.rs b/core/engine/src/compiled/host/extensions.rs index 9968bd241..dacd0347e 100644 --- a/core/engine/src/compiled/host/extensions.rs +++ b/core/engine/src/compiled/host/extensions.rs @@ -11,6 +11,8 @@ use anyhow::Context; use std::cell::OnceCell; use std::sync::Arc; +pub(crate) type Runtime = Arc>; + #[derive(Debug, Clone)] pub struct NodeHandlerExtensions { pub(crate) function_runtime: Arc>, diff --git a/core/engine/src/compiled/host/function/v2/module/console.rs b/core/engine/src/compiled/host/function/v2/module/console.rs index 9f6650217..ce260c386 100644 --- a/core/engine/src/compiled/host/function/v2/module/console.rs +++ b/core/engine/src/compiled/host/function/v2/module/console.rs @@ -20,8 +20,9 @@ impl RuntimeListener for ConsoleListener { ) -> Pin + 'js>> { Box::pin(async move { match event { - RuntimeEvent::Startup => Console::init(&ctx)?, - RuntimeEvent::SoftReset => Console::init(&ctx)?, + RuntimeEvent::Startup | RuntimeEvent::SoftReset => { + Console::init(&ctx)?; + } } Ok(()) 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 fddf65dcd..5715df19e 100644 --- a/core/engine/src/compiled/host/function/v2/module/zen.rs +++ b/core/engine/src/compiled/host/function/v2/module/zen.rs @@ -85,9 +85,20 @@ impl ZenListener { )) } }; - call.traced(&graph, context.0, None, &extensions.context) + let start = Instant::now(); + let run = call + .traced(&graph, context.0, None, &extensions.context) .await - .map_err(|error| rquickjs::Exception::throw_message(ctx, &error.to_string()))? + .map_err(|error| rquickjs::Exception::throw_message(ctx, &error.to_string()))?; + let trace = Some(crate::decision_graph::graph::EvaluationTrace::Graph( + run.recording.graph_map(), + )); + run.result + .map(|result| DecisionGraphResponse { + performance: format!("{:.1?}", start.elapsed()), + result, + trace, + }) .or_throw(ctx) } } diff --git a/core/engine/src/compiled/host/graph/graph.rs b/core/engine/src/compiled/host/graph/graph.rs index 97f77e532..09770a355 100644 --- a/core/engine/src/compiled/host/graph/graph.rs +++ b/core/engine/src/compiled/host/graph/graph.rs @@ -2,10 +2,9 @@ use crate::compiled::host::graph::walker::StableDiDecisionGraph; use crate::compiled::host::{ NodeContext, NodeContextBase, NodeDataType, NodeHandler, NodeResult, TraceDataType, }; -use crate::decision_graph::graph::{DecisionGraphResponse, EvaluationTrace}; -use crate::engine::EvaluationTraceKind; +use crate::decision_graph::graph::DecisionGraphResponse; use crate::model::{DecisionNodeKind, GraphContent}; -use crate::workspace::types::EvaluationResult; +use crate::workspace::EvaluationResult; use crate::{DecisionGraphValidationError, EvaluationError}; use ahash::{HashMap, HashMapExt}; use petgraph::algo::is_cyclic_directed; @@ -84,24 +83,12 @@ pub(crate) struct Responses; impl Responses { pub(crate) fn policy(result: EvaluationResult) -> DecisionGraphResponse { - DecisionGraphResponse { - performance: format!("{:.1?}", result.duration), - result: result.output, - trace: result.trace.map(EvaluationTrace::Policy), - } + DecisionGraphResponse::from(result) } pub(crate) fn serialized( response: Result>, - mode: EvaluationTraceKind, ) -> Result { - match response { - Ok(ok) => Ok(ok - .serialize_with_mode(serde_json::value::Serializer, mode) - .unwrap_or_default()), - Err(err) => Err(err - .serialize_with_mode(serde_json::value::Serializer, mode) - .unwrap_or_default()), - } + DecisionGraphResponse::serialized(response) } } diff --git a/core/engine/src/compiled/host/graph/mod.rs b/core/engine/src/compiled/host/graph/mod.rs index fba0c0e1a..50091de82 100644 --- a/core/engine/src/compiled/host/graph/mod.rs +++ b/core/engine/src/compiled/host/graph/mod.rs @@ -1,4 +1,3 @@ #[allow(clippy::module_inception)] pub(crate) mod graph; -pub(crate) mod tracer; pub(crate) mod walker; diff --git a/core/engine/src/compiled/host/graph/tracer.rs b/core/engine/src/compiled/host/graph/tracer.rs deleted file mode 100644 index 7a57e3657..000000000 --- a/core/engine/src/compiled/host/graph/tracer.rs +++ /dev/null @@ -1,120 +0,0 @@ -use crate::compiled::host::NodeResult; -use crate::DecisionGraphTrace; -use ahash::HashMap; -use serde::Serialize; -use std::rc::Rc; -use std::sync::Arc; -use zen_expression::variable::ToVariable; -use zen_types::decision::SwitchStatement; -use zen_types::decision::{DecisionNode, DecisionNodeKind}; -use zen_types::variable::Variable; - -pub(crate) struct NodeTracer(Option, DecisionGraphTrace>>); - -impl NodeTracer { - pub fn new(enabled: bool) -> Self { - Self(enabled.then(|| HashMap::default())) - } - - pub fn record_execution( - &mut self, - node: &DecisionNode, - input_trace: Variable, - result: &NodeResult, - duration: std::time::Duration, - ) { - let Some(traces) = &mut self.0 else { - return; - }; - - if matches!(node.kind, DecisionNodeKind::SwitchNode { .. }) { - return; - } - - let input = match &node.kind { - DecisionNodeKind::InputNode { .. } => Variable::Null, - _ => input_trace, - }; - - let mut trace = DecisionGraphTrace { - id: node.id.clone(), - name: node.name.clone(), - input, - order: traces.len() as u32, - output: Variable::Null, - trace_data: None, - performance: Some(Arc::from(format!("{:.1?}", duration))), - }; - - match &result { - Ok(ok) => { - trace.trace_data = ok.trace_data.clone(); - if !matches!(node.kind, DecisionNodeKind::OutputNode { .. }) { - trace.output = ok.output.clone(); - } - } - Err(err) => { - trace.trace_data = err.trace.clone(); - } - }; - - traces.insert(node.id.clone(), trace); - } - - pub fn trace_callback(&mut self) -> Option { - let Some(traces) = &mut self.0 else { - return None; - }; - - Some(|mut trace: DecisionGraphTrace| { - trace.order = traces.len() as u32; - traces.insert(trace.id.clone(), trace); - }) - } - - pub fn into_traces(self) -> Option, DecisionGraphTrace>> { - self.0 - } -} - -#[derive(Debug, Clone, ToVariable)] -pub struct ExpressionNodeTraceItem { - pub(crate) result: Variable, -} - -#[derive(Debug, Clone, Serialize, ToVariable)] -pub struct DecisionTableRowTrace { - pub(crate) index: usize, - pub(crate) reference_map: HashMap, Variable>, - pub(crate) rule: HashMap, Rc>, -} - -#[derive(Debug, Clone, Serialize, ToVariable)] -#[serde(untagged)] -pub enum DecisionTableNodeTrace { - FirstHit(DecisionTableRowTrace), - Collect(Vec), -} - -impl Default for DecisionTableNodeTrace { - fn default() -> Self { - DecisionTableNodeTrace::Collect(Default::default()) - } -} - -#[derive(ToVariable)] -pub(crate) struct SwitchStatementTrace { - pub(crate) statements: Vec, -} - -#[derive(ToVariable, Clone)] -#[serde(rename_all = "camelCase")] -pub(crate) struct SwitchStatementTraceRow { - pub id: Arc, -} - -impl From for SwitchStatementTraceRow { - fn from(value: SwitchStatement) -> Self { - Self { id: value.id } - } -} diff --git a/core/engine/src/compiled/host/mod.rs b/core/engine/src/compiled/host/mod.rs index e7516141f..b5f5f4d0f 100644 --- a/core/engine/src/compiled/host/mod.rs +++ b/core/engine/src/compiled/host/mod.rs @@ -1,7 +1,6 @@ mod context; pub(crate) mod custom; mod definition; -pub(crate) mod expression; mod extensions; pub(crate) mod function; pub(crate) mod graph; @@ -14,6 +13,6 @@ pub(crate) use crate::nodes::decision_table; pub(crate) use crate::nodes::variable_json; pub(crate) use context::{NodeContext, NodeContextBase, NodeContextConfig, NodeContextExt}; pub(crate) use definition::{NodeDataType, NodeHandler, TraceDataType}; -pub(crate) use extensions::NodeHandlerExtensions; +pub(crate) use extensions::{NodeHandlerExtensions, Runtime}; pub(crate) use function::http_handler; pub(crate) use result::{NodeError, NodeResponse, NodeResult}; diff --git a/core/engine/src/compiled/leaf/column.rs b/core/engine/src/compiled/leaf/column.rs index d0af0b066..7047f440d 100644 --- a/core/engine/src/compiled/leaf/column.rs +++ b/core/engine/src/compiled/leaf/column.rs @@ -477,6 +477,170 @@ impl<'a> Leaf<'a> { } } + pub fn shared(&self, row: usize) -> Variable { + match self { + Leaf::Records(records) => records.dense().get(row).cloned().unwrap_or(Variable::Null), + Leaf::Templated(templated) => templated + .dense() + .get(row) + .cloned() + .unwrap_or(Variable::Null), + Leaf::Picked(_) | Leaf::Stitched(_) => self + .source(row) + .map_or(Variable::Null, |(leaf, at)| leaf.shared(at)), + _ => self.get(row), + } + } + + pub fn listed(&self, row: usize) -> Option<(&Records<'a>, usize)> { + match self { + Leaf::Records(records) => Some((records, row)), + Leaf::Picked(_) | Leaf::Stitched(_) => { + let (leaf, at) = self.source(row)?; + leaf.listed(at) + } + _ => None, + } + } + + pub fn plain(&self) -> Option<(Column<'_>, u8)> { + if matches!(self, Leaf::Any(_) | Leaf::Records(_) | Leaf::Templated(_)) { + return None; + } + let column = self.column(); + let kind = match column.values { + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) => 0, + Values::Dict { values, .. } => match values { + Dictionary::Text { .. } => 0, + Dictionary::Scaled { .. } => 1, + Dictionary::Bool { .. } => 2, + _ => return None, + }, + Values::Scaled { .. } | Values::I64(_) | Values::Dec(_) => 1, + Values::Bool { .. } => 2, + _ => return None, + }; + Some((column, kind)) + } + + pub fn scalars(&self) -> Option<(Column<'_>, bool)> { + if matches!(self, Leaf::Any(_) | Leaf::Records(_) | Leaf::Templated(_)) { + return None; + } + let column = self.column(); + let text = matches!( + column.values, + Values::Utf8 { .. } | Values::Text { .. } | Values::LargeUtf8 { .. } | Values::Strs(_) + ) || matches!(column.values, Values::Dict { values, .. } if matches!(values, Dictionary::Text { .. })); + let number = matches!(column.values, Values::Scaled { .. } | Values::I64(_)); + (text || number).then_some((column, text)) + } + + pub fn codes(&self, rows: usize) -> (Vec, u32) { + type Fast = + std::collections::HashMap>; + let mut numbers: Fast<(i128, u32)> = Default::default(); + let mut texts: Fast = Default::default(); + let mut next = 5u32; + let mut number = |key: (i128, u32)| { + *numbers.entry(key).or_insert_with(|| { + next += 1; + next - 1 + }) + }; + let typed = !matches!(self, Leaf::Any(_) | Leaf::Records(_) | Leaf::Templated(_)); + let column = typed.then(|| self.column()); + let codes: Vec = match column.map(|column| (column, column.values)) { + Some((column, Values::Dict { values, .. })) + if !matches!(values, Dictionary::Any(_)) => + { + (0..rows) + .map(|row| match ColumnBuilder::null_at(&column, row) { + true => 0, + false => column.code(row).map_or(0, |code| 5 + code as u32), + }) + .collect() + } + Some((column, Values::Scaled { mant, scale })) => (0..rows) + .map(|row| match ColumnBuilder::null_at(&column, row) { + true => 0, + false => number((i128::from(mant[row]), u32::from(scale[row]) | 1 << 31)), + }) + .collect(), + _ => { + let mut next = 1u32 << 30; + (0..rows) + .map(|row| match self.listed(row) { + Some((records, at)) => match records.range(at) { + Some(_) => Variable::empty_array(), + None => Variable::Null, + }, + None => self.get(row), + }) + .map(|value| match value { + Variable::Null => 0, + Variable::Array(_) | Variable::Object(_) => 1, + Variable::Dynamic(_) => 2, + Variable::Bool(flag) => 3 + u32::from(flag), + Variable::Number(d) => number((d.mantissa(), d.scale())), + Variable::String(text) => *texts.entry(text).or_insert_with(|| { + next += 1; + next - 1 + }), + }) + .collect() + } + }; + let mut dense: Fast = Default::default(); + let codes: Vec = codes + .into_iter() + .map(|code| { + let next = dense.len() as u32; + *dense.entry(code).or_insert(next) + }) + .collect(); + (codes, dense.len().max(1) as u32) + } + + pub fn words(&self, row: usize, key: &mut Vec) -> bool { + if matches!(self, Leaf::Any(_) | Leaf::Records(_)) { + return false; + } + let column = self.column(); + if ColumnBuilder::null_at(&column, row) { + return false; + } + match column.values { + Values::Dict { values, .. } if !matches!(values, Dictionary::Any(_)) => { + match column.code(row) { + Some(code) => { + key.extend_from_slice(&[1, code as u64]); + true + } + None => false, + } + } + Values::Scaled { mant, scale } => match (mant.get(row), scale.get(row)) { + (Some(&mant), Some(&scale)) => { + key.extend_from_slice(&[2, mant as u64, u64::from(scale)]); + true + } + _ => false, + }, + Values::I64(values) => match values.get(row) { + Some(&value) => { + key.extend_from_slice(&[3, value as u64]); + true + } + None => false, + }, + _ => false, + } + } + pub fn pick(&self, positions: &Rc<[usize]>) -> Leaf<'a> { match self { Leaf::Picked(picked) => Leaf::Picked(Rc::new(Picked { diff --git a/core/engine/src/compiled/leaf/json.rs b/core/engine/src/compiled/leaf/json.rs new file mode 100644 index 000000000..ebec4396e --- /dev/null +++ b/core/engine/src/compiled/leaf/json.rs @@ -0,0 +1,125 @@ +use super::{Bits, ColumnBuilder, Leaf, Records}; +use zen_expression::lane::{Column, Values}; +use zen_expression::Variable; + +pub(crate) enum Json<'c, 'a> { + Text(Column<'c>), + Number(Column<'c>), + List(&'c Records<'a>, Vec<(&'c str, &'c [u64], Json<'c, 'a>)>), + Other(&'c Leaf<'a>), +} + +impl<'c, 'a> Json<'c, 'a> { + pub fn of(leaf: &'c Leaf<'a>) -> Self { + if let Leaf::Records(records) = leaf { + if let Some(labels) = records.labels() { + return Json::List( + records, + records + .fields + .iter() + .zip(labels) + .map(|((_, leaf, present), label)| (&**label, &**present, Json::of(leaf))) + .collect(), + ); + } + } + match leaf.scalars() { + Some((column, true)) => Json::Text(column), + Some((column, false)) => Json::Number(column), + None => Json::Other(leaf), + } + } + + pub fn write(&self, row: usize, out: &mut Vec) -> bool { + let mark = out.len(); + let written = match self { + Json::Text(column) => match column.valid(row) { + false => None, + true => column + .text(row) + .map(|text| serde_json::to_writer(&mut *out, text).is_ok()), + }, + Json::Number(column) => match (column.valid(row), column.values) { + (false, _) => None, + (true, Values::Scaled { mant, scale }) if scale.get(row) == Some(&0) => { + mant.get(row).map(|whole| { + out.extend_from_slice(itoa::Buffer::new().format(*whole).as_bytes()); + true + }) + } + (true, _) => column.number(row).map(|number| { + serde_json::to_writer(&mut *out, &Variable::Number(number)).is_ok() + }), + }, + Json::List(records, fields) => records.range(row).map(|(start, end)| { + out.push(b'['); + for item in start..end { + if item > start { + out.push(b','); + } + if records.nulled.as_ref().is_some_and(|n| Bits::get(n, item)) { + out.extend_from_slice(b"null"); + continue; + } + out.push(b'{'); + let mut any = false; + for (label, present, field) in fields { + if !Bits::get(present, item) { + continue; + } + if any { + out.push(b','); + } + any = true; + out.extend_from_slice(label.as_bytes()); + field.write(item, out); + } + out.push(b'}'); + } + out.push(b']'); + true + }), + Json::Other(leaf) => match leaf.get(row) { + Variable::Null => None, + value => Some(serde_json::to_writer(&mut *out, &value).is_ok()), + }, + }; + match written { + Some(true) => true, + _ => { + out.truncate(mark); + match (self, written) { + (Json::Text(_) | Json::Number(_), Some(false) | None) if !self.null(row) => { + self.slow(row, out) + } + _ => { + out.extend_from_slice(b"null"); + false + } + } + } + } + } + + fn null(&self, row: usize) -> bool { + match self { + Json::Text(column) | Json::Number(column) => ColumnBuilder::null_at(column, row), + _ => true, + } + } + + fn slow(&self, row: usize, out: &mut Vec) -> bool { + let value = match self { + Json::Text(column) | Json::Number(column) => column.variable(row), + _ => Variable::Null, + }; + match value { + Variable::Null => { + out.extend_from_slice(b"null"); + false + } + value => serde_json::to_writer(&mut *out, &value).is_ok(), + } + } +} diff --git a/core/engine/src/compiled/leaf/mod.rs b/core/engine/src/compiled/leaf/mod.rs index 96181107b..9423600f9 100644 --- a/core/engine/src/compiled/leaf/mod.rs +++ b/core/engine/src/compiled/leaf/mod.rs @@ -2,6 +2,7 @@ mod array; mod builder; mod column; mod dict; +mod json; mod literal; mod mask; mod records; @@ -11,6 +12,7 @@ pub(crate) use array::{Array, Store}; pub(crate) use builder::ColumnBuilder; pub(crate) use column::Leaf; pub(crate) use dict::Dict; +pub(crate) use json::Json; pub(crate) use literal::Literal; pub(crate) use mask::Mask; pub(crate) use records::{Field, Items, Records}; diff --git a/core/engine/src/compiled/leaf/records.rs b/core/engine/src/compiled/leaf/records.rs index 6cd680979..ede200f4f 100644 --- a/core/engine/src/compiled/leaf/records.rs +++ b/core/engine/src/compiled/leaf/records.rs @@ -7,6 +7,11 @@ use zen_types::symbol::Symbol; use zen_types::variable::VariableMap; pub(crate) type Field<'a> = (Symbol, Leaf<'a>, Rc<[u64]>); + +pub(crate) struct Listing<'c> { + pub fields: Vec<(&'c str, &'c [u64], Column<'c>, u8)>, + pub nulled: Option<&'c [u64]>, +} type Lanes = (Vec>, Option>); #[derive(Debug)] @@ -19,6 +24,7 @@ pub(crate) struct Records<'a> { dense: OnceCell>, lanes: OnceCell, maker: OnceCell>, + labels: OnceCell>>>, } #[derive(Debug)] @@ -91,6 +97,53 @@ impl<'a> Records<'a> { Records::new(rows, offsets, valid, fields, nulled) } + pub fn fresh(&self) -> bool { + self.dense.get().is_none() + } + + pub fn id(&self) -> usize { + self as *const Self as usize + } + + pub fn listing(&self) -> Option> { + if self.fields.len() >= 8 && !self.fresh() || self.fields.len() > 32 { + return None; + } + let fields = self + .fields + .iter() + .map(|(key, leaf, present)| { + let key = key.as_str(); + if key.starts_with('$') || key.contains('.') { + return None; + } + let (column, kind) = leaf.plain()?; + Some((key, &**present, column, kind)) + }) + .collect::>()?; + Some(Listing { + fields, + nulled: self.nulled.as_deref(), + }) + } + + pub(super) fn labels(&self) -> Option<&[Box]> { + self.labels + .get_or_init(|| { + self.fields + .iter() + .map(|(key, _, _)| { + (!key.as_str().contains('.')).then(|| { + let mut text = serde_json::to_string(key.as_str()).unwrap_or_default(); + text.push(':'); + text.into_boxed_str() + }) + }) + .collect() + }) + .as_deref() + } + pub fn plain(&self) -> bool { self.nulled.is_none() } @@ -115,6 +168,7 @@ impl<'a> Records<'a> { dense: OnceCell::new(), lanes: OnceCell::new(), maker: OnceCell::new(), + labels: OnceCell::new(), } } diff --git a/core/engine/src/compiled/mod.rs b/core/engine/src/compiled/mod.rs index 25fe8c646..0e33dc099 100644 --- a/core/engine/src/compiled/mod.rs +++ b/core/engine/src/compiled/mod.rs @@ -17,6 +17,7 @@ pub(crate) mod prepared; mod shred; pub(crate) mod switches; pub(crate) mod table; +pub(crate) mod trace; pub use graph::ColumnarOutput; pub(crate) use graph::{call, traced, CompiledGraph, CompiledPlan, Invalid}; diff --git a/core/engine/src/compiled/output.rs b/core/engine/src/compiled/output.rs index b0321ba93..33f4ab576 100644 --- a/core/engine/src/compiled/output.rs +++ b/core/engine/src/compiled/output.rs @@ -1,10 +1,120 @@ -use crate::compiled::leaf::Leaf; +use crate::compiled::leaf::{Json, Leaf}; use std::sync::Arc; use zen_expression::lane::Column; use zen_expression::Variable; pub struct OutputColumn<'a>(pub(crate) Leaf<'a>); +enum Part { + Leaf(Box, usize), + Branch(Box, Vec), +} + +pub(crate) struct Layout(Option>); + +impl Layout { + pub(crate) fn new(columns: &[(Arc, OutputColumn)]) -> Self { + let paths: Vec> = columns + .iter() + .map(|(path, _)| path.split('.').collect()) + .collect(); + let plain = columns.iter().all(|(path, _)| !path.is_empty()); + let all: Vec = (0..paths.len()).collect(); + Layout(match plain { + true => Self::parts(&paths, &all, 0), + false => None, + }) + } + + fn label(key: &str) -> Box { + let mut text = serde_json::to_string(key).unwrap_or_default(); + text.push(':'); + text.into_boxed_str() + } + + fn parts(paths: &[Vec<&str>], items: &[usize], depth: usize) -> Option> { + let mut parts: Vec = Vec::new(); + let mut seen: Vec<&str> = Vec::new(); + let mut start = 0; + while start < items.len() { + let key = *paths[items[start]].get(depth)?; + let end = (start..items.len()) + .find(|&at| paths[items[at]].get(depth) != Some(&key)) + .unwrap_or(items.len()); + if seen.contains(&key) { + return None; + } + seen.push(key); + let group = &items[start..end]; + let leaf = group.iter().any(|&index| paths[index].len() == depth + 1); + match (leaf, group) { + (true, [index]) => parts.push(Part::Leaf(Self::label(key), *index)), + (true, _) => return None, + (false, _) => parts.push(Part::Branch( + Self::label(key), + Self::parts(paths, group, depth + 1)?, + )), + } + start = end; + } + Some(parts) + } + + fn fill(parts: &[Part], cells: &[Json], row: usize, out: &mut Vec) -> bool { + let mut any = false; + for part in parts { + let mark = out.len(); + if any { + out.push(b','); + } + let written = match part { + Part::Leaf(label, index) => { + out.extend_from_slice(label.as_bytes()); + cells[*index].write(row, out) + } + Part::Branch(label, children) => { + out.extend_from_slice(label.as_bytes()); + out.push(b'{'); + let filled = Self::fill(children, cells, row, out); + out.push(b'}'); + filled + } + }; + match written { + true => any = true, + false => out.truncate(mark), + } + } + any + } + + pub(crate) fn cells<'c, 'a>(columns: &'c [(Arc, OutputColumn<'a>)]) -> Vec> { + columns + .iter() + .map(|(_, column)| Json::of(&column.0)) + .collect() + } + + pub(crate) fn write( + &self, + columns: &[(Arc, OutputColumn)], + cells: &[Json], + row: usize, + out: &mut Vec, + ) { + match &self.0 { + Some(parts) => { + out.push(b'{'); + Self::fill(parts, cells, row, out); + out.push(b'}'); + } + None => { + let _ = serde_json::to_writer(&mut *out, &OutputColumn::row(columns, row)); + } + } + } +} + pub struct RecordsView<'c> { pub offsets: &'c [i32], pub valid: Vec, diff --git a/core/engine/src/compiled/pinning.rs b/core/engine/src/compiled/pinning.rs index d5b4f8b70..36094bf10 100644 --- a/core/engine/src/compiled/pinning.rs +++ b/core/engine/src/compiled/pinning.rs @@ -1,18 +1,41 @@ +use crate::engine::EvaluationOptions; 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, + location, parse_timezone, system_now, system_timezone, EvaluationContext, Site, Timezone, }; -pub(crate) fn single(pinned: Pinned) -> EvaluationContext { - EvaluationContext::new(pinned) +pub(crate) fn single(options: &EvaluationOptions) -> EvaluationContext { + let context = EvaluationContext::new(options.pinned()); + if options.trace.is_on() { + context.now(); + } + context +} + +pub(crate) fn batch(options: &EvaluationOptions) -> EvaluationContext { + EvaluationContext::batch(options.pinned()) } -pub(crate) fn batch(pinned: Pinned) -> EvaluationContext { - EvaluationContext::batch(pinned) +pub(crate) fn evaluation(context: &EvaluationContext) -> crate::compiled::trace::Evaluation { + crate::compiled::trace::Evaluation { + evaluated_at: Some(context.evaluated_at()), + timezone: Some(context.zone()), + seed: context.seed(), + } +} + +pub(crate) fn row_evaluation( + context: &EvaluationContext, + row: usize, +) -> crate::compiled::trace::Evaluation { + crate::compiled::trace::Evaluation { + evaluated_at: Some(context.evaluated_at()), + timezone: Some(context.zone()), + seed: context.row_seed(row), + } } pub(crate) struct Located; diff --git a/core/engine/src/compiled/policy/artifact.rs b/core/engine/src/compiled/policy/artifact.rs index 111aa9233..3e047a734 100644 --- a/core/engine/src/compiled/policy/artifact.rs +++ b/core/engine/src/compiled/policy/artifact.rs @@ -11,15 +11,14 @@ use zen_expression::variable::Variable; use zen_expression::lane::{Bits, Programs}; +use crate::compiled::trace::{PolicyTrace, TraceFormat}; use crate::policy::blocks::Block; use crate::policy::ir::PropertyPath; use crate::policy::queries::dependency::{DataModelPaths, WriteScope}; use crate::policy::queries::scope::{EntityForm, ReferenceField}; use crate::policy::refs::RefPoolIndex; use crate::workspace::db::Db; -use crate::workspace::types::{ - BlockRef, EvaluateRequest, EvaluationError, EvaluationResult, Trace, -}; +use crate::workspace::{BlockRef, EvaluateRequest, EvaluationError, EvaluationResult, Trace}; use zen_types::path::DotPath; pub(crate) struct Artifact { @@ -30,6 +29,8 @@ pub(crate) struct Artifact { requirements: OnceLock, programs: OnceLock>, pub(crate) indexes: TableIndexes, + documents: Arc<[Arc]>, + documents_json: OnceLock>, } impl Deref for Artifact { @@ -41,15 +42,102 @@ impl Deref for Artifact { } impl Artifact { - pub(crate) fn new(base: Arc, input_schema: InputSchema) -> Self { + pub(crate) fn new(db: &Db, policy: &str, base: Arc) -> Self { Self { base, - input_schema, + input_schema: InputSchema::of(db, policy), compiled: OnceLock::new(), goal_plans: Mutex::new(HashMap::new()), requirements: OnceLock::new(), programs: OnceLock::new(), indexes: TableIndexes::default(), + documents: Self::release_of(db, policy), + documents_json: OnceLock::new(), + } + } + + fn release_of(db: &Db, policy: &str) -> Arc<[Arc]> { + let mut seen: Vec> = vec![Arc::from(policy)]; + let mut out: Vec> = Vec::new(); + let mut at = 0; + while at < seen.len() { + let path = seen[at].clone(); + at += 1; + let Some(doc) = db.raw_document(&path) else { + continue; + }; + if let crate::model::DecisionContent::Policy(policy) = doc.as_ref() { + for import in &policy.0.imports { + if !seen.iter().any(|s| s == import) { + seen.push(import.clone()); + } + } + } + out.push(doc); + } + Arc::from(out) + } + + pub(crate) fn snapshot(&self, req: &EvaluateRequest, extras: bool) -> Option { + (req.trace == TraceFormat::V1).then(|| match extras { + true => req.input.deep_clone(), + false => req.input.clone(), + }) + } + + fn documents_json(&self) -> &str { + self.documents_json.get_or_init(|| { + Arc::from(serde_json::to_string(&*self.documents).unwrap_or_else(|_| "[]".to_string())) + }) + } + + fn converted( + &self, + request: &Variable, + trace: PolicyTrace, + context: &EvaluationContext, + ) -> PolicyTrace { + match trace { + PolicyTrace::Legacy(trace) => PolicyTrace::V1(crate::compiled::trace::policy_v1( + trace, + request, + self.documents_json(), + Some(&crate::compiled::pinning::evaluation(context)), + )), + other => other, + } + } + + pub(crate) fn finish( + &self, + req: &EvaluateRequest, + request: Option, + result: Result, + context: &EvaluationContext, + ) -> Result { + let Some(request) = request.filter(|_| req.trace == TraceFormat::V1) else { + return result; + }; + match result { + Ok(mut result) => { + result.trace = result.trace.map(|t| self.converted(&request, t, context)); + Ok(result) + } + Err(EvaluationError::ExpressionFailed { + policy_path, + block_id, + expression, + source, + partial_trace, + }) => Err(EvaluationError::ExpressionFailed { + policy_path, + block_id, + expression, + source, + partial_trace: partial_trace + .map(|t| Box::new(self.converted(&request, *t, context))), + }), + Err(other) => Err(other), } } @@ -289,7 +377,7 @@ impl Artifacts { return kept.clone(); } } - let artifact = Arc::new(Artifact::new(base, InputSchema::of(db, policy))); + let artifact = Arc::new(Artifact::new(db, policy, base)); self.kept .borrow_mut() .insert(Arc::from(policy), artifact.clone()); @@ -332,7 +420,9 @@ impl Runtime { } Self::check_imports_resolved(db, &req.policy_path)?; let mut req = req.clone(); - req.trace = true; + if req.trace != crate::compiled::trace::TraceFormat::V1 { + req.trace = crate::compiled::trace::TraceFormat::Legacy; + } artifacts .get(db, &req.policy_path) .evaluate(&req, true, context) @@ -350,7 +440,7 @@ impl Runtime { policy_path: policy_path.clone(), input: Variable::Null, goals: goals.to_vec(), - trace: false, + trace: crate::compiled::trace::TraceFormat::Off, }; Self::check_evaluable(db, &probe)?; let artifact = artifacts.get(db, policy_path); @@ -432,7 +522,7 @@ impl Artifact { &self, key: &str, input: Variable, - trace: bool, + trace: crate::compiled::trace::TraceFormat, context: &EvaluationContext, ) -> Result { let request = EvaluateRequest { @@ -451,7 +541,7 @@ impl Artifact { context: &EvaluationContext, ) -> Result { let plan = self.plan(&req.goals); - if !req.trace && !extras { + if !req.trace.is_on() && !extras { if let Some(result) = plan .evaluate(self, std::slice::from_ref(req), context) .pop() @@ -459,7 +549,13 @@ impl Artifact { return result; } } - plan.traced(self, req, extras, context) + let request = self.snapshot(req, extras); + self.finish( + req, + request, + plan.traced(self, req, extras, context), + context, + ) } const GOAL_PLANS: usize = 32; @@ -511,14 +607,14 @@ impl Artifact { (0..requests.len()).map(|_| None).collect(); let mut groups: Vec<(&[Arc], Vec)> = Vec::new(); for (index, request) in requests.iter().enumerate() { - match request.trace { + match request.trace.is_on() { true => { - results[index] = Some(self.plan(&request.goals).traced( - self, - request, - false, - &context.at(index), - )) + let context = context.at(index); + let snapshot = self.snapshot(request, false); + let traced = self + .plan(&request.goals) + .traced(self, request, false, &context); + results[index] = Some(self.finish(request, snapshot, traced, &context)) } false => match groups .iter_mut() @@ -847,6 +943,12 @@ impl StoreOps for Variable { } } +impl From for EvaluationError { + fn from(error: crate::policy::blocks::ExecutionError) -> Self { + ::from(error).into() + } +} + impl EvaluationError { pub(crate) fn partially_traced(self, trace: Option) -> Self { match (self, trace) { @@ -864,7 +966,7 @@ impl EvaluationError { block_id, expression, source, - partial_trace: Some(Box::new(trace)), + partial_trace: Some(Box::new(crate::compiled::trace::PolicyTrace::Legacy(trace))), }, (other, _) => other, } diff --git a/core/engine/src/compiled/policy/columnar/evaluate.rs b/core/engine/src/compiled/policy/columnar/evaluate.rs index 079583010..6f9f2e13d 100644 --- a/core/engine/src/compiled/policy/columnar/evaluate.rs +++ b/core/engine/src/compiled/policy/columnar/evaluate.rs @@ -6,7 +6,7 @@ use crate::compiled::policy::entity::Entity; use crate::compiled::policy::{PolicyPlan, Rows}; use crate::compiled::shred::{Shred, Shredder}; use crate::compiled::ColumnarOutput; -use crate::workspace::types::{EvaluateRequest, EvaluationError}; +use crate::workspace::{EvaluateRequest, EvaluationError}; use std::cell::{OnceCell, RefCell}; use std::sync::Arc; use zen_expression::context::EvaluationContext; @@ -198,7 +198,7 @@ impl PolicyPlan { policy_path: policy_path.clone(), input: columns.row(row), goals: goals.to_vec(), - trace: false, + trace: crate::compiled::trace::TraceFormat::Off, }; let sheet = Sheet::new(columns); let Some(mut sheet) = sheet else { diff --git a/core/engine/src/compiled/policy/columnar/output.rs b/core/engine/src/compiled/policy/columnar/output.rs index c2e162af0..8004ae527 100644 --- a/core/engine/src/compiled/policy/columnar/output.rs +++ b/core/engine/src/compiled/policy/columnar/output.rs @@ -2,7 +2,7 @@ use crate::compiled::diagnostics::Paths; use crate::compiled::output::OutputColumn; use crate::compiled::shred::Shredder; use crate::compiled::ColumnarOutput; -use crate::workspace::types::{EvaluationError, EvaluationResult}; +use crate::workspace::{EvaluationError, EvaluationResult}; use std::rc::Rc; use std::sync::Arc; @@ -20,6 +20,7 @@ pub(super) fn output<'a>( .map(|error| error.map(|error| Rc::new(crate::EvaluationError::Policy(error)))) .collect(), paths, + traces: None, } } diff --git a/core/engine/src/compiled/policy/host.rs b/core/engine/src/compiled/policy/host.rs index b3c9be13e..5c06f2f4b 100644 --- a/core/engine/src/compiled/policy/host.rs +++ b/core/engine/src/compiled/policy/host.rs @@ -9,7 +9,7 @@ use crate::compiled::exact::policy::Exact; use crate::compiled::policy::artifact::Artifact as EvalArtifact; use crate::compiled::policy::site::{Evaluate, HostState, Pick, Picked, Site}; use crate::policy::blocks::{Block, BlockKind, ExecutionError}; -use crate::workspace::types::{BlockExecution, BlockRef, BlockTrace, EvaluationError}; +use crate::workspace::{BlockExecution, BlockRef, BlockTrace, EvaluationError}; pub(crate) struct Host<'a> { pub(crate) state: HostState<'a>, diff --git a/core/engine/src/compiled/policy/mod.rs b/core/engine/src/compiled/policy/mod.rs index 9defaa724..10f6420c0 100644 --- a/core/engine/src/compiled/policy/mod.rs +++ b/core/engine/src/compiled/policy/mod.rs @@ -20,7 +20,7 @@ use crate::compiled::table::{Table, TableIr}; use crate::policy::blocks::Block; use crate::policy::blocks::{AssertionIr, BlockKind, MatchIr}; use crate::workspace::types::BlockRef; -use crate::workspace::types::{EvaluateRequest, EvaluationError, EvaluationResult}; +use crate::workspace::{EvaluateRequest, EvaluationError, EvaluationResult}; use schedule::{Blocks, Demand, End, Event, Replay, Segment}; use std::cell::RefCell; use std::sync::Arc; diff --git a/core/engine/src/compiled/policy/site.rs b/core/engine/src/compiled/policy/site.rs index 54f007a3a..c8e1c3b36 100644 --- a/core/engine/src/compiled/policy/site.rs +++ b/core/engine/src/compiled/policy/site.rs @@ -11,7 +11,7 @@ use zen_types::symbol::Symbol; use crate::compiled::policy::artifact::{Artifact as EvalArtifact, Iteration}; use crate::compiled::policy::blocks::{MatchSelection, TableIndexes, TableSelection}; use crate::policy::blocks::{Block, BlockKind, BlockReadPlan, ExecutionError, PropertyRead}; -use crate::workspace::types::{BlockExecution, BlockRef, BlockTrace, EvaluationError, WriteTrace}; +use crate::workspace::{BlockExecution, BlockRef, BlockTrace, EvaluationError, WriteTrace}; pub(crate) struct Site<'a> { pub(crate) store: &'a Variable, diff --git a/core/engine/src/compiled/policy/traced.rs b/core/engine/src/compiled/policy/traced.rs index fc1d6b65f..5a550308b 100644 --- a/core/engine/src/compiled/policy/traced.rs +++ b/core/engine/src/compiled/policy/traced.rs @@ -5,7 +5,7 @@ use super::schedule::{Demand, End, Event}; use super::{Host, PolicyPlan}; use crate::compiled::policy::artifact::{Artifact as EvalArtifact, StoreOps}; use crate::compiled::policy::site::Picked; -use crate::workspace::types::{EvaluateRequest, EvaluationError, EvaluationResult, Trace}; +use crate::workspace::{EvaluateRequest, EvaluationError, EvaluationResult, Trace}; impl PolicyPlan { pub(crate) fn traced( @@ -21,14 +21,14 @@ impl PolicyPlan { artifact, &store, &req.policy_path, - req.trace, + req.trace.is_on(), extras, &self.programs, context.clone(), ); let outcome = self.replay(artifact, &mut host); - let trace = req.trace.then(|| Trace { + let trace = req.trace.is_on().then(|| Trace { engine_version: Arc::from(crate::ENGINE_VERSION), properties: store.snapshot(&order_to_run), executions: host.executions(), @@ -41,7 +41,7 @@ impl PolicyPlan { Ok(EvaluationResult { output: store, duration: start.elapsed(), - trace, + trace: trace.map(crate::compiled::trace::PolicyTrace::Legacy), }) } diff --git a/core/engine/src/compiled/table/collect.rs b/core/engine/src/compiled/table/collect.rs index ee5c74613..2ce2907cb 100644 --- a/core/engine/src/compiled/table/collect.rs +++ b/core/engine/src/compiled/table/collect.rs @@ -184,7 +184,9 @@ impl Table { let rows = bound.rows(); let words = self.words; let (candidates, deferred) = self.candidates(runner, bound, false); + let exact = deferred.is_empty(); let first = self.choose(runner, bound, &candidates, deferred); + self.record_hits(bound, &candidates, Some(&first), exact); let lists = self.collect_columns.len(); let targeted = self.targets(); let (targets, templates) = &targeted; @@ -251,6 +253,7 @@ impl Table { return None; } let (candidates, _) = self.candidates(runner, bound, false); + self.record_hits(bound, &candidates, None, true); let (codes, sets) = self.sets(&candidates, bound.rows()); let templates: Vec> = sets .iter() @@ -378,6 +381,7 @@ impl Table { let names = self.record_names()?; let rows = bound.rows(); let (candidates, _) = self.candidates(runner, bound, false); + self.record_hits(bound, &candidates, None, true); let (codes, sets) = self.sets(&candidates, rows); let sets: Vec> = sets .into_iter() diff --git a/core/engine/src/compiled/table/first.rs b/core/engine/src/compiled/table/first.rs index 84eadd2f6..f6a5a3aa4 100644 --- a/core/engine/src/compiled/table/first.rs +++ b/core/engine/src/compiled/table/first.rs @@ -94,6 +94,20 @@ impl Table { } pub fn first(&self, runner: &mut LaneRunner, bound: &Bound) -> First { + let first = self.chosen_first(runner, bound); + if let Some(probe) = &bound.probe { + probe.record_first(self.origins_of(&first)); + } + first + } + + pub(crate) fn origins_of(&self, first: &First) -> Vec> { + (0..first.codes.len()) + .map(|row| first.chosen(row).map(|rule| self.origin(rule))) + .collect() + } + + fn chosen_first(&self, runner: &mut LaneRunner, bound: &Bound) -> First { if let (Some(dispatch), true) = (&self.dispatch, self.literal) { if let (Some(keys), Some(chosen)) = (self.keyed(dispatch, runner, bound), &dispatch.chosen) diff --git a/core/engine/src/compiled/table/mod.rs b/core/engine/src/compiled/table/mod.rs index 7b28d4786..7f26f4546 100644 --- a/core/engine/src/compiled/table/mod.rs +++ b/core/engine/src/compiled/table/mod.rs @@ -8,12 +8,14 @@ mod strict; use crate::compiled::bound::{Bound, Outs}; use crate::compiled::leaf::{Array, Bits, Dict, Literal, Store}; +use crate::compiled::trace::record::FieldColumn; use cells::{Built, OutputCells}; pub(crate) use dispatch::Dispatch; pub(crate) use first::First; use fused::FusedCells; use profile::{Empty, Resolve}; pub(crate) use profile::{Profile, TableIr}; +use smallvec::SmallVec; use std::borrow::Cow; use std::rc::Rc; use std::sync::Arc; @@ -137,6 +139,7 @@ type Keyed<'k, T> = (Cow<'k, [u64]>, Rc<[T]>); type Found<'k> = (Rc, Cow<'k, [u64]>, Cow<'k, [u64]>); pub(crate) struct Table { + origins: Vec, id: u64, profile: Profile, fused: Option, @@ -147,6 +150,7 @@ pub(crate) struct Table { rules: usize, words: usize, columns: Vec, + fields: Vec>>, outputs: Vec, collect_columns: Vec<(usize, Arc)>, split: Option]>>, @@ -162,10 +166,11 @@ enum Part { } impl Table { - fn reachable(mut ir: TableIr) -> TableIr { + fn reachable(mut ir: TableIr) -> (TableIr, Vec) { + let all: Vec = (0..ir.rules.len() as u32).collect(); if ir.collect || ir.profile.resolve != Resolve::Row || ir.outputs.iter().any(|o| o.collect) { - return ir; + return (ir, all); } let ids: Vec<&Arc> = ir .inputs @@ -186,18 +191,29 @@ impl Table { ) }) .collect(); + let origins = all + .into_iter() + .zip(&keep) + .filter(|(_, kept)| **kept) + .map(|(at, _)| at) + .collect(); let mut keep = keep.into_iter(); ir.rules.retain(|_| keep.next().unwrap_or(true)); - ir + (ir, origins) + } + + pub fn origin(&self, rule: usize) -> u32 { + self.origins.get(rule).copied().unwrap_or(rule as u32) } pub fn compile(ir: TableIr) -> Result { - let ir = Self::reachable(ir); + let (ir, origins) = Self::reachable(ir); let rules = ir.rules.len(); let words = rules.div_ceil(64).max(1); let strict = ir.profile.strict(); let bit = |bits: &mut Vec, rule: usize| bits[rule / 64] |= 1 << (rule % 64); let mut columns = Vec::with_capacity(ir.inputs.len()); + let mut fields: Vec>> = Vec::with_capacity(ir.inputs.len()); let mut ordered = Vec::new(); let mut plain_sources: Vec<(usize, usize, Arc)> = Vec::new(); for input in ir.inputs.iter() { @@ -253,6 +269,7 @@ impl Table { cells: Box::new(set), empty, }); + fields.push(Some(Arc::from(field))); } None => { let mut distinct: Vec<(Arc, Option, Vec)> = Vec::new(); @@ -300,10 +317,12 @@ impl Table { owners, optimistic, }); + fields.push(None); } } } let mut table = Self { + origins, id: Self::next_id(), profile: ir.profile, fused: None, @@ -314,6 +333,7 @@ impl Table { rules, words, columns, + fields, outputs: Vec::new(), collect_columns: Vec::new(), split: None, @@ -624,6 +644,31 @@ impl Table { } } + fn record_fields(&self, runner: &mut LaneRunner, bound: &Bound) { + let Some(probe) = bound.probe.as_ref().filter(|probe| probe.wants_fields()) else { + return; + }; + let rows = bound.rows(); + let mut fields = Vec::new(); + for (index, column) in self.columns.iter().enumerate() { + let (Column::Field { field, .. }, Some(Some(name))) = (column, self.fields.get(index)) + else { + continue; + }; + let mut failed = vec![false; rows]; + let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); + let column = direct.or_else(|| typed.as_ref().map(Array::column)); + fields.push(FieldColumn { + name: name.clone(), + values: (0..rows) + .map(|row| column.map_or(Variable::Null, |c| c.variable(row))) + .collect(), + failed, + }); + } + probe.record_fields(fields); + } + fn candidates( &self, runner: &mut LaneRunner, @@ -631,6 +676,7 @@ impl Table { lazy: bool, ) -> (Vec, Vec) { if let Some(dispatch) = &self.dispatch { + self.record_fields(runner, bound); return (self.dispatched(dispatch, runner, bound), Vec::new()); } let (rows, words) = (bound.rows(), self.words); @@ -639,6 +685,11 @@ impl Table { let mut bits = Vec::new(); let mut deferred = Vec::new(); let fused = self.fused_truths(runner, bound); + let mut tapped: Option> = bound + .probe + .as_ref() + .filter(|probe| probe.wants_fields()) + .map(|_| Vec::new()); for (index, column) in self.columns.iter().enumerate() { match column { Column::Field { @@ -649,6 +700,17 @@ impl Table { let mut failed = vec![false; rows]; 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(tapped), Some(Some(name))) = + (tapped.as_mut(), self.fields.get(index)) + { + tapped.push(FieldColumn { + name: name.clone(), + values: (0..rows) + .map(|row| column.map_or(Variable::Null, |c| c.variable(row))) + .collect(), + failed: failed.clone(), + }); + } if let (Some(truths), Some(view), true) = (&fused, direct, self.fuses(index)) { cells.indexed_column(&view, rows, &mut bits, bound.context.timezone()); for other in 0..cells.others() { @@ -833,9 +895,62 @@ impl Table { } } } + if let (Some(tapped), Some(probe)) = (tapped, &bound.probe) { + probe.record_fields(tapped); + } (all, deferred) } + fn literal_outputs(&self) -> bool { + self.outputs + .iter() + .all(|o| o.paths.is_empty() || o.literals.is_some()) + } + + pub(crate) fn record_hits( + &self, + bound: &Bound, + candidates: &[u64], + first: Option<&First>, + exact: bool, + ) { + let Some(probe) = &bound.probe else { + return; + }; + if !exact || !self.literal_outputs() { + probe.record_hits(None); + return; + } + let words = self.words; + let hits = candidates + .chunks_exact(words) + .enumerate() + .map(|(row, bits)| { + let from = match first { + None => 0, + Some(first) => match first.chosen(row) { + None => return SmallVec::new(), + Some(chosen) => chosen, + }, + }; + let mut out: SmallVec<[u32; 4]> = SmallVec::new(); + if first.is_some() { + out.push(self.origin(from)); + } + out.extend( + Bits::rows(bits) + .filter(|&rule| match first { + None => true, + Some(_) => rule > from, + }) + .map(|rule| self.origin(rule)), + ); + out + }) + .collect(); + probe.record_hits(Some(hits)); + } + const FUSED: usize = 64; const THAWS: usize = 4096; @@ -1062,6 +1177,13 @@ impl Table { Hit::Collect => { let words = self.words; let (candidates, _) = self.candidates(runner, bound, false); + let mut hits: Option>> = + bound.probe.as_ref().map(|_| vec![SmallVec::new(); rows]); + let mut hit = |lane: usize, rule: usize| { + if let Some(hits) = hits.as_mut().and_then(|hits| hits.get_mut(lane)) { + hits.push(self.origin(rule)); + } + }; let mut result: Vec> = vec![Vec::new(); rows]; let mut any = vec![0u64; words]; candidates @@ -1076,17 +1198,19 @@ impl Table { } let outputs = &self.outputs[rule]; match (outputs.paths.is_empty(), &outputs.literals) { - (true, _) => lanes - .iter() - .for_each(|&l| result[l].push(Variable::empty_object())), + (true, _) => lanes.iter().for_each(|&l| { + result[l].push(Variable::empty_object()); + hit(l, rule); + }), (false, Some(literals)) => { let values: Vec = literals.iter().map(Literal::variable).collect(); let template = self.built(self.builder(rule, None).as_ref(), rule, None, &values); - lanes - .iter() - .for_each(|&l| result[l].push(template.deep_clone())); + lanes.iter().for_each(|&l| { + result[l].push(template.deep_clone()); + hit(l, rule); + }); } (false, None) => { let builder = self.builder(rule, None); @@ -1103,12 +1227,16 @@ impl Table { None, &values, )); + hit(lane, rule); } }, ) } } } + if let (Some(probe), Some(hits)) = (&bound.probe, hits) { + probe.record_hits(Some(hits)); + } result .into_iter() .map(|items| TableOut::Value(Variable::from_array(items))) @@ -1116,7 +1244,9 @@ impl Table { } Hit::FirstCollect => { let (candidates, deferred) = self.candidates(runner, bound, false); + let exact = deferred.is_empty(); let first = self.choose(runner, bound, &candidates, deferred); + self.record_hits(bound, &candidates, Some(&first), exact); let mut collected = self.gather(runner, bound, &first, &candidates, &self.targets()); (0..rows) diff --git a/core/engine/src/compiled/trace/api.rs b/core/engine/src/compiled/trace/api.rs new file mode 100644 index 000000000..8e2ba25d2 --- /dev/null +++ b/core/engine/src/compiled/trace/api.rs @@ -0,0 +1,195 @@ +pub use super::migrate::api::{convert, inspect, redact, restore, restore_json, testing}; +use super::value::{self, Val}; +pub use super::{PolicyTrace, TraceBatch, TraceDocument, TraceFormat}; +use zen_types::variable::Variable; + +#[derive(Debug, thiserror::Error)] +pub enum TraceError { + #[error("{0}")] + Invalid(String), + #[error("this policy trace needs its documents to restore reads")] + DocumentsRequired, + #[error("{0}")] + Json(String), + #[error("malformed trace: {0}")] + Malformed(String), +} + +pub(crate) type R = Result; + +pub(crate) fn bad(msg: impl Into) -> TraceError { + TraceError::Invalid(msg.into()) +} + +pub(crate) fn malformed(what: impl Into) -> TraceError { + TraceError::Malformed(what.into()) +} + +pub(crate) trait Need { + fn need(self, what: &str) -> R; +} + +impl Need for Option { + #[inline] + fn need(self, what: &str) -> R { + match self { + Some(v) => Ok(v), + None => Err(malformed(what)), + } + } +} + +#[derive(Clone, Copy)] +pub enum Input<'a> { + Variable(&'a Variable), + Json(&'a str), +} + +#[derive(Clone, Copy)] +pub enum LegacyTrace<'a> { + Variable(&'a Variable), + Json(&'a str), + Reference(&'a Variable), + ReferenceString(&'a str), +} + +#[derive(Clone, Copy)] +pub struct NodeError<'a> { + pub node: &'a str, + pub message: Option<&'a str>, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Evaluation { + pub evaluated_at: Option>, + pub timezone: Option>, + pub seed: Option, +} + +impl Evaluation { + pub fn write(&self, out: &mut String) { + if let Some(at) = &self.evaluated_at { + out.push_str(",\"evaluatedAt\":"); + value::write_str(at, out); + } + if let Some(zone) = &self.timezone { + out.push_str(",\"timezone\":"); + value::write_str(zone, out); + } + if let Some(seed) = self.seed { + out.push_str(",\"seed\":"); + out.push_str(itoa::Buffer::new().format(seed)); + } + } + + pub(crate) fn stamp(&self, doc: Val) -> Val { + let Val::Obj(o) = &doc else { return doc }; + let mut out = value::Obj::with_capacity(o.len() + 3); + let mut placed = false; + let place = |out: &mut value::Obj| { + if let Some(at) = &self.evaluated_at { + out.insert(std::rc::Rc::from("evaluatedAt"), Val::str(at)); + } + if let Some(zone) = &self.timezone { + out.insert(std::rc::Rc::from("timezone"), Val::str(zone)); + } + if let Some(seed) = self.seed { + out.insert( + std::rc::Rc::from("seed"), + Val::Num(rust_decimal::Decimal::from(seed)), + ); + } + }; + for (k, v) in o.iter() { + if matches!(&**k, "evaluatedAt" | "timezone" | "seed") { + continue; + } + if !placed && !matches!(&**k, "version" | "kind" | "engine") { + place(&mut out); + placed = true; + } + out.insert(k.clone(), v.clone()); + } + if !placed { + place(&mut out); + } + Val::obj(out) + } + + pub fn stamp_json(&self, json: &str) -> Option { + if self.evaluated_at.is_none() && self.timezone.is_none() && self.seed.is_none() { + return Some(json.to_string()); + } + let doc = value::parse(json).ok()?; + doc.as_obj()?; + Some(self.stamp(doc).to_json()) + } +} + +pub struct ConvertArgs<'a> { + pub trace: LegacyTrace<'a>, + pub request: Input<'a>, + pub error: Option>, + pub engine_version: Option<&'a str>, + pub documents: Option>, + pub verify: bool, + pub evaluation: Option<&'a Evaluation>, +} + +impl<'a> ConvertArgs<'a> { + pub fn new(trace: LegacyTrace<'a>, request: Input<'a>) -> Self { + Self { + trace, + request, + error: None, + engine_version: None, + documents: None, + verify: true, + evaluation: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Status { + Converted, + Verbatim { reason: String }, +} + +#[derive(Debug, Clone)] +pub struct ConvertOutput { + pub json: String, + pub status: Status, +} + +impl ConvertOutput { + pub fn document(&self) -> Variable { + value::parse(&self.json) + .map(|v| value::to_variable(&v)) + .unwrap_or(Variable::Null) + } +} + +pub fn parse_document(json: &str) -> Result { + value::parse(json) + .map(|v| value::to_variable(&v)) + .map_err(|e| TraceError::Json(e.to_string())) +} + +pub struct RestoreArgs<'a> { + pub trace: Input<'a>, + pub request: Input<'a>, + pub documents: Option>, +} + +#[derive(Debug, Clone)] +pub struct Inspection { + pub kind: String, + pub engine: Option, + pub requires: Vec, + pub evaluated_at: Option, + pub timezone: Option, + pub seed: Option, + pub context: Option, + pub truncated: bool, +} diff --git a/core/engine/src/compiled/trace/batch.rs b/core/engine/src/compiled/trace/batch.rs new file mode 100644 index 000000000..0e07b7a7f --- /dev/null +++ b/core/engine/src/compiled/trace/batch.rs @@ -0,0 +1,1783 @@ +use super::collect::{Fact, Hit, Level, Record, Slot, Template}; +use super::rows::RowWriter; +use crate::compiled::graph::data::{Data, Keys}; +use crate::compiled::host::graph::walker::GraphWalker; +use smallvec::SmallVec; +use std::cell::OnceCell; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::Variable; + +pub(crate) type Masked<'a> = (crate::compiled::leaf::Leaf<'a>, Option>); + +pub(crate) enum Cols<'a> { + Owned(Vec>), + Lazy(Vec>, Option>), +} + +impl<'a> Cols<'a> { + pub(crate) fn len(&self) -> usize { + match self { + Cols::Owned(leaves) => leaves.len(), + Cols::Lazy(leaves, _) => leaves.len(), + } + } + + fn listed( + &self, + index: usize, + position: usize, + ) -> Option<(&crate::compiled::leaf::Leaf<'a>, usize)> { + match self { + Cols::Owned(_) => None, + Cols::Lazy(leaves, rows) => { + let row = match rows { + Some(rows) => *rows.get(position)?, + None => position, + }; + let (leaf, present) = leaves.get(index)?; + if present + .as_ref() + .is_some_and(|present| !crate::compiled::leaf::Bits::get(present, row)) + { + return None; + } + Some((leaf, row)) + } + } + } + + fn plain(&self, index: usize) -> Option<(zen_expression::lane::Column<'_>, u8)> { + match self { + Cols::Owned(leaves) => leaves.get(index)?.plain(), + Cols::Lazy(leaves, None) => match leaves.get(index)? { + (leaf, None) => leaf.plain(), + _ => None, + }, + Cols::Lazy(..) => None, + } + } + + pub(crate) fn get(&self, index: usize, position: usize) -> Variable { + match self { + Cols::Owned(leaves) => leaves[index].get(position), + Cols::Lazy(leaves, rows) => { + let row = match rows { + Some(rows) => rows[position], + None => position, + }; + let (leaf, present) = &leaves[index]; + match present + .as_ref() + .is_some_and(|present| !crate::compiled::leaf::Bits::get(present, row)) + { + true => Variable::Null, + false => leaf.shared(row), + } + } + } + } +} + +pub(crate) enum Facts<'a> { + None, + Results((Arc<[Arc]>, Cols<'a>)), + Objects(Arc<[Arc]>, Rc<[Variable]>), + First(Vec>), + Branches(Vec>), + Rows(Vec), + Fields(Vec>, Rc<[super::record::FieldColumn]>), + Collected(super::record::RuleHits, Rc<[super::record::FieldColumn]>), + Loop(Rc<[(u32, u32)]>, Box>), +} + +impl Facts<'_> { + fn at(&self, position: usize, template: &Template, slot: Slot, input: &Variable) -> Fact { + match self { + Facts::None => Fact::None, + Facts::Results((keys, leaves)) => Fact::Results( + keys.iter() + .enumerate() + .map(|(index, key)| (key.clone(), leaves.get(index, position))) + .collect(), + ), + Facts::Objects(keys, values) => { + let object = values.get(position).cloned().unwrap_or(Variable::Null); + Fact::Results( + keys.iter() + .map(|key| (key.clone(), object.dot(key).unwrap_or(Variable::Null))) + .collect(), + ) + } + Facts::First(rules) => match rules.get(position).copied().flatten() { + Some(rule) => Fact::Hit(Hit { + rule, + refs: Some(template.refs(slot, rule, input)), + }), + None => Fact::None, + }, + Facts::Branches(taken) => { + Fact::Branches(taken.get(position).cloned().unwrap_or_default()) + } + Facts::Rows(facts) => facts.get(position).cloned().unwrap_or(Fact::None), + Facts::Fields(rules, fields) => rules + .get(position) + .copied() + .flatten() + .and_then(|rule| { + super::record::KernelFacts::captured_hit(template, slot, rule, fields, position) + }) + .map_or(Fact::None, Fact::Hit), + Facts::Collected(rules, fields) => Fact::Hits( + rules + .get(position) + .into_iter() + .flatten() + .filter_map(|rule| { + super::record::KernelFacts::captured_hit( + template, slot, *rule, fields, position, + ) + }) + .collect(), + ), + Facts::Loop(spans, inner) => { + let Some(&(start, count)) = spans.get(position) else { + return Fact::None; + }; + Fact::Items( + (start..start + count) + .map(|item| match inner.as_ref() { + Facts::First(rules) => { + match rules.get(item as usize).copied().flatten() { + Some(rule) => Fact::Hit(Hit { rule, refs: None }), + None => Fact::None, + } + } + other => other.at(item as usize, template, slot, input), + }) + .collect(), + ) + } + } + } +} + +pub(crate) enum Value<'a> { + Null, + Data(Rc>), +} + +impl Value<'_> { + fn row(&self, position: usize) -> Variable { + match self { + Value::Null => Variable::Null, + Value::Data(data) => data.materialize_row(position), + } + } +} + +pub(crate) enum Encoding<'a> { + Generic, + Request, + Null, + Passed, + Touched(Option>>), + Record, + Checked(bool), + Results(Rc<[bool]>), +} + +pub(crate) struct BatchEvent<'a> { + pub(crate) slot: Slot, + pub(crate) parents: Box<[Slot]>, + pub(crate) rows: Rc<[usize]>, + pub(crate) input: bool, + pub(crate) output: Option>, + pub(crate) ns: u64, + pub(crate) facts: Facts<'a>, + pub(crate) encoding: Encoding<'a>, +} + +pub(crate) struct Asked<'x> { + cell: OnceCell, + make: &'x dyn Fn() -> Variable, +} + +impl<'x> Asked<'x> { + pub(crate) fn new(make: &'x dyn Fn() -> Variable) -> Self { + Self { + cell: OnceCell::new(), + make, + } + } + + pub(crate) fn get(&self) -> &Variable { + self.cell.get_or_init(|| (self.make)()) + } +} + +pub(crate) struct Reserved<'a> { + pub(crate) paths: bool, + pub(crate) leaves: Vec>, + pub(crate) rows: usize, + plain: OnceCell, +} + +impl<'a> Reserved<'a> { + pub(crate) fn new( + paths: bool, + leaves: Vec>, + rows: usize, + ) -> Self { + Self { + paths, + leaves, + rows, + plain: OnceCell::new(), + } + } + + fn plain(&self) -> bool { + *self.plain.get_or_init(|| { + self.paths + && self + .leaves + .iter() + .all(|leaf| (0..self.rows).all(|row| !super::rows::reserved(&leaf.get(row)))) + }) + } +} + +pub(crate) struct Traces<'a> { + pub(crate) derived: Option>, + pub(crate) template: Arc