test: golden references for graph and policy evaluation (outputs, errors, traces) and single-row latency benches

This commit is contained in:
Stefan Miljakovic
2026-10-09 09:47:19 +02:00
parent 42905d6e34
commit e0de7cdbef
133 changed files with 2806 additions and 862 deletions
+5 -1
View File
@@ -69,4 +69,8 @@ name = "engine"
[features]
default = []
bindgen = ["rquickjs/bindgen"]
arbitrary_precision = ["serde_json/arbitrary_precision", "zen-expression/arbitrary_precision", "zen-types/arbitrary_precision", "zen-tmpl/arbitrary_precision"]
arbitrary_precision = ["serde_json/arbitrary_precision", "zen-expression/arbitrary_precision", "zen-types/arbitrary_precision", "zen-tmpl/arbitrary_precision"]
[[test]]
name = "golden"
required-features = ["arbitrary_precision"]
+138 -164
View File
@@ -1,179 +1,53 @@
mod support;
#[path = "support/fixture.rs"]
mod fixture;
use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use support::columns::Built;
use support::test_data_root;
use zen_engine::model::{DecisionContent, GraphContent};
use support::golden::{Canon, Reference};
use zen_engine::model::GraphContent;
use zen_engine::{Decision, EvaluationOptions};
use zen_expression::Variable;
struct Fixture {
name: String,
content: GraphContent,
inputs: Vec<Value>,
}
impl Fixture {
fn load_all() -> Vec<Fixture> {
let root = PathBuf::from(test_data_root());
let mut paths: Vec<PathBuf> = fs::read_dir(root.join("graphs"))
.into_iter()
.flatten()
.chain(fs::read_dir(&root).into_iter().flatten())
.chain(fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/compiled")).into_iter().flatten())
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
paths.sort();
paths.iter().filter_map(|p| Self::load(p)).collect()
}
fn load(path: &Path) -> Option<Fixture> {
let text = fs::read_to_string(path).ok()?;
let raw: Value = serde_json::from_str(&text).ok()?;
let content: DecisionContent = serde_json::from_value(raw.clone()).ok()?;
let DecisionContent::Graph(graph) = content else {
return None;
};
let mut inputs: Vec<Value> = raw
.get("tests")
.and_then(Value::as_array)
.map(|tests| tests.iter().filter_map(|t| t.get("input").cloned()).collect())
.unwrap_or_default();
if inputs.is_empty() {
inputs.push(json!({}));
}
Some(Fixture {
name: path.file_name()?.to_string_lossy().to_string(),
content: (*graph).clone(),
inputs,
})
}
fn typed_variants(&self) -> Vec<Value> {
let mut out: Vec<Value> = Vec::new();
for base in &self.inputs {
out.push(base.clone());
let Some(object) = base.as_object() else {
continue;
};
for (key, value) in object {
let mut with = |replacement: Option<Value>| {
let mut copy = object.clone();
match replacement {
Some(v) => copy.insert(key.clone(), v),
None => copy.remove(key),
};
out.push(Value::Object(copy));
};
with(None);
match value {
Value::Number(n) => {
for delta in ["1", "-1", "0", "1000000", "0.5"] {
let shifted: Option<rust_decimal::Decimal> = n
.to_string()
.parse::<rust_decimal::Decimal>()
.ok()
.zip(delta.parse::<rust_decimal::Decimal>().ok())
.and_then(|(a, b)| a.checked_add(b));
if let Some(v) = shifted.and_then(|d| serde_json::from_str(&d.to_string()).ok()) {
with(Some(v));
}
}
}
Value::String(s) => {
with(Some(json!("")));
with(Some(json!(format!("{s}x"))));
}
Value::Bool(b) => with(Some(json!(!b))),
_ => {}
}
}
}
out.truncate(400);
out
}
fn variants(&self) -> Vec<Value> {
let mut out: Vec<Value> = Vec::new();
for base in &self.inputs {
out.push(base.clone());
let Some(object) = base.as_object() else {
continue;
};
for (key, value) in object {
let mut with = |replacement: Option<Value>| {
let mut copy = object.clone();
match replacement {
Some(v) => {
copy.insert(key.clone(), v);
}
None => {
copy.remove(key);
}
}
out.push(Value::Object(copy));
};
with(None);
with(Some(Value::Null));
match value {
Value::Number(n) => {
let text = n.to_string();
for delta in ["1", "-1", "0", "1000000", "0.5"] {
let shifted: Option<rust_decimal::Decimal> = text
.parse::<rust_decimal::Decimal>()
.ok()
.zip(delta.parse::<rust_decimal::Decimal>().ok())
.and_then(|(a, b)| a.checked_add(b));
if let Some(v) = shifted.and_then(|d| serde_json::from_str(&d.to_string()).ok()) {
with(Some(v));
}
}
with(Some(json!("text")));
}
Value::String(s) => {
with(Some(json!("")));
with(Some(json!(format!("{s}x"))));
with(Some(json!(42)));
}
Value::Bool(b) => with(Some(json!(!b))),
Value::Array(items) => {
with(Some(json!([])));
let mut doubled = items.clone();
doubled.extend(items.iter().cloned());
with(Some(Value::Array(doubled)));
}
Value::Object(_) => with(Some(json!({}))),
Value::Null => with(Some(json!(1))),
}
}
}
out.truncate(400);
out
}
}
const NETWORK_BOUND: &[&str] = &["http-function.json"];
const TIME_BOUND: &[&str] = &["infinite-function.json", "sleep-function.json"];
struct Outcome;
impl Outcome {
const CLOCK: &'static str = "2025-08-19T16:55:02.078Z";
fn of(result: Result<zen_engine::DecisionGraphResponse, Box<zen_engine::EvaluationError>>) -> Result<String, String> {
result
.map(|r| serde_json::to_string(&r.result).unwrap_or_default())
.map_err(|e| serde_json::to_value(&*e).map(|v| v.to_string()).unwrap_or_else(|_| e.to_string()))
}
fn recorded(outcome: &support::golden::Outcome) -> Result<String, String> {
match outcome {
support::golden::Outcome::Ok(value) => Ok(Canon::value(Canon::restore(value).to_value()).to_string()),
support::golden::Outcome::Err { value, .. } => Err(value.to_string()),
}
}
fn canonical(result: Result<String, String>) -> Result<String, String> {
let canon = |text: String| serde_json::from_str::<Value>(&text).map(|v| Canon::value(v).to_string()).unwrap_or(text);
result.map(canon).map_err(canon)
}
fn columnar(outcome: &support::golden::Outcome) -> Result<Value, String> {
match outcome {
support::golden::Outcome::Ok(value) => Ok(Built::normalized(Canon::restore(value).to_value())),
support::golden::Outcome::Err { value, .. } => Err(value.to_string()),
}
}
}
#[tokio::test]
async fn compiled_graphs_match_the_walker() {
std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z");
Reference::prepare(Outcome::CLOCK);
let reference = Reference::open("graph-fixtures");
let mut census: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut failures: Vec<String> = Vec::new();
let mut compared = 0usize;
@@ -196,12 +70,19 @@ async fn compiled_graphs_match_the_walker() {
let options = EvaluationOptions::default();
let batch = compiled.evaluate_batch(&contexts, options).await;
for (i, input) in variants.iter().enumerate() {
let want = Outcome::of(walker.evaluate(Variable::from(input.clone())).await);
let context = Variable::from(input.clone());
let want = reference
.graph(|| Canon::key(&fixture.name, &[], &context), || async { Outcome::of(walker.evaluate(Variable::from(input.clone())).await) }, Outcome::recorded)
.await;
let single = Outcome::of(compiled.evaluate(Variable::from(input.clone())).await);
let batched = batch.get(i).map(|r| match r {
Ok(r) => Ok(serde_json::to_string(&r.result).unwrap_or_default()),
Err(e) => Err(serde_json::to_value(&**e).map(|v| v.to_string()).unwrap_or_else(|_| e.to_string())),
});
let (single, batched) = match reference.is_live() {
true => (single, batched),
false => (Outcome::canonical(single), batched.map(Outcome::canonical)),
};
compared += 1;
if single != want {
failures.push(format!("{} single {input}\n walker {want:?}\n compiled {single:?}", fixture.name));
@@ -215,6 +96,7 @@ async fn compiled_graphs_match_the_walker() {
println!("{verdict}: {} {:?}", files.len(), files);
}
println!("compared {compared} inputs");
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.iter().take(20).cloned().collect::<Vec<_>>().join("\n"));
}
@@ -291,7 +173,8 @@ async fn compiled_graph_throughput() {
#[tokio::test]
async fn columnar_graphs_match_the_walker() {
std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z");
Reference::prepare(Outcome::CLOCK);
let reference = Reference::open("graph-fixtures");
let mut failures: Vec<String> = Vec::new();
let (mut compared, mut skipped) = (0usize, 0usize);
for fixture in Fixture::load_all() {
@@ -317,11 +200,18 @@ async fn columnar_graphs_match_the_walker() {
let output = compiled.evaluate_columns(&columns, EvaluationOptions::default()).await;
for row in 0..built.rows {
let input = columns.row(row);
let want = walker.evaluate(input.clone()).await;
let want = match want {
Ok(r) => Ok(Built::normalized(r.result.to_value())),
Err(e) => Err(serde_json::to_value(&*e).map(|v| v.to_string()).unwrap_or_default()),
};
let want = reference
.graph(
|| Canon::key(&fixture.name, &[], &input),
|| async {
match walker.evaluate(input.clone()).await {
Ok(r) => Ok(Built::normalized(r.result.to_value())),
Err(e) => Err(serde_json::to_value(&*e).map(|v| v.to_string()).unwrap_or_default()),
}
},
Outcome::columnar,
)
.await;
let got = match &output.errors[row] {
Some(e) => Err(serde_json::to_value(&**e).map(|v| v.to_string()).unwrap_or_default()),
None => Ok(Built::normalized(output.row(row).to_value())),
@@ -334,6 +224,7 @@ async fn columnar_graphs_match_the_walker() {
}
}
println!("compared {compared} rows, {skipped} fixtures skipped");
failures.extend(reference.missing());
let mut kinds: Vec<&str> = failures.iter().filter_map(|f| f.split_whitespace().next()).collect();
kinds.dedup();
assert!(failures.is_empty(), "{} mismatches in {kinds:?}:\n{}", failures.len(), failures.iter().take(15).cloned().collect::<Vec<_>>().join("\n"));
@@ -342,7 +233,7 @@ async fn columnar_graphs_match_the_walker() {
#[tokio::test]
async fn struct_inputs_match_the_walker() {
use zen_expression::lane::{Column, Columns, Values};
std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z");
Reference::prepare(Outcome::CLOCK);
let mut failures: Vec<String> = Vec::new();
let mut compared = 0usize;
for fixture in Fixture::load_all() {
@@ -512,6 +403,89 @@ async fn columnar_graph_throughput() {
);
}
struct Latency;
impl Latency {
async fn measure<F, Fut>(contexts: &[Variable], reps: usize, mut f: F) -> f64
where
F: FnMut(Variable) -> Fut,
Fut: std::future::Future<Output = ()>,
{
let mut best = f64::MAX;
for _ in 0..reps {
let fresh: Vec<Variable> = contexts.iter().map(|c| c.depth_clone(usize::MAX)).collect();
let start = std::time::Instant::now();
for context in fresh {
f(context).await;
}
best = best.min(start.elapsed().as_nanos() as f64 / contexts.len() as f64);
}
best
}
fn geomean(values: &[f64]) -> f64 {
(values.iter().map(|v| v.ln()).sum::<f64>() / values.len().max(1) as f64).exp()
}
}
#[tokio::test]
#[ignore]
async fn single_row_latency() {
std::env::set_var("__ZEN_MOCK_UTC_TIME", Outcome::CLOCK);
let reps: usize = std::env::var("BENCH_REPS").ok().and_then(|v| v.parse().ok()).unwrap_or(5);
let filter = std::env::var("BENCH_FILE").ok();
let traced = EvaluationOptions { trace: true, max_depth: 10 };
let mut columns: [Vec<f64>; 5] = Default::default();
println!("{:44} {:>10} {:>10} {:>10} {:>10} {:>10}", "fixture", "compiled", "cold", "traced", "walker", "w-traced");
for fixture in Fixture::load_all() {
if NETWORK_BOUND.contains(&fixture.name.as_str())
|| TIME_BOUND.contains(&fixture.name.as_str())
|| filter.as_ref().is_some_and(|f| !fixture.name.contains(f.as_str()))
{
continue;
}
let content = Arc::new(fixture.content.clone());
let mut compiled = Decision::from(content.clone());
compiled.compile();
if !matches!(compiled.compiled_verdict(), Some(Ok(()))) {
continue;
}
let walker = compiled.interpreted();
let contexts: Vec<Variable> = fixture.variants().into_iter().take(64).map(Variable::from).collect();
let times = [
Latency::measure(&contexts, reps, |c| {
let compiled = &compiled;
async move { drop(compiled.evaluate(c).await) }
})
.await,
Latency::measure(&contexts, reps, |c| {
let content = content.clone();
async move { drop(Decision::from(content).evaluate(c).await) }
})
.await,
Latency::measure(&contexts, reps, |c| {
let compiled = &compiled;
async move { drop(compiled.evaluate_with_opts(c, traced).await) }
})
.await,
Latency::measure(&contexts, reps, |c| {
let walker = &walker;
async move { drop(walker.evaluate(c).await) }
})
.await,
Latency::measure(&contexts, reps, |c| {
let walker = &walker;
async move { drop(walker.evaluate_with_opts(c, traced).await) }
})
.await,
];
println!("{:44} {:>10.0} {:>10.0} {:>10.0} {:>10.0} {:>10.0}", fixture.name, times[0], times[1], times[2], times[3], times[4]);
columns.iter_mut().zip(times).for_each(|(column, t)| column.push(t));
}
let gm: Vec<f64> = columns.iter().map(|c| Latency::geomean(c)).collect();
println!("geomean ns/eval ({} fixtures): compiled {:.0} cold {:.0} traced {:.0} walker {:.0} walker-traced {:.0}", columns[0].len(), gm[0], gm[1], gm[2], gm[3], gm[4]);
}
struct Noise(u64);
impl Noise {
@@ -1085,7 +1059,7 @@ async fn graph_typed_strings() {
#[tokio::test]
async fn graph_typed_dates() {
std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z");
Reference::prepare(Outcome::CLOCK);
let mut noise = Noise::new(31);
let days = [
"2024-01-15", "2024-02-29", "2023-12-31 23:59:59", "2024-03-31T01:30:00Z", "2025-03-30 02:30:00", "2024-10-27 02:30:00", "1900-01-01", "9999-12-31",
@@ -1186,7 +1160,7 @@ async fn graph_typed_extremes() {
#[tokio::test]
async fn graph_fixtures_are_fully_typed() {
std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z");
Reference::prepare(Outcome::CLOCK);
let mut failures = Vec::new();
let fixtures: Vec<Fixture> = Fixture::load_all().into_iter().filter(|f| Chain::FULLY_TYPED.contains(&f.name.as_str())).collect();
assert_eq!(fixtures.len(), Chain::FULLY_TYPED.len(), "fixtures found");
+174 -478
View File
@@ -3,31 +3,21 @@ mod policy_gen;
#[allow(dead_code)]
mod conformance;
mod support;
#[allow(dead_code)]
#[path = "support/policies.rs"]
mod policies;
use policies::{Anchor, Batch, Generated, PolicyCase};
use policy_gen::{Gen, Rng};
use serde::Deserialize;
use serde_json::{json, Value};
use std::sync::Arc;
use support::columns::Built;
use support::golden::{Canon, Outcome, Reference};
use zen_engine::policy::{EvaluateRequest, EvaluationError, EvaluationResult, PolicyWorkspace};
use zen_expression::Variable;
const FIXTURES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/policy/fixtures/");
const EVALUATION: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/policy/evaluation.toml");
#[derive(Deserialize)]
struct EvaluationFile {
test: Vec<EvaluationCase>,
}
#[derive(Deserialize)]
struct EvaluationCase {
name: String,
policies: Vec<String>,
input: toml::Value,
}
struct Differential {
reference: Reference,
compared: usize,
succeeded: usize,
failures: Vec<String>,
@@ -35,10 +25,27 @@ struct Differential {
}
impl Differential {
fn new(reference: Reference) -> Differential {
Differential {
reference,
compared: 0,
succeeded: 0,
failures: Vec::new(),
kinds: Default::default(),
}
}
fn shape(result: &Result<EvaluationResult, EvaluationError>) -> Result<Value, String> {
match result {
Ok(result) => Ok(result.output.clone().into()),
Err(error) => Err(format!("{error:?}")),
Err(error) => Err(Reference::debug(error)),
}
}
fn recorded(outcome: &Outcome) -> Result<Value, String> {
match outcome {
Outcome::Ok(value) => Ok(Canon::restore(value).into()),
Outcome::Err { debug, .. } => Err(debug.clone()),
}
}
@@ -46,60 +53,42 @@ impl Differential {
Self::with_goals(path, input, &[])
}
fn with_goals(path: &str, input: &Value, goals: &[&str]) -> EvaluateRequest {
fn with_goals(path: &str, input: &Value, goals: &[String]) -> EvaluateRequest {
EvaluateRequest {
policy_path: Arc::from(path),
input: Variable::from(input.clone()),
goals: goals.iter().map(|g| Arc::from(*g)).collect(),
goals: goals.iter().map(|g| Arc::from(g.as_str())).collect(),
trace: false,
}
}
fn leaves(value: &Value, prefix: &str, out: &mut Vec<String>) {
let Value::Object(map) = value else {
out.push(prefix.to_string());
return;
};
for (key, child) in map {
let path = match prefix.is_empty() {
true => key.clone(),
false => format!("{prefix}.{key}"),
};
Self::leaves(child, &path, out);
}
fn driver(&self, suite: &str, ws: &PolicyWorkspace, path: &str, input: &Value, goals: &[String]) -> Result<Value, String> {
self.reference.policy(
|| Canon::key(suite, goals, &Variable::from(input.clone())),
|| Self::shape(&ws.evaluate_with_driver(&Self::with_goals(path, input, goals))),
Self::recorded,
)
}
fn computed(ws: &PolicyWorkspace, path: &str, inputs: &[Value]) -> Vec<String> {
let mut out = Vec::new();
for input in inputs {
let Ok(result) = ws.evaluate_with_driver(&Self::request(path, input)) else {
continue;
};
let (mut produced, mut given) = (Vec::new(), Vec::new());
Self::leaves(&result.output.into(), "", &mut produced);
Self::leaves(input, "", &mut given);
out = produced.into_iter().filter(|p| !given.contains(p)).collect();
break;
}
out
fn computed(&self, suite: &str, ws: &PolicyWorkspace, path: &str, inputs: &[Value]) -> Vec<String> {
inputs
.iter()
.find_map(|input| self.driver(suite, ws, path, input, &[]).ok().map(|output| PolicyCase::computed(&output, input)))
.unwrap_or_default()
}
fn run(&mut self, label: &str, ws: &PolicyWorkspace, path: &str, inputs: &[Value]) {
let computed = Self::computed(ws, path, inputs);
let choices: Vec<Vec<&str>> = std::iter::once(Vec::new())
.chain(computed.iter().map(|c| vec![c.as_str()]))
.chain(computed.windows(2).map(|w| vec![w[0].as_str(), w[1].as_str()]))
.collect();
let goals = |i: usize| choices[(i * 7) % choices.len()].as_slice();
let computed = self.computed(label, ws, path, inputs);
let requests: Vec<EvaluateRequest> = inputs
.iter()
.enumerate()
.map(|(i, input)| Self::with_goals(path, input, goals(i)))
.map(|(i, input)| Self::with_goals(path, input, &PolicyCase::goals(&computed, i)))
.collect();
let batch = ws.evaluate_batch(&requests);
for (i, (input, batched)) in inputs.iter().zip(&batch).enumerate() {
let want = Self::shape(&ws.evaluate_with_driver(&Self::with_goals(path, input, goals(i))));
let single = Self::shape(&ws.evaluate(&Self::with_goals(path, input, goals(i))));
let goals = PolicyCase::goals(&computed, i);
let want = self.driver(label, ws, path, input, &goals);
let single = Self::shape(&ws.evaluate(&Self::with_goals(path, input, &goals)));
let batched = Self::shape(batched);
self.compared += 1;
self.succeeded += usize::from(want.is_ok());
@@ -107,6 +96,9 @@ impl Differential {
let kind: String = error.chars().take_while(|c| c.is_alphanumeric()).collect();
*self.kinds.entry(kind).or_default() += 1;
}
if self.reference.ordered(|| Canon::key(label, &goals, &Variable::from(input.clone()))) {
continue;
}
if single != want {
self.failures.push(format!("{label} single {input}\n driver {want:?}\n compiled {single:?}"));
}
@@ -116,43 +108,8 @@ impl Differential {
}
}
fn variants(base: &Value) -> Vec<Value> {
let mut out = vec![base.clone()];
let Some(object) = base.as_object() else {
return out;
};
for (key, value) in object {
let mut with = |replacement: Option<Value>| {
let mut copy = object.clone();
match replacement {
Some(v) => copy.insert(key.clone(), v),
None => copy.remove(key),
};
out.push(Value::Object(copy));
};
with(None);
with(Some(Value::Null));
if let Value::Object(inner) = value {
for (field, v) in inner {
let mut nested = inner.clone();
nested.insert(
field.clone(),
match v {
Value::Number(_) => json!("text"),
Value::String(_) => json!(7),
Value::Bool(b) => json!(!b),
Value::Array(_) => json!([]),
_ => Value::Null,
},
);
with(Some(Value::Object(nested)));
}
}
}
out
}
fn finish(self) {
fn finish(mut self) {
self.failures.extend(self.reference.missing());
println!("compared {} inputs, {} evaluated without error, errors {:?}", self.compared, self.succeeded, self.kinds);
assert!(
self.failures.is_empty(),
@@ -165,51 +122,27 @@ impl Differential {
#[test]
fn compiled_policies_match_the_driver_on_fixtures() {
let raw = std::fs::read_to_string(EVALUATION).expect("evaluation.toml");
let file: EvaluationFile = toml::from_str(&raw).expect("evaluation cases");
let mut differential = Differential {
compared: 0,
succeeded: 0,
failures: Vec::new(),
kinds: Default::default(),
};
for case in &file.test {
let mut ws = PolicyWorkspace::new();
for path in &case.policies {
let text = std::fs::read_to_string(format!("{FIXTURES_DIR}{path}")).expect("fixture");
ws.set_policy(path.as_str(), serde_json::from_str(&text).expect("policy document"));
}
let input: Value = serde_json::to_value(&case.input).expect("input");
differential.run(&case.name, &ws, &case.policies[0], &Differential::variants(&input));
let mut differential = Differential::new(Reference::open("policy-fixtures"));
for case in PolicyCase::load_all() {
differential.run(&case.name, &case.workspace, &case.path, &case.inputs);
}
differential.finish();
}
#[test]
fn compiled_policies_match_the_driver_on_generated_documents() {
let seeds: u64 = std::env::var("POLICY_SEEDS").ok().and_then(|v| v.parse().ok()).unwrap_or(300);
let mut differential = Differential {
compared: 0,
succeeded: 0,
failures: Vec::new(),
kinds: Default::default(),
};
for seed in 0..seeds {
let document = Gen::document(seed);
let mut ws = PolicyWorkspace::new();
let Ok(parsed) = serde_json::from_value(document) else {
let mut differential = Differential::new(Reference::open("generated/policy"));
for seed in 0..Generated::seeds() {
let Some(ws) = Generated::workspace(seed) else {
continue;
};
ws.set_policy("generated.json", parsed);
let mut rng = Rng(seed.wrapping_mul(7919) | 1);
let inputs: Vec<Value> = (0..24)
.map(|i| match i % 3 {
0 => Gen::input(&mut rng),
_ => Gen::valid_input(&mut rng),
})
.collect();
differential.run(&format!("seed {seed}"), &ws, "generated.json", &inputs);
Columnar::check(&format!("seed {seed}"), &ws, &inputs, &mut differential.failures);
let inputs = Generated::inputs(seed);
let label = Generated::label(seed);
if differential.reference.stale(|| Canon::key(&label, &[], &Variable::from(inputs[0].clone())), &Generated::fingerprint(seed)) {
differential.failures.push(format!("{label}: generated document changed since the goldens were recorded"));
}
differential.run(&label, &ws, Generated::PATH, &inputs);
Columnar::check(&differential.reference, &label, &ws, &inputs, &mut differential.failures);
}
differential.finish();
}
@@ -217,38 +150,39 @@ fn compiled_policies_match_the_driver_on_generated_documents() {
struct Columnar;
impl Columnar {
fn check(label: &str, ws: &PolicyWorkspace, inputs: &[Value], failures: &mut Vec<String>) {
fn check(reference: &Reference, label: &str, ws: &PolicyWorkspace, inputs: &[Value], failures: &mut Vec<String>) {
for built in Built::new(inputs).into_iter().chain(Built::lists(inputs)) {
Self::compare(label, ws, &built.columns(), failures);
Self::compare(reference, label, ws, &built.columns(), failures);
}
if let Some(built) = Built::nested(inputs) {
let fields = built.fields();
let structs = built.structs(&fields);
Self::compare(label, ws, &built.columns_with(&structs), failures);
Self::compare(reference, label, ws, &built.columns_with(&structs), failures);
}
}
fn compare(label: &str, ws: &PolicyWorkspace, columns: &zen_expression::lane::Columns, failures: &mut Vec<String>) {
let Ok(output) = ws.evaluate_columns(&Arc::from("generated.json"), &[], columns) else {
fn compare(reference: &Reference, label: &str, ws: &PolicyWorkspace, columns: &zen_expression::lane::Columns, failures: &mut Vec<String>) {
let Ok(output) = ws.evaluate_columns(&Arc::from(Generated::PATH), &[], columns) else {
return;
};
for row in 0..columns.rows {
let input = columns.row(row);
let request = EvaluateRequest {
policy_path: Arc::from("generated.json"),
policy_path: Arc::from(Generated::PATH),
input: input.depth_clone(64),
goals: Vec::new(),
trace: false,
};
let want = ws
.evaluate_with_driver(&request)
.map(|r| Built::normalized(r.output.to_value()))
.map_err(|e| format!("{e:?}"));
let want = reference.policy(
|| Canon::key(label, &[], &input),
|| ws.evaluate_with_driver(&request).map(|r| Built::normalized(r.output.to_value())).map_err(|e| format!("{e:?}")),
|outcome| Differential::recorded(outcome).map(Built::normalized),
);
let got = match &output.errors[row] {
Some(error) => Err(format!("{error:?}")),
Some(error) => Err(Reference::debug(error)),
None => Ok(Built::normalized(output.row(row).to_value())),
};
if got != want {
if got != want && !reference.ordered(|| Canon::key(label, &[], &input)) {
failures.push(format!("{label} columnar row {row} input {}\n driver {want:?}\n columnar {got:?}", input.to_value()));
}
}
@@ -372,33 +306,7 @@ async fn engine_batch_matches_single_evaluations() {
}
}
struct Anchor;
impl Anchor {
const POLICY: &'static str = r#"{
models: {
customer: {age: "number", income: "number", tier: "string", rate: "number", accounts: "account[]"},
account: {balance: "number", kind: "string", active: "boolean"},
},
blocks: [
{expression: "account.fee", value: "account.balance * customer.rate / 100 * (account.kind == 'loan' ? 2 : 1)"},
{match: "account.label", arms: [["account.kind == 'savings'", "'S'"], ["account.kind == 'checking'", "'C'"], ["", "'L'"]]},
{expression: "customer.total", value: "sum(map(filter(customer.accounts, #.active), #.balance))"},
{expression: "customer.fees", value: "sum(map(customer.accounts, #.fee))"},
{match: "customer.risk", arms: [["customer.total > customer.income * 2", "'high'"], ["customer.total > customer.income", "'mid'"], ["", "'low'"]]},
{table: "discount", inputs: ["customer.tier", "customer.risk"], outputs: ["customer.discount"], rules: [
["'gold'", "'low'", "0.15"],
["'gold'", "'mid'", "0.1"],
["'silver'", "'low'", "0.1"],
["'silver'", "'mid'", "0.05"],
["", "'low'", "0.02"],
["", "", "0"],
]},
{expression: "customer.net", value: "customer.total - customer.fees - customer.discount"},
{assertion: "customer.eligible", conditions: ["customer.age >= 18", "customer.risk != 'high'"]},
],
}"#;
const PROGRAMS: [(&'static str, &'static str); 8] = [
("fee", "account.balance * customer.rate / 100 * (account.kind == 'loan' ? 2 : 1)"),
("label", "account.kind == 'savings' ? 'S' : (account.kind == 'checking' ? 'C' : 'L')"),
@@ -504,80 +412,32 @@ impl Anchor {
})
}
fn rows(count: usize, seed: u64) -> Vec<Value> {
let mut state = seed | 1;
let mut pick = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
(0..count)
.map(|_| {
let accounts: Vec<Value> = (0..pick(8))
.map(|_| {
let (balance, kind, active) = (pick(5000), ["savings", "checking", "loan"][pick(3) as usize], pick(4) != 0);
json!({"balance": balance, "kind": kind, "active": active})
})
.collect();
let (age, income, tier, rate) = (16 + pick(64), 1000 + pick(9000), ["gold", "silver", "bronze"][pick(3) as usize], 1 + pick(5));
json!({"customer": {"age": age, "income": income, "tier": tier, "rate": rate, "accounts": accounts}})
})
.collect()
}
fn workspace() -> PolicyWorkspace {
Self::workspace_with(Self::POLICY)
}
fn workspace_with(policy: &str) -> PolicyWorkspace {
let literal = conformance::literal::Parser::document(policy).expect("policy literal");
let document = conformance::policy::Policy::expand(&literal[0]).expect("policy expand");
let mut ws = PolicyWorkspace::new();
ws.set_policy("anchor", serde_json::from_value(document).expect("policy json"));
ws
}
fn typed() -> bool {
std::env::var("ZEN_TYPED").map_or(true, |v| v.trim() != "0")
}
fn check(ws: &PolicyWorkspace, columns: &zen_expression::lane::Columns, failures: &mut Vec<String>) -> (usize, usize, usize) {
let output = ws.evaluate_columns(&Arc::from("anchor"), &[], columns).expect("columnar");
fn check(reference: &Reference, suite: &str, ws: &PolicyWorkspace, columns: &zen_expression::lane::Columns, failures: &mut Vec<String>) -> (usize, usize, usize) {
let output = ws.evaluate_columns(&Arc::from(Anchor::PATH), &[], columns).expect("columnar");
for row in 0..columns.rows {
let input = columns.row(row);
let request = EvaluateRequest {
policy_path: Arc::from("anchor"),
input: columns.row(row),
policy_path: Arc::from(Anchor::PATH),
input: input.depth_clone(64),
goals: Vec::new(),
trace: false,
};
let want = ws
.evaluate_with_driver(&request)
.map(|r| Built::normalized(r.output.to_value()))
.map_err(|e| format!("{e:?}"));
let want = reference.policy(
|| Canon::key(suite, &[], &input),
|| ws.evaluate_with_driver(&request).map(|r| Built::normalized(r.output.to_value())).map_err(|e| format!("{e:?}")),
|outcome| Differential::recorded(outcome).map(Built::normalized),
);
let got = match &output.errors[row] {
Some(error) => Err(format!("{error:?}")),
Some(error) => Err(Reference::debug(error)),
None => Ok(Built::normalized(output.row(row).to_value())),
};
if got != want {
failures.push(format!("row {row} input {}\n driver {want:?}\n columnar {got:?}", columns.row(row).to_value()));
if got != want && !reference.ordered(|| Canon::key(suite, &[], &input)) {
failures.push(format!("row {row} input {}\n driver {want:?}\n columnar {got:?}", input.to_value()));
}
}
(output.typed, output.laned, output.hosted)
}
fn checked(ws: &PolicyWorkspace, values: &[Value], failures: &mut Vec<String>) -> Vec<(usize, usize, usize)> {
let mut counts = Vec::new();
let built = Built::new(values).expect("flat columns");
counts.push(Self::check(ws, &built.columns(), failures));
if let Some(built) = Built::nested(values) {
let fields = built.fields();
let structs = built.structs(&fields);
counts.push(Self::check(ws, &built.columns_with(&structs), failures));
}
counts
}
fn time(rows: usize, mut f: impl FnMut() -> f64) -> f64 {
(0..7).map(|_| f()).fold(f64::MAX, f64::min) / rows as f64
}
@@ -691,6 +551,20 @@ impl Anchor {
}
}
impl Batch {
fn checked(&self, reference: &Reference, ws: &PolicyWorkspace, failures: &mut Vec<String>) -> Vec<(usize, usize, usize)> {
let mut counts = Vec::new();
let built = Built::new(&self.values).expect("flat columns");
counts.push(Anchor::check(reference, self.suite, ws, &built.columns(), failures));
if let Some(built) = Built::nested(&self.values) {
let fields = built.fields();
let structs = built.structs(&fields);
counts.push(Anchor::check(reference, self.suite, ws, &built.columns_with(&structs), failures));
}
counts
}
}
#[test]
fn policy_columnar_shredded_irregular_lists() {
let mut values = Anchor::rows(96, 11);
@@ -762,9 +636,11 @@ fn policy_columnar_shredded_irregular_lists() {
#[test]
fn policy_anchor_is_fully_typed() {
let ws = Anchor::workspace();
let reference = Reference::open("anchor");
let batch = Anchor::base();
let mut failures = Vec::new();
let counts = Anchor::checked(&ws, &Anchor::rows(1024, 7), &mut failures);
let counts = batch.checked(&reference, &batch.workspace(), &mut failures);
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));
for (typed, laned, hosted) in counts {
assert_eq!(hosted, 0, "anchor rows hosted");
@@ -776,14 +652,12 @@ fn policy_anchor_is_fully_typed() {
#[test]
fn policy_typed_falls_back_per_unit() {
let policy = Anchor::POLICY.replace(
" {match: \"customer.risk\"",
" {expression: \"customer.label\", value: \"split(customer.tier, 'l')\"},\n {match: \"customer.risk\"",
);
assert_ne!(policy, Anchor::POLICY);
let ws = Anchor::workspace_with(&policy);
let reference = Reference::open("anchor");
let batch = Anchor::fallback();
assert_ne!(batch.policy, Anchor::POLICY);
let mut failures = Vec::new();
let counts = Anchor::checked(&ws, &Anchor::rows(256, 5), &mut failures);
let counts = batch.checked(&reference, &batch.workspace(), &mut failures);
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));
for (typed, laned, hosted) in counts {
assert_eq!(hosted, 0, "rows hosted");
@@ -796,15 +670,12 @@ fn policy_typed_falls_back_per_unit() {
#[test]
fn policy_typed_fuses_lane_runs() {
let policy = Anchor::POLICY.replace(
" {match: \"customer.risk\"",
" {expression: \"customer.label\", value: \"split(customer.tier, 'l')\"},\n {expression: \"customer.tag\", value: \"split(customer.tier, 'o')\"},\n {match: \"customer.risk\"",
);
assert_ne!(policy, Anchor::POLICY);
let ws = Anchor::workspace_with(&policy);
let reference = Reference::open("anchor");
assert_ne!(Anchor::fused_policy(), Anchor::POLICY);
let ws = Anchor::workspace_with(&Anchor::fused_policy());
let mut failures = Vec::new();
for seed in [5, 6, 7] {
for (typed, laned, hosted) in Anchor::checked(&ws, &Anchor::rows(256, seed), &mut failures) {
for (typed, laned, hosted) in Anchor::fusion(seed).checked(&reference, &ws, &mut failures) {
assert_eq!(hosted, 0, "rows hosted");
if Anchor::typed() {
assert!(typed > 0 && laned >= 2, "units typed {typed}, laned {laned}");
@@ -812,293 +683,85 @@ fn policy_typed_fuses_lane_runs() {
}
}
}
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));
}
#[test]
fn policy_typed_member_tables_and_math() {
let policy = Anchor::POLICY
.replace(
" {expression: \"customer.total\"",
" {table: \"band\", inputs: [\"account.balance\", \"customer.tier\"], outputs: [\"account.band\", \"account.boost\"], rules: [\n [\"> 4000\", \"'gold'\", \"'A'\", \"1.5\"],\n [\"> 2000\", \"\", \"'B'\", \"2\"],\n [\"\", \"\", \"'C'\", \"0\"],\n ]},\n {expression: \"customer.total\"",
)
.replace(
" {assertion: \"customer.eligible\"",
" {expression: \"customer.rich\", value: \"some(customer.accounts, #.balance > 4000)\"},\n {expression: \"customer.active\", value: \"all(customer.accounts, #.active)\"},\n {expression: \"customer.loans\", value: \"count(customer.accounts, #.kind == 'loan')\"},\n {expression: \"customer.third\", value: \"round(customer.total / 3, 2) + customer.total % 7\"},\n {expression: \"customer.gap\", value: \"abs(customer.total - customer.income) + min([customer.total, customer.income, 100])\"},\n {expression: \"customer.square\", value: \"floor(customer.income / 7) ^ 2\"},\n {assertion: \"customer.eligible\"",
);
let reference = Reference::open("anchor");
let policy = Anchor::members_policy();
assert!(policy.contains("account.band") && policy.contains("customer.square"));
let ws = Anchor::workspace_with(&policy);
let mut failures = Vec::new();
for seed in [5, 9] {
for (typed, laned, hosted) in Anchor::checked(&ws, &Anchor::rows(300, seed), &mut failures) {
for (typed, laned, hosted) in Anchor::members(seed).checked(&reference, &ws, &mut failures) {
assert_eq!(hosted, 0, "rows hosted");
if Anchor::typed() {
assert_eq!((typed, laned), (15, 0), "units typed {typed}, laned {laned}");
}
}
}
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));
}
#[test]
fn policy_typed_lists_and_closures() {
let policy = r#"{
models: {
customer: {limit: "number", rate: "number", tags: "string[]", scores: "number[]", companies: "company[]", holdings: "holding[]"},
company: {revenue: "number", active: "boolean", depts: "dept[]"},
holding: {value: "number", lots: "lot[]"},
dept: {size: "number", cost: "number"},
lot: {qty: "number"},
},
blocks: [
{expression: "company.cost", value: "sum(map(company.depts, #.cost))"},
{expression: "company.wide", value: "count(company.depts, #.size > customer.limit)"},
{expression: "company.sizes", value: "map(company.depts, #.size * 2)"},
{expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"},
{expression: "customer.lots", value: "sum(map(customer.holdings, sum(map(#.lots, #.qty))))"},
{expression: "customer.big", value: "map(filter(customer.holdings, #.value > customer.limit), #.value)"},
{expression: "customer.score", value: "sum(customer.scores)"},
{expression: "customer.vip", value: "'vip' in customer.tags"},
{expression: "customer.hit", value: "contains(customer.scores, 3)"},
{expression: "customer.scaled", value: "map(customer.scores, # * customer.rate)"},
{expression: "customer.kept", value: "count(filter(customer.holdings, #.value > 10), len(#.lots) > 1)"},
{expression: "customer.top", value: "max(map(customer.holdings, #.value))"},
],
}"#;
let mut state = 23u64;
let mut pick = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let mut values: Vec<Value> = (0..300)
.map(|_| {
let companies: Vec<Value> = (0..pick(4))
.map(|_| {
let depts: Vec<Value> = (0..pick(4)).map(|_| json!({"size": pick(30), "cost": pick(900) as f64 / 4.0})).collect();
json!({"revenue": pick(10_000), "active": pick(3) != 0, "depts": depts})
})
.collect();
let holdings: Vec<Value> = (0..pick(4))
.map(|_| {
let lots: Vec<Value> = (0..pick(4)).map(|_| json!({"qty": pick(100)})).collect();
json!({"value": pick(50), "lots": lots})
})
.collect();
let scores: Vec<Value> = (0..pick(5)).map(|_| json!(pick(8))).collect();
let tags: Vec<Value> = (0..pick(3)).map(|_| json!(["a", "vip", "b"][pick(3) as usize])).collect();
json!({"customer": {"limit": pick(20), "rate": pick(4) as f64 / 2.0, "tags": tags, "scores": scores, "companies": companies, "holdings": holdings}})
})
.collect();
let odd = [
json!({"customer": {"limit": 1, "rate": 1, "tags": [], "scores": [], "companies": [], "holdings": []}}),
json!({"customer": {"limit": null, "rate": null, "tags": null, "scores": null, "companies": null, "holdings": null}}),
json!({"customer": {"limit": 2, "rate": 0.5, "tags": ["vip"], "scores": [9223372036854775807i64, 9223372036854775807i64], "companies": [{"revenue": 9223372036854775807i64, "active": true, "depts": [{"size": 1, "cost": 9223372036854775807i64}, {"size": 2, "cost": 9223372036854775807i64}]}], "holdings": [{"value": 1, "lots": [{"qty": 9223372036854775807i64}, {"qty": 9223372036854775807i64}]}]}}),
json!({"customer": {"limit": 3, "rate": 2, "tags": ["a"], "scores": [1.50, 0.00, 3], "companies": [{"revenue": 1, "active": null, "depts": null}], "holdings": [{"value": null, "lots": null}]}}),
json!({"customer": {"limit": 3, "rate": 2, "tags": ["a", 1], "scores": ["x"], "companies": [{"revenue": "lots", "depts": []}], "holdings": [{"value": 4}]}}),
json!({"customer": {"limit": 0, "rate": 0.25, "tags": [null], "scores": [null, 3], "companies": [{"revenue": 5, "active": false, "depts": [{"size": null, "cost": 0.000000001}]}], "holdings": [{"value": 30, "lots": [{"qty": 1}, {"qty": 2}]}]}}),
json!({"customer": {"limit": 5}}),
];
for (at, row) in odd.into_iter().enumerate() {
values.insert(at * 37 + 4, row);
}
let ws = Anchor::workspace_with(policy);
let reference = Reference::open("anchor");
let batch = Anchor::lists();
let mut failures = Vec::new();
for (typed, laned, hosted) in Anchor::checked(&ws, &values, &mut failures) {
for (typed, laned, hosted) in batch.checked(&reference, &batch.workspace(), &mut failures) {
eprintln!("lists typed {typed} laned {laned} hosted {hosted}");
if Anchor::typed() {
assert!(typed > 0, "units typed {typed}, laned {laned}");
}
}
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));
}
#[test]
fn policy_typed_strings() {
let policy = r#"{
models: {
customer: {name: "string", city: "string", tier: "string", amount: "number", qty: "number", flag: "boolean", tags: "string[]", items: "item[]"},
item: {name: "string", qty: "number"},
},
blocks: [
{expression: "item.label", value: "upper(item.name) + '-' + customer.tier"},
{expression: "item.same", value: "item.name == customer.name"},
{expression: "item.s", value: "string(item.qty * customer.amount)"},
{expression: "customer.s", value: "string(customer.amount)"},
{expression: "customer.tpl", value: "`${customer.name}:${customer.qty}:${customer.flag}`"},
{expression: "customer.cat", value: "customer.name + '/' + customer.city"},
{expression: "customer.up", value: "upper(customer.name)"},
{expression: "customer.tr", value: "trim(customer.city)"},
{expression: "customer.has", value: "contains(lower(customer.name), 'an')"},
{expression: "customer.tz", value: "customer.tier ?? 'none'"},
{expression: "customer.pick", value: "customer.qty > 4 ? customer.name : 'nobody'"},
{expression: "customer.same", value: "customer.name == customer.city"},
{expression: "customer.gold", value: "customer.tz in ['gold', 'none']"},
{expression: "customer.names", value: "map(customer.items, #.name)"},
{expression: "customer.cnt", value: "count(customer.items, #.name == customer.tier)"},
{expression: "customer.intag", value: "customer.city in customer.tags"},
{expression: "customer.rx", value: "matches(customer.name, '^[A-Z]')"},
{expression: "customer.big", value: "string(customer.amount * 1000000000000)"},
{expression: "customer.again", value: "upper(customer.tz) + '!'"},
{table: "lvl", inputs: ["customer.qty"], outputs: ["customer.lvl"], rules: [
["> 7", "customer.name"],
["> 3", "customer.city"],
["", "'small'"],
]},
{expression: "customer.lv", value: "customer.lvl + ':' + customer.tz"},
],
}"#;
let mut state = 41u64;
let mut pick = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let names = ["Anna", "bob", " Cara ", "Émile", "straße", "", "İstanbul", "日本", "Bart"];
let cities = ["Berlin", "bonn", "Anna", " x ", ""];
let tiers = ["gold", "silver", "Gold"];
let mut values: Vec<Value> = (0..300)
.map(|_| {
let items: Vec<Value> = (0..pick(4)).map(|_| json!({"name": names[pick(9) as usize], "qty": pick(9)})).collect();
let tags: Vec<Value> = (0..pick(3)).map(|_| json!(cities[pick(5) as usize])).collect();
json!({"customer": {"name": names[pick(9) as usize], "city": cities[pick(5) as usize], "tier": tiers[pick(3) as usize], "amount": pick(40_000) as f64 / 8.0 - 2000.0, "qty": pick(10), "flag": pick(2) == 0, "tags": tags, "items": items}})
})
.collect();
let long = "ab".repeat(600);
let odd = [
json!({"customer": {"name": null, "city": "Berlin", "tier": null, "amount": null, "qty": 3, "flag": null, "tags": null, "items": null}}),
json!({"customer": {"name": long, "city": long, "tier": "gold", "amount": 9223372036854775807i64, "qty": 9, "flag": false, "tags": [], "items": []}}),
json!({"customer": {"name": "ß", "city": "Dž", "tier": "", "amount": -0.0, "qty": 0, "flag": true, "tags": ["Dž"], "items": [{"name": "ß", "qty": 1}]}}),
json!({"customer": {"name": "\u{1F600} x", "city": "\u{2003}a\u{2003}", "tier": "silver", "amount": 0.000000001, "qty": 6, "flag": false, "tags": ["\u{2003}a\u{2003}"], "items": [{"qty": 2}]}}),
json!({"customer": {"qty": 5}}),
json!({"customer": {"name": "Anna", "city": "Anna", "tier": "gold", "amount": 1.50, "qty": 8, "flag": true, "tags": ["Anna"], "items": [{"name": "gold", "qty": 9223372036854775807i64}]}}),
];
for (at, row) in odd.into_iter().enumerate() {
values.insert(at * 37 + 4, row);
}
let ws = Anchor::workspace_with(policy);
let reference = Reference::open("anchor");
let [first, second] = Anchor::strings();
let ws = first.workspace();
let mut failures = Vec::new();
for (typed, laned, hosted) in Anchor::checked(&ws, &values, &mut failures) {
for (typed, laned, hosted) in first.checked(&reference, &ws, &mut failures) {
eprintln!("strings typed {typed} laned {laned} hosted {hosted}");
if Anchor::typed() {
assert!(typed > laned, "units typed {typed}, laned {laned}");
}
}
values.insert(12, json!({"customer": {"name": "q", "city": "q", "tier": "gold", "amount": 1, "qty": 2, "flag": true, "tags": [null], "items": [{"name": null, "qty": 2}]}}));
values.insert(9, json!({"customer": {"name": 7, "city": true, "tier": 1.5, "amount": "x", "qty": 1, "flag": true, "tags": [1], "items": [{"name": 3, "qty": "a"}]}}));
Anchor::checked(&ws, &values, &mut failures);
second.checked(&reference, &ws, &mut failures);
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.iter().take(10).cloned().collect::<Vec<_>>().join("\n"));
}
#[test]
fn policy_typed_dates() {
let policy = r#"{
models: {
customer: {start: "string", other: "string", days: "number", events: "event[]"},
event: {on: "string", amt: "number"},
},
blocks: [
{expression: "event.due", value: "d(event.on).add(customer.days, 'day')"},
{expression: "event.late", value: "d(event.on) > d(customer.start)"},
{expression: "event.s", value: "string(d(event.on).startOf('month'))"},
{expression: "customer.f", value: "d(customer.start).format('%d.%m.%Y')"},
{expression: "customer.y", value: "d(customer.start).year()"},
{expression: "customer.ok", value: "d(customer.start).isValid()"},
{expression: "customer.past", value: "d(customer.start) < d()"},
{expression: "customer.same", value: "d(customer.start) == customer.other"},
{expression: "customer.dts", value: "map(customer.events, d(#.on).endOf('day'))"},
{expression: "customer.any", value: "some(customer.events, d(#.on).isBefore(d(customer.other)))"},
{expression: "customer.first", value: "min(map(customer.events, d(#.on)))"},
{expression: "customer.cnt", value: "count(customer.events, #.on > d(customer.start))"},
{table: "era", inputs: ["customer.start"], outputs: ["customer.era"], rules: [
["< d('2000-01-01')", "'old'"],
["", "'new'"],
]},
],
}"#;
let mut state = 43u64;
let mut pick = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let days = ["2024-01-15", "2024-02-29", "2023-12-31 23:59:59", "2024-03-31T01:30:00Z", "1999-06-30", "2025-03-30 02:30:00", "9999-12-31", "2024/01/15", "2024-07"];
let bad = ["nope", "", "2024-02-30"];
let mut day = |pick: &mut dyn FnMut(u64) -> u64| match pick(15) {
0 => json!(bad[pick(3) as usize]),
_ => json!(days[pick(9) as usize]),
};
let mut values: Vec<Value> = (0..300)
.map(|_| {
let events: Vec<Value> = (0..1 + pick(4)).map(|_| json!({"on": day(&mut pick), "amt": pick(100)})).collect();
json!({"customer": {"start": day(&mut pick), "other": day(&mut pick), "days": pick(400) as i64 - 200, "events": events}})
})
.collect();
let odd = [
json!({"customer": {"start": null, "other": null, "days": 0, "events": []}}),
json!({"customer": {"start": "0001-01-01", "other": "9999-12-31", "days": 1000000000, "events": [{"on": "9999-12-31", "amt": 1}]}}),
json!({"customer": {"start": "2024-02-29", "other": "2024-02-29T00:00:00Z", "days": -366, "events": [{"amt": 1}]}}),
];
for (at, row) in odd.into_iter().enumerate() {
values.insert(at * 37 + 4, row);
}
let ws = Anchor::workspace_with(policy);
let reference = Reference::open("anchor");
let [first, second] = Anchor::dates();
let ws = first.workspace();
let mut failures = Vec::new();
for (typed, laned, hosted) in Anchor::checked(&ws, &values, &mut failures) {
for (typed, laned, hosted) in first.checked(&reference, &ws, &mut failures) {
eprintln!("dates typed {typed} laned {laned} hosted {hosted}");
if Anchor::typed() {
assert!(typed > laned, "units typed {typed}, laned {laned}");
}
}
values.insert(9, json!({"customer": {"start": 7, "other": true, "days": "x", "events": [{"on": 3, "amt": "a"}]}}));
values.insert(15, json!({"customer": {"start": "2024-02-29", "other": null, "days": 1, "events": [{"on": null, "amt": 1}]}}));
Anchor::checked(&ws, &values, &mut failures);
second.checked(&reference, &ws, &mut failures);
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.iter().take(10).cloned().collect::<Vec<_>>().join("\n"));
}
#[test]
fn policy_typed_extremes() {
let customer = |accounts: Value| json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": accounts}});
let overflow = [
customer(json!([{"balance": 9223372036854775807i64, "kind": "loan", "active": true}])),
customer(json!([{"balance": 4611686018427387904i64, "kind": "savings", "active": true}, {"balance": 4611686018427387904i64, "kind": "savings", "active": true}])),
json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 9223372036854775807i64, "accounts": [{"balance": 3, "kind": "loan", "active": true}]}}),
];
let odd = [
json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": -0.0, "accounts": [{"balance": 3, "kind": "loan", "active": true}]}}),
customer(json!([])),
customer(json!([{"balance": 0, "kind": "loan", "active": true}, {"balance": 0, "kind": "savings", "active": false}])),
customer(json!([{"balance": 12.5, "kind": "checking", "active": true}, {"balance": 0.000000001, "kind": "savings", "active": true}])),
customer(json!([{"balance": 0.00, "kind": "savings", "active": true}, {"balance": 1.50, "kind": "loan", "active": true}])),
customer(json!([{"balance": -250, "kind": "other", "active": true}, {"balance": 7, "kind": "", "active": false}])),
json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 0.25, "accounts": [{"balance": 100, "kind": "savings", "active": true}]}}),
json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2}}),
json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": null}}),
json!({"customer": {"age": null, "income": 4000, "tier": "gold", "rate": 2, "accounts": []}}),
json!({"customer": {"age": 30, "income": null, "tier": null, "rate": null, "accounts": []}}),
json!({"customer": {"age": 17, "income": 0, "tier": "platinum", "rate": 0, "accounts": [{"balance": 5000, "kind": "loan", "active": true}]}}),
json!({"customer": {"age": 18, "income": 0.01, "tier": "silver", "rate": 1.000, "accounts": [{"balance": 1, "kind": "checking", "active": false}]}}),
json!({"customer": {"age": 64, "income": 1.10, "tier": "bronze", "rate": 0.00, "accounts": [{"balance": 0.10, "kind": "loan", "active": true}, {"balance": 3.333, "kind": "checking", "active": true}]}}),
];
let nulls = [
customer(json!([{"balance": -0.0, "kind": "loan", "active": true}])),
customer(json!([{"balance": null, "kind": null, "active": null}])),
customer(json!([{"balance": 5, "kind": "loan"}, {"kind": "savings", "active": true}])),
customer(json!([null])),
];
let mut values = Anchor::rows(128, 13);
for (at, row) in odd.into_iter().enumerate() {
values.insert(at * 7 + 2, row);
}
for (at, row) in overflow.iter().enumerate() {
values.insert(at * 31 + 5, row.clone());
}
let reference = Reference::open("anchor");
let [first, second] = Anchor::extremes();
let ws = Anchor::workspace();
let mut failures = Vec::new();
let counts = Anchor::checked(&ws, &values, &mut failures);
let counts = first.checked(&reference, &ws, &mut failures);
assert_eq!(counts.len(), 2, "flat and struct-list columns");
for (typed, laned, hosted) in counts {
eprintln!("extremes typed {typed} laned {laned} hosted {hosted}");
@@ -1108,13 +771,46 @@ fn policy_typed_extremes() {
assert_eq!(typed + laned, 8, "anchor units typed {typed} / laned {laned}");
}
}
for (at, row) in nulls.into_iter().enumerate() {
values.insert(at * 11 + 3, row);
}
Anchor::checked(&ws, &values, &mut failures);
second.checked(&reference, &ws, &mut failures);
failures.extend(reference.missing());
assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));
}
#[test]
#[ignore]
fn single_row_latency() {
let count: usize = std::env::var("BENCH_ROWS").ok().and_then(|v| v.parse().ok()).unwrap_or(256);
let rows: Vec<Variable> = Anchor::rows(count, 7).into_iter().map(Variable::from).collect();
let ws = Anchor::workspace();
let traced = |rows: &[Variable]| -> Vec<EvaluateRequest> { Anchor::fresh(rows).into_iter().map(|r| EvaluateRequest { trace: true, ..r }).collect() };
let results: [(&str, f64); 5] = [
("evaluate", Anchor::time(count, || {
let fresh = Anchor::fresh(&rows);
Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate(r))))
})),
("evaluate traced", Anchor::time(count, || {
let fresh = traced(&rows);
Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate(r))))
})),
("enhance_trace", Anchor::time(count, || {
let fresh = Anchor::fresh(&rows);
Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.enhance_trace(r))))
})),
("driver", Anchor::time(count, || {
let fresh = Anchor::fresh(&rows);
Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate_with_driver(r))))
})),
("driver traced", Anchor::time(count, || {
let fresh = traced(&rows);
Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate_with_driver(r))))
})),
];
for (name, t) in results {
println!("{name:24} {t:>10.0} ns/eval");
}
}
#[test]
#[ignore]
fn policy_anchor_throughput() {
+5
View File
@@ -3,6 +3,7 @@
pub mod graph;
pub mod literal;
pub mod policy;
pub mod run;
use literal::{Kind, Lit, Parser};
use serde_json::Value;
@@ -53,6 +54,10 @@ pub struct Suite {
}
impl Suite {
pub fn id(&self) -> String {
format!("{}#{}", self.file, self.name)
}
pub fn location(&self, case: &Case) -> String {
format!("{}:{} [{}]", self.file, case.line, self.name)
}
+225
View File
@@ -0,0 +1,225 @@
use crate::conformance::{Case, Suite};
use crate::support::golden::{Canon, Outcome, Reference};
use serde_json::Value;
use std::sync::Arc;
use zen_engine::loader::MemoryLoader;
use zen_engine::model::DecisionContent;
use zen_engine::nodes::custom::{CustomNodeAdapter, CustomNodeRequest};
use zen_engine::nodes::{NodeError, NodeResponse, NodeResult};
use zen_engine::policy::{EvaluateRequest, EvaluationResult, PolicyWorkspace, Severity};
use zen_engine::{Decision, DecisionEngine, DecisionGraphResponse, EvaluationError};
use zen_expression::Variable;
#[derive(Debug)]
pub struct SpecNodes;
impl SpecNodes {
pub fn respond(request: &CustomNodeRequest) -> Result<Variable, String> {
let config = &request.node.config;
match request.node.kind.as_ref() {
"echo" => Ok(request.input.clone()),
"config" => Ok(Variable::from(config.as_ref().clone())),
"render" => {
let out = Variable::empty_object();
for key in config.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default() {
let value = request.get_field(&key).map_err(|e| e.to_string())?.unwrap_or(Variable::Null);
out.dot_insert(&key, value);
}
Ok(out)
}
"fail" => Err(config.get("message").and_then(|m| m.as_str()).unwrap_or("custom node failed").to_string()),
other => Err(format!("unknown spec custom node kind {other:?}")),
}
}
}
impl CustomNodeAdapter for SpecNodes {
fn handle(&self, request: CustomNodeRequest) -> std::pin::Pin<Box<dyn std::future::Future<Output = NodeResult> + '_>> {
Box::pin(async move {
Self::respond(&request)
.map(|output| NodeResponse { output, trace_data: None })
.map_err(|message| NodeError { trace: None, node_id: request.node.id.clone(), source: message.into() })
})
}
}
pub struct GraphRun {
pub walker: Decision,
pub compiled: Decision,
pub engine: DecisionEngine,
}
impl GraphRun {
pub fn new(suite: &Suite) -> Result<GraphRun, String> {
let content = |value: &Value| -> Result<DecisionContent, String> {
serde_json::from_value::<DecisionContent>(value.clone()).map_err(|e| format!("{}: invalid content: {e}", suite.name))
};
let (plain, built) = (Arc::new(MemoryLoader::default()), Arc::new(MemoryLoader::default()));
for (key, doc) in &suite.documents {
plain.add(key.as_str(), content(doc)?);
built.add(key.as_str(), Self::compiled(content(doc)?));
}
let DecisionContent::Graph(graph) = content(&suite.content)? else {
return Err(format!("{}: graph suite content is not a graph", suite.name));
};
let shared = Arc::new(MemoryLoader::default());
for (key, doc) in &suite.documents {
shared.add(key.as_str(), content(doc)?);
}
shared.add(Self::MAIN, content(&suite.content)?);
let engine = DecisionEngine::default().with_loader(shared).with_adapter(Arc::new(SpecNodes));
engine.compile();
let walker = Decision::from(graph.clone()).with_loader(plain).with_adapter(Arc::new(SpecNodes));
let mut compiled = Decision::from(graph).with_loader(built).with_adapter(Arc::new(SpecNodes));
compiled.compile();
Ok(GraphRun { walker, compiled, engine })
}
pub const MAIN: &'static str = "spec-main";
pub fn compiled(content: DecisionContent) -> DecisionContent {
match content {
DecisionContent::Graph(mut graph) => {
Arc::make_mut(&mut graph).compile();
DecisionContent::Graph(graph)
}
other => other,
}
}
pub fn outcome(result: Result<DecisionGraphResponse, Box<EvaluationError>>) -> Result<Variable, String> {
result.map(|r| r.result).map_err(|e| Self::error(&e))
}
pub fn error(error: &EvaluationError) -> String {
serde_json::to_value(error).map(|v| v.to_string()).unwrap_or_else(|_| error.to_string())
}
pub async fn walker(&self, case: &Case) -> Result<Variable, String> {
Self::outcome(self.walker.evaluate(case.input.depth_clone(64)).await)
}
}
pub struct PolicyRun {
pub workspace: PolicyWorkspace,
pub blocking: Vec<String>,
pub gate: bool,
pub engine: DecisionEngine,
}
impl PolicyRun {
pub const MAIN: &'static str = "main";
pub fn new(suite: &Suite) -> Result<PolicyRun, String> {
let mut workspace = PolicyWorkspace::new();
let loader = Arc::new(MemoryLoader::default());
let policy = |value: &Value| serde_json::from_value(value.clone()).map_err(|e| format!("{}: invalid policy: {e}", suite.name));
let document = |value: &Value| serde_json::from_value::<DecisionContent>(value.clone()).map_err(|e| format!("{}: invalid document: {e}", suite.name));
workspace.set_policy(Self::MAIN, policy(&suite.content)?);
loader.add(Self::MAIN, document(&suite.content)?);
for (key, doc) in &suite.documents {
match doc.get("nodes") {
Some(_) => workspace.set_document(key.as_str(), document(doc)?),
None => workspace.set_policy(key.as_str(), policy(doc)?),
}
loader.add(key.as_str(), document(doc)?);
}
let mut blocking: Vec<String> = workspace
.evaluation_diagnostics(Self::MAIN)
.into_iter()
.filter(|d| d.severity == Severity::Error)
.map(|d| serde_json::to_value(d.code).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default())
.collect();
blocking.sort();
blocking.dedup();
let engine = DecisionEngine::default().with_loader(loader);
let gate = suite.diagnostics.is_none();
Ok(PolicyRun { workspace, blocking, gate, engine })
}
pub fn gated(&self, result: &Result<EvaluationResult, zen_engine::policy::EvaluationError>) -> Result<Variable, String> {
match self.blocking.is_empty() || !self.gate {
true => Self::outcome(result),
false => Err(format!("CompilationErrors {:?}", self.blocking)),
}
}
pub fn driver(&self, case: &Case) -> Result<Variable, String> {
self.gated(&self.workspace.evaluate_with_driver(&Self::request(case)))
}
pub fn compiled(&self, case: &Case) -> Result<Variable, String> {
self.gated(&self.workspace.evaluate(&Self::request(case)))
}
pub fn engine(&self, case: &Case) -> Result<Variable, String> {
let result = Guard::block(self.engine.evaluate(Self::MAIN, case.input.depth_clone(64)));
match (&result, self.blocking.is_empty()) {
(Err(_), false) => Err(format!("CompilationErrors {:?}", self.blocking)),
(Err(error), true) => match &**error {
EvaluationError::Policy(error) => Err(Reference::debug(error)),
other => Err(GraphRun::error(other)),
},
(Ok(response), _) => Ok(response.result.clone()),
}
}
pub fn request(case: &Case) -> EvaluateRequest {
EvaluateRequest {
policy_path: Arc::from(Self::MAIN),
input: case.input.depth_clone(64),
goals: case.goals.iter().map(|g| Arc::from(g.as_str())).collect(),
trace: false,
}
}
pub fn outcome(result: &Result<EvaluationResult, zen_engine::policy::EvaluationError>) -> Result<Variable, String> {
result.as_ref().map(|r| r.output.clone()).map_err(Reference::debug)
}
}
pub struct Guard;
impl Guard {
pub fn run<T>(label: String, failures: &mut Vec<String>, work: impl FnOnce() -> T) -> Option<T> {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) {
Ok(value) => Some(value),
Err(payload) => {
let message = payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
.unwrap_or_default();
failures.push(format!("{label} | PANIC: {message}"));
None
}
}
}
pub fn block<F: std::future::Future>(future: F) -> F::Output {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime")
.block_on(future)
}
}
impl GraphRun {
pub fn recorded(outcome: &Outcome) -> Result<Variable, String> {
match outcome {
Outcome::Ok(value) => Ok(Canon::restore(value)),
Outcome::Err { value, .. } => Err(value.to_string()),
}
}
}
impl PolicyRun {
pub fn recorded(&self, outcome: &Outcome) -> Result<Variable, String> {
match (self.blocking.is_empty() || !self.gate, outcome) {
(false, _) => Err(format!("CompilationErrors {:?}", self.blocking)),
(true, Outcome::Ok(value)) => Ok(Canon::restore(value)),
(true, Outcome::Err { debug, .. }) => Err(debug.clone()),
}
}
}
+815
View File
@@ -0,0 +1,815 @@
#[path = "support/policy_gen.rs"]
mod policy_gen;
#[allow(dead_code)]
mod conformance;
mod support;
#[path = "support/fixture.rs"]
mod fixture;
#[allow(dead_code)]
#[path = "support/policies.rs"]
mod policies;
use conformance::run::{GraphRun, Guard, PolicyRun};
use conformance::{Dialect, Spec, Suite};
use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND};
use policies::{Anchor, Generated, PolicyCase};
use serde_json::{json, Value};
use std::collections::BTreeSet;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex, MutexGuard};
use support::columns::Built;
use support::golden::{Canon, Entry, Golden, Outcome};
use zen_engine::policy::{EvaluateRequest, PolicyWorkspace};
use zen_engine::{Decision, EvaluationError, EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind, ZEN_CONFIG};
use zen_expression::lane::Columns;
use zen_expression::Variable;
static GRAPH: Mutex<()> = Mutex::new(());
struct Nodes;
impl Nodes {
const CHAPTER: &'static str = "15-nodes-references";
fn modes(suite: &Suite) -> Vec<bool> {
match suite.file.contains(Self::CHAPTER) {
true => vec![true, false],
false => vec![true],
}
}
fn id(suite: &Suite, nodes: bool) -> String {
match nodes {
true => suite.id(),
false => format!("{}#nodes-off", suite.id()),
}
}
fn set(nodes: bool) {
ZEN_CONFIG.nodes_in_context.store(nodes, Ordering::Relaxed);
}
fn lock() -> MutexGuard<'static, ()> {
GRAPH.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
}
struct Rows;
impl Rows {
fn cycled(rows: &[Value], times: usize) -> Vec<Value> {
(0..rows.len() * times).map(|i| rows[i % rows.len()].clone()).collect()
}
fn spec_graph(rows: &[Value]) -> Vec<(Built, bool)> {
let cycled = Self::cycled(rows, 3);
Built::new(rows)
.into_iter()
.chain(Built::lists(rows))
.chain(Built::new(&cycled))
.chain(Built::nested(rows))
.chain(Built::nested(&cycled))
.map(|b| (b, true))
.collect()
}
fn spec_policy(rows: &[Value]) -> Vec<(Built, bool)> {
let cycled = Self::cycled(rows, 3);
let flat = Built::new(rows).into_iter().chain(Built::lists(rows)).chain(Built::new(&cycled)).map(|b| (b, false));
let nested = Built::nested(rows).into_iter().chain(Built::nested(&cycled)).map(|b| (b, true));
flat.chain(nested).collect()
}
fn generated(inputs: &[Value]) -> Vec<(Built, bool)> {
let flat = Built::new(inputs).into_iter().chain(Built::lists(inputs)).map(|b| (b, false));
flat.chain(Built::nested(inputs).map(|b| (b, true))).collect()
}
fn fixture(variants: &[Value]) -> Vec<(Built, bool)> {
let Some(first) = Built::new(variants) else {
return Vec::new();
};
let cycled = Self::cycled(variants, 4);
std::iter::once(first)
.chain(Built::lists(variants))
.chain(Built::new(&cycled))
.chain(Built::nested(variants))
.chain(Built::nested(&cycled))
.map(|b| (b, true))
.collect()
}
fn with<T>(built: &Built, structs: bool, f: impl FnOnce(&Columns) -> T) -> T {
match structs {
true => {
let fields = built.fields();
let parts = built.structs(&fields);
f(&built.columns_with(&parts))
}
false => f(&built.columns()),
}
}
fn of(builds: &[(Built, bool)]) -> Vec<Variable> {
builds.iter().flat_map(|(built, structs)| Self::with(built, *structs, |c| (0..c.rows).map(|r| c.row(r)).collect::<Vec<_>>())).collect()
}
}
struct Graphs;
impl Graphs {
fn traced() -> EvaluationOptions {
EvaluationOptions { trace: true, max_depth: 10 }
}
fn serialized() -> EvaluationSerializedOptions {
EvaluationSerializedOptions {
trace: EvaluationTraceKind::Reference,
max_depth: 10,
}
}
async fn record(golden: &mut Golden, id: &str, walker: &Decision, input: &Variable, traced: bool) {
let plain = Outcome::graph(&walker.evaluate(input.depth_clone(64)).await);
let entry = Entry::new(id, &[], input, plain);
let entry = match traced {
true => {
let traced = Outcome::graph_traced(&walker.evaluate_with_opts(input.depth_clone(64), Self::traced()).await, EvaluationTraceKind::Default);
let reference = Canon::reference(&traced, walker.evaluate_serialized(input.depth_clone(64), Self::serialized()).await);
entry.traced(traced, Some(reference))
}
false => entry,
};
golden.insert(entry);
}
async fn verify(check: &mut Check, golden: &Golden, id: &str, decision: &Decision, input: &Variable, label: &str) {
let key = Canon::key(id, &[], input);
let Some(entry) = check.entry(golden, &key) else {
return;
};
let plain = Outcome::graph(&decision.evaluate(input.depth_clone(64)).await);
check.same(&key, &format!("{label} single"), &entry.plain, &plain);
if let Some(traced) = &entry.traced {
let got = Outcome::graph_traced(&decision.evaluate_with_opts(input.depth_clone(64), Self::traced()).await, EvaluationTraceKind::Default);
check.same(&key, &format!("{label} traced"), traced, &got);
let reference = Canon::reference(traced, decision.evaluate_serialized(input.depth_clone(64), Self::serialized()).await);
check.values(&key, &format!("{label} reference"), entry.reference.as_ref(), Some(&reference));
}
}
async fn columns(check: &mut Check, golden: &Golden, id: &str, decision: &Decision, builds: &[(Built, bool)]) {
for (built, _) in builds {
let fields = built.fields();
let structs = built.structs(&fields);
let columns = built.columns_with(&structs);
let output = decision.evaluate_columns(&columns, EvaluationOptions::default()).await;
for row in 0..columns.rows {
let input = columns.row(row);
let key = Canon::key(id, &[], &input);
let Some(entry) = check.entry(golden, &key) else {
continue;
};
let got = match &output.errors[row] {
Some(error) => Outcome::Err {
debug: error.to_string(),
value: Canon::value(serde_json::to_value(&**error).unwrap_or(Value::Null)),
},
None => Outcome::Ok(Canon::variable(&output.row(row))),
};
check.same(&key, "columns", &entry.plain.normalized(Built::normalized), &got.normalized(Built::normalized));
}
}
}
async fn batch(check: &mut Check, golden: &Golden, id: &str, decision: &Decision, inputs: &[Variable], label: &str) {
let keys: Vec<String> = inputs.iter().map(|input| Canon::key(id, &[], input)).collect();
let results = decision.evaluate_batch(inputs, EvaluationOptions::default()).await;
for (key, result) in keys.into_iter().zip(&results) {
if let Some(entry) = check.entry(golden, &key) {
check.same(&key, label, &entry.plain, &Outcome::graph(result));
}
}
}
}
struct Policies;
impl Policies {
fn request(path: &str, input: &Variable, goals: &[String], trace: bool) -> EvaluateRequest {
EvaluateRequest {
policy_path: Arc::from(path),
input: input.depth_clone(64),
goals: goals.iter().map(|g| Arc::from(g.as_str())).collect(),
trace,
}
}
fn record(golden: &mut Golden, ws: &PolicyWorkspace, id: &str, path: &str, input: &Variable, goals: &[String], traced: bool, fingerprint: Option<String>) {
let plain = Outcome::policy(ws.evaluate_with_driver(&Self::request(path, input, goals, false)));
let entry = Entry::new(id, goals, input, plain).fingerprint(fingerprint);
let entry = match traced {
true => entry
.traced(Outcome::policy_traced(ws.evaluate(&Self::request(path, input, goals, true))), None)
.enhanced(Outcome::policy_traced(ws.enhance_trace(&Self::request(path, input, goals, false)))),
false => entry,
};
golden.insert(entry);
}
fn verify(check: &mut Check, golden: &Golden, ws: &PolicyWorkspace, id: &str, path: &str, input: &Variable, goals: &[String], fingerprint: Option<&str>) {
let key = Canon::key(id, goals, input);
let Some(entry) = check.entry(golden, &key) else {
return;
};
if fingerprint.is_some() && entry.fingerprint.as_deref() != fingerprint {
check.failures.push(format!("{key}: fingerprint changed, goldens are stale"));
}
check.same(&key, "single", &entry.plain, &Outcome::policy(ws.evaluate(&Self::request(path, input, goals, false))));
if let Some(traced) = &entry.traced {
check.same(&key, "traced", traced, &Outcome::policy_traced(ws.evaluate(&Self::request(path, input, goals, true))));
}
if let Some(enhanced) = &entry.enhanced {
check.same(&key, "enhanced", enhanced, &Outcome::policy_traced(ws.enhance_trace(&Self::request(path, input, goals, false))));
}
}
fn batch(check: &mut Check, golden: &Golden, ws: &PolicyWorkspace, id: &str, path: &str, requests: &[(Variable, Vec<String>)]) {
let batch: Vec<EvaluateRequest> = requests.iter().map(|(input, goals)| Self::request(path, input, goals, false)).collect();
for ((input, goals), result) in requests.iter().zip(ws.evaluate_batch(&batch)) {
let key = Canon::key(id, goals, input);
if let Some(entry) = check.entry(golden, &key) {
check.same(&key, "batch", &entry.plain, &Outcome::policy(result));
}
}
}
fn columns(check: &mut Check, golden: &Golden, ws: &PolicyWorkspace, id: &str, path: &str, goals: &[String], builds: &[(Built, bool)]) {
let targets: Vec<Arc<str>> = goals.iter().map(|g| Arc::from(g.as_str())).collect();
for (built, structs) in builds {
Rows::with(built, *structs, |columns| {
let output = ws.evaluate_columns(&Arc::from(path), &targets, columns);
for row in 0..columns.rows {
let input = columns.row(row);
let key = Canon::key(id, goals, &input);
let Some(entry) = check.entry(golden, &key) else {
continue;
};
let error = match &output {
Ok(output) => output.errors[row].as_ref(),
Err(refused) => Some(refused),
};
let got = match (error, &output) {
(Some(error), _) => Outcome::Err {
debug: Outcome::debug(error),
value: Value::Null,
},
(None, Ok(output)) => Outcome::Ok(Canon::variable(&output.row(row))),
(None, Err(_)) => Outcome::missing(&key),
};
let want = match &entry.plain {
Outcome::Err { debug, .. } => Outcome::Err {
debug: debug.clone(),
value: Value::Null,
},
ok => ok.normalized(Built::normalized),
};
check.same(&key, "columns", &want, &got.normalized(Built::normalized));
}
});
}
}
}
#[derive(Default)]
struct Check {
failures: Vec<String>,
compared: usize,
ordered: usize,
divergent: BTreeSet<String>,
skipped: usize,
}
impl Check {
fn entry<'g>(&mut self, golden: &'g Golden, key: &str) -> Option<&'g Entry> {
match golden.get(key) {
None => {
self.failures.push(format!("{key}: missing golden entry"));
None
}
Some(entry) if entry.ordered => {
self.ordered += 1;
None
}
entry => entry,
}
}
fn diverges(&mut self, suite: &Suite, id: &str, inputs: impl IntoIterator<Item = Variable>) {
for input in inputs {
let value = Built::normalized(input.to_value());
let case = suite.cases.iter().find(|c| Built::normalized(c.input.to_value()) == value).unwrap_or(&suite.cases[0]);
if case.engines.is_some() {
self.divergent.insert(Canon::key(id, &[], &input));
}
}
}
fn same(&mut self, key: &str, path: &str, want: &Outcome, got: &Outcome) {
if self.divergent.contains(key) {
self.skipped += 1;
return;
}
self.compared += 1;
if want != got {
self.failures.push(format!("{key} {path}\n golden {}\n got {}", want.show(), got.show()));
}
}
fn values(&mut self, key: &str, path: &str, want: Option<&Value>, got: Option<&Value>) {
self.compared += 1;
if want != got {
self.failures.push(format!("{key} {path}\n golden {want:?}\n got {got:?}"));
}
}
fn finish(mut self, golden: &Golden, label: &str) {
let unvisited = golden.unvisited();
if !unvisited.is_empty() {
self.failures.push(format!("{} golden entries never checked, e.g. {:?}", unvisited.len(), unvisited.iter().take(5).collect::<Vec<_>>()));
}
eprintln!("{label}: {} entries, {} comparisons, {} key-order dependent lookups and {} documented engine divergences skipped, {} failures", golden.len(), self.compared, self.ordered, self.skipped, self.failures.len());
let limit = std::env::var("SPEC_SHOW").ok().and_then(|v| v.parse().ok()).unwrap_or(40);
assert!(self.failures.is_empty(), "{} failures:\n{}", self.failures.len(), self.failures.iter().take(limit).cloned().collect::<Vec<_>>().join("\n"));
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Corpus {
SpecGraph,
SpecPolicy,
Generated,
PolicyFixtures,
Anchor,
GraphFixtures,
}
impl Corpus {
const ALL: [Corpus; 6] = [Corpus::SpecGraph, Corpus::SpecPolicy, Corpus::Generated, Corpus::PolicyFixtures, Corpus::Anchor, Corpus::GraphFixtures];
fn name(&self) -> &'static str {
match self {
Corpus::SpecGraph => "spec-graph",
Corpus::SpecPolicy => "spec-policy",
Corpus::Generated => "generated/policy",
Corpus::PolicyFixtures => "policy-fixtures",
Corpus::Anchor => "anchor",
Corpus::GraphFixtures => "graph-fixtures",
}
}
fn shard(&self, entry: &Entry) -> Option<String> {
match self {
Corpus::SpecGraph | Corpus::SpecPolicy => {
let file = entry.suite.split('#').next().unwrap_or_default();
let name = file.rsplit('/').next().unwrap_or(file);
Some(name.trim_end_matches(".json5").to_string())
}
_ => None,
}
}
fn selected() -> Vec<Corpus> {
let only = std::env::var("GOLDEN_CORPUS").ok();
Self::ALL.into_iter().filter(|c| only.as_ref().is_none_or(|o| c.name().contains(o.as_str()))).collect()
}
fn record(&self) -> Golden {
Golden::prepare();
let mut golden = Golden::new(self.name());
let mut failures = Vec::new();
match self {
Corpus::SpecGraph => Self::spec_graph(&mut golden, &mut failures),
Corpus::SpecPolicy => Self::spec_policy(&mut golden, &mut failures),
Corpus::Generated => Self::generated(&mut golden),
Corpus::PolicyFixtures => Self::policy_fixtures(&mut golden),
Corpus::Anchor => Self::anchor(&mut golden),
Corpus::GraphFixtures => Guard::block(Self::graph_fixtures(&mut golden)),
}
failures.extend(golden.conflicts.iter().cloned());
assert!(failures.is_empty(), "{}: recording failed:\n{}", self.name(), failures.join("\n"));
golden
}
fn spec_graph(golden: &mut Golden, failures: &mut Vec<String>) {
let (suites, problems) = Spec::suites(Dialect::Graph);
failures.extend(problems);
let _guard = Nodes::lock();
for suite in &suites {
for nodes in Nodes::modes(suite) {
Nodes::set(nodes);
let Ok(run) = GraphRun::new(suite) else {
continue;
};
let id = Nodes::id(suite, nodes);
let rows: Vec<Value> = suite.cases.iter().map(|c| c.input.to_value()).collect();
let label = format!("{id} record");
Guard::run(label, failures, || {
Guard::block(async {
for case in &suite.cases {
Graphs::record(golden, &id, &run.walker, &case.input, true).await;
}
for row in Rows::of(&Rows::spec_graph(&rows)) {
Graphs::record(golden, &id, &run.walker, &row, false).await;
}
})
});
}
}
Nodes::set(true);
}
fn spec_policy(golden: &mut Golden, failures: &mut Vec<String>) {
let (suites, problems) = Spec::suites(Dialect::Policy);
failures.extend(problems);
for suite in &suites {
let Ok(run) = PolicyRun::new(suite) else {
continue;
};
let id = suite.id();
let label = format!("{id} record");
Guard::run(label, failures, || {
golden.insert(Entry::new(&format!("{id}#diagnostics"), &[], &Variable::Null, Outcome::Ok(json!(run.blocking))));
for case in &suite.cases {
Policies::record(golden, &run.workspace, &id, PolicyRun::MAIN, &case.input, &case.goals, true, None);
}
if !run.blocking.is_empty() && run.gate {
return;
}
for (goals, rows) in Self::goal_rows(suite) {
for row in Rows::of(&Rows::spec_policy(&rows)) {
Policies::record(golden, &run.workspace, &id, PolicyRun::MAIN, &row, &goals, false, None);
}
}
});
}
}
fn goal_rows(suite: &Suite) -> Vec<(Vec<String>, Vec<Value>)> {
let mut goal_sets: Vec<&Vec<String>> = suite.cases.iter().map(|c| &c.goals).collect();
goal_sets.dedup();
goal_sets
.into_iter()
.map(|goals| (goals.clone(), suite.cases.iter().filter(|c| &c.goals == goals).map(|c| c.input.to_value()).collect()))
.collect()
}
fn computed(ws: &PolicyWorkspace, path: &str, inputs: &[Value]) -> Vec<String> {
inputs
.iter()
.find_map(|input| ws.evaluate_with_driver(&Policies::request(path, &Variable::from(input.clone()), &[], false)).ok().map(|r| PolicyCase::computed(&r.output.to_value(), input)))
.unwrap_or_default()
}
fn goal_sets(computed: &[String], i: usize) -> Vec<Vec<String>> {
let goals = PolicyCase::goals(computed, i);
match goals.is_empty() {
true => vec![goals],
false => vec![Vec::new(), goals],
}
}
fn generated(golden: &mut Golden) {
for seed in 0..Generated::seeds() {
let Some(ws) = Generated::workspace(seed) else {
continue;
};
let (inputs, label, fingerprint) = (Generated::inputs(seed), Generated::label(seed), Generated::fingerprint(seed));
let computed = Self::computed(&ws, Generated::PATH, &inputs);
for (i, input) in inputs.iter().enumerate() {
for goals in Self::goal_sets(&computed, i) {
Policies::record(golden, &ws, &label, Generated::PATH, &Variable::from(input.clone()), &goals, i < 8, Some(fingerprint.clone()));
}
}
for row in Rows::of(&Rows::generated(&inputs)) {
Policies::record(golden, &ws, &label, Generated::PATH, &row, &[], false, Some(fingerprint.clone()));
}
}
}
fn policy_fixtures(golden: &mut Golden) {
for case in PolicyCase::load_all() {
let computed = Self::computed(&case.workspace, &case.path, &case.inputs);
for (i, input) in case.inputs.iter().enumerate() {
for goals in Self::goal_sets(&computed, i) {
Policies::record(golden, &case.workspace, &case.name, &case.path, &Variable::from(input.clone()), &goals, false, None);
}
}
}
}
fn anchor(golden: &mut Golden) {
for batch in Anchor::batches() {
let ws = batch.workspace();
for row in batch.column_rows() {
Policies::record(golden, &ws, batch.suite, Anchor::PATH, &row, &[], false, None);
}
}
let base = Anchor::base();
let ws = base.workspace();
for (at, value) in base.values.iter().enumerate() {
Policies::record(golden, &ws, base.suite, Anchor::PATH, &Variable::from(value.clone()), &[], at < 32, None);
}
}
fn fixtures() -> Vec<Fixture> {
Fixture::load_all()
.into_iter()
.filter(|f| !NETWORK_BOUND.contains(&f.name.as_str()))
.collect()
}
fn slow(fixture: &Fixture) -> bool {
TIME_BOUND.contains(&fixture.name.as_str())
}
fn fixture_inputs(fixture: &Fixture) -> Vec<Variable> {
fixture.variants().into_iter().chain(fixture.typed_variants()).map(Variable::from).collect()
}
fn compiled(fixture: &Fixture) -> Decision {
let mut compiled = Decision::from(Arc::new(fixture.content.clone()));
compiled.compile();
compiled
}
async fn graph_fixtures(golden: &mut Golden) {
let _guard = Nodes::lock();
for fixture in Self::fixtures() {
let walker = Decision::from(Arc::new(fixture.content.clone()));
for input in Self::fixture_inputs(&fixture) {
Graphs::record(golden, &fixture.name, &walker, &input, !Self::slow(&fixture)).await;
}
if !Self::slow(&fixture) && matches!(Self::compiled(&fixture).compiled_verdict(), Some(Ok(()))) {
for row in Rows::of(&Rows::fixture(&fixture.variants())) {
Graphs::record(golden, &fixture.name, &walker, &row, false).await;
}
}
}
}
fn verify(&self) {
Golden::prepare();
let golden = Golden::open(self.name());
let mut check = Check::default();
match self {
Corpus::SpecGraph => Self::verify_spec_graph(&golden, &mut check),
Corpus::SpecPolicy => Self::verify_spec_policy(&golden, &mut check),
Corpus::Generated => Self::verify_generated(&golden, &mut check),
Corpus::PolicyFixtures => Self::verify_policy_fixtures(&golden, &mut check),
Corpus::Anchor => Self::verify_anchor(&golden, &mut check),
Corpus::GraphFixtures => Guard::block(Self::verify_graph_fixtures(&golden, &mut check)),
}
check.finish(&golden, self.name());
}
fn verify_spec_graph(golden: &Golden, check: &mut Check) {
let (suites, _) = Spec::suites(Dialect::Graph);
let _guard = Nodes::lock();
for suite in &suites {
for nodes in Nodes::modes(suite) {
Nodes::set(nodes);
let Ok(run) = GraphRun::new(suite) else {
continue;
};
let id = Nodes::id(suite, nodes);
let rows: Vec<Value> = suite.cases.iter().map(|c| c.input.to_value()).collect();
let builds = Rows::spec_graph(&rows);
check.diverges(suite, &id, suite.cases.iter().map(|c| c.input.clone()).chain(Rows::of(&builds)));
let mut failures = Vec::new();
Guard::run(format!("{id} verify"), &mut failures, || {
Guard::block(async {
for case in &suite.cases {
Graphs::verify(check, golden, &id, &run.compiled, &case.input, "compiled").await;
Graphs::verify(check, golden, &id, &run.walker, &case.input, "uncompiled").await;
let key = Canon::key(&id, &[], &case.input);
if let Some(entry) = case.engines.is_none().then(|| check.entry(golden, &key)).flatten() {
let engine = Outcome::graph(&run.engine.evaluate(GraphRun::MAIN, case.input.depth_clone(64)).await);
check.same(&key, "engine", &entry.plain, &engine);
if let Some(traced) = &entry.traced {
let got = Outcome::graph_traced(&run.engine.evaluate_with_opts(GraphRun::MAIN, case.input.depth_clone(64), Graphs::traced()).await, EvaluationTraceKind::Default);
check.same(&key, "engine traced", traced, &got);
}
}
}
let contexts: Vec<Variable> = suite.cases.iter().cycle().take(suite.cases.len() * 3).map(|c| c.input.depth_clone(64)).collect();
Graphs::batch(check, golden, &id, &run.compiled, &contexts, "batch").await;
Graphs::columns(check, golden, &id, &run.compiled, &builds).await;
})
});
check.failures.extend(failures);
}
}
Nodes::set(true);
}
fn verify_spec_policy(golden: &Golden, check: &mut Check) {
let (suites, _) = Spec::suites(Dialect::Policy);
for suite in &suites {
let Ok(run) = PolicyRun::new(suite) else {
continue;
};
let id = suite.id();
let mut failures = Vec::new();
Guard::run(format!("{id} verify"), &mut failures, || {
let key = Canon::key(&format!("{id}#diagnostics"), &[], &Variable::Null);
if let Some(entry) = check.entry(golden, &key) {
check.same(&key, "diagnostics", &entry.plain, &Outcome::Ok(json!(run.blocking)));
}
for case in &suite.cases {
Policies::verify(check, golden, &run.workspace, &id, PolicyRun::MAIN, &case.input, &case.goals, None);
let key = Canon::key(&id, &case.goals, &case.input);
if case.goals.is_empty() && run.gate && run.blocking.is_empty() && case.engines.is_none() {
if let Some(entry) = check.entry(golden, &key) {
let engine = match Guard::block(run.engine.evaluate(PolicyRun::MAIN, case.input.depth_clone(64))) {
Ok(response) => Outcome::Ok(Canon::variable(&response.result)),
Err(error) => match *error {
EvaluationError::Policy(error) => Outcome::policy(Err(error)),
other => Outcome::Err {
debug: other.to_string(),
value: Value::Null,
},
},
};
check.same(&key, "engine", &entry.plain, &engine);
}
}
}
let requests: Vec<(Variable, Vec<String>)> = suite.cases.iter().cycle().take(suite.cases.len() * 3).map(|c| (c.input.clone(), c.goals.clone())).collect();
Policies::batch(check, golden, &run.workspace, &id, PolicyRun::MAIN, &requests);
if !run.blocking.is_empty() && run.gate {
return;
}
for (goals, rows) in Self::goal_rows(suite) {
Policies::columns(check, golden, &run.workspace, &id, PolicyRun::MAIN, &goals, &Rows::spec_policy(&rows));
}
});
check.failures.extend(failures);
}
}
fn goals_from(golden: &Golden, id: &str, inputs: &[Value]) -> Vec<String> {
inputs
.iter()
.find_map(|input| match golden.get(&Canon::key(id, &[], &Variable::from(input.clone()))).map(|e| &e.plain) {
Some(Outcome::Ok(output)) => Some(PolicyCase::computed(output, input)),
_ => None,
})
.unwrap_or_default()
}
fn verify_generated(golden: &Golden, check: &mut Check) {
for seed in 0..Generated::seeds() {
let Some(ws) = Generated::workspace(seed) else {
continue;
};
let (inputs, label, fingerprint) = (Generated::inputs(seed), Generated::label(seed), Generated::fingerprint(seed));
let computed = Self::goals_from(golden, &label, &inputs);
let mut requests = Vec::new();
for (i, input) in inputs.iter().enumerate() {
for goals in Self::goal_sets(&computed, i) {
let variable = Variable::from(input.clone());
Policies::verify(check, golden, &ws, &label, Generated::PATH, &variable, &goals, Some(&fingerprint));
requests.push((variable, goals));
}
}
Policies::batch(check, golden, &ws, &label, Generated::PATH, &requests);
Policies::columns(check, golden, &ws, &label, Generated::PATH, &[], &Rows::generated(&inputs));
}
}
fn verify_policy_fixtures(golden: &Golden, check: &mut Check) {
for case in PolicyCase::load_all() {
let computed = Self::goals_from(golden, &case.name, &case.inputs);
let mut requests = Vec::new();
for (i, input) in case.inputs.iter().enumerate() {
for goals in Self::goal_sets(&computed, i) {
let variable = Variable::from(input.clone());
Policies::verify(check, golden, &case.workspace, &case.name, &case.path, &variable, &goals, None);
requests.push((variable, goals));
}
}
Policies::batch(check, golden, &case.workspace, &case.name, &case.path, &requests);
}
}
fn verify_anchor(golden: &Golden, check: &mut Check) {
for batch in Anchor::batches() {
let ws = batch.workspace();
let rows = batch.column_rows();
let builds: Vec<(Built, bool)> = Built::new(&batch.values).map(|b| (b, false)).into_iter().chain(Built::nested(&batch.values).map(|b| (b, true))).collect();
Policies::columns(check, golden, &ws, batch.suite, Anchor::PATH, &[], &builds);
for row in &rows {
Policies::verify(check, golden, &ws, batch.suite, Anchor::PATH, row, &[], None);
}
let requests: Vec<(Variable, Vec<String>)> = rows.into_iter().map(|r| (r, Vec::new())).collect();
Policies::batch(check, golden, &ws, batch.suite, Anchor::PATH, &requests);
}
let base = Anchor::base();
let ws = base.workspace();
for value in &base.values {
Policies::verify(check, golden, &ws, base.suite, Anchor::PATH, &Variable::from(value.clone()), &[], None);
}
}
async fn verify_graph_fixtures(golden: &Golden, check: &mut Check) {
let _guard = Nodes::lock();
for fixture in Self::fixtures() {
let compiled = Self::compiled(&fixture);
let uncompiled = Decision::from(Arc::new(fixture.content.clone()));
let inputs = Self::fixture_inputs(&fixture);
for input in &inputs {
Graphs::verify(check, golden, &fixture.name, &compiled, input, "compiled").await;
if !Self::slow(&fixture) {
Graphs::verify(check, golden, &fixture.name, &uncompiled, input, "uncompiled").await;
}
}
if Self::slow(&fixture) {
continue;
}
Graphs::batch(check, golden, &fixture.name, &compiled, &inputs, "batch").await;
if matches!(compiled.compiled_verdict(), Some(Ok(()))) {
Graphs::columns(check, golden, &fixture.name, &compiled, &Rows::fixture(&fixture.variants())).await;
}
}
}
}
#[test]
#[ignore]
fn capture() {
assert!(std::env::var("GOLDEN_WRITE").is_ok_and(|v| v == "1"), "set GOLDEN_WRITE=1 to rewrite the goldens");
for corpus in Corpus::selected() {
let started = std::time::Instant::now();
let golden = corpus.record();
let written = golden.write(|entry| corpus.shard(entry));
let (raw, stored) = written.iter().fold((0u64, 0u64), |(r, s), w| (r + w.raw, s + w.stored));
let traced = golden.entries().filter(|e| e.traced.is_some()).count();
let ordered: Vec<&str> = golden.entries().filter(|e| e.ordered).map(|e| e.suite.as_str()).collect();
if !ordered.is_empty() {
eprintln!("{}: {} entries depend on input key order: {:?}", corpus.name(), ordered.len(), ordered);
}
let enhanced = golden.entries().filter(|e| e.enhanced.is_some()).count();
eprintln!(
"{:18} {:>7} entries ({traced} traced, {enhanced} enhanced) {:>3} files raw {:>11} stored {:>11} in {:.1}s",
corpus.name(),
golden.len(),
written.len(),
raw,
stored,
started.elapsed().as_secs_f64()
);
}
}
#[test]
fn goldens_are_current() {
let mut failures = Vec::new();
for corpus in Corpus::selected() {
let live = corpus.record();
let recorded = Golden::open(corpus.name());
failures.extend(live.compare(&recorded));
}
let limit = std::env::var("SPEC_SHOW").ok().and_then(|v| v.parse().ok()).unwrap_or(20);
assert!(failures.is_empty(), "{} stale golden entries:\n{}", failures.len(), failures.iter().take(limit).cloned().collect::<Vec<_>>().join("\n"));
}
#[test]
fn goldens_spec_graph() {
Corpus::SpecGraph.verify();
}
#[test]
fn goldens_spec_policy() {
Corpus::SpecPolicy.verify();
}
#[test]
fn goldens_generated_policy() {
Corpus::Generated.verify();
}
#[test]
fn goldens_policy_fixtures() {
Corpus::PolicyFixtures.verify();
}
#[test]
fn goldens_anchor() {
Corpus::Anchor.verify();
}
#[test]
fn goldens_graph_fixtures() {
Corpus::GraphFixtures.verify();
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More