feat(engine): prepare policy input as columns (dates, defaults, references)

This commit is contained in:
Ivan Miletic
2026-10-13 15:46:58 +02:00
parent 08bc977727
commit fa520af6de
129 changed files with 21072 additions and 333 deletions
Generated
+8
View File
@@ -5967,6 +5967,12 @@ dependencies = [
"tap",
]
[[package]]
name = "xxhash-rust"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
[[package]]
name = "yoke"
version = "0.8.3"
@@ -6010,6 +6016,7 @@ dependencies = [
"arc-swap",
"async-trait",
"base64",
"bumpalo",
"criterion",
"downcast-rs",
"fixedbitset",
@@ -6077,6 +6084,7 @@ dependencies = [
"strum_macros 0.27.2",
"thiserror 1.0.69",
"toml",
"xxhash-rust",
"zen-macros",
"zen-types",
]
+45 -2
View File
@@ -29,7 +29,19 @@ export type PolicyCursorTarget =
| { kind: 'decisionTableRow'; row: string }
| { kind: 'dataModelName' }
| { kind: 'dataModelProperty'; id: string }
| { kind: 'transformInput' };
| { kind: 'transformInput' }
/** A data model property's `feature.expr` (`id` is the property id). */
| { kind: 'featureExpr'; id: string }
/** A data model property's `outcome.expr` (`id` is the property id). */
| { kind: 'outcomeExpr'; id: string }
/** A data model property's per-event `compute`. */
| { kind: 'computeExpr'; id: string }
/** The request path given to a model input, `model.inputs[input]`. */
| { kind: 'modelInput'; id: string; input: string }
/** A model's `model.when` condition. */
| { kind: 'modelWhen'; id: string }
| { kind: 'modelRequest'; id: string }
| { kind: 'modelResponse'; id: string };
/**
* How an entity field came into existence — declared by a DataModel
@@ -38,11 +50,35 @@ export type PolicyCursorTarget =
* through filter / index / slice) carry `instanceOf`.
*/
export type PolicyFieldOrigin =
| { origin: 'schema'; source: string; fieldKind: PolicyFieldKindInfo }
| {
origin: 'schema';
source: string;
fieldKind: PolicyFieldKindInfo;
/** The type as written when checked as another: `integer`, `decimal`, `timestamp`, `object`, `any`. */
exactType?: string;
/** Supplied by the host rather than the request. */
supply?: PolicyFieldSupply;
}
| { origin: 'computed'; writtenBy: PolicyPropertyWriter; instanceOf?: PolicyInstanceOf };
/**
* How the host supplies a field. A feature with windows is one field per
* window: `txn_count` over `1h` is the field `txn_count_1h` with
* `base: 'txn_count'`, `window: '1h'`. A feature without `default` is
* nullable (unknown or not covered). An outcome is known only after the
* decision: computed offline, never in a request, never read by rules
* (always nullable); `maturity` is in days (`30d`): when a decision is old
* enough to trust a "no" (the answer itself is never hidden).
*/
export type PolicyFieldSupply =
| { kind: 'feature'; base: string; expr: string; window?: string; default?: unknown }
| { kind: 'outcome'; expr?: string; maturity?: string }
| { kind: 'compute'; expr: string }
| { kind: 'model'; datasource?: string }
| { kind: 'members'; by: 'key' | 'events' };
export type PolicyDiagnosticCode =
| 'UNDEFINED_VARIABLE'
| 'TYPE_MISMATCH'
| 'NULLABLE_CONDITION'
| 'INVALID_EXPRESSION'
| 'PARSE_ERROR'
| 'MISSING_DEFAULT_BRANCH'
@@ -60,6 +96,13 @@ export type PolicyDiagnosticCode =
| 'DUPLICATE_PROPERTY'
| 'DUPLICATE_ENUM_VALUE'
| 'INVALID_NAME'
| 'INVALID_RELATIONSHIP'
| 'INVALID_DURATION'
| 'DEPRECATED_TYPE'
| 'FEATURE_SHAPE'
| 'IGNORED_ATTRIBUTE'
| 'INVALID_OUTCOME'
| 'OUTCOME_READ'
| 'MAX_DEPTH_EXCEEDED'
| 'IMPORT_NOT_FOUND'
| 'CIRCULAR_IMPORT'
+58 -2
View File
@@ -29,7 +29,19 @@ export type PolicyCursorTarget =
| { kind: 'decisionTableRow'; row: string }
| { kind: 'dataModelName' }
| { kind: 'dataModelProperty'; id: string }
| { kind: 'transformInput' };
| { kind: 'transformInput' }
/** A data model property's `feature.expr` (`id` is the property id). */
| { kind: 'featureExpr'; id: string }
/** A data model property's `outcome.expr` (`id` is the property id). */
| { kind: 'outcomeExpr'; id: string }
/** A data model property's per-event `compute`. */
| { kind: 'computeExpr'; id: string }
/** The request path given to a model input, `model.inputs[input]`. */
| { kind: 'modelInput'; id: string; input: string }
/** A model's `model.when` condition. */
| { kind: 'modelWhen'; id: string }
| { kind: 'modelRequest'; id: string }
| { kind: 'modelResponse'; id: string };
/**
* How an entity field came into existence — declared by a DataModel
@@ -38,11 +50,35 @@ export type PolicyCursorTarget =
* through filter / index / slice) carry `instanceOf`.
*/
export type PolicyFieldOrigin =
| { origin: 'schema'; source: string; fieldKind: PolicyFieldKindInfo }
| {
origin: 'schema';
source: string;
fieldKind: PolicyFieldKindInfo;
/** The type as written when checked as another: `integer`, `decimal`, `timestamp`, `object`, `any`. */
exactType?: string;
/** Supplied by the host rather than the request. */
supply?: PolicyFieldSupply;
}
| { origin: 'computed'; writtenBy: PolicyPropertyWriter; instanceOf?: PolicyInstanceOf };
/**
* How the host supplies a field. A feature with windows is one field per
* window: `txn_count` over `1h` is the field `txn_count_1h` with
* `base: 'txn_count'`, `window: '1h'`. A feature without `default` is
* nullable (unknown or not covered). An outcome is known only after the
* decision: computed offline, never in a request, never read by rules
* (always nullable); `maturity` is in days (`30d`): when a decision is old
* enough to trust a "no" (the answer itself is never hidden).
*/
export type PolicyFieldSupply =
| { kind: 'feature'; base: string; expr: string; window?: string; default?: unknown }
| { kind: 'outcome'; expr?: string; maturity?: string }
| { kind: 'compute'; expr: string }
| { kind: 'model'; datasource?: string }
| { kind: 'members'; by: 'key' | 'events' };
export type PolicyDiagnosticCode =
| 'UNDEFINED_VARIABLE'
| 'TYPE_MISMATCH'
| 'NULLABLE_CONDITION'
| 'INVALID_EXPRESSION'
| 'PARSE_ERROR'
| 'MISSING_DEFAULT_BRANCH'
@@ -60,6 +96,13 @@ export type PolicyDiagnosticCode =
| 'DUPLICATE_PROPERTY'
| 'DUPLICATE_ENUM_VALUE'
| 'INVALID_NAME'
| 'INVALID_RELATIONSHIP'
| 'INVALID_DURATION'
| 'DEPRECATED_TYPE'
| 'FEATURE_SHAPE'
| 'IGNORED_ATTRIBUTE'
| 'INVALID_OUTCOME'
| 'OUTCOME_READ'
| 'MAX_DEPTH_EXCEEDED'
| 'IMPORT_NOT_FOUND'
| 'CIRCULAR_IMPORT'
@@ -402,6 +445,7 @@ export declare class Workspace {
setPolicy(path: string, document: any): void
removePath(path: string): boolean
isGraph(path: string): boolean
endpoint(path: string): 'graph' | 'policy' | null
uncheckedNodes(path: string): Array<string>
paths(): Array<string>
changesSince(cursor: number): PolicyChanges
@@ -422,6 +466,8 @@ export declare class Workspace {
references(target: any, origin?: string | undefined | null): PolicyReferenceSite[]
search(query: string, limit?: number | undefined | null): PolicySearchHit[]
inputSkeleton(req: PolicyScopeRequest): unknown
requestSchema(req: PolicyScopeRequest, audience: 'contract' | 'evaluated'): Record<string, unknown>
responseSchema(req: PolicyScopeRequest): Record<string, unknown>
dependencies(target: string, document?: string | undefined | null): PolicyDependencyNode
evaluate(req: PolicyEvaluateRequest): PolicyEvaluationResult
enhanceTrace(req: PolicyEvaluateRequest): PolicyEvaluationResult
@@ -589,6 +635,16 @@ export interface PolicyGuardedProperty {
export interface PolicyInputProperty {
path: string
resolvedType: PolicyVariableType
/** The caller may leave it out: it is optional or has a default. */
optional: boolean
/** Who supplies it: the request, or the host (features, calls, entities read from the store). */
suppliedBy: 'request' | 'host'
/** Filled in when the caller leaves it out. */
default?: any
/** A reference: the entity it names (the engine reads the record; a host that fills records in from ids can take the id). */
reference?: string
/** A relationship: its records' reference fields, each with the entity it names. */
recordReferences?: Record<string, string>
}
export interface PolicyInspectResult {
+53
View File
@@ -142,6 +142,19 @@ pub struct PolicyInputProperty {
pub path: String,
#[napi(ts_type = "PolicyVariableType")]
pub resolved_type: Value,
/// The caller may leave it out: it is optional or has a default.
pub optional: bool,
/// Who supplies it: the request, or the host (features, calls, entities read from the store).
#[napi(ts_type = "'request' | 'host'")]
pub supplied_by: String,
/// Filled in when the caller leaves it out.
pub default: Option<Value>,
/// A reference: the entity it names (the engine reads the record; a host
/// that fills records in from ids can take the id).
pub reference: Option<String>,
/// A relationship: its records' reference fields, each with the entity it names.
#[napi(ts_type = "Record<string, string>")]
pub record_references: Option<Value>,
}
#[napi(object)]
@@ -612,6 +625,14 @@ impl Workspace {
self.inner.is_graph(&path)
}
#[napi(ts_return_type = "'graph' | 'policy' | null")]
pub fn endpoint(&self, path: String) -> Option<String> {
self.inner.endpoint(&path).map(|kind| match kind {
workspace::EndpointKind::Graph => "graph".to_string(),
workspace::EndpointKind::Policy => "policy".to_string(),
})
}
#[napi]
pub fn unchecked_nodes(&self, env: Env, path: String) -> napi::Result<Vec<String>> {
self.ensure_function_types(&env)?;
@@ -780,6 +801,16 @@ impl Workspace {
.map(|p| PolicyInputProperty {
path: p.path.to_string(),
resolved_type: variable_type_to_json(&p.resolved_type),
optional: p.optional,
supplied_by: match p.supplied_by {
zen_engine::policy::SuppliedBy::Host => "host".to_string(),
zen_engine::policy::SuppliedBy::Request => "request".to_string(),
},
default: p.default,
reference: p.reference.map(|target| target.to_string()),
record_references: (!p.record_references.is_empty()).then(|| {
serde_json::to_value(&p.record_references).unwrap_or_default()
}),
})
.collect())
}
@@ -926,6 +957,28 @@ impl Workspace {
Ok(self.inner.input_skeleton(&inner))
}
#[napi(
ts_args_type = "req: PolicyScopeRequest, audience: 'contract' | 'evaluated'",
ts_return_type = "Record<string, unknown>"
)]
pub fn request_schema(
&self,
env: Env,
req: PolicyScopeRequest,
audience: String,
) -> napi::Result<Value> {
self.ensure_function_types(&env)?;
let audience: workspace::SchemaAudience = serde_json::from_value(Value::String(audience))
.map_err(|e| anyhow!("Invalid audience: {e}"))?;
Ok(self.inner.request_schema(&req.into(), audience))
}
#[napi(ts_return_type = "Record<string, unknown>")]
pub fn response_schema(&self, env: Env, req: PolicyScopeRequest) -> napi::Result<Value> {
self.ensure_function_types(&env)?;
Ok(self.inner.response_schema(&req.into()))
}
#[napi(ts_return_type = "PolicyDependencyNode")]
pub fn dependencies(
&self,
+2
View File
@@ -29,6 +29,7 @@ tokio = { workspace = true, features = ["sync", "time"] }
rquickjs = { version = "0.10", features = ["macro", "loader", "rust-alloc", "futures", "either", "properties"] }
zen-types = { path = "../types", version = "2.1.2" }
zen-expression = { path = "../expression", version = "2.1.2" }
bumpalo = { workspace = true }
zen-tmpl = { path = "../template", version = "2.1.2" }
nohash-hasher = { workspace = true }
downcast-rs = { version = "2.0", features = ["std", "sync"] }
@@ -69,6 +70,7 @@ name = "engine"
[features]
default = []
driver = []
data = []
bindgen = ["rquickjs/bindgen"]
arbitrary_precision = ["serde_json/arbitrary_precision", "zen-expression/arbitrary_precision", "zen-types/arbitrary_precision", "zen-tmpl/arbitrary_precision"]
+21
View File
@@ -255,6 +255,27 @@ impl NullableOperand {
.collect()
}
/// A type error only because an operand may be null (`number?` and
/// `number` under `/` or `>`): where null in gives null out, as in the
/// feature store's derived expressions, not an error.
pub(crate) fn null_propagates(diagnostic: &Diagnostic) -> bool {
if diagnostic.code != DiagnosticCode::TypeMismatch {
return false;
}
let Some((operator, left, right)) = Self::parse_message(&diagnostic.message) else {
return false;
};
let nullable = left.ends_with('?') || right.ends_with('?');
let (left, right) = (left.trim_end_matches('?'), right.trim_end_matches('?'));
let numeric = matches!(operator.as_str(), "+" | "-" | "*" | "/" | "%" | "^");
let ordered = matches!(operator.as_str(), ">" | "<" | ">=" | "<=");
nullable
&& left == right
&& ((numeric && left == "number")
|| (ordered && matches!(left, "number" | "date"))
|| (operator == "+" && left == "string"))
}
fn parse_message(message: &str) -> Option<(String, String, String)> {
let rest = message.strip_prefix("Operator `")?;
let parts: Vec<&str> = rest.split('`').collect();
+41 -1
View File
@@ -48,17 +48,28 @@ pub struct ColumnarOutput<'a> {
pub errors: Vec<Option<Rc<EvaluationError>>>,
pub typed: usize,
pub laned: usize,
/// Rows decided one at a time (the rest as columns).
pub hosted: usize,
/// Rows read whole: their value as decided, where columns drop part.
pub(crate) exact: Vec<Option<Variable>>,
}
impl ColumnarOutput<'_> {
impl<'a> ColumnarOutput<'a> {
pub(crate) fn from_results(results: Vec<Result<crate::DecisionGraphResponse, Box<EvaluationError>>>) -> Self {
let rows = results.len();
let mut paths: Vec<Arc<str>> = Vec::new();
let mut values: Vec<Vec<Variable>> = Vec::new();
let mut errors = Vec::with_capacity(rows);
let mut exact: Vec<Option<Variable>> = Vec::new();
for (row, result) in results.into_iter().enumerate() {
match result {
Ok(response) => {
if crate::compiled::shred::Shredder::lossy(&response.result) {
if exact.is_empty() {
exact = vec![None; rows];
}
exact[row] = Some(response.result.clone());
}
let mut entries = Vec::new();
CompiledGraph::flatten(&response.result, "", &mut entries);
for (path, value) in entries {
@@ -87,10 +98,39 @@ impl ColumnarOutput<'_> {
errors,
typed: 0,
laned: 0,
hosted: rows,
exact,
}
}
/// A policy's columnar output as a document's: the same columns, each
/// failure as the engine's error.
pub(crate) fn from_policy(output: crate::compiled::policy::PolicyColumnarOutput<'a>) -> Self {
ColumnarOutput {
rows: output.rows,
columns: output.columns,
errors: output
.errors
.into_iter()
.map(|error| error.map(|error| Rc::new(EvaluationError::Policy(error))))
.collect(),
typed: output.typed,
laned: output.laned,
hosted: output.hosted,
exact: output.exact,
}
}
/// The row's value kept whole, where its columns can't say it (a
/// property written as null, an empty object): read it, not them.
pub fn whole(&self, row: usize) -> Option<&Variable> {
self.exact.get(row).and_then(Option::as_ref)
}
pub fn row(&self, row: usize) -> Variable {
if let Some(Some(value)) = self.exact.get(row) {
return value.clone();
}
let object = Variable::empty_object();
for (path, column) in &self.columns {
let value = column.get(row);
@@ -126,6 +126,8 @@ impl<'a> Run<'_, 'a> {
errors: std::mem::take(&mut store.errors),
typed: store.counts.0,
laned: store.counts.1,
hosted: 0,
exact: Vec::new(),
}
}
}
+15 -1
View File
@@ -31,7 +31,21 @@ impl CompiledGraph {
return;
};
let data = match step.kind {
Kind::Input => Data::plain(rows.clone(), rows.iter().map(|&r| inputs[r].clone()).collect()),
Kind::Input => {
let mut values: Vec<Variable> = rows.iter().map(|&r| inputs[r].clone()).collect();
if let Some(request) = Self::request(step, content, extensions).await {
for (i, value) in values.iter_mut().enumerate() {
match request.clone().and_then(|prepared| prepared.prepare(value)) {
Ok(prepared) => *value = prepared,
Err(message) => {
Self::fail(state, rows[i], &step.node, message);
*value = Variable::Null;
}
}
}
}
Data::plain(rows.clone(), values.into())
}
_ => Self::input_of(state, &event.parents, rows),
};
let (nodes, extra) = self.node_inputs(step, state, &event.visible, rows, with_nodes, step.column_path(rows.len()));
+44 -1
View File
@@ -1,4 +1,5 @@
use crate::decision_graph::graph::DecisionGraph;
use crate::decision_graph::request_entity::RequestPreparation;
use crate::loader::DynamicLoader;
use crate::model::{DecisionNodeKind, GraphContent};
use ahash::HashMap;
@@ -354,12 +355,45 @@ impl CompiledGraph {
}
pub(in crate::compiled::graph) fn columnar_input(step: &Step, content: &GraphContent, extensions: &NodeHandlerExtensions) -> bool {
if Self::entity(step).is_some() {
return false;
}
match Self::validator(step, content, extensions) {
None => !step.schema && Self::unresolved(content, &step.node),
Some((_, schema)) => !DeclaredDates::mentions(&schema),
}
}
fn entity(step: &Step) -> Option<&InputNodeContent> {
match &step.node.kind {
DecisionNodeKind::InputNode { content } if content.target.is_some() => Some(content),
_ => None,
}
}
/// A request typed by an entity (`target`), prepared as a policy's
/// request is: by the graph's preparation, loaded through its imports
/// once. `None` for any other step. Not with a schema too.
pub(in crate::compiled::graph) async fn request(
step: &Step,
content: &GraphContent,
extensions: &NodeHandlerExtensions,
) -> Option<Result<Arc<RequestPreparation>, String>> {
let input = Self::entity(step)?;
if input.schema.is_some() {
return Some(Err(
"the request is typed twice: by a schema and by an entity (`target`); keep one".to_string(),
));
}
let target = input.target.as_ref()?;
Some(
content
.request_preparation
.get_or_load(extensions.loader(), &content.imports, target)
.await,
)
}
pub(in crate::compiled::graph) fn unresolved(content: &GraphContent, node: &DecisionNode) -> bool {
content
.resolved_schemas
@@ -404,10 +438,19 @@ impl CompiledGraph {
if let Some((_, salt)) = &resolved {
base.config.validation_salt = *salt;
}
if let Some(request) = Self::request(step, content, &base.extensions).await {
match request.and_then(|prepared| prepared.prepare(&base.input)) {
Ok(prepared) => base.input = prepared,
Err(message) => return base.error(message),
}
}
match &node.kind {
DecisionNodeKind::InputNode { content } => {
let content = match resolved {
Some((schema, _)) => InputNodeContent { schema: Some(schema) },
Some((schema, _)) => InputNodeContent {
schema: Some(schema),
target: content.target.clone(),
},
None => content.clone(),
};
DecisionGraph::handle(base, content, InputNodeHandler).await
@@ -104,17 +104,22 @@ impl PolicyPlan {
})
}
/// The policy over `original`, as given or `prepared` (see
/// [`super::prepare`]): the prepared columns evaluated, the rows forced
/// (and any row hosted) evaluated as `original`'s rows.
pub(crate) fn evaluate_columns<'a>(
&self,
artifact: &EvalArtifact,
policy_path: &Arc<str>,
goals: &[Arc<str>],
columns: &'a Columns<'a>,
original: &'a Columns<'a>,
prepared: Option<&'a super::prepare::Prepared<'a>>,
) -> PolicyColumnarOutput<'a> {
let columns = prepared.map_or(original, |prepared| &prepared.hydrated);
let rows = columns.rows;
let request = |row: usize| EvaluateRequest {
policy_path: policy_path.clone(),
input: columns.row(row),
input: original.row(row),
goals: goals.to_vec(),
trace: false,
};
@@ -126,25 +131,33 @@ impl PolicyPlan {
let mut errors: Vec<Option<EvaluationError>> = (0..rows).map(|_| None).collect();
let stores: Vec<OnceCell<Variable>> = (0..rows).map(|_| OnceCell::new()).collect();
sheet.entities = self.entities(artifact, &sheet);
sheet.refs = artifact.reference_fields.iter().map(|field| field.path.clone()).collect();
let shared = !artifact.reference_fields.is_empty()
// Prepared references are resolved: read as any other column.
if prepared.is_none() {
sheet.refs = artifact.reference_fields.iter().map(|field| field.path.clone()).collect();
}
let shared = (!artifact.reference_fields.is_empty() && prepared.is_none())
|| self.iterations.iter().enumerate().any(|(block, iteration)| match iteration {
Some((_, path, _)) => !sheet.entities.iter().any(|e| e.path == *path),
None => self.natives[block].is_none() && self.tables[block].is_none(),
});
let mut fallback = vec![false; rows];
let mut erred = false;
let sure = match shared {
true => None,
false => Entity::sure(artifact, columns, &sheet.entities, goals),
let sure = match (shared, prepared) {
(true, _) => None,
(false, Some(prepared)) => artifact.sure_prepared(&prepared.converted, columns, goals),
(false, None) => Entity::sure(artifact, columns, &sheet.entities, goals),
};
sheet.entities.iter().filter_map(|entity| entity.hosted.as_deref()).flatten().for_each(|&row| fallback[row] = true);
if let Some(prepared) = prepared {
prepared.forced.iter().enumerate().filter(|(_, forced)| **forced).for_each(|(row, _)| fallback[row] = true);
}
for row in 0..rows {
if sure.as_ref().is_some_and(|sure| sure[row]) {
if sure.as_ref().is_some_and(|sure| sure[row]) || (prepared.is_some() && fallback[row]) {
continue;
}
let req = request(row);
if artifact.input_schema.convert_dates(&req.input).is_some() {
// Prepared columns hold the row converted: checked here only.
if prepared.is_none() && artifact.input_schema.convert_dates(&req.input).is_some() {
fallback[row] = true;
continue;
}
@@ -226,6 +239,7 @@ impl PolicyPlan {
};
if hosted.is_empty() && owned.iter().all(Option::is_none) {
let columns = sheet.output(&finished);
let exact = sheet.exact(&finished);
return PolicyColumnarOutput {
rows,
columns,
@@ -233,22 +247,25 @@ impl PolicyPlan {
hosted: 0,
typed: counts.0,
laned: counts.1,
exact,
};
}
let requests: Vec<EvaluateRequest> = hosted.iter().map(|&row| request(row)).collect();
let mut shredder = Shredder::new(rows);
for &row in &finished {
match owned.get(row) {
Some(Some(store)) => shredder.visit(store, 0, row),
_ => shredder.visit(&sheet.object(row), 0, row),
Some(Some(store)) => shredder.row(store, row),
// As a row: a written null (which columns drop) kept whole.
_ => shredder.row(&sheet.object(row), row),
}
}
for (&row, result) in hosted.iter().zip(self.evaluate(artifact, &requests)) {
match result {
Ok(result) => shredder.visit(&result.output, 0, row),
Ok(result) => shredder.row(&result.output, row),
Err(error) => errors[row] = Some(error),
}
}
let exact = shredder.exact();
PolicyColumnarOutput {
rows,
columns: Sheet::columns(shredder.finish()),
@@ -256,6 +273,7 @@ impl PolicyPlan {
hosted: hosted.len(),
typed: counts.0,
laned: counts.1,
exact,
}
}
}
@@ -5,12 +5,14 @@ mod host;
mod lane;
mod member;
mod output;
pub(crate) mod prepare;
mod sheet;
mod table;
mod typed;
pub(super) use fuse::Fusions;
pub use output::PolicyColumnarOutput;
pub use prepare::ColumnStore;
use member::Member;
use sheet::{Bind, Sheet, Slot, Units};
use super::schedule::{Demand, End, Event, Segment};
@@ -136,7 +138,11 @@ impl<'s, 'a> Pass<'s, 'a> {
if self.supported(at, block, positions) {
return self.member(at, block, event, positions);
}
if selected || self.sheet.entities[at].cached() {
// An arm of this entity's members chosen here and not yet
// committed: the host, given the entity, would not know it.
let owned = |b: usize| b != block && self.owners[b].is_some() && self.entity_of(b) == Some(at);
let pending = self.members.iter().map(|(b, _)| *b).chain(self.chosen.iter().map(|(b, _)| *b)).any(owned);
if selected || pending || self.sheet.entities[at].cached() {
positions.iter().for_each(|&row| self.fall(row));
return;
}
@@ -12,10 +12,15 @@ pub struct PolicyColumnarOutput<'a> {
pub hosted: usize,
pub typed: usize,
pub laned: usize,
/// Rows read whole: their value as decided, where columns drop part.
pub(crate) exact: Vec<Option<Variable>>,
}
impl PolicyColumnarOutput<'_> {
pub fn row(&self, row: usize) -> Variable {
if let Some(Some(value)) = self.exact.get(row) {
return value.clone();
}
let object = Variable::empty_object();
for (path, column) in &self.columns {
let value = column.get(row);
@@ -32,12 +37,13 @@ impl PolicyColumnarOutput<'_> {
for (row, result) in results.into_iter().enumerate() {
match result {
Ok(result) => {
shredder.visit(&result.output, 0, row);
shredder.row(&result.output, row);
errors.push(None);
}
Err(error) => errors.push(Some(error)),
}
}
let exact = shredder.exact();
PolicyColumnarOutput {
rows,
columns: Sheet::columns(shredder.finish()),
@@ -45,6 +51,7 @@ impl PolicyColumnarOutput<'_> {
hosted: rows,
typed: 0,
laned: 0,
exact,
}
}
}
@@ -0,0 +1,343 @@
//! Columnar input made what each row's evaluation sees once prepared, for
//! every row at once: declared dates converted, missing or null properties
//! given their default, and references replaced by the pool items they name.
//!
//! A row this cannot prepare exactly as the row path would (a date that
//! does not parse, a reference to an item not in its pool, a reference that
//! is null or not a string) is forced onto the row path, which reports or
//! keeps it as it always has.
use bumpalo::Bump;
use typed_arena::Arena;
use zen_expression::lane::{Column, Columns, Dictionary, Values};
use zen_expression::{DateValue, Variable};
use crate::policy::evaluator::EvalArtifact;
use crate::policy::ir::{Property, PropertyTypeIr};
use crate::policy::validator::InputSchema;
/// What prepared columns are made of, held for as long as they (and the
/// output read from them) are.
pub struct ColumnStore<'a> {
bump: Bump,
values: Arena<Vec<Variable>>,
prepared: Arena<Prepared<'a>>,
}
impl Default for ColumnStore<'_> {
fn default() -> Self {
Self {
bump: Bump::new(),
values: Arena::new(),
prepared: Arena::new(),
}
}
}
impl<'a> ColumnStore<'a> {
pub fn new() -> Self {
Self::default()
}
fn values(&'a self, values: Vec<Variable>) -> &'a [Variable] {
self.values.alloc(values).as_slice()
}
fn bits(&'a self, set: impl Iterator<Item = bool>, rows: usize) -> &'a [u64] {
let words = self.bump.alloc_slice_fill_copy(rows.div_ceil(64).max(1), 0u64);
for (row, set) in set.enumerate() {
if set {
words[row / 64] |= 1 << (row % 64);
}
}
words
}
pub(crate) fn keep(&'a self, prepared: Prepared<'a>) -> &'a Prepared<'a> {
self.prepared.alloc(prepared)
}
}
pub(crate) struct Prepared<'a> {
/// Dates converted and defaults filled: what a row is validated as.
pub converted: Columns<'a>,
/// And references replaced by their items: what a row is evaluated as.
pub hydrated: Columns<'a>,
/// Rows left to the row path.
pub forced: Vec<bool>,
}
/// The prepared columns of `columns`, or `None` when their shape is one
/// this does not prepare (the row path then prepares every row).
pub(crate) fn prepare<'a>(artifact: &EvalArtifact, columns: &'a Columns<'a>, store: &'a ColumnStore<'a>) -> Option<Prepared<'a>> {
let schema = &artifact.input_schema;
if schema.converts_globals() {
return None;
}
let rows = columns.rows;
let mut forced = vec![false; rows];
let mut converted = Columns::new(rows);
for (path, column) in &columns.columns {
let column = match path.split_once('.') {
None if schema.is_pool(path) => pool(schema, path, column, store, &mut forced)?,
None if schema.is_root(path) && schema.is_dated(path) => return None,
None => *column,
Some((root, rest)) if schema.is_root(root) => match schema.is_dated(root) {
false => *column,
true if rest.contains('.') => return None,
true => match schema.model(root)?.properties.iter().find(|p| p.name.as_ref() == rest) {
None => *column,
Some(property) => property_column(schema, property, column, store, &mut forced, |row| row)?,
},
},
Some((root, _)) if schema.is_pool(root) => return None,
Some(_) => *column,
};
converted = converted.column(path, column);
}
defaults(schema, &mut converted, store);
let mut hydrated = converted.clone();
for field in &artifact.reference_fields {
if field.array {
return None;
}
hydrated = hydrate(&hydrated, &field.path, &field.target, store, &mut forced)?;
}
Some(Prepared {
converted,
hydrated,
forced,
})
}
/// A root's property column as converted: dates parsed (a row whose date
/// does not parse forced), other kinds as given. `row_of` maps a value's
/// index to its row (an item's to the row of its pool).
fn property_column<'a>(
schema: &InputSchema,
property: &Property,
column: &Column<'a>,
store: &'a ColumnStore<'a>,
forced: &mut [bool],
row_of: impl Fn(usize) -> usize,
) -> Option<Column<'a>> {
match (&property.kind, property.array) {
(PropertyTypeIr::Date, false) => {
let values = (0..column.len())
.map(|at| match column.variable(at) {
Variable::Null => Variable::Null,
// As the row path: parsed, else kept (an empty text is
// a valid date left as is; any other fails there).
Variable::String(text) => DateValue::from_text(&text).unwrap_or_else(|| {
if !text.is_empty() {
forced[row_of(at)] = true;
}
Variable::String(text)
}),
other => {
forced[row_of(at)] = true;
other
}
})
.collect();
Some(Column {
values: Values::Any(store.values(values)),
validity: column.validity,
})
}
(PropertyTypeIr::Date, true) => None,
(PropertyTypeIr::Relationship { target }, _) if schema.is_dated(target) => None,
_ => Some(*column),
}
}
/// A pool (a list of items per row) with its items converted and their
/// defaults filled.
fn pool<'a>(schema: &InputSchema, target: &str, column: &Column<'a>, store: &'a ColumnStore<'a>, forced: &mut [bool]) -> Option<Column<'a>> {
if !schema.is_dated(target) {
return Some(*column);
}
let Values::List { offsets, child } = column.values else {
return None;
};
let item = child.column();
let Values::Struct { fields, len } = item.values else {
return None;
};
let model = schema.model(target)?;
// Each item's row, for the rows a conversion forces.
let mut owner = vec![0usize; len];
for row in 0..column.len() {
let (a, b) = (offsets[row].max(0) as usize, offsets[row + 1].max(0) as usize);
owner[a.min(len)..b.min(len)].iter_mut().for_each(|o| *o = row);
}
let mut converted: Vec<(&'a str, Column<'a>)> = Vec::with_capacity(fields.len());
for (name, field) in fields {
let field = match model.properties.iter().find(|p| p.name.as_ref() == *name) {
Some(property) => property_column(schema, property, field, store, forced, |at| owner[at])?,
None => *field,
};
converted.push((name, field));
}
for property in schema.defaults_of(target) {
let default = schema.default_value(property)?;
match converted.iter_mut().find(|(name, _)| *name == property.name.as_ref()) {
Some((_, field)) => *field = filled(field, len, &default, None, store),
None => {
let name = store.bump.alloc_str(&property.name);
let values = vec![default; len];
converted.push((name, Column::new(Values::Any(store.values(values)))));
}
}
}
let fields = store.bump.alloc_slice_copy(&converted);
let item = store.bump.alloc(Column {
values: Values::Struct { fields, len },
validity: item.validity,
});
Some(Column {
values: Values::List {
offsets,
child: Dictionary::Column(item),
},
validity: column.validity,
})
}
/// `column` with its missing (where `present`) and null values set to
/// `default`.
fn filled<'a>(column: &Column<'a>, len: usize, default: &Variable, present: Option<&[bool]>, store: &'a ColumnStore<'a>) -> Column<'a> {
let values = (0..len)
.map(|at| match column.variable(at) {
Variable::Null if present.is_none_or(|p| p[at]) => default.clone(),
value => value,
})
.collect();
let validity = present.map(|present| {
let bits = store.bits((0..len).map(|at| present[at] || column.valid(at)), len);
(bits, 0)
});
Column {
values: Values::Any(store.values(values)),
validity,
}
}
/// Each root entity's properties with a default, filled where the row has
/// the entity and the property is missing or null.
fn defaults<'a>(schema: &InputSchema, columns: &mut Columns<'a>, store: &'a ColumnStore<'a>) {
let rows = columns.rows;
let mut roots: Vec<&'a str> = columns
.columns
.iter()
.map(|(path, _)| path.split_once('.').map_or(*path, |(root, _)| root))
.filter(|root| schema.is_root(root))
.collect();
roots.sort_unstable();
roots.dedup();
for root in roots {
let properties = schema.defaults_of(root);
if properties.is_empty() {
continue;
}
// A row has the entity when a column under it is given there.
let present: Vec<bool> = (0..rows)
.map(|row| {
columns.columns.iter().any(|(path, column)| {
path.strip_prefix(root).is_some_and(|rest| rest.is_empty() || rest.starts_with('.')) && column.valid(row)
})
})
.collect();
for property in properties {
let Some(default) = schema.default_value(property) else {
continue;
};
let path = store.bump.alloc_str(&format!("{root}.{}", property.name));
let given = columns.find(path).map(|at| columns.columns[at].1);
let column = match given {
Some(column) => filled(&column, rows, &default, Some(&present), store),
None => filled(&Column::new(Values::Any(store.values(vec![Variable::Null; rows]))), rows, &default, Some(&present), store),
};
match columns.find(path) {
Some(at) => columns.columns[at].1 = column,
None => columns.columns.push((path, column)),
}
}
}
}
/// The columns with the reference at `path` replaced by the fields of the
/// `target` pool's item it names (its `id`; the last such item, as the row
/// path indexes them). A row whose reference is given but not found, not
/// a string, or null is forced.
fn hydrate<'a>(columns: &Columns<'a>, path: &str, target: &str, store: &'a ColumnStore<'a>, forced: &mut [bool]) -> Option<Columns<'a>> {
let under = |p: &str| p.strip_prefix(path).is_some_and(|rest| rest.starts_with('.'));
if columns.columns.iter().any(|(p, _)| under(p)) {
return None;
}
let Some(at) = columns.find(path) else {
// No row gives the reference.
return Some(columns.clone());
};
let key = columns.columns[at].1;
let pool = columns.find(target).map(|at| columns.columns[at].1);
let items = pool.and_then(|pool| match pool.values {
Values::List { child, .. } => match child {
Dictionary::Column(item) => match item.values {
Values::Struct { fields, .. } => Some((pool, item, fields)),
_ => None,
},
_ => None,
},
_ => None,
});
if pool.is_some() && items.is_none() {
return None;
}
let rows = columns.rows;
let mut codes = vec![-1i32; rows];
for row in 0..rows {
// No reference: nothing to replace (nor to find).
if !key.valid(row) {
continue;
}
let found = match (key.variable(row), items) {
(Variable::String(id), Some((pool, item, fields))) => {
let ids = fields.iter().find(|(name, _)| *name == "id").map(|(_, c)| c);
pool.range(row).and_then(|(a, b)| {
(a..b).rev().find(|&i| item.valid(i) && ids.is_some_and(|ids| ids.text(i) == Some(id.as_str())))
})
}
_ => None,
};
match found.and_then(|i| i32::try_from(i).ok()) {
Some(code) => codes[row] = code,
None => forced[row] = true,
}
}
let mut out = Columns::new(rows);
for (i, (p, column)) in columns.columns.iter().enumerate() {
if i != at {
out = out.column(p, *column);
}
}
let Some((_, _, fields)) = items else {
return Some(out);
};
let keys = store.bump.alloc_slice_copy(&codes);
for (name, field) in fields.iter() {
let bits = store.bits(codes.iter().map(|&code| code >= 0 && field.valid(code as usize)), rows);
let name = store.bump.alloc_str(&format!("{path}.{name}"));
out = out.column(
name,
Column {
values: Values::Dict {
keys,
values: Dictionary::Column(field),
},
validity: Some((bits, 0)),
},
);
}
Some(out)
}
@@ -192,6 +192,31 @@ impl<'a> Sheet<'a> {
object
}
/// The rows a column can't say whole: a property written as null
/// (columns read null as absent), each then read as its object.
pub(super) fn exact(&self, finished: &[usize]) -> Vec<Option<Variable>> {
let written_null = |row: usize| {
self.order.iter().any(|&index| {
let entry = &self.entries[index];
!entry.dead
&& !entry.input
&& self.active(index).is_none()
&& Self::present(entry, row)
&& matches!(entry.leaf.get(row), Variable::Null)
})
};
let mut exact: Vec<Option<Variable>> = Vec::new();
for &row in finished {
if written_null(row) {
if exact.is_empty() {
exact = vec![None; self.rows];
}
exact[row] = Some(self.object(row));
}
}
exact
}
pub(super) fn write(&mut self, path: Arc<str>, leaf: Leaf<'a>, positions: &[usize]) {
let present: Option<Rc<[u64]>> = match positions.len() == self.rows {
true => None,
+2 -2
View File
@@ -1,11 +1,11 @@
mod columnar;
pub(crate) mod columnar;
mod entity;
mod host;
mod schedule;
mod traced;
pub use columnar::PolicyColumnarOutput;
pub use columnar::{ColumnStore, PolicyColumnarOutput};
pub(crate) use host::Host;
use crate::policy::blocks::{AssertionIr, BlockKind, MatchIr, MatchSelection};
+33
View File
@@ -46,6 +46,9 @@ pub(crate) struct Shredder {
rows: usize,
nodes: Vec<Trie>,
columns: Vec<(Arc<str>, Vec<Variable>, Vec<u64>)>,
/// A row's value as given, when its columns can't say it all (a
/// property that is null, an empty object): a row reads it whole.
exact: Vec<Option<Variable>>,
}
pub(crate) struct Listing<'a> {
@@ -70,9 +73,39 @@ impl Shredder {
column: None,
}],
columns: Vec::new(),
exact: Vec::new(),
}
}
/// A row's whole value: its columns, and the value itself when they
/// would drop part of it.
pub(crate) fn row(&mut self, value: &Variable, row: usize) {
if Self::lossy(value) {
if self.exact.is_empty() {
self.exact = vec![None; self.rows];
}
self.exact[row] = Some(value.clone());
}
self.visit(value, 0, row);
}
/// Whether an object holds a null or an empty object (columns keep
/// neither); lists are kept whole, so what they hold is kept.
pub(crate) fn lossy(value: &Variable) -> bool {
match value {
Variable::Object(map) => {
let map = map.borrow();
map.is_empty() || map.iter().any(|(_, child)| matches!(child, Variable::Null) || Self::lossy(child))
}
_ => false,
}
}
/// The rows' values kept whole (empty when none was).
pub(crate) fn exact(&mut self) -> Vec<Option<Variable>> {
std::mem::take(&mut self.exact)
}
fn child(&mut self, node: usize, key: &str) -> usize {
if let Some((_, at)) = self.nodes[node].children.iter().find(|(k, _)| k.as_ref() == key) {
return *at;
+742
View File
@@ -0,0 +1,742 @@
use std::collections::BTreeMap;
use rust_decimal::Decimal;
use serde::Deserialize;
use serde_json::Value;
use zen_expression::lane::{LaneProgram, LaneRunner, Session};
use zen_expression::{ExpressionKind, IsolateError, Scope, Variable};
/// Declarative, mergeable aggregation over impact records — the SQL
/// `GROUP BY` + `FILTER (WHERE …)` vocabulary compiled to ZEN expressions.
/// Every metric is distributive or algebraic, so shard states merge exactly;
/// holistic metrics (quantiles, distinct) are deliberately out of scope.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AggregateSpec {
#[serde(default)]
pub facts: BTreeMap<String, String>,
pub metrics: BTreeMap<String, MetricSpec>,
}
/// One raw metric declaration — classified by which field is present.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MetricSpec {
/// `true` counts every record; an expression counts strict-`true` results.
#[serde(default)]
pub count: Option<Value>,
#[serde(default)]
pub sum: Option<String>,
#[serde(default)]
pub min: Option<String>,
#[serde(default)]
pub max: Option<String>,
/// Group key expression; `metrics` nest one level (no groups in groups).
#[serde(default)]
pub by: Option<String>,
#[serde(default)]
pub metrics: Option<BTreeMap<String, MetricSpec>>,
/// Bounded exemplar collection: keeps the first N matching records
/// (by record index, exact across shard merges).
#[serde(default)]
pub sample: Option<usize>,
/// Sample payload expression (an object literal, usually).
#[serde(default)]
pub value: Option<String>,
/// Ranked samples: keep the N records with the LARGEST value of this
/// expression (numeric), instead of the first N. Mergeable exactly.
#[serde(default)]
pub rank_by: Option<String>,
/// SQL FILTER clause: the metric sees only records where this is `true`.
#[serde(default)]
pub when: Option<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum AggregateError {
#[error("metric '{name}': {message}")]
Spec { name: String, message: String },
#[error("expression '{source_text}' failed to compile: {message}")]
Compile {
source_text: String,
message: String,
},
#[error("state does not match the spec: {0}")]
State(String),
}
enum CompiledKind {
Count(Option<LaneProgram>),
Sum(LaneProgram),
Min(LaneProgram),
Max(LaneProgram),
Group {
by: LaneProgram,
metrics: Vec<CompiledMetric>,
},
Sample {
limit: usize,
value: LaneProgram,
rank_by: Option<LaneProgram>,
},
}
struct CompiledMetric {
name: String,
when: Option<LaneProgram>,
kind: CompiledKind,
}
pub struct Aggregator {
facts: Vec<(String, LaneProgram)>,
metrics: Vec<CompiledMetric>,
state: Vec<MetricState>,
index: u64,
/// One lane runner reused across every expression evaluation (its frames
/// are kept), at ~19 expressions/record.
runner: LaneRunner,
}
#[derive(Debug, Clone)]
enum MetricState {
Count(u64),
Sum(Decimal),
Min(Option<Decimal>),
Max(Option<Decimal>),
Group(BTreeMap<String, Vec<MetricState>>),
/// (order key, payload): record index for first-N samples, negated rank
/// for ranked ones — ascending sort works for both.
Sample(Vec<(Decimal, Variable)>),
}
fn compile(source: &str) -> Result<LaneProgram, AggregateError> {
LaneProgram::compile_exact(source, ExpressionKind::Standard).map_err(|e| AggregateError::Compile {
source_text: source.to_string(),
message: e.to_string(),
})
}
fn compile_metric(
name: &str,
spec: &MetricSpec,
nested: bool,
) -> Result<CompiledMetric, AggregateError> {
let err = |message: &str| AggregateError::Spec {
name: name.to_string(),
message: message.to_string(),
};
let when = spec.when.as_deref().map(compile).transpose()?;
let kind = if let Some(count) = &spec.count {
match count {
Value::Bool(true) => CompiledKind::Count(None),
Value::String(expression) => CompiledKind::Count(Some(compile(expression)?)),
_ => return Err(err("count must be true or an expression")),
}
} else if let Some(sum) = &spec.sum {
CompiledKind::Sum(compile(sum)?)
} else if let Some(min) = &spec.min {
CompiledKind::Min(compile(min)?)
} else if let Some(max) = &spec.max {
CompiledKind::Max(compile(max)?)
} else if let Some(by) = &spec.by {
if nested {
return Err(err("groups cannot nest"));
}
let Some(metric_specs) = &spec.metrics else {
return Err(err("a group needs `metrics`"));
};
let mut metrics = Vec::with_capacity(metric_specs.len());
for (child_name, child) in metric_specs {
metrics.push(compile_metric(child_name, child, true)?);
}
CompiledKind::Group {
by: compile(by)?,
metrics,
}
} else if let Some(limit) = spec.sample {
let Some(value) = &spec.value else {
return Err(err("a sample needs `value`"));
};
CompiledKind::Sample {
limit,
value: compile(value)?,
rank_by: spec.rank_by.as_deref().map(compile).transpose()?,
}
} else {
return Err(err("declare one of count/sum/min/max/by/sample"));
};
Ok(CompiledMetric {
name: name.to_string(),
when,
kind,
})
}
fn with_facts(
facts: &[(String, LaneProgram)],
context: Variable,
runner: &mut LaneRunner,
) -> Variable {
if facts.is_empty() {
return context;
}
let augmented = context.depth_clone(1);
if let Variable::Object(object) = &augmented {
let mut computed = Vec::with_capacity(facts.len());
for (name, expression) in facts {
if let Ok(value) = eval(expression, &augmented, runner) {
computed.push((name.as_str(), value));
}
}
let mut borrowed = object.borrow_mut();
for (name, value) in computed {
borrowed.insert(name.into(), value);
}
}
augmented
}
fn initial_state(metric: &CompiledMetric) -> MetricState {
match &metric.kind {
CompiledKind::Count(_) => MetricState::Count(0),
CompiledKind::Sum(_) => MetricState::Sum(Decimal::ZERO),
CompiledKind::Min(_) => MetricState::Min(None),
CompiledKind::Max(_) => MetricState::Max(None),
CompiledKind::Group { .. } => MetricState::Group(BTreeMap::new()),
CompiledKind::Sample { .. } => MetricState::Sample(Vec::new()),
}
}
fn is_true(value: Result<Variable, IsolateError>) -> bool {
matches!(value, Ok(Variable::Bool(true)))
}
fn eval(
expression: &LaneProgram,
context: &Variable,
runner: &mut LaneRunner,
) -> Result<Variable, IsolateError> {
runner.evaluate_one(expression, &Scope::new(context.clone()))
}
fn as_decimal(value: Result<Variable, IsolateError>) -> Option<Decimal> {
match value {
Ok(Variable::Number(number)) => Some(number),
_ => None,
}
}
fn group_key(value: Result<Variable, IsolateError>) -> Option<String> {
match value {
Ok(Variable::String(text)) => Some(text.to_string()),
Ok(Variable::Number(number)) => Some(number.to_string()),
Ok(Variable::Bool(flag)) => Some(flag.to_string()),
_ => None,
}
}
fn apply(
metric: &CompiledMetric,
state: &mut MetricState,
context: &Variable,
index: u64,
runner: &mut LaneRunner,
) {
if let Some(when) = &metric.when {
if !is_true(eval(when, context, runner)) {
return;
}
}
match (&metric.kind, state) {
(CompiledKind::Count(condition), MetricState::Count(count)) => {
let matched = match condition {
None => true,
Some(expression) => is_true(eval(expression, context, runner)),
};
if matched {
*count += 1;
}
}
(CompiledKind::Sum(expression), MetricState::Sum(total)) => {
if let Some(number) = as_decimal(eval(expression, context, runner)) {
*total += number;
}
}
(CompiledKind::Min(expression), MetricState::Min(slot)) => {
if let Some(number) = as_decimal(eval(expression, context, runner)) {
*slot = Some(slot.map_or(number, |current| current.min(number)));
}
}
(CompiledKind::Max(expression), MetricState::Max(slot)) => {
if let Some(number) = as_decimal(eval(expression, context, runner)) {
*slot = Some(slot.map_or(number, |current| current.max(number)));
}
}
(CompiledKind::Group { by, metrics }, MetricState::Group(groups)) => {
let Some(key) = group_key(eval(by, context, runner)) else {
return;
};
let states = groups
.entry(key)
.or_insert_with(|| metrics.iter().map(initial_state).collect());
for (child, child_state) in metrics.iter().zip(states.iter_mut()) {
apply(child, child_state, context, index, runner);
}
}
(
CompiledKind::Sample {
limit,
value,
rank_by,
},
MetricState::Sample(items),
) => {
let key = match rank_by {
None => Decimal::from(index),
Some(expression) => match as_decimal(eval(expression, context, runner)) {
Some(rank) => -rank,
None => return,
},
};
if items.len() >= *limit {
let Some((worst, _)) = items.last() else {
return;
};
if key >= *worst {
return;
}
}
if let Ok(payload) = eval(value, context, runner) {
items.push((key, payload));
items.sort_by(|a, b| a.0.cmp(&b.0));
items.truncate(*limit);
}
}
_ => {}
}
}
fn merge_state(metric: &CompiledMetric, into: &mut MetricState, from: MetricState) {
match (into, from) {
(MetricState::Count(a), MetricState::Count(b)) => *a += b,
(MetricState::Sum(a), MetricState::Sum(b)) => *a += b,
(MetricState::Min(a), MetricState::Min(b)) => {
*a = match (*a, b) {
(Some(x), Some(y)) => Some(x.min(y)),
(x, y) => x.or(y),
}
}
(MetricState::Max(a), MetricState::Max(b)) => {
*a = match (*a, b) {
(Some(x), Some(y)) => Some(x.max(y)),
(x, y) => x.or(y),
}
}
(MetricState::Group(a), MetricState::Group(b)) => {
let CompiledKind::Group { metrics, .. } = &metric.kind else {
return;
};
for (key, states) in b {
match a.remove(&key) {
None => {
a.insert(key, states);
}
Some(mut existing) => {
for ((child, into_state), from_state) in
metrics.iter().zip(existing.iter_mut()).zip(states)
{
merge_state(child, into_state, from_state);
}
a.insert(key, existing);
}
}
}
}
(MetricState::Sample(a), MetricState::Sample(b)) => {
let CompiledKind::Sample { limit, .. } = &metric.kind else {
return;
};
a.extend(b);
a.sort_by(|x, y| x.0.cmp(&y.0));
a.truncate(*limit);
}
_ => {}
}
}
fn state_to_value(state: &MetricState) -> Value {
match state {
MetricState::Count(count) => Value::from(*count),
MetricState::Sum(total) => decimal_value(*total),
MetricState::Min(slot) | MetricState::Max(slot) => {
slot.map(decimal_value).unwrap_or(Value::Null)
}
MetricState::Group(groups) => Value::Object(
groups
.iter()
.map(|(key, states)| {
(key.clone(), Value::Array(states.iter().map(state_to_value).collect()))
})
.collect(),
),
MetricState::Sample(items) => Value::Array(
items
.iter()
.map(|(key, value)| serde_json::json!({ "i": key.to_string(), "v": value.to_value() }))
.collect(),
),
}
}
fn decimal_value(number: Decimal) -> Value {
serde_json::from_str::<serde_json::Number>(&number.normalize().to_string())
.map(Value::Number)
.unwrap_or(Value::Null)
}
fn state_from_value(metric: &CompiledMetric, value: Value) -> Result<MetricState, AggregateError> {
let bad = |what: &str| AggregateError::State(format!("metric '{}': {what}", metric.name));
let number = |value: Value, what: &str| -> Result<Decimal, AggregateError> {
value
.as_str()
.map(str::to_string)
.or_else(|| value.as_f64().map(|f| f.to_string()))
.or_else(|| Some(value.to_string()))
.and_then(|text| text.parse::<Decimal>().ok())
.ok_or_else(|| bad(what))
};
Ok(match &metric.kind {
CompiledKind::Count(_) => MetricState::Count(value.as_u64().ok_or_else(|| bad("count"))?),
CompiledKind::Sum(_) => MetricState::Sum(number(value, "sum")?),
CompiledKind::Min(_) => MetricState::Min(match value {
Value::Null => None,
other => Some(number(other, "min")?),
}),
CompiledKind::Max(_) => MetricState::Max(match value {
Value::Null => None,
other => Some(number(other, "max")?),
}),
CompiledKind::Group { metrics, .. } => {
let Value::Object(map) = value else {
return Err(bad("group"));
};
let mut groups = BTreeMap::new();
for (key, entry) in map {
let Value::Array(items) = entry else {
return Err(bad("group entry"));
};
if items.len() != metrics.len() {
return Err(bad("group arity"));
}
let states = metrics
.iter()
.zip(items)
.map(|(child, item)| state_from_value(child, item))
.collect::<Result<Vec<_>, _>>()?;
groups.insert(key, states);
}
MetricState::Group(groups)
}
CompiledKind::Sample { .. } => {
let Value::Array(items) = value else {
return Err(bad("sample"));
};
let mut collected = Vec::with_capacity(items.len());
for item in items {
let key = item
.get("i")
.and_then(|raw| match raw {
Value::String(text) => text.parse::<Decimal>().ok(),
Value::Number(number) => number.to_string().parse::<Decimal>().ok(),
_ => None,
})
.ok_or_else(|| bad("sample key"))?;
let payload = item.get("v").cloned().unwrap_or(Value::Null);
collected.push((key, Variable::from(&payload)));
}
MetricState::Sample(collected)
}
})
}
impl Aggregator {
pub fn compile(spec: &AggregateSpec) -> Result<Self, AggregateError> {
let mut facts = Vec::with_capacity(spec.facts.len());
for (name, source) in &spec.facts {
facts.push((name.clone(), compile(source)?));
}
let mut metrics = Vec::with_capacity(spec.metrics.len());
for (name, metric) in &spec.metrics {
metrics.push(compile_metric(name, metric, false)?);
}
let state = metrics.iter().map(initial_state).collect();
Ok(Self {
facts,
metrics,
state,
index: 0,
runner: LaneRunner::new(),
})
}
/// Records one impact context — `{input, before, after, errors?}` — after
/// augmenting it with the computed facts at top level (facts win on name
/// clashes, mirroring how the canonical filter context shadows).
pub fn record(&mut self, context: Variable) {
let index = self.index;
self.record_at(context, index);
}
/// Like [`Self::record`] with an explicit GLOBAL record index — sharded
/// hosts pass the dataset position so sample ordering merges exactly.
pub fn record_at(&mut self, context: Variable, index: u64) {
let context = with_facts(&self.facts, context, &mut self.runner);
self.index += 1;
for (metric, state) in self.metrics.iter().zip(self.state.iter_mut()) {
apply(metric, state, &context, index, &mut self.runner);
}
}
/// Opaque, additive state — ship it across any boundary and merge exactly.
pub fn state(&self) -> Value {
serde_json::json!({
"index": self.index,
"metrics": self
.metrics
.iter()
.zip(self.state.iter())
.map(|(metric, state)| (metric.name.clone(), state_to_value(state)))
.collect::<serde_json::Map<String, Value>>(),
})
}
pub fn merge_value(&mut self, state: Value) -> Result<(), AggregateError> {
let index = state
.get("index")
.and_then(Value::as_u64)
.ok_or_else(|| AggregateError::State("missing index".to_string()))?;
let Some(Value::Object(map)) = state.get("metrics").cloned().into() else {
return Err(AggregateError::State("missing metrics".to_string()));
};
self.index += index;
for (metric, into) in self.metrics.iter().zip(self.state.iter_mut()) {
let Some(entry) = map.get(&metric.name).cloned() else {
return Err(AggregateError::State(format!(
"missing metric '{}'",
metric.name
)));
};
let from = state_from_value(metric, entry)?;
merge_state(metric, into, from);
}
Ok(())
}
/// The aggregate results as a report-template context: scalars for
/// counts/sums, `[{key, …metrics}]` arrays for groups (key-ordered),
/// index-ordered payload arrays for samples.
pub fn finalize(&self) -> Value {
let mut out = serde_json::Map::new();
out.insert("recordCount".to_string(), Value::from(self.index));
for (metric, state) in self.metrics.iter().zip(self.state.iter()) {
out.insert(metric.name.clone(), finalize_state(metric, state));
}
Value::Object(out)
}
/// Renders a report template against the finalized aggregate: any object
/// of the exact shape `{"$": "expression"}` evaluates in place; every
/// other node passes through untouched. Iteration, arithmetic and string
/// assembly all live in the expressions themselves (`map(bands, {...})`).
pub fn render(&self, template: &Value) -> Value {
render_node(template, &Variable::from(&self.finalize()))
}
}
fn finalize_state(metric: &CompiledMetric, state: &MetricState) -> Value {
match state {
MetricState::Count(count) => Value::from(*count),
MetricState::Sum(total) => decimal_value(*total),
MetricState::Min(slot) | MetricState::Max(slot) => {
slot.map(decimal_value).unwrap_or(Value::Null)
}
MetricState::Group(groups) => {
let CompiledKind::Group { metrics, .. } = &metric.kind else {
return Value::Null;
};
Value::Array(
groups
.iter()
.map(|(key, states)| {
let mut object = serde_json::Map::new();
object.insert("key".to_string(), Value::String(key.clone()));
for (child, child_state) in metrics.iter().zip(states.iter()) {
object.insert(child.name.clone(), finalize_state(child, child_state));
}
Value::Object(object)
})
.collect(),
)
}
MetricState::Sample(items) => {
Value::Array(items.iter().map(|(_, value)| value.to_value()).collect())
}
}
}
fn render_node(template: &Value, context: &Variable) -> Value {
match template {
Value::Object(map) => {
if map.len() == 1 {
if let Some(Value::String(expression)) = map.get("$") {
return Session::with_environment(context.clone())
.run_standard(expression)
.map(|value| value.to_value())
.unwrap_or(Value::Null);
}
}
Value::Object(
map.iter()
.map(|(key, value)| (key.clone(), render_node(value, context)))
.collect(),
)
}
Value::Array(items) => Value::Array(
items
.iter()
.map(|item| render_node(item, context))
.collect(),
),
other => other.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn perf_drilldown() {
let parsed: AggregateSpec = serde_json::from_value(serde_json::json!({
"facts": {
"band": "input.applicant.creditScore >= 760 ? '760+' : input.applicant.creditScore >= 700 ? '700-759' : input.applicant.creditScore >= 660 ? '660-699' : input.applicant.creditScore >= 620 ? '620-659' : 'under 620'",
"approvedBoth": "before.approved == true and after.approved == true",
},
"metrics": {
"total": { "count": true },
"failed": { "count": "errors != null" },
"approvedBefore": { "count": "before.approved == true" },
"approvedAfter": { "count": "after.approved == true" },
"rateSumBefore": { "sum": "before.interestRate", "when": "approvedBoth" },
"rateSumAfter": { "sum": "after.interestRate", "when": "approvedBoth" },
"rateCount": { "count": "approvedBoth" },
"limitBefore": { "sum": "before.creditLimit" },
"limitAfter": { "sum": "after.creditLimit" },
"newlyApproved": { "count": "before.approved != true and after.approved == true" },
"newlyDeclined": { "count": "before.approved == true and after.approved != true" },
"bands": { "by": "band", "metrics": {
"total": { "count": true },
"approvedBefore": { "count": "before.approved == true" },
"approvedAfter": { "count": "after.approved == true" },
"limitBefore": { "sum": "before.creditLimit" },
"limitAfter": { "sum": "after.creditLimit" },
} },
"movers": { "sample": 8, "when": "before.approved != after.approved", "value": "{id: input.evaluationId}" },
},
})).unwrap();
let mut aggregator = Aggregator::compile(&parsed).unwrap();
let contexts: Vec<Variable> = (0..20_000u64).map(|i| Variable::from(&serde_json::json!({
"input": { "evaluationId": format!("e{i}"), "applicant": { "creditScore": 500 + (i % 400) } },
"before": { "approved": i % 4 == 0, "interestRate": 7.49, "creditLimit": if i % 4 == 0 { 5000 } else { 0 } },
"after": { "approved": i % 4 == 0, "interestRate": 7.49, "creditLimit": if i % 4 == 0 { 5000 } else { 0 } },
}))).collect();
let started = std::time::Instant::now();
for context in &contexts {
aggregator.record(context.clone());
}
let elapsed = started.elapsed();
eprintln!(
"record(): {:.2} us/rec over {} records",
elapsed.as_micros() as f64 / contexts.len() as f64,
contexts.len()
);
}
fn spec() -> AggregateSpec {
serde_json::from_value(serde_json::json!({
"facts": {
"band": "input.score >= 700 ? 'high' : 'low'",
"flip": "before.approved != after.approved",
},
"metrics": {
"total": { "count": true },
"approvedAfter": { "count": "after.approved == true" },
"limitAfter": { "sum": "after.limit" },
"bestRate": { "min": "after.rate", "when": "after.approved == true" },
"bands": {
"by": "band",
"metrics": {
"total": { "count": true },
"approvedAfter": { "count": "after.approved == true" },
},
},
"movers": {
"sample": 2,
"when": "flip",
"value": "{id: input.id, after: after.approved}",
},
},
}))
.unwrap()
}
fn record(id: u64, score: i64, before: bool, after: bool, limit: i64, rate: f64) -> Variable {
Variable::from(&serde_json::json!({
"input": { "id": id, "score": score },
"before": { "approved": before },
"after": { "approved": after, "limit": limit, "rate": rate },
}))
}
#[test]
fn aggregates_and_merges() {
let parsed = spec();
let mut a = Aggregator::compile(&parsed).unwrap();
let mut b = Aggregator::compile(&parsed).unwrap();
a.record(record(1, 720, true, true, 5000, 7.5));
a.record(record(2, 650, true, false, 0, 9.0));
b.record_at(record(3, 710, false, true, 3000, 6.5), 2);
b.record_at(record(4, 600, false, false, 0, 0.0), 3);
let mut merged = Aggregator::compile(&parsed).unwrap();
merged.merge_value(a.state()).unwrap();
merged.merge_value(b.state()).unwrap();
let out = merged.finalize();
assert_eq!(out["recordCount"], 4);
assert_eq!(out["total"], Value::from(4u64));
assert_eq!(out["approvedAfter"], Value::from(2u64));
assert_eq!(out["limitAfter"].to_string(), "8000");
assert_eq!(out["bestRate"].to_string(), "6.5");
let bands = out["bands"].as_array().unwrap();
assert_eq!(bands.len(), 2);
assert_eq!(bands[0]["key"], "high");
assert_eq!(bands[0]["total"], Value::from(2u64));
assert_eq!(bands[0]["approvedAfter"], Value::from(2u64));
let movers = out["movers"].as_array().unwrap();
assert_eq!(movers.len(), 2);
assert_eq!(movers[0]["id"], Value::from(2u64));
let report = merged.render(&serde_json::json!({
"summary": { "$": "approvedAfter == 2 ? 'ok' : 'bad'" },
"series": { "$": "map(bands, {label: #.key, value: #.approvedAfter / #.total})" },
"static": "unchanged",
}));
assert_eq!(report["summary"], "ok");
assert_eq!(report["static"], "unchanged");
assert_eq!(report["series"].as_array().unwrap().len(), 2);
}
}
+273
View File
@@ -0,0 +1,273 @@
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use zen_expression::variable::VariableMap;
use zen_expression::Variable;
use crate::decision::Decision;
use crate::engine::{DecisionEngine, EvaluationOptions};
use crate::error::ContentKindError;
use crate::loader::LoaderError;
use crate::EvaluationError;
/// Compares evaluation outcomes between two engines — candidate vs baseline.
/// The engines may differ in loaders, documents and configuration; the
/// comparison itself is engine-agnostic: evaluate both arms per input, compare
/// the result variables structurally, and materialise outputs only when they
/// differ (or fail).
pub struct ImpactAnalysis {
candidate: Arc<DecisionEngine>,
baseline: Arc<DecisionEngine>,
}
#[derive(Debug, thiserror::Error)]
pub enum ImpactError {
#[error("failed to load '{key}': {source}")]
Load { key: String, source: LoaderError },
#[error("'{key}' is not an evaluable graph: {source}")]
ContentKind {
key: String,
source: ContentKindError,
},
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImpactRow {
pub changed: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub before: Option<Variable>,
#[serde(skip_serializing_if = "Option::is_none")]
pub after: Option<Variable>,
/// Carrying mode only: the single shared output of an UNCHANGED row —
/// consumers that aggregate over every record read it as both arms while
/// the payload stays at one copy instead of two.
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Variable>,
#[serde(skip_serializing_if = "Option::is_none")]
pub before_error: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub after_error: Option<serde_json::Value>,
}
impl ImpactRow {
pub fn failed(&self) -> bool {
self.before_error.is_some() || self.after_error.is_some()
}
/// The aggregation context for this row — `{input, changed, before, after,
/// errors?}`. Unchanged carrying rows expose the single shared result as
/// both arms; `changed` is the engine's exact structural comparison (ZEN
/// `!=` does not deep-compare objects, so specs must not recompute it).
pub fn into_aggregate_context(self, input: Variable) -> Variable {
let mut context = VariableMap::new();
context.insert("input".into(), input);
context.insert("changed".into(), Variable::Bool(self.changed));
if self.failed() {
let mut errors = VariableMap::new();
if let Some(error) = &self.before_error {
errors.insert("before".into(), Variable::from(error));
}
if let Some(error) = &self.after_error {
errors.insert("after".into(), Variable::from(error));
}
context.insert("errors".into(), Variable::from_object(errors));
}
let (before, after) = match self.result {
Some(result) => (Some(result.clone()), Some(result)),
None => (self.before, self.after),
};
context.insert("before".into(), before.unwrap_or(Variable::Null));
context.insert("after".into(), after.unwrap_or(Variable::Null));
Variable::from_object(context)
}
}
/// Headline counts over impact rows. `changed` counts rows where both arms
/// succeeded with differing results; rows with any failure count under
/// `failed` instead, so `total = unchanged + changed + failed`. Summaries
/// from separate batches merge additively, which is what makes incremental
/// runs exact rather than approximate.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImpactSummary {
pub total: u64,
pub changed: u64,
pub failed: u64,
pub before_errors: u64,
pub after_errors: u64,
}
impl ImpactSummary {
pub fn record(&mut self, row: &ImpactRow) {
self.total += 1;
if row.failed() {
self.failed += 1;
self.before_errors += u64::from(row.before_error.is_some());
self.after_errors += u64::from(row.after_error.is_some());
} else if row.changed {
self.changed += 1;
}
}
pub fn merge(&mut self, other: &ImpactSummary) {
self.total += other.total;
self.changed += other.changed;
self.failed += other.failed;
self.before_errors += other.before_errors;
self.after_errors += other.after_errors;
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImpactBatch {
pub rows: Vec<ImpactRow>,
pub summary: ImpactSummary,
}
impl ImpactAnalysis {
pub fn new(candidate: Arc<DecisionEngine>, baseline: Arc<DecisionEngine>) -> Self {
Self {
candidate,
baseline,
}
}
/// Resolves both decision handles once — every evaluation in the
/// comparison reuses them, so decision content is parsed per comparison,
/// never per record.
pub async fn compare(
&self,
candidate_key: &str,
baseline_key: &str,
) -> Result<ImpactComparison, ImpactError> {
let candidate = resolve(&self.candidate, candidate_key).await?;
let baseline = resolve(&self.baseline, baseline_key).await?;
Ok(ImpactComparison {
candidate,
baseline,
})
}
}
async fn resolve(engine: &DecisionEngine, key: &str) -> Result<Decision, ImpactError> {
engine
.get_decision(key)
.await
.map_err(|source| ImpactError::Load {
key: key.to_string(),
source,
})?
.map_err(|source| ImpactError::ContentKind {
key: key.to_string(),
source,
})
}
pub struct ImpactComparison {
candidate: Decision,
baseline: Decision,
}
impl ImpactComparison {
/// Each input evaluates through both arms off the same variable (an Rc
/// bump, not a copy). Per-arm failures land in the row — a bad record
/// never aborts the batch.
pub async fn run_batch(
&self,
inputs: Vec<Variable>,
options: EvaluationOptions,
) -> ImpactBatch {
self.run_batch_with(inputs, options, false).await
}
/// Like [`Self::run_batch`], but unchanged rows carry their single shared
/// output in `result` — for consumers that aggregate over every record and
/// would otherwise need both full outputs per row.
pub async fn run_batch_carrying(
&self,
inputs: Vec<Variable>,
options: EvaluationOptions,
) -> ImpactBatch {
self.run_batch_with(inputs, options, true).await
}
async fn run_batch_with(
&self,
inputs: Vec<Variable>,
options: EvaluationOptions,
carry_unchanged: bool,
) -> ImpactBatch {
let mut rows = Vec::with_capacity(inputs.len());
let mut summary = ImpactSummary::default();
for input in inputs {
let row = self.run_one_with(input, options, carry_unchanged).await;
summary.record(&row);
rows.push(row);
}
ImpactBatch { rows, summary }
}
pub async fn run_one_carrying(&self, input: Variable, options: EvaluationOptions) -> ImpactRow {
self.run_one_with(input, options, true).await
}
async fn run_one_with(
&self,
input: Variable,
options: EvaluationOptions,
carry_unchanged: bool,
) -> ImpactRow {
let after = self
.candidate
.evaluate_with_opts(input.clone(), options)
.await;
let before = self.baseline.evaluate_with_opts(input, options).await;
match (before, after) {
(Ok(before), Ok(after)) => {
let changed = before.result != after.result;
ImpactRow {
changed,
before: changed.then_some(before.result),
after: changed.then(|| after.result.clone()),
result: (!changed && carry_unchanged).then_some(after.result),
before_error: None,
after_error: None,
}
}
(before, after) => {
let (before_value, before_error) = split(before);
let (after_value, after_error) = split(after);
ImpactRow {
changed: true,
before: before_value,
after: after_value,
result: None,
before_error,
after_error,
}
}
}
}
}
fn split(
outcome: Result<crate::DecisionGraphResponse, Box<EvaluationError>>,
) -> (Option<Variable>, Option<serde_json::Value>) {
match outcome {
Ok(response) => (Some(response.result), None),
Err(error) => (
None,
Some(
error
.serialize_with_mode(
serde_json::value::Serializer,
crate::engine::EvaluationTraceKind::None,
)
.unwrap_or_default(),
),
),
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod aggregate;
pub mod impact;
+1
View File
@@ -1,6 +1,7 @@
pub(crate) mod cleaner;
mod error;
pub(crate) mod graph;
pub(crate) mod request_entity;
pub(crate) mod schema_dict;
pub(crate) mod tracer;
#[cfg(feature = "driver")]
@@ -0,0 +1,155 @@
//! A graph's Request node typed by an entity (`target`): the request is that
//! entity, flat (`{ txn_id, amount, customer }`), and is prepared as a
//! policy's is before the first node runs: dates converted and checked
//! against the entity. A reference holds the record it names (the host places
//! it, with the record's features); an id alone does not fit.
use std::fmt;
use std::sync::Arc;
use ahash::{HashMap, HashMapExt};
use zen_expression::variable::{Variable, VariableMap};
use crate::decision_graph::schema_dict;
use crate::loader::DynamicLoader;
use crate::policy::ir::{DictionaryIr, Policy, PropertyTypeIr};
use crate::policy::validator::InputSchema;
use crate::workspace::graph::{merge_entities, with_inline_references};
pub(crate) struct RequestPreparation {
target: Arc<str>,
schema: InputSchema,
/// The target's references: field, the entity it names.
references: Vec<(Arc<str>, Arc<str>)>,
}
impl fmt::Debug for RequestPreparation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RequestPreparation")
.field("target", &self.target)
.finish()
}
}
impl RequestPreparation {
/// The preparation for `target`, from the entities and dictionaries the
/// graph's imports make visible, walked and merged as the editor's
/// analysis does: an entity declared in several policies is one entity;
/// the first dictionary of a name wins.
pub(crate) async fn load(
loader: &DynamicLoader,
imports: &[Arc<str>],
target: &Arc<str>,
) -> Result<Self, String> {
let closure = schema_dict::load_import_closure(loader, imports).await?;
let parsed: Vec<_> = closure
.iter()
.map(|(key, document)| Policy::parse(key, document))
.collect();
let entities = merge_entities(parsed.iter().flat_map(|p| {
p.policy
.entity_data_models()
.map(|(_, dm)| dm)
.filter(|dm| !dm.name.is_empty())
}));
let mut dictionaries: HashMap<Arc<str>, Arc<DictionaryIr>> = HashMap::new();
for p in &parsed {
for block in &p.policy.dictionaries {
dictionaries
.entry(block.ir.name.clone())
.or_insert_with(|| block.ir.clone());
}
}
if !entities.contains_key(target) {
return Err(format!(
"no entity `{target}` visible from this graph's imports; import the policy that defines it"
));
}
let references = entities
.get(target)
.map(|dm| {
dm.properties
.iter()
.filter_map(|prop| match &prop.kind {
PropertyTypeIr::Reference { target: named }
if entities.contains_key(named) =>
{
Some((prop.name.clone(), named.clone()))
}
_ => None,
})
.collect()
})
.unwrap_or_default();
// References carry their records here: checked as those entities.
let inline = with_inline_references(&entities);
let schema = InputSchema::for_request(
Arc::new(inline),
target.clone(),
std::iter::empty(),
dictionaries,
);
Ok(Self {
target: target.clone(),
schema,
references,
})
}
/// The request as nodes read it, or why it does not fit the entity.
pub(crate) fn prepare(&self, input: &Variable) -> Result<Variable, String> {
if !matches!(input, Variable::Object(_)) {
return Err(format!(
"the request is not a valid `{}`: expected an object, got {}",
self.target,
input.type_name()
));
}
// A reference sent as its id: say so, and what it carries instead.
for (field, named) in &self.references {
let ids: Vec<String> = match input.dot(field.as_ref()) {
Some(Variable::String(id)) => vec![id.to_string()],
Some(Variable::Array(items)) => items
.borrow()
.iter()
.filter_map(|item| item.as_str().map(str::to_string))
.collect(),
_ => continue,
};
let Some(first) = ids.first() else {
continue;
};
return Err(format!(
"the request is not a valid `{}`: '{field}' is the id \"{first}\", but a reference carries its record: send the `{named}` itself (e.g. {{ \"id\": \"{first}\", … }})",
self.target
));
}
// Checked and converted as the entity under its name, as policies are.
let mut root = VariableMap::new();
root.insert(
zen_types::symbol::Symbol::from(self.target.as_ref()),
input.clone(),
);
let wrapped = Variable::from_object(root);
let wrapped = self.schema.convert_dates(&wrapped).unwrap_or(wrapped);
let errors = self.schema.validate(&wrapped);
if !errors.is_empty() {
let prefix = format!("{}.", self.target);
let listed: Vec<String> = errors
.iter()
.map(|e| {
let path = e.path.strip_prefix(&prefix).unwrap_or(&e.path);
format!("'{path}': expected {}, got {}", e.expected, e.got)
})
.collect();
return Err(format!(
"the request is not a valid `{}`: {}",
self.target,
listed.join("; ")
));
}
Ok(wrapped
.dot(self.target.as_ref())
.unwrap_or_else(|| input.clone()))
}
}
+21 -6
View File
@@ -1,3 +1,4 @@
use std::collections::VecDeque;
use std::hash::Hasher;
use std::sync::Arc;
@@ -5,7 +6,7 @@ use ahash::{AHasher, HashMap, HashMapExt, HashSet, HashSetExt};
use serde_json::{Map, Value};
use crate::loader::DynamicLoader;
use crate::policy::raw::BlockDoc;
use crate::policy::raw::{BlockDoc, PolicyDocument};
pub(crate) fn schema_references_dictionary(value: &Value) -> bool {
match value {
@@ -17,14 +18,17 @@ pub(crate) fn schema_references_dictionary(value: &Value) -> bool {
}
}
pub(crate) async fn load_import_dictionaries(
/// The policies a graph's imports make visible: the imports and what they
/// import, breadth-first, each import in the order listed (as the editor
/// walks them).
pub(crate) async fn load_import_closure(
loader: &DynamicLoader,
imports: &[Arc<str>],
) -> Result<HashMap<Arc<str>, Vec<Arc<str>>>, String> {
let mut out: HashMap<Arc<str>, Vec<Arc<str>>> = HashMap::new();
) -> Result<Vec<(Arc<str>, Arc<PolicyDocument>)>, String> {
let mut out: Vec<(Arc<str>, Arc<PolicyDocument>)> = Vec::new();
let mut visited: HashSet<Arc<str>> = HashSet::new();
let mut queue: Vec<Arc<str>> = imports.to_vec();
while let Some(key) = queue.pop() {
let mut queue: VecDeque<Arc<str>> = imports.iter().cloned().collect();
while let Some(key) = queue.pop_front() {
if !visited.insert(key.clone()) {
continue;
}
@@ -37,6 +41,17 @@ pub(crate) async fn load_import_dictionaries(
};
let document = policy.0.clone();
queue.extend(document.imports.iter().cloned());
out.push((key, document));
}
Ok(out)
}
pub(crate) async fn load_import_dictionaries(
loader: &DynamicLoader,
imports: &[Arc<str>],
) -> Result<HashMap<Arc<str>, Vec<Arc<str>>>, String> {
let mut out: HashMap<Arc<str>, Vec<Arc<str>>> = HashMap::new();
for (_, document) in load_import_closure(loader, imports).await? {
for block in &document.blocks {
if let BlockDoc::Dictionary { data, .. } = block {
out.entry(data.name.clone()).or_insert_with(|| {
+15
View File
@@ -226,6 +226,20 @@ impl DecisionGraph {
let mut base_ctx = self.build_node_context(node.deref(), input, walker.nodes_context());
let node_execution = match &node.kind {
DecisionNodeKind::InputNode { content } if content.target.is_some() => {
match self
.config
.content
.request_input(self.config.extensions.loader(), content, &context)
.await
{
Err(message) => base_ctx.error(message),
Ok(prepared) => {
base_ctx.input = prepared;
Self::handle_node(base_ctx, content.clone(), InputNodeHandler).await
}
}
}
DecisionNodeKind::InputNode { content } => {
base_ctx.input = context.clone();
match self
@@ -244,6 +258,7 @@ impl DecisionGraph {
base_ctx.config.validation_salt = salt;
let resolved = InputNodeContent {
schema: Some(schema),
target: content.target.clone(),
};
Self::handle_node(base_ctx, resolved, InputNodeHandler).await
}
+66 -2
View File
@@ -1,3 +1,4 @@
use crate::compiled::ColumnarOutput;
use crate::decision::Decision;
use crate::decision_graph::graph::{DecisionGraphResponse, EvaluationTrace};
use crate::error::ContentKindError;
@@ -155,6 +156,13 @@ impl DecisionEngine {
failures
}
/// The paths a compiled document reads from its request (`transaction.amount`,
/// `card.txn_count_7d`); None when unknown (a dynamic read, an opaque node)
/// or when the document isn't compiled. Available after `compile()`.
pub fn reads(&self, key: &str) -> Option<std::collections::BTreeSet<String>> {
self.compiled.load_full()?.reads(key)
}
pub fn compile_failures(&self) -> Vec<CompileFailure> {
self.compiled
.load_full()
@@ -187,10 +195,15 @@ impl DecisionEngine {
{
let key_str = key.as_ref();
if let Some(set) = self.compiled.load_full() {
if let Some(entry) = set.get(key_str) {
// Compiled under its path with or without `.json`, as loaders
// find documents either way; evaluated under that path.
let compiled = set
.key_of(key_str)
.and_then(|key| Some((set.get(&key)?, key)));
if let Some((entry, compiled_key)) = compiled {
return match entry {
CompiledEntry::Policy(artifact) => artifact
.evaluate_entry(key_str, context, options.trace)
.evaluate_entry(&compiled_key, context, options.trace)
.map(|r| DecisionGraphResponse {
performance: format!("{:.1?}", r.duration),
result: r.output,
@@ -284,6 +297,57 @@ impl DecisionEngine {
results
}
/// Evaluates `key` over columnar input: Arrow-shaped buffers borrowed by
/// [`zen_expression::lane::Columns`], one column per dotted input path,
/// with no value built per row. The result is columns by dotted path
/// (`""` is a whole result) and a failure per row. A document compiled
/// by [`Self::compile`] runs its compiled plan (a policy decides all its
/// goals, its input prepared as columns in `store`, which holds them as
/// long as the output is read); anything else is evaluated row by row
/// and given as columns.
pub async fn evaluate_columns<'a, K>(
&self,
key: K,
columns: &'a zen_expression::lane::Columns<'a>,
store: &'a crate::ColumnStore<'a>,
options: EvaluationOptions,
) -> ColumnarOutput<'a>
where
K: AsRef<str>,
{
let key_str = key.as_ref();
if let Some(set) = self.compiled.load_full() {
let compiled = set
.key_of(key_str)
.and_then(|key| Some((set.get(&key)?.clone(), key)));
if let Some((entry, compiled_key)) = compiled {
return match entry {
CompiledEntry::Policy(artifact) => ColumnarOutput::from_policy(
artifact.evaluate_columns(&compiled_key, &[], columns, store),
),
CompiledEntry::Graph(graph) => {
self.decision_from_graph(graph)
.evaluate_columns(columns, options)
.await
}
};
}
}
if let Ok(content) = self.loader.load(key_str).await {
if let DecisionContent::Graph(_) = content.as_ref() {
return self
.decision_from_graph_arc(content)
.evaluate_columns(columns, options)
.await;
}
}
let mut results = Vec::with_capacity(columns.rows);
for row in 0..columns.rows {
results.push(self.evaluate_with_opts(key_str, columns.row(row), options).await);
}
ColumnarOutput::from_results(results)
}
pub async fn evaluate_serialized<K>(
&self,
key: K,
+3 -1
View File
@@ -127,6 +127,8 @@
mod analysis;
mod compiled;
mod config;
#[cfg(feature = "data")]
pub mod data;
mod decision;
mod decision_graph;
mod engine;
@@ -139,7 +141,7 @@ pub mod workspace;
pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
pub use compiled::policy::PolicyColumnarOutput;
pub use compiled::policy::{ColumnStore, PolicyColumnarOutput};
pub use compiled::{ColumnarOutput, OutputColumn, RecordsView};
pub use config::ZEN_CONFIG;
pub use decision::Decision;
+46 -2
View File
@@ -31,13 +31,27 @@ impl FilesystemLoader {
}
}
/// The file of a key: as named, else with `.json` (BRMS names documents
/// and their imports without an extension, `models/cards`, while a
/// folder on disk usually has `models/cards.json`).
/// A folder of the same name (`models/cards/`) is never the file.
fn key_to_path<K: AsRef<str>>(&self, key: K) -> PathBuf {
Path::new(&self.root).join(key.as_ref())
let path = Path::new(&self.root).join(key.as_ref());
// A dotted name (`fraud.rules`) is a name, not an extension.
if path.is_file() || key.as_ref().ends_with(".json") {
return path;
}
let with_json = Path::new(&self.root).join(format!("{}.json", key.as_ref()));
if with_json.is_file() {
with_json
} else {
path
}
}
fn read_content<K: AsRef<str>>(&self, key: K) -> LoaderResponse {
let path = self.key_to_path(key.as_ref());
if !Path::exists(&path) {
if !path.is_file() {
return Err(LoaderError::NotFound(String::from(key.as_ref())));
}
@@ -120,6 +134,36 @@ mod tests {
assert!(loader.load("table.json").await.is_ok());
assert!(loader.load_sync("table.json").unwrap().is_ok());
// A key without its extension, as BRMS imports name documents.
assert!(loader.load("table").await.is_ok());
}
#[test]
fn key_resolves_to_the_file_beside_a_folder_of_the_same_name() {
let root = std::env::temp_dir().join(format!("zen-fs-loader-{}", std::process::id()));
std::fs::create_dir_all(root.join("models/cards")).unwrap();
std::fs::write(root.join("models/cards.json"), "{}").unwrap();
let loader = FilesystemLoader::new(FilesystemLoaderOptions {
root: root.to_string_lossy().to_string(),
});
assert_eq!(
loader.key_to_path("models/cards"),
root.join("models/cards.json")
);
// A dotted name is a name: `<key>.json` is still tried.
std::fs::write(root.join("models/rules.v2.json"), "{}").unwrap();
assert_eq!(
loader.key_to_path("models/rules.v2"),
root.join("models/rules.v2.json")
);
// A key naming its `.json` is the file as named.
assert_eq!(
loader.key_to_path("models/cards.json"),
root.join("models/cards.json")
);
assert!(loader.load_sync("models").unwrap().is_err());
std::fs::remove_dir_all(&root).unwrap();
}
#[tokio::test]
+88
View File
@@ -11,6 +11,7 @@ use std::sync::Arc;
type ResolvedSchemas = HashMap<Arc<str>, (Arc<serde_json::Value>, u64)>;
use zen_types::decision::{DecisionEdge, DecisionNode, DecisionNodeKind, FunctionNodeContent};
use crate::decision_graph::request_entity::RequestPreparation;
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
@@ -119,6 +120,10 @@ pub struct GraphContent {
#[serde(skip)]
pub resolved_schemas: Option<Arc<ResolvedSchemas>>,
/// The Request node's entity preparation (`target`), loaded once.
#[serde(skip)]
pub(crate) request_preparation: RequestPreparationCache,
#[serde(skip)]
pub(crate) validator_cache: ValidatorCache,
@@ -207,7 +212,21 @@ impl GraphContent {
self.dt_indexes = Some(Arc::new(indexes));
}
/// The entity a Request node names (`target`): the host passes a flat
/// body under this name.
pub fn request_target(&self) -> Option<Arc<str>> {
self.nodes.iter().find_map(|node| match &node.kind {
DecisionNodeKind::InputNode { content } => content.target.clone(),
_ => None,
})
}
pub async fn resolve_schemas(&mut self, loader: &DynamicLoader) -> Result<(), String> {
if let Some(target) = self.request_target() {
self.request_preparation
.get_or_load(loader, &self.imports, &target)
.await?;
}
if self.resolved_schemas.is_some() {
return Ok(());
}
@@ -242,6 +261,32 @@ impl GraphContent {
Ok(())
}
/// A request typed by an entity (`target`), prepared as a policy's
/// request is: by the graph's preparation, loaded through its imports
/// once. Not with a schema too.
#[cfg(feature = "driver")]
pub(crate) async fn request_input(
&self,
loader: &DynamicLoader,
content: &zen_types::decision::InputNodeContent,
context: &zen_expression::Variable,
) -> Result<zen_expression::Variable, String> {
let Some(target) = &content.target else {
return Ok(context.clone());
};
if content.schema.is_some() {
return Err(
"the request is typed twice: by a schema and by an entity (`target`); keep one"
.to_string(),
);
}
let prepared = self
.request_preparation
.get_or_load(loader, &self.imports, target)
.await?;
prepared.prepare(context)
}
pub(crate) async fn validation_schema(
&self,
loader: &DynamicLoader,
@@ -327,3 +372,46 @@ mod tests {
assert!(content.as_policy().is_some());
}
}
/// A graph's Request entity preparation, loaded once: by `resolve_schemas`,
/// or by the first evaluation that needs it (so content made without a
/// caching loader doesn't load its imports on every request). Shared by the
/// clones of a graph (a decision evaluates prepared and hosted copies of its
/// content), and kept per (target, imports), so a clone that changes either
/// loads its own. Equal whatever it holds, as the other caches of a graph are.
#[derive(Default, Debug, Clone)]
pub(crate) struct RequestPreparationCache(Arc<std::sync::Mutex<Option<LoadedRequest>>>);
type LoadedRequest = (Arc<str>, Vec<Arc<str>>, Arc<RequestPreparation>);
impl RequestPreparationCache {
/// The preparation for `target`, loaded through `imports` the first time.
/// A failure isn't kept: the next call loads again.
pub(crate) async fn get_or_load(
&self,
loader: &DynamicLoader,
imports: &[Arc<str>],
target: &Arc<str>,
) -> Result<Arc<RequestPreparation>, String> {
if let Some(prepared) = self.get(imports, target) {
return Ok(prepared);
}
let loaded = Arc::new(RequestPreparation::load(loader, imports, target).await?);
if let Ok(mut slot) = self.0.lock() {
*slot = Some((target.clone(), imports.to_vec(), loaded.clone()));
}
Ok(loaded)
}
fn get(&self, imports: &[Arc<str>], target: &Arc<str>) -> Option<Arc<RequestPreparation>> {
let slot = self.0.lock().ok()?;
let (loaded_target, loaded_imports, prepared) = slot.as_ref()?;
(loaded_target == target && loaded_imports.as_slice() == imports).then(|| prepared.clone())
}
}
impl PartialEq for RequestPreparationCache {
fn eq(&self, _: &Self) -> bool {
true
}
}
+28 -4
View File
@@ -13,7 +13,7 @@ use crate::analysis::table::{HitMode, VerifyInput, VerifyOutput, VerifyTable};
use crate::policy::ir::PropertyPath;
use crate::policy::queries::dependency::{DataModelPaths, PathPrefix};
use crate::policy::queries::scope::VariableTypeScope;
use crate::workspace::db::AnalysisPass;
use crate::workspace::db::{AnalysisPass, Db};
use crate::workspace::types::{
CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, DiagnosticLocation, ExpressionKind,
Severity,
@@ -162,8 +162,9 @@ impl AnalysisContext {
&self.scope,
),
};
let reads_from = self.reads.len();
self.record_reads(&analysis, &expression_id);
self.absorb_diagnostics(&analysis, &expression_id, source, kind);
self.absorb_diagnostics(&analysis, &expression_id, source, kind, reads_from);
analysis
}
@@ -198,8 +199,15 @@ impl AnalysisContext {
scope,
),
};
let reads_from = self.reads.len();
self.record_reads(&analysis, &expression_id);
self.absorb_diagnostics(&analysis, &expression_id, source, ExpressionKind::Unary);
self.absorb_diagnostics(
&analysis,
&expression_id,
source,
ExpressionKind::Unary,
reads_from,
);
analysis
}
@@ -427,7 +435,8 @@ impl AnalysisContext {
}
let resolved = self.scope.resolve_at(&read.path);
let unknown = match resolved {
VariableType::Any => true,
// Under a value declared open (`any`), every path may exist.
VariableType::Any => !Self::under_open(&self.scope, &read.path),
VariableType::Null => !Self::path_declared(&self.scope, &read.path),
_ => false,
};
@@ -448,6 +457,19 @@ impl AnalysisContext {
}
}
/// Whether `path` is below a declared value typed `any` (a call's
/// `response`, an open field): nothing more is known of its shape.
fn under_open(scope: &VariableType, path: &str) -> bool {
let mut parent = path;
while let Some((head, _)) = parent.rsplit_once('.') {
if matches!(scope.resolve_at(head), VariableType::Any) && Self::path_declared(scope, head) {
return true;
}
parent = head;
}
false
}
fn path_declared(scope: &VariableType, path: &str) -> bool {
match path.rsplit_once('.') {
Some((parent, key)) => Self::scope_has_key(&scope.resolve_at(parent), key),
@@ -486,6 +508,7 @@ impl AnalysisContext {
expression_id: &Option<Arc<str>>,
source: &str,
kind: ExpressionKind,
reads_from: usize,
) {
let first = self.diagnostics.len();
for diag in &analysis.diagnostics {
@@ -506,6 +529,7 @@ impl AnalysisContext {
matches!(kind, ExpressionKind::Unary),
OnError::Raise,
);
Db::locate_unknown_members(&mut self.diagnostics[first..], &self.reads[reads_from..]);
}
}
+43 -4
View File
@@ -240,6 +240,7 @@ impl Db {
policy_path: &Arc<str>,
goals: &[Arc<str>],
columns: &'a zen_expression::lane::Columns<'a>,
store: &'a crate::compiled::policy::ColumnStore<'a>,
) -> Result<crate::compiled::policy::PolicyColumnarOutput<'a>, EvaluationError> {
let probe = EvaluateRequest {
policy_path: policy_path.clone(),
@@ -248,8 +249,7 @@ impl Db {
trace: false,
};
self.check_evaluable(&probe)?;
let artifact = self.eval_artifact(policy_path);
Ok(artifact.plan(goals).evaluate_columns(&artifact, policy_path, goals, columns))
Ok(self.eval_artifact(policy_path).evaluate_columns(policy_path, goals, columns, store))
}
pub fn evaluate_batch(
@@ -370,6 +370,26 @@ impl EvalArtifact {
plan
}
/// The policy's `goals` (every goal when none) over columnar input, on
/// its compiled plan: the input first prepared as columns (dates,
/// defaults, references) in `store` when the policy converts it and its
/// shape allows; else each row prepared as it is evaluated.
pub(crate) fn evaluate_columns<'a>(
&self,
policy_path: &Arc<str>,
goals: &[Arc<str>],
columns: &'a zen_expression::lane::Columns<'a>,
store: &'a crate::compiled::policy::ColumnStore<'a>,
) -> crate::compiled::policy::PolicyColumnarOutput<'a> {
use crate::compiled::policy::columnar::prepare;
let converts = !self.reference_fields.is_empty() || self.input_schema.converts();
let prepared = converts
.then(|| prepare::prepare(self, columns, store))
.flatten()
.map(|prepared| store.keep(prepared));
self.plan(goals).evaluate_columns(self, policy_path, goals, columns, prepared)
}
pub(crate) fn evaluate_batch(
&self,
requests: &[EvaluateRequest],
@@ -441,7 +461,26 @@ impl EvalArtifact {
if !goals.is_empty() || !self.reference_fields.is_empty() {
return None;
}
let mut sure = self.input_schema.sure(columns)?;
let sure = self.input_schema.sure(columns)?;
Some(self.required(columns, sure))
}
/// The prepared rows certain to pass: validated as `converted`, their
/// requirements met in `hydrated` (as the row path checks each).
pub(crate) fn sure_prepared(
&self,
converted: &zen_expression::lane::Columns,
hydrated: &zen_expression::lane::Columns,
goals: &[Arc<str>],
) -> Option<Vec<bool>> {
if !goals.is_empty() {
return None;
}
let sure = self.input_schema.sure_prepared(converted)?;
Some(self.required(hydrated, sure))
}
fn required(&self, columns: &zen_expression::lane::Columns, mut sure: Vec<bool>) -> Vec<bool> {
for check in &self.requirements().checks {
let primary = Steps::new(&check.primary, columns);
if primary.always(columns) {
@@ -457,7 +496,7 @@ impl EvalArtifact {
}
}
}
Some(sure)
sure
}
fn requirements(&self) -> &Requirements {
+668 -4
View File
@@ -129,6 +129,18 @@ pub struct DataModelIr {
pub name: Arc<str>,
pub scope: Scope,
pub properties: Vec<Property>,
/// What the entity's records are, for the feature store.
pub records: Records,
}
/// What an entity's records are: plain request data, events (`events`) or
/// reference data (`reference`). Windowed features aggregate the latter two.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Records {
#[default]
Plain,
Events,
Reference,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -159,6 +171,134 @@ pub struct Property {
pub kind: PropertyTypeIr,
pub array: bool,
pub optional: bool,
/// The type as written when it is checked as another (`integer` as
/// `number`, `timestamp` as `date`).
pub exact: Option<Arc<str>>,
/// Supplied by the host rather than the request: a feature, a value
/// computed per event, or a model's output.
pub supply: Option<Arc<Supply>>,
/// Filled in when the value is missing or null (a property's or a
/// feature's `default`), so never null.
pub default: Option<Arc<serde_json::Value>>,
}
/// How the host supplies a property.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Supply {
/// A feature: `base` is the property as written, `window` the one this
/// property is (`txn_count` over `1h` is `txn_count_1h`).
Feature {
base: Arc<str>,
expr: Arc<str>,
#[serde(skip_serializing_if = "Option::is_none")]
window: Option<Arc<str>>,
#[serde(skip_serializing_if = "Option::is_none")]
default: Option<serde_json::Value>,
},
/// An outcome: what happened after the decision, computed offline by
/// the host (training labels, impact analysis). Never in the request
/// and never read by rules; `maturity` (days, `30d`) as written: when a
/// "no" can be trusted (the answer itself is never hidden).
/// Without `expr`, the entity's own column (a column outcome).
Outcome {
#[serde(skip_serializing_if = "Option::is_none")]
expr: Option<Arc<str>>,
#[serde(skip_serializing_if = "Option::is_none")]
maturity: Option<Arc<str>>,
},
/// Computed per event from the event's other properties.
Compute { expr: Arc<str> },
/// A model's output.
Model {
#[serde(skip_serializing_if = "Option::is_none")]
datasource: Option<Arc<str>>,
},
/// A stored relationship's members, found by the host: the instances of
/// the target sharing this entity's key (`on`), or its counterparties in
/// an events entity (`through`). Never in the request; features on this
/// entity aggregate them.
Members { by: MembersBy },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum MembersBy {
Key,
Events,
}
impl Supply {
/// Shown after the type: `count(transaction) · 1h`.
pub fn summary(&self) -> String {
match self {
Supply::Feature { expr, window, .. } => match window {
Some(window) => format!("{expr} · {window}"),
None => expr.to_string(),
},
Supply::Outcome { expr, maturity } => {
let outcome = match expr {
Some(expr) => format!("outcome {expr}"),
None => "outcome from its column".to_string(),
};
match maturity {
Some(days) => format!("{outcome} · mature after {days}"),
None => outcome,
}
}
Supply::Compute { expr } => expr.to_string(),
Supply::Model { datasource } => match datasource {
Some(datasource) => format!("model {datasource}"),
None => "model".to_string(),
},
Supply::Members { by: MembersBy::Key } => "members by key".to_string(),
Supply::Members { by: MembersBy::Events } => "counterparties in events".to_string(),
}
}
}
impl Property {
/// A stored relationship: members the host finds (`on` / `through`).
pub fn is_stored(&self) -> bool {
matches!(self.supply.as_deref(), Some(Supply::Members { .. }))
}
/// An outcome: known only after the decision, so never in a request
/// and never read by rules, features or calls.
pub fn is_outcome(&self) -> bool {
matches!(self.supply.as_deref(), Some(Supply::Outcome { .. }))
}
/// An outcome's `maturity` (`30d`), when it declares one.
pub fn outcome_maturity(&self) -> Option<&Arc<str>> {
match self.supply.as_deref() {
Some(Supply::Outcome { maturity, .. }) => maturity.as_ref(),
_ => None,
}
}
/// The type as written, with `[]` and `?`: `integer?`.
pub fn type_label(&self) -> String {
let base = match &self.exact {
Some(exact) => exact.to_string(),
None => match &self.kind {
PropertyTypeIr::Relationship { target } | PropertyTypeIr::Reference { target } => {
target.to_string()
}
PropertyTypeIr::Enum(_) => "enum".to_string(),
kind => kind.to_string(),
},
};
let array = if self.array { "[]" } else { "" };
let optional = if self.optional { "?" } else { "" };
format!("{base}{array}{optional}")
}
/// `integer? · count(transaction) · 1h` for a host-supplied property.
pub fn supply_detail(&self) -> Option<String> {
let supply = self.supply.as_ref()?;
Some(format!("{} · {}", self.type_label(), supply.summary()))
}
}
#[derive(Debug, Clone)]
@@ -170,6 +310,8 @@ pub enum PropertyTypeIr {
Date,
Relationship { target: Arc<str> },
Reference { target: Arc<str> },
/// Any value (`object`, `any`): not checked.
Any,
}
impl DataModelIr {
@@ -186,6 +328,8 @@ impl DataModelIr {
}
for prop in &dm.properties {
match &prop.kind {
// A stored relationship's target stays a root: its members are found, not nested.
PropertyTypeIr::Relationship { .. } if prop.is_stored() => {}
PropertyTypeIr::Relationship { target } => {
if dm.scope.is_global() {
global_relationship_targets.insert(target.clone());
@@ -226,6 +370,7 @@ impl DataModelIr {
PropertyTypeIr::Enum(values) => VariableType::Enum(None, enum_values_to_rc(values)),
PropertyTypeIr::Number => VariableType::Number,
PropertyTypeIr::Boolean => VariableType::Bool,
PropertyTypeIr::Any => VariableType::Any,
PropertyTypeIr::Reference { .. } => VariableType::String,
PropertyTypeIr::Relationship { target } => match dictionaries.get(target.as_ref()) {
Some(dict) if !entities.contains_key(target.as_ref()) => dict.enum_type(),
@@ -250,7 +395,13 @@ impl DataModelIr {
}
let mut fields: HashMap<Rc<str>, VariableType> = HashMap::new();
if let Some(dm) = entities.get(name) {
for prop in &dm.properties {
// A stored relationship is never on the wire: the host finds its
// members. Nor is an outcome: it is known only after the decision.
for prop in dm
.properties
.iter()
.filter(|p| !p.is_stored() && !p.is_outcome())
{
fields.insert(
Rc::from(prop.name.as_ref()),
Self::wire_property_type(prop, entities, dictionaries, visited),
@@ -394,9 +545,12 @@ impl DataModelIr {
PropertyTypeIr::Enum(trimmed)
}
}
PropertyTypeDoc::Number => PropertyTypeIr::Number,
PropertyTypeDoc::Number | PropertyTypeDoc::Decimal | PropertyTypeDoc::Integer => {
PropertyTypeIr::Number
}
PropertyTypeDoc::Boolean => PropertyTypeIr::Boolean,
PropertyTypeDoc::Date => PropertyTypeIr::Date,
PropertyTypeDoc::Date | PropertyTypeDoc::Timestamp => PropertyTypeIr::Date,
PropertyTypeDoc::Object | PropertyTypeDoc::Any => PropertyTypeIr::Any,
PropertyTypeDoc::Relationship { target } => PropertyTypeIr::Relationship {
target: target.trimmed(),
},
@@ -405,23 +559,532 @@ impl DataModelIr {
},
};
// The type as written when it says more than the engine's type:
// `object` and `any` are both any here. (`decimal`, `integer` and
// `timestamp` are old names for number and date.)
let exact: Option<Arc<str>> = match &prop.property_type {
PropertyTypeDoc::Object => Some(Arc::from("object")),
PropertyTypeDoc::Any => Some(Arc::from("any")),
_ => None,
};
let at = || {
DiagnosticLocation::expression(
policy_path.clone(),
id.clone(),
prop.id.clone(),
None,
)
};
if prop.feature.is_some() && prop.outcome.is_some() {
diagnostics.push(Diagnostic::error(
DiagnosticCode::InvalidOutcome,
at(),
format!(
"`{prop_name}` in entity '{name}' has both `feature` and `outcome`: a property is a feature (known at the decision) or an outcome (known after it), not both"
),
));
}
// An outcome: known only after the decision, computed offline by
// the host. Never in the request, so null to anything that reads
// the entity (rules can't: see the diagnostics).
// Without `expr`, the entity's own column (typed by `type`).
if let (None, Some(outcome)) = (&prop.feature, &prop.outcome) {
if outcome.rest.contains_key("unknownFor") {
diagnostics.push(Diagnostic::warning(
DiagnosticCode::InvalidOutcome,
at(),
format!(
"`unknownFor` is now `maturity` in outcome '{prop_name}' in entity '{name}'"
),
));
}
let maturity = match &outcome.maturity {
None => None,
Some(serde_json::Value::String(days)) if is_duration(days, &["d"]) => {
Some(Arc::from(days.as_str()))
}
Some(other) => {
let shown = match other {
serde_json::Value::String(text) => text.clone(),
other => other.to_string(),
};
diagnostics.push(Diagnostic::error(
DiagnosticCode::InvalidDuration,
at(),
format!(
"`maturity` of outcome '{prop_name}' in entity '{name}' is a number of days such as 30d, 120d or 365d, not `{shown}`"
),
));
None
}
};
properties.push(Property {
id: prop.id.clone(),
name: prop_name,
kind,
array: prop.array,
optional: true,
exact,
default: None,
supply: Some(Arc::new(Supply::Outcome {
expr: outcome.expr.clone(),
maturity,
})),
});
continue;
}
// A feature: the host supplies it, one property per window
// (`txn_count` over 1h, 7d: `txn_count_1h`, `txn_count_7d`).
// Without a `default` (or `required`) it is absent when unknown
// (not covered), so optional: rules handle null. With one, the
// host always supplies a value (or rejects the request).
if let Some(feature) = &prop.feature {
let optional = feature
.default
.as_ref()
.is_none_or(serde_json::Value::is_null)
&& prop.required != Some(true);
let windows = feature.window.as_ref().map(|w| w.list()).unwrap_or_default();
let names: Vec<(Arc<str>, Option<Arc<str>>)> = if windows.is_empty() {
vec![(prop_name.clone(), None)]
} else {
let listed = windows.len() > 1;
windows
.iter()
.filter_map(|window| {
if !is_window(window) {
diagnostics.push(Diagnostic::error(
DiagnosticCode::InvalidDuration,
DiagnosticLocation::expression(
policy_path.clone(),
id.clone(),
prop.id.clone(),
None,
),
format!(
"window '{window}' of feature '{prop_name}' in entity '{name}' is not a duration such as 10m, 1h or 7d"
),
));
return None;
}
Some((window_name(&prop_name, window, listed), Some(window.clone())))
})
.collect()
};
let default = feature.default.clone();
for (feature_name, window) in names {
if feature_name != prop_name {
if let Some(prev_id) = seen.get(&feature_name) {
diagnostics.push(Diagnostic::error(
DiagnosticCode::DuplicateProperty,
DiagnosticLocation::expression(
policy_path.clone(),
id.clone(),
prev_id.clone(),
None,
),
format!("duplicate property '{feature_name}' in entity '{name}'"),
));
continue;
}
seen.insert(feature_name.clone(), prop.id.clone());
}
properties.push(Property {
id: prop.id.clone(),
name: feature_name,
kind: kind.clone(),
array: prop.array,
optional,
exact: exact.clone(),
default: default.clone().filter(|d| !d.is_null()).map(Arc::new),
supply: Some(Arc::new(Supply::Feature {
base: prop_name.clone(),
expr: feature.expr.clone(),
window,
default: default.clone(),
})),
});
}
continue;
}
// A model's output: supplied by the host; null when the model was
// not called (`when`) or fell back without a value, unless
// `required` or a fallback value makes it always there.
let host_optional = prop.model.as_ref().is_some_and(|m| {
prop.required != Some(true) && m.get("fallback").is_none_or(serde_json::Value::is_null)
});
properties.push(Property {
id: prop.id.clone(),
name: prop_name,
kind,
array: prop.array,
optional: prop.optional,
// Filled with its `default` when missing: always there. (A
// compute is null when what it reads may be: see below.)
optional: (prop.optional || host_optional)
&& prop.required != Some(true)
&& prop.rest.get("default").is_none_or(serde_json::Value::is_null),
exact,
default: prop
.rest
.get("default")
.filter(|d| !d.is_null())
.map(|d| Arc::new(d.clone())),
supply: match (&prop.compute, &prop.model) {
(Some(expr), _) => Some(Arc::new(Supply::Compute { expr: expr.clone() })),
(None, Some(model)) => Some(Arc::new(Supply::Model {
datasource: model
.get("datasource")
.and_then(serde_json::Value::as_str)
.filter(|d| !d.is_empty())
.map(Arc::from),
})),
(None, None) => match (&prop.property_type, prop.rest.get("on"), prop.rest.get("through")) {
(PropertyTypeDoc::Relationship { .. }, Some(_), _) => {
Some(Arc::new(Supply::Members { by: MembersBy::Key }))
}
(PropertyTypeDoc::Relationship { .. }, None, Some(_)) => {
Some(Arc::new(Supply::Members { by: MembersBy::Events }))
}
_ => None,
},
},
});
}
Self::computes_propagate_null(doc, &mut properties);
// An outcome with `maturity` gives its outcome expressions a flag,
// `<name>_mature`: a real property of that name would hide it.
for prop in &properties {
let Some(base) = prop.name.strip_suffix(MATURE_SUFFIX) else {
continue;
};
if properties
.iter()
.any(|p| *p.name == *base && p.outcome_maturity().is_some())
{
diagnostics.push(Diagnostic::error(
DiagnosticCode::InvalidOutcome,
DiagnosticLocation::expression(
policy_path.clone(),
id.clone(),
prop.id.clone(),
None,
),
format!(
"`{}` clashes with the maturity flag of outcome `{base}`; rename one",
prop.name
),
));
}
}
let records = if doc.events.is_some() {
Records::Events
} else if doc.reference.is_some() {
Records::Reference
} else {
Records::Plain
};
Some(DataModelIr {
name,
scope,
properties,
records,
})
}
}
impl DataModelIr {
/// A compute is null when anything it reads may be (null in, null out)
/// or when it can give null itself (`x > 0 ? y : null`), unless
/// `required` or a `default` says it is always there. What it reads
/// through a relationship, a reference or `$root` counts as nullable.
fn computes_propagate_null(doc: &DataModelDoc, properties: &mut [Property]) {
use zen_expression::intellisense::{IntelliSense, ReadDependency};
let decides = |prop: &Property| {
matches!(prop.supply.as_deref(), Some(Supply::Compute { .. }))
&& prop.default.is_none()
&& doc
.properties
.iter()
.find(|p| p.id == prop.id)
.is_none_or(|p| p.required != Some(true))
};
let computes: Vec<usize> = (0..properties.len())
.filter(|&i| decides(&properties[i]))
.collect();
if computes.is_empty() {
return;
}
let mut intellisense = IntelliSense::new();
// Each compute's own-field reads, or `None` when it may be null whatever they are.
let reads: Vec<Option<Vec<Arc<str>>>> = computes
.iter()
.map(|&i| {
let Some(Supply::Compute { expr }) = properties[i].supply.as_deref() else {
return None;
};
let own = |path: &[Rc<str>]| -> Option<Arc<str>> {
let [name] = path else { return None };
let prop = properties.iter().find(|p| *p.name == **name)?;
(!matches!(prop.kind, PropertyTypeIr::Relationship { .. }))
.then(|| prop.name.clone())
};
let mut names = Vec::new();
for read in intellisense.reads(expr) {
match read {
ReadDependency::Direct { path, .. } => names.push(own(&path)?),
ReadDependency::Iteration { collection, .. } => {
names.push(own(&collection)?)
}
ReadDependency::Unresolved { .. } => return None,
}
}
let fields: HashMap<Rc<str>, VariableType> = properties
.iter()
.map(|p| {
let kind = match &p.kind {
PropertyTypeIr::String | PropertyTypeIr::Reference { .. } => {
VariableType::String
}
PropertyTypeIr::Enum(values) => {
VariableType::Enum(None, enum_values_to_rc(values))
}
PropertyTypeIr::Number => VariableType::Number,
PropertyTypeIr::Boolean => VariableType::Bool,
PropertyTypeIr::Date => VariableType::Date,
PropertyTypeIr::Relationship { .. } | PropertyTypeIr::Any => {
VariableType::Any
}
};
let kind = if p.array { kind.array() } else { kind };
(Rc::from(p.name.as_ref()), kind)
})
.collect();
let data = VariableType::Object(Rc::new(RefCell::new(fields)));
let returns = intellisense.analyze(expr, &data).return_type.clone();
(!matches!(returns, VariableType::Null | VariableType::Nullable(_)))
.then_some(names)
})
.collect();
// Until nothing changes: a compute may read another.
let mut changed = true;
while changed {
changed = false;
for (&i, reads) in computes.iter().zip(&reads) {
if properties[i].optional {
continue;
}
let nullable = reads.as_ref().is_none_or(|names| {
names
.iter()
.any(|name| properties.iter().any(|p| p.name == *name && p.optional))
});
if nullable {
properties[i].optional = true;
changed = true;
}
}
}
}
}
/// What names an outcome's maturity flag: `fraud_mature` for `fraud`.
pub(crate) const MATURE_SUFFIX: &str = "_mature";
/// The detail of a maturity flag in completions and hover.
pub(crate) fn maturity_flag_detail(outcome: &str, maturity: &str) -> String {
format!("bool · whether `{outcome}` is mature (after {maturity})")
}
/// Who reads an outcome too early, for [`outcome_read_message`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OutcomeReader {
/// A rule block or a graph node.
Rules,
/// A feature's expression or a compute.
Features,
/// A call's request, response or `when`.
Calls,
}
/// A read of an outcome before it is known: `transaction.fraud` is
/// known only after the decision.
pub(crate) fn outcome_read_message(field: &str, reader: OutcomeReader) -> String {
let who = match reader {
OutcomeReader::Rules => "rules",
OutcomeReader::Features => "features",
OutcomeReader::Calls => "calls",
};
format!("`{field}` is an outcome: known only after the decision; {who} cannot read it")
}
impl DataModelIr {
/// The outcome a maturity flag names (`fraud_mature` → `fraud`), with
/// or without `maturity`; none when `name` is a real property (it
/// hides the flag) or names no outcome.
pub(crate) fn flagged_outcome(&self, name: &str) -> Option<&Property> {
let base = name.strip_suffix(MATURE_SUFFIX)?;
if self.properties.iter().any(|p| *p.name == *name) {
return None;
}
self.properties
.iter()
.find(|p| *p.name == *base && p.is_outcome())
}
/// A maturity flag: `fraud_mature` of `fraud`, an outcome with `maturity`.
pub(crate) fn is_maturity_flag(&self, name: &str) -> bool {
self.flagged_outcome(name)
.is_some_and(|p| p.outcome_maturity().is_some())
}
/// The outcome a read reaches, as `entity.field`: on the way through
/// references and relationships (`claim.customer.claims_after`), from
/// `entity`'s own fields when the path starts with one, else from the
/// entity it names (`transaction.fraud`, `$root.transaction.fraud`).
pub(crate) fn outcome_at<S: std::hash::BuildHasher>(
entities: &std::collections::HashMap<Arc<str>, Arc<DataModelIr>, S>,
entity: Option<&str>,
path: &str,
) -> Option<String> {
let segments: Vec<&str> = path.split('.').collect();
let (rooted, segments) = match segments.split_first() {
Some((&"$root", rest)) => (true, rest),
_ => (false, segments.as_slice()),
};
let first = *segments.first()?;
let has = |dm: &DataModelIr, field: &str| {
dm.properties.iter().any(|p| *p.name == *field) || dm.is_maturity_flag(field)
};
let (mut current, mut rest) = match entity.and_then(|e| entities.get(e)) {
Some(dm) if !rooted && has(dm, first) => (dm.clone(), segments),
_ => (entities.get(first)?.clone(), &segments[1..]),
};
while let Some((field, tail)) = rest.split_first() {
// A maturity flag is as much an outcome as its outcome.
if tail.is_empty() && current.is_maturity_flag(field) {
return Some(format!("{}.{field}", current.name));
}
let prop = current.properties.iter().find(|p| *p.name == **field)?;
if prop.is_outcome() {
return Some(format!("{}.{field}", current.name));
}
match &prop.kind {
PropertyTypeIr::Reference { target } | PropertyTypeIr::Relationship { target }
if !tail.is_empty() =>
{
current = entities.get(target)?.clone();
rest = tail;
}
_ => return None,
}
}
None
}
/// The entity a path's value is, through references and relationships
/// (`transaction.card` → `card`): from `entity`'s own fields when the
/// path starts with one, else from the entity it names (`$root.card`).
pub(crate) fn entity_at<'a, S: std::hash::BuildHasher>(
entities: &'a std::collections::HashMap<Arc<str>, Arc<DataModelIr>, S>,
entity: Option<&str>,
path: &str,
) -> Option<&'a Arc<DataModelIr>> {
let segments: Vec<&str> = path.split('.').collect();
let (rooted, segments) = match segments.split_first() {
Some((&"$root", rest)) => (true, rest),
_ => (false, segments.as_slice()),
};
let first = *segments.first()?;
let own = entity
.and_then(|e| entities.get(e))
.filter(|dm| dm.properties.iter().any(|p| *p.name == *first));
let named = entities.get(first).map(|dm| (dm, &segments[1..]));
let (mut current, rest) = match (rooted, own, named) {
(true, _, Some(named)) | (false, None, Some(named)) => named,
(_, Some(own), _) => (own, segments),
_ => return None,
};
for field in rest {
let prop = current.properties.iter().find(|p| *p.name == **field)?;
match &prop.kind {
PropertyTypeIr::Reference { target } | PropertyTypeIr::Relationship { target } => {
current = entities.get(target)?;
}
_ => return None,
}
}
Some(current)
}
/// What reading `name`, no field of this entity, means: a windowed
/// feature's name as written lists its windows (`txn_count` →
/// `txn_count_7d` or `txn_count_30d`), else the entity has no `name`.
/// None when `name` is a field (or a maturity flag) after all.
pub(crate) fn unknown_member_message(&self, name: &str) -> Option<String> {
if self.properties.iter().any(|p| *p.name == *name) || self.is_maturity_flag(name) {
return None;
}
let windows: Vec<String> = self
.properties
.iter()
.filter(|p| match p.supply.as_deref() {
Some(Supply::Feature {
base,
window: Some(_),
..
}) => **base == *name,
_ => false,
})
.map(|p| format!("`{}`", p.name))
.collect();
Some(match windows.split_last() {
None => format!("`{}` has no `{name}`", self.name),
Some((last, [])) => format!("`{name}` has windows: read {last}"),
Some((last, rest)) => {
format!("`{name}` has windows: read {} or {last}", rest.join(", "))
}
})
}
}
/// A feature window as written: a positive whole number (no leading zero)
/// of minutes, hours or days (`10m`, `1h`, `7d`), or `all` (all time).
fn is_window(window: &str) -> bool {
// `all`: every day there is data for.
window == "all" || is_duration(window, &["m", "h", "d"])
}
/// A positive whole number (no leading zero, no spaces) followed by one of
/// `units`: `30s`, `10m`, `250ms`.
pub(crate) fn is_duration(text: &str, units: &[&str]) -> bool {
units.iter().any(|unit| {
text.strip_suffix(unit).is_some_and(|digits| {
!digits.is_empty()
&& !digits.starts_with('0')
&& digits.bytes().all(|b| b.is_ascii_digit())
})
})
}
/// The property a feature window becomes: `<name>_<window>`; a single
/// window already at the end of the name (`txn_count_7d`) is not doubled.
/// The feature store names its features the same way.
pub fn window_name(name: &Arc<str>, window: &str, listed: bool) -> Arc<str> {
let suffix = format!("_{window}");
if !listed && name.ends_with(&suffix) {
name.clone()
} else {
Arc::from(format!("{name}{suffix}"))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DictionaryIr {
pub name: Arc<str>,
@@ -551,6 +1214,7 @@ impl std::fmt::Display for PropertyTypeIr {
}
PropertyTypeIr::Number => f.write_str("number"),
PropertyTypeIr::Boolean => f.write_str("bool"),
PropertyTypeIr::Any => f.write_str("any"),
PropertyTypeIr::Date => f.write_str("date"),
PropertyTypeIr::Reference { target } => {
write!(f, "reference id (string → {target})")
+3 -1
View File
@@ -23,11 +23,13 @@ pub use crate::workspace::{
EngineEdit, Entity, EntityField, EvaluateRequest, EvaluationError, EvaluationResult,
ExpressionFacts, ExpressionKind, FieldOrigin, FunctionResolutionRequest, FunctionTypeResolver,
GraphAnalysis, GraphNodeAnalysis, GraphSignature, GraphTraceMap, GuardedProperty,
InputProperty, InputValidationError, InspectResult, OutputProperty, PrepareRename,
InputProperty, InputValidationError, InspectResult, OutputProperty, PrepareRename, SuppliedBy,
PropertyKind, ReferenceKind, ReferenceSite, RenameTarget, SchemaFieldKind, SchemaGroup,
ScopeRequest, Severity, SlotResponse, SlotRole, Span, Trace, Workspace, WriteConflict,
WriteTrace,
};
pub use crate::workspace::{EndpointKind, SchemaAudience};
pub use ir::Supply;
pub use raw::{BlockDoc, PolicyDocument};
pub type PolicyWorkspace = Workspace;
@@ -75,6 +75,11 @@ impl Drop for EnrichedState {
}
impl EnrichedState {
/// The request as declared by the data models, before any rule writes.
pub(crate) fn declared_scope(&self) -> VariableType {
VariableType::Object(Rc::new(RefCell::new(self.base_fields.clone())))
}
pub(crate) fn declared_at(&self, path: &str) -> VariableType {
let (root, rest) = path.split_once('.').unwrap_or((path, ""));
match self.base_fields.get(root) {
File diff suppressed because it is too large Load Diff
+60 -11
View File
@@ -3,13 +3,14 @@ use std::sync::Arc;
use ahash::{HashMap, HashSet};
use zen_expression::variable::VariableType;
use crate::policy::ir::DataModelIr;
use crate::policy::ir::{DataModelIr, Records};
use crate::policy::queries::dependency::{DependencyGraph, PathPrefix};
use crate::policy::queries::scope::PropertyScope;
use crate::workspace::db::{Db, DictionaryUnitEntry};
use crate::workspace::types::{
Dictionary, DictionaryEntryInfo, Entity, EntityField, FieldOrigin, Global, InputProperty,
OutputProperty, PropertyKind, ScopeRequest,
SuppliedBy,
};
impl Db {
@@ -71,6 +72,8 @@ impl Db {
origin: FieldOrigin::Schema {
source: vp.policy_path,
kind: vp.property.kind.to_schema_field_kind(vp.property.array),
exact_type: vp.property.exact.clone(),
supply: vp.property.supply.clone(),
},
});
}
@@ -147,25 +150,54 @@ impl Db {
let visible = &unit.members;
let entities = &unit.entities;
let (root_entities, ref_targets) = self.classify_root_entities(visible);
// Only the root entities its rules (and its imports') read or write: an
// imported model may declare entities this policy never touches. All of
// them when a read can't be followed (`$`, unresolved) or there are no
// rules (a document of data models: its request is all of them).
let touched: Option<HashSet<Arc<str>>> = {
let shallow = self.shallow();
let mut touched = HashSet::default();
let mut known = true;
let mut rules = 0;
for rule in shallow.per_rule.iter().filter(|r| visible.contains(&r.policy_path)) {
rules += 1;
for read in &rule.reads {
let path = read.path.as_ref();
if path.starts_with('$') || read.unresolved {
known = false;
}
touched.insert(Arc::from(path.split('.').next().unwrap_or(path)));
}
for write in &rule.writes {
let path = write.path.as_ref();
touched.insert(Arc::from(path.split('.').next().unwrap_or(path)));
}
}
(known && rules > 0).then_some(touched)
};
let mut result: Vec<InputProperty> = self
.walk_visible_properties(&req.policy_path)
.into_iter()
// An outcome is known only after the decision: never an input.
.filter(|vp| !vp.property.is_outcome())
.filter(|vp| match &vp.scope {
PropertyScope::Entity(entity) => root_entities.contains(entity),
PropertyScope::Entity(entity) => {
root_entities.contains(entity)
&& touched.as_ref().is_none_or(|t| t.contains(entity))
}
PropertyScope::Global => true,
})
.map(|vp| {
let mut visited: HashSet<Arc<str>> = HashSet::default();
InputProperty {
path: vp.dotted_path(),
resolved_type: DataModelIr::wire_property_type(
&vp.property,
entities,
&unit.dictionaries,
&mut visited,
),
}
let property = &vp.property;
let resolved_type = DataModelIr::wire_property_type(
property,
entities,
&unit.dictionaries,
&mut visited,
);
InputProperty::of_property(vp.dotted_path(), property, resolved_type, entities)
})
.collect();
@@ -177,9 +209,24 @@ impl Db {
let entity_type =
DataModelIr::wire_object(target, entities, &unit.dictionaries, &mut visited);
if !matches!(entity_type, VariableType::Any) {
// A referenced entity's records: sent by the caller, unless it
// comes from the store or a source (events, reference data,
// features).
let hosted = entities.get(target).is_some_and(|dm| {
dm.records != Records::Plain
|| dm
.properties
.iter()
.any(|p| p.supply.is_some() && !p.is_outcome())
});
result.push(InputProperty {
path: target.clone(),
resolved_type: entity_type.array(),
optional: hosted,
supplied_by: if hosted { SuppliedBy::Host } else { SuppliedBy::Request },
default: None,
reference: None,
record_references: Default::default(),
});
}
}
@@ -241,6 +288,8 @@ impl Db {
let origin = FieldOrigin::Schema {
source: vp.policy_path,
kind: vp.property.kind.to_schema_field_kind(vp.property.array),
exact_type: vp.property.exact.clone(),
supply: vp.property.supply.clone(),
};
Some((
entity,
+4
View File
@@ -424,6 +424,8 @@ impl Snapshot {
}
for prop in &dm.properties {
match &prop.kind {
// A stored relationship isn't where its target lives: its members are found.
PropertyTypeIr::Relationship { .. } if prop.is_stored() => {}
PropertyTypeIr::Relationship { target } => {
let (path, owner) = if dm.scope.is_global() {
(Arc::from(prop.name.as_ref()), None)
@@ -673,6 +675,7 @@ impl PropertyTypeIr {
)),
PropertyTypeIr::Number => Some(VariableType::Number),
PropertyTypeIr::Boolean => Some(VariableType::Bool),
PropertyTypeIr::Any => Some(VariableType::Any),
PropertyTypeIr::Date => Some(VariableType::Date),
PropertyTypeIr::Relationship { .. } | PropertyTypeIr::Reference { .. } => None,
}
@@ -693,6 +696,7 @@ impl Property {
}
PropertyTypeIr::Number => VariableType::Number,
PropertyTypeIr::Boolean => VariableType::Bool,
PropertyTypeIr::Any => VariableType::Any,
PropertyTypeIr::Relationship { target } | PropertyTypeIr::Reference { target } => {
match entity_map.get(target.as_ref()) {
Some(t) => t.shallow_clone(),
+305 -1
View File
@@ -219,6 +219,74 @@ pub struct DataModelDoc {
pub scope: ScopeDoc,
#[serde(default)]
pub properties: Vec<PropertyDoc>,
/// An entity whose records are events (`{ "id": .., "time": .. }`):
/// read by the feature store, kept as is here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub events: Option<serde_json::Value>,
/// An entity whose records are reference data, optionally versioned
/// (`{ "validFrom": .., "validTo": .. }`): read by the feature store,
/// kept as is here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reference: Option<serde_json::Value>,
/// The key property (`id` when absent), or a list for a composite key:
/// read by the feature store, kept as is here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<serde_json::Value>,
/// Has-many reference rows: the property identifying a row, when it is
/// not the key. Kept as is here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub row_key: Option<Arc<str>>,
/// Where the entity's data comes from (`history`, `stream`, `changes`,
/// `live`), by datasource name: read by the feature store, kept as is.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sources: Option<serde_json::Value>,
/// The daily rebuild of its features from the history: kept as is.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rebuild: Option<serde_json::Value>,
/// An events entity that may have no events on a day: kept as is.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sparse: Option<bool>,
/// Attributes the engine doesn't read, kept as is.
#[serde(flatten)]
pub rest: serde_json::Map<String, serde_json::Value>,
}
impl DataModelDoc {
/// The source of a property's expression: `feature.expr`, `compute`, a
/// model input's request path or `model.when` (empty when not written).
pub fn expression(&self, target: &crate::workspace::types::CursorTarget) -> Option<Arc<str>> {
use crate::workspace::types::CursorTarget;
let (CursorTarget::FeatureExpr { id }
| CursorTarget::OutcomeExpr { id }
| CursorTarget::ComputeExpr { id }
| CursorTarget::ModelInput { id, .. }
| CursorTarget::ModelWhen { id }
| CursorTarget::ModelRequest { id }
| CursorTarget::ModelResponse { id }) = target
else {
return None;
};
let prop = self.properties.iter().find(|p| p.id == *id)?;
let model_str = |value: Option<&serde_json::Value>| {
Arc::from(value.and_then(serde_json::Value::as_str).unwrap_or(""))
};
Some(match target {
CursorTarget::FeatureExpr { .. } => prop.feature.as_ref()?.expr.clone(),
CursorTarget::OutcomeExpr { .. } => prop
.outcome
.as_ref()?
.expr
.clone()
.unwrap_or_else(|| Arc::from("")),
CursorTarget::ComputeExpr { .. } => prop.compute.clone().unwrap_or_else(|| Arc::from("")),
CursorTarget::ModelInput { input, .. } => {
model_str(prop.model.as_ref()?.get("inputs")?.get(input.as_ref()))
}
CursorTarget::ModelRequest { .. } => model_str(prop.model.as_ref()?.get("request")),
CursorTarget::ModelResponse { .. } => model_str(prop.model.as_ref()?.get("response")),
_ => model_str(prop.model.as_ref()?.get("when")),
})
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
@@ -230,7 +298,7 @@ pub enum ScopeDoc {
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(rename_all = "camelCase", from = "PropertyDocWire")]
pub struct PropertyDoc {
pub id: Arc<str>,
pub name: Arc<str>,
@@ -240,6 +308,170 @@ pub struct PropertyDoc {
pub array: bool,
#[serde(default)]
pub optional: bool,
/// A feature: a value the host computes and supplies (e.g. a windowed
/// aggregate over an events entity). Each window becomes an optional
/// input property `<name>_<window>`; see [`FeatureDoc`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub feature: Option<FeatureDoc>,
/// An outcome: what happened after the decision (a chargeback, how a
/// claim ended), computed offline by the host; see [`OutcomeDoc`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<OutcomeDoc>,
/// Computed per event by the host from the event's other properties
/// (an events entity's `amount_gbp = amount * fx_rate`): always supplied.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compute: Option<Arc<str>>,
/// The column in the source data when it differs from the name: read by
/// the feature store, kept as is.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub column: Option<Arc<str>>,
/// A model's output: the host calls the model with the property's
/// inputs and supplies it. Kept as is here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<serde_json::Value>,
/// The host always supplies it, or rejects the request: never null.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub required: Option<bool>,
/// Attributes the engine doesn't read, kept as is.
#[serde(flatten)]
pub rest: serde_json::Map<String, serde_json::Value>,
}
/// [`PropertyDoc`] as read. Two flattened fields both see every key: the
/// tagged type takes `type`/`enum`/`scale`/`target`, and `rest` collects
/// them again. Left there they would be written twice (a JSON string with
/// duplicate keys, which doesn't read back) and override edits to the type.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PropertyDocWire {
id: Arc<str>,
name: Arc<str>,
#[serde(flatten)]
property_type: PropertyTypeDoc,
#[serde(default)]
array: bool,
#[serde(default)]
optional: bool,
#[serde(default)]
feature: Option<FeatureDoc>,
#[serde(default)]
outcome: Option<OutcomeDoc>,
#[serde(default)]
compute: Option<Arc<str>>,
#[serde(default)]
column: Option<Arc<str>>,
#[serde(default)]
model: Option<serde_json::Value>,
#[serde(default)]
required: Option<bool>,
#[serde(flatten)]
rest: serde_json::Map<String, serde_json::Value>,
}
/// The keys [`PropertyTypeDoc`] reads (its tag and its variants' fields).
const PROPERTY_TYPE_KEYS: [&str; 4] = ["type", "enum", "scale", "target"];
impl From<PropertyDocWire> for PropertyDoc {
fn from(wire: PropertyDocWire) -> Self {
let mut rest = wire.rest;
for key in PROPERTY_TYPE_KEYS {
rest.remove(key);
}
Self {
id: wire.id,
name: wire.name,
property_type: wire.property_type,
array: wire.array,
optional: wire.optional,
feature: wire.feature,
outcome: wire.outcome,
compute: wire.compute,
column: wire.column,
model: wire.model,
required: wire.required,
rest,
}
}
}
/// A property computed by the host's feature store. The engine only needs
/// its windows (which properties exist); everything else is kept as is.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FeatureDoc {
#[serde(default)]
pub expr: Arc<str>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window: Option<WindowsDoc>,
/// The value when the feature is unknown (not covered): never null then.
/// `Some(null)` when written as `null`, kept as written.
#[serde(
default,
deserialize_with = "written",
skip_serializing_if = "Option::is_none"
)]
pub default: Option<serde_json::Value>,
#[serde(flatten)]
pub rest: serde_json::Map<String, serde_json::Value>,
}
/// An outcome on a property: what is known about the entity after the
/// decision, read offline (training labels, impact analysis), never by
/// rules. `expr` is a feature expression that also reads `decidedAt`;
/// without one (absent, or blank: read as absent and written back without
/// it) the outcome is the entity's own column, named like the property (or
/// its `column`), read by the host. The answer is always the value as known
/// (never hidden); `maturity` (days, `30d`) says when a decision is old
/// enough to trust a negative answer. Kept as written (`maturity` as any
/// value, checked by the parser).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OutcomeDoc {
#[serde(
default,
deserialize_with = "non_blank",
skip_serializing_if = "Option::is_none"
)]
pub expr: Option<Arc<str>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maturity: Option<serde_json::Value>,
#[serde(flatten)]
pub rest: serde_json::Map<String, serde_json::Value>,
}
/// A string, `None` when absent, `null` or blank.
fn non_blank<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Arc<str>>, D::Error> {
Ok(Option::<Arc<str>>::deserialize(deserializer)?.filter(|text| !text.trim().is_empty()))
}
/// A value as written, `null` included (`Some(null)`, not `None`).
fn written<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<serde_json::Value>, D::Error> {
serde_json::Value::deserialize(deserializer).map(Some)
}
/// A call's named `inputs` (the earlier format, which wins over `request`):
/// `None` when absent or `null`.
pub(crate) fn call_inputs(model: &serde_json::Value) -> Option<&serde_json::Value> {
model.get("inputs").filter(|inputs| !inputs.is_null())
}
/// One window (`"7d"`) or several (`["1h", "7d"]`).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum WindowsDoc {
One(Arc<str>),
Many(Vec<Arc<str>>),
}
impl WindowsDoc {
pub fn list(&self) -> Vec<Arc<str>> {
match self {
WindowsDoc::One(w) => vec![w.clone()],
WindowsDoc::Many(ws) => ws.clone(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -270,6 +502,18 @@ pub enum PropertyTypeDoc {
Number,
Boolean,
Date,
/// An old name for `number` (a `scale` with it is dropped): still read,
/// with a warning to use `number`.
Decimal,
/// An old name for `number`: still read, with a warning.
Integer,
/// An old name for `date`: still read, with a warning.
Timestamp,
/// A structured value (a map, such as a feature grouped by a column):
/// any value here.
Object,
/// Any value.
Any,
Relationship {
target: Arc<str>,
},
@@ -282,6 +526,66 @@ pub enum PropertyTypeDoc {
mod tests {
use super::*;
#[test]
fn unknown_data_model_attributes_round_trip() {
let doc_json = serde_json::json!({
"blocks": [{ "id": "dm", "type": "dataModel", "props": { "data": {
"name": "card",
"owner": "risk",
"properties": [
{ "id": "p1", "name": "limit", "type": "decimal", "scale": 2, "description": "credit limit", "unit": "GBP" },
{ "id": "p2", "name": "holder", "type": "reference", "target": "customer", "ui": { "pinned": true } },
{ "id": "p3", "name": "status", "type": "string", "enum": ["a", "b"], "column": "status_cd" },
{ "id": "p4", "name": "txn_count", "type": "integer",
"feature": { "expr": "count(transaction)", "window": ["1h"], "bucket": "5m" } }
]
} } }]
});
let doc: PolicyDocument = serde_json::from_value(doc_json).unwrap();
let out = serde_json::to_value(&doc).unwrap();
let data = &out["blocks"][0]["props"]["data"];
assert_eq!(data["owner"], "risk");
let props = &data["properties"];
assert_eq!(props[0]["description"], "credit limit");
assert_eq!(props[0]["unit"], "GBP");
// `decimal` is an old name for `number`; its `scale` is dropped.
assert_eq!(props[0]["type"], "decimal");
assert!(props[0].get("scale").is_none());
assert_eq!(props[1]["ui"], serde_json::json!({ "pinned": true }));
assert_eq!(props[1]["target"], "customer");
assert_eq!(props[2]["column"], "status_cd");
assert_eq!(props[3]["feature"]["bucket"], "5m");
// Read back the same.
let again: PolicyDocument = serde_json::from_value(out.clone()).unwrap();
assert_eq!(serde_json::to_value(&again).unwrap(), out);
}
#[test]
fn property_type_keys_are_written_once() {
let doc_json = serde_json::json!({
"blocks": [{ "id": "dm", "type": "dataModel", "props": { "data": {
"name": "card",
"properties": [
{ "id": "p1", "name": "limit", "type": "decimal", "scale": 2, "unit": "GBP" },
{ "id": "p2", "name": "holder", "type": "reference", "target": "customer" },
{ "id": "p3", "name": "status", "type": "string", "enum": ["a", "b"] }
]
} } }]
});
let doc: PolicyDocument = serde_json::from_value(doc_json).unwrap();
// As text: no key twice, so it reads back.
let text = serde_json::to_string(&doc).unwrap();
assert_eq!(text.matches("\"type\":\"reference\"").count(), 1, "{text}");
assert_eq!(text.matches("\"target\"").count(), 1, "{text}");
let again: PolicyDocument = serde_json::from_str(&text).unwrap();
assert_eq!(
serde_json::to_value(&again).unwrap(),
serde_json::to_value(&doc).unwrap()
);
// Unknown attributes are still kept.
assert!(text.contains("\"unit\":\"GBP\""), "{text}");
}
#[test]
fn unknown_block_round_trips_losslessly() {
let doc_json = serde_json::json!({
+64 -1
View File
@@ -114,12 +114,16 @@ pub(crate) enum CompiledEntry {
pub(crate) struct CompiledSet {
entries: HashMap<Arc<str>, CompiledEntry>,
failures: Vec<CompileFailure>,
/// What each compiled document reads from its request (None: unknown).
reads: HashMap<Arc<str>, Option<std::collections::BTreeSet<String>>>,
}
impl CompiledSet {
pub(crate) fn build_sync(loader: &DynamicLoader, keys: &[Arc<str>]) -> CompiledSet {
let mut workspace = Workspace::new();
let mut policy_keys: Vec<Arc<str>> = Vec::new();
let mut graph_keys: Vec<Arc<str>> = Vec::new();
let mut outcomes = false;
let mut failures: Vec<CompileFailure> = Vec::new();
let mut entries: HashMap<Arc<str>, CompiledEntry> = HashMap::default();
@@ -141,6 +145,7 @@ impl CompiledSet {
};
match content.as_ref() {
DecisionContent::Policy(policy) => {
outcomes |= Self::declares_outcomes(&policy.0);
workspace.set_policy_arc(key.clone(), policy.0.clone());
policy_keys.push(key.clone());
}
@@ -152,9 +157,11 @@ impl CompiledSet {
error: Some(error.to_string()),
}),
Ok(()) => {
workspace.set_document_arc(key.clone(), content.clone());
let mut compiled = graph.clone();
Arc::make_mut(&mut compiled).compile();
entries.insert(key.clone(), CompiledEntry::Graph(compiled));
graph_keys.push(key.clone());
}
},
}
@@ -189,7 +196,63 @@ impl CompiledSet {
});
}
CompiledSet { entries, failures }
// A graph node reading an outcome (known only after the decision)
// fails its graph, as it fails a policy.
if outcomes {
for key in &graph_keys {
let diagnostics: Vec<Diagnostic> = workspace
.diagnostics(key)
.into_iter()
.filter(|d| {
d.severity == Severity::Error
&& d.code == crate::workspace::types::DiagnosticCode::OutcomeRead
})
.collect();
if diagnostics.is_empty() {
continue;
}
entries.remove(key);
failures.push(CompileFailure {
key: key.clone(),
kind: "graph",
diagnostics,
error: None,
});
}
}
let reads = entries.keys().map(|key| (key.clone(), workspace.reads(key))).collect();
CompiledSet { entries, failures, reads }
}
pub(crate) fn reads(&self, key: &str) -> Option<std::collections::BTreeSet<String>> {
let key = self.key_of(key)?;
self.reads.get(&key).cloned().flatten()
}
/// The key a document is compiled under: as given, or with/without
/// `.json` (loaders find documents either way).
pub(crate) fn key_of(&self, key: &str) -> Option<Arc<str>> {
let candidates = [
Some(key.to_string()),
key.strip_suffix(".json").map(str::to_string),
(!key.ends_with(".json")).then(|| format!("{key}.json")),
];
candidates.into_iter().flatten().find_map(|candidate| {
self.entries
.get_key_value(candidate.as_str())
.map(|(k, _)| k.clone())
})
}
/// Whether a policy declares an outcome on a data model property.
fn declares_outcomes(policy: &PolicyDocument) -> bool {
policy.blocks.iter().any(|block| match block {
crate::policy::raw::BlockDoc::DataModel { data, .. } => {
data.properties.iter().any(|p| p.outcome.is_some())
}
_ => false,
})
}
fn error_diagnostics(workspace: &Workspace, key: &Arc<str>) -> Vec<Diagnostic> {
+225 -14
View File
@@ -18,15 +18,13 @@ impl Db {
let visible_dms = self.visible_data_models(policy_path);
let (roots, ref_targets) =
DataModelIr::classify_roots(visible_dms.iter().map(|dm| dm.as_ref()));
let dated = InputSchema::dated(&entities);
InputSchema {
InputSchema::new(
entities,
globals,
roots,
ref_targets,
dated,
dictionaries: self.unit(policy_path).dictionaries.clone(),
}
self.unit(policy_path).dictionaries.clone(),
)
}
fn visible_globals(&self, policy_path: &str) -> HashMap<Arc<str>, Property> {
@@ -77,9 +75,73 @@ pub(crate) struct InputSchema {
ref_targets: HashSet<Arc<str>>,
dated: HashSet<Arc<str>>,
dictionaries: HashMap<Arc<str>, Arc<DictionaryIr>>,
/// The properties with a `default`, per entity and global (by name):
/// found once, not on every evaluation. Kept as JSON (a `Variable` isn't
/// `Send`), made a value only when filled in.
defaults: Defaults,
}
#[derive(Default)]
struct Defaults {
entities: HashMap<Arc<str>, Vec<Property>>,
globals: Vec<Property>,
}
impl Defaults {
fn is_empty(&self) -> bool {
self.entities.is_empty() && self.globals.is_empty()
}
}
impl InputSchema {
fn new(
entities: Arc<HashMap<Arc<str>, Arc<DataModelIr>>>,
globals: HashMap<Arc<str>, Property>,
roots: HashSet<Arc<str>>,
ref_targets: HashSet<Arc<str>>,
dictionaries: HashMap<Arc<str>, Arc<DictionaryIr>>,
) -> Self {
let with_default = |props: &mut dyn Iterator<Item = &Property>| -> Vec<Property> {
props.filter(|p| p.default.is_some()).cloned().collect()
};
let mut global_defaults = with_default(&mut globals.values());
global_defaults.sort_by(|a, b| a.name.cmp(&b.name));
let defaults = Defaults {
entities: entities
.iter()
.map(|(name, model)| (name.clone(), with_default(&mut model.properties.iter())))
.filter(|(_, props)| !props.is_empty())
.collect(),
globals: global_defaults,
};
InputSchema {
dated: Self::dated(&entities, &defaults),
entities,
globals,
roots,
ref_targets,
dictionaries,
defaults,
}
}
/// The schema of a graph's request typed by an entity: `target` at the
/// root, the entities it references as pools beside it.
pub(crate) fn for_request(
entities: Arc<HashMap<Arc<str>, Arc<DataModelIr>>>,
target: Arc<str>,
pools: impl IntoIterator<Item = Arc<str>>,
dictionaries: HashMap<Arc<str>, Arc<DictionaryIr>>,
) -> Self {
InputSchema::new(
entities,
HashMap::new(),
std::iter::once(target).collect(),
pools.into_iter().collect(),
dictionaries,
)
}
pub(crate) fn validate(&self, input: &Variable) -> Vec<InputValidationError> {
let ref_pools = RefPoolIndex::from_input(input, self.ref_targets.iter().cloned());
let mut validator = InputValidator {
@@ -123,8 +185,14 @@ impl InputSchema {
}
impl InputSchema {
fn dated(entities: &HashMap<Arc<str>, Arc<DataModelIr>>) -> HashSet<Arc<str>> {
let mut dated: HashSet<Arc<str>> = HashSet::default();
/// The entities whose instances a request may change: a `Date`
/// property or a property with a `default`, directly or through a
/// relationship. Any other entity is passed through untouched.
fn dated(
entities: &HashMap<Arc<str>, Arc<DataModelIr>>,
defaults: &Defaults,
) -> HashSet<Arc<str>> {
let mut dated: HashSet<Arc<str>> = defaults.entities.keys().cloned().collect();
loop {
let before = dated.len();
for (name, model) in entities.iter() {
@@ -146,8 +214,12 @@ impl InputSchema {
}
}
/// The input with declared dates converted and missing (or null)
/// properties given their `default`, on every entity instance: roots,
/// pool items and nested objects. `None` when nothing changes; the
/// input itself is never modified.
pub(crate) fn convert_dates(&self, input: &Variable) -> Option<Variable> {
DeclaredDates::rewrite_fields(input, |key, value| {
let converted = DeclaredDates::rewrite_fields(input, |key, value| {
if self.ref_targets.contains(key) {
DeclaredDates::rewrite_items(value, |item| self.convert_entity(item, key, 0))
} else if self.roots.contains(key) {
@@ -155,7 +227,11 @@ impl InputSchema {
} else {
self.convert_property(value, self.globals.get(key)?, 0)
}
})
});
if input.as_object().is_none() || self.defaults.is_empty() {
return converted;
}
self.fill_defaults(converted, input, &self.defaults.globals, 0)
}
fn convert_entity(&self, value: &Variable, entity: &str, depth: usize) -> Option<Variable> {
@@ -163,10 +239,55 @@ impl InputSchema {
return None;
}
let model = self.entities.get(entity)?;
DeclaredDates::rewrite_fields(value, |key, child| {
let converted = DeclaredDates::rewrite_fields(value, |key, child| {
let property = model.properties.iter().find(|p| *p.name == *key)?;
self.convert_property(child, property, depth + 1)
})
});
match self.defaults.entities.get(entity) {
Some(defaults) => self.fill_defaults(converted, value, defaults, depth + 1),
None => converted,
}
}
/// Sets each missing or null property that has a `default` (converted
/// like a supplied value), on a copy.
fn fill_defaults(
&self,
converted: Option<Variable>,
value: &Variable,
properties: &[Property],
depth: usize,
) -> Option<Variable> {
if properties.is_empty() {
return converted;
}
let current = converted.as_ref().unwrap_or(value);
let object = current.as_object()?;
let missing: Vec<(Arc<str>, Variable)> = {
let fields = object.borrow();
properties
.iter()
.filter_map(|p| {
let default = p.default.as_ref()?;
let absent = fields
.get(&zen_types::symbol::Symbol::from(p.name.as_ref()))
.is_none_or(|v| matches!(v, Variable::Null));
absent.then(|| {
let filled = Variable::from(default.as_ref().clone());
let filled = self.convert_property(&filled, p, depth).unwrap_or(filled);
(p.name.clone(), filled)
})
})
.collect()
};
if missing.is_empty() {
return converted;
}
let mut next = object.borrow().clone();
for (name, filled) in missing {
next.insert_str(&name, filled);
}
Some(Variable::from_object(next))
}
fn convert_property(
@@ -259,10 +380,11 @@ impl InputValidator<'_> {
if matches!(val, Variable::Null) {
continue;
}
// A stored relationship's members are the host's, never checked as input.
let Some(prop) = dm_props
.properties
.iter()
.find(|p| *p.name == *key.as_str())
.find(|p| *p.name == *key.as_str() && !p.is_stored())
else {
continue;
};
@@ -324,6 +446,7 @@ impl InputValidator<'_> {
}
PropertyTypeIr::Number => matches!(value, Variable::Number(_)),
PropertyTypeIr::Boolean => matches!(value, Variable::Bool(_)),
PropertyTypeIr::Any => true,
PropertyTypeIr::Date => match value {
Variable::String(text) => {
text.is_empty() || zen_expression::DateValue::is_text(text)
@@ -402,6 +525,9 @@ struct Sureness<'s> {
schema: &'s InputSchema,
rows: usize,
sure: Vec<bool>,
/// Columns already prepared (dates converted, defaults filled, pools
/// given as lists): dates and references there were checked then.
prepared: bool,
}
impl Sureness<'_> {
@@ -440,6 +566,13 @@ impl Sureness<'_> {
_ => false,
},
PropertyTypeIr::Relationship { target } => self.objects(target, column, at),
PropertyTypeIr::Any => true,
PropertyTypeIr::Date if self.prepared => match column.variable(at) {
Variable::String(text) => text.is_empty(),
other => zen_expression::DateValue::is(&other),
},
// Each prepared row's reference was found in its pool.
PropertyTypeIr::Reference { .. } if self.prepared => true,
PropertyTypeIr::Date | PropertyTypeIr::Reference { .. } => false,
}
}
@@ -534,7 +667,23 @@ impl Sureness<'_> {
let segments: Vec<&str> = path.split('.').collect();
let (first, rest) = segments.split_first()?;
if self.schema.ref_targets.contains(*first) {
return None;
// A prepared pool: each row's items checked as entities.
return match (self.prepared, rest.is_empty(), column.values) {
(true, true, zen_expression::lane::Values::List { child, .. }) => {
let child = child.column();
let zen_expression::lane::Values::Struct { fields, .. } = child.values else {
return None;
};
let target: Arc<str> = Arc::from(*first);
self.mark(column, |s, row| {
column.range(row).is_none_or(|(a, b)| {
(a..b).all(|item| !child.valid(item) || s.structs(&target, fields, item))
})
});
Some(())
}
_ => None,
};
}
if self.schema.roots.contains(*first) {
let mut entity: Arc<str> = Arc::from(*first);
@@ -579,17 +728,79 @@ impl InputSchema {
PropertyTypeIr::Relationship { target } => self.dated.contains(target),
_ => false,
});
if !self.dated.is_empty() || !self.ref_targets.is_empty() || dated_global {
if !self.dated.is_empty() || !self.ref_targets.is_empty() || dated_global || !self.defaults.globals.is_empty() {
return None;
}
let mut sureness = Sureness {
schema: self,
rows: columns.rows,
sure: vec![true; columns.rows],
prepared: false,
};
for (path, column) in &columns.columns {
sureness.path(path, column)?;
}
Some(sureness.sure)
}
/// [`Self::sure`] of prepared columns (see
/// `compiled::policy::columnar::prepare`): the rows certain to pass
/// validation as their row's prepared input would.
pub(crate) fn sure_prepared(&self, columns: &zen_expression::lane::Columns) -> Option<Vec<bool>> {
if self.converts_globals() {
return None;
}
let mut sureness = Sureness {
schema: self,
rows: columns.rows,
sure: vec![true; columns.rows],
prepared: true,
};
for (path, column) in &columns.columns {
sureness.path(path, column)?;
}
Some(sureness.sure)
}
/// Whether a global (outside any entity) is converted: a date, a
/// dated relationship, or a default.
pub(crate) fn converts_globals(&self) -> bool {
self.globals.values().any(|p| match &p.kind {
PropertyTypeIr::Date => true,
PropertyTypeIr::Relationship { target } => self.dated.contains(target),
_ => false,
}) || !self.defaults.globals.is_empty()
}
/// Whether any input is converted before evaluation (dates, defaults).
pub(crate) fn converts(&self) -> bool {
!self.dated.is_empty() || self.converts_globals()
}
pub(crate) fn is_root(&self, name: &str) -> bool {
self.roots.contains(name)
}
pub(crate) fn is_pool(&self, name: &str) -> bool {
self.ref_targets.contains(name)
}
pub(crate) fn is_dated(&self, entity: &str) -> bool {
self.dated.contains(entity)
}
pub(crate) fn model(&self, entity: &str) -> Option<&Arc<DataModelIr>> {
self.entities.get(entity)
}
/// The properties of `entity` with a default.
pub(crate) fn defaults_of(&self, entity: &str) -> &[Property] {
self.defaults.entities.get(entity).map_or(&[], Vec::as_slice)
}
/// A property's default as its value (converted like a given one).
pub(crate) fn default_value(&self, property: &Property) -> Option<Variable> {
let filled = Variable::from(property.default.as_ref()?.as_ref().clone());
Some(self.convert_property(&filled, property, 0).unwrap_or(filled))
}
}
+6 -25
View File
@@ -12,9 +12,7 @@ use crate::policy::blocks::{
SharedIntelliSense,
};
use crate::policy::evaluator::EvalArtifact;
use crate::policy::ir::{
DataModelIr, DictionaryIr, ParsedPolicy, Policy, Property, PropertyPath, Scope,
};
use crate::policy::ir::{DataModelIr, DictionaryIr, ParsedPolicy, Policy, PropertyPath};
use crate::policy::queries::dependency::{
DataModelPaths, DependencyGraph, EnrichedState, EvalGraph, RuleShallowAnalysis, ShallowAnalyses,
};
@@ -1058,28 +1056,11 @@ impl Snapshot {
) -> HashMap<Arc<str>, Arc<DataModelIr>> {
let mut sorted: Vec<&Arc<str>> = subset.keys().collect();
sorted.sort();
let mut props_by_entity: HashMap<Arc<str>, Vec<Property>> = HashMap::new();
for pp in sorted {
for (_, dm) in subset[pp].policy.entity_data_models() {
let bucket = props_by_entity.entry(dm.name.clone()).or_default();
for prop in &dm.properties {
if !bucket.iter().any(|p| p.name == prop.name) {
bucket.push(prop.clone());
}
}
}
}
props_by_entity
.into_iter()
.map(|(name, properties)| {
let dm = Arc::new(DataModelIr {
name: name.clone(),
scope: Scope::Entity,
properties,
});
(name, dm)
})
.collect()
crate::workspace::graph::merge_entities(
sorted
.into_iter()
.flat_map(|pp| subset[pp].policy.entity_data_models().map(|(_, dm)| dm)),
)
}
fn parse_all(
+95 -3
View File
@@ -1,8 +1,9 @@
use std::rc::Rc;
use std::sync::Arc;
use ahash::{HashMap, HashMapExt, HashSet};
use serde_json::Value;
use zen_expression::intellisense::completion::Completions;
use zen_expression::intellisense::completion::{CompletionKind, Completions};
use zen_expression::intellisense::Reference;
use zen_expression::slot::SlotRole;
use zen_expression::variable::VariableType;
@@ -28,15 +29,79 @@ impl Db {
role,
&scope,
)?;
let detail = r.detail.or_else(|| {
let path = Self::dotted_path_before(source.get(..r.span.1 as usize)?)?;
self.supply_detail(cursor, &path)
});
Some(InspectResult {
span: SpanOps::char_span(&source, r.span),
kind: r.kind,
label: r.label,
detail: r.detail,
detail,
info: r.info,
})
}
/// The dotted path ending the text: `transaction.card.txn_count_1h`.
fn dotted_path_before(text: &str) -> Option<Vec<&str>> {
let start = text
.char_indices()
.rev()
.take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '.' || *c == '$')
.last()
.map(|(i, _)| i)?;
let path: Vec<&str> = text[start..].split('.').collect();
path.iter().all(|s| !s.is_empty()).then_some(path)
}
/// `integer? · count(transaction) · 1h` for a property the host supplies
/// (a feature, a per-event compute, a model's output), by its path.
fn supply_detail(&self, cursor: &Cursor, path: &[&str]) -> Option<String> {
if self.is_graph(&cursor.policy_path) {
return None;
}
let unit = self.unit(&cursor.policy_path);
let (field, parent) = path.split_last()?;
let entity: Arc<str> = if parent.is_empty() {
// An entity's own properties, in its derived features and computes.
if !matches!(
cursor.target,
CursorTarget::FeatureExpr { .. }
| CursorTarget::OutcomeExpr { .. }
| CursorTarget::ComputeExpr { .. }
| CursorTarget::ModelRequest { .. }
| CursorTarget::ModelResponse { .. }
| CursorTarget::ModelWhen { .. }
) {
return None;
}
unit.data_models
.iter()
.find(|e| e.policy_path == cursor.policy_path && e.block_id == cursor.block_id)?
.ir
.name
.clone()
} else {
let segments: Vec<Rc<str>> = parent.iter().map(|s| Rc::from(*s)).collect();
unit.entity_graph.resolve_path_to_element(&segments)?
};
let dm = unit.entities.get(&entity)?;
match dm.properties.iter().find(|p| p.name.as_ref() == *field) {
Some(prop) => prop.supply_detail(),
// A maturity flag, in the entity's own outcome expressions.
None if parent.is_empty()
&& matches!(cursor.target, CursorTarget::OutcomeExpr { .. }) =>
{
let outcome = dm.flagged_outcome(field)?;
Some(crate::policy::ir::maturity_flag_detail(
&outcome.name,
outcome.outcome_maturity()?,
))
}
None => None,
}
}
pub fn completions(&self, cursor: &Cursor) -> Vec<Completion> {
let Some((source, _, _)) = self.resolve_cursor(cursor) else {
return Vec::new();
@@ -68,7 +133,31 @@ impl Db {
);
let mut completions = Completions::from_slot(source, pos, &scope.scope, &result.slot);
if !self.is_graph(&cursor.policy_path) {
completions.retain(|c| c.label != "$root");
// `$root` is the graph's request; a policy has none, unless the
// scope names it (a call's request: the whole request).
let scoped_root = matches!(
&scope.scope,
VariableType::Object(fields) if fields.borrow().contains_key("$root")
);
if !scoped_root {
completions.retain(|c| c.label != "$root");
}
let before = source.get(..result.slot.replace_span.0 as usize).unwrap_or("");
let parent = match before.strip_suffix('.') {
Some(receiver) => Self::dotted_path_before(receiver),
None => Some(Vec::new()),
};
if let Some(parent) = parent {
for completion in completions.iter_mut().filter(|c| {
matches!(c.kind, CompletionKind::Property | CompletionKind::Variable)
}) {
let path: Vec<&str> =
parent.iter().copied().chain([completion.label.as_str()]).collect();
if let Some(detail) = self.supply_detail(cursor, &path) {
completion.detail = detail;
}
}
}
}
completions
}
@@ -322,6 +411,9 @@ impl Db {
(BlockDoc::Assertion { data, .. }, CursorTarget::AssertionOutput) => {
data.output.clone()
}
(BlockDoc::DataModel { data, .. }, target) if target.is_data_model_expression() => {
data.expression(target)?
}
(BlockDoc::Match { data, .. }, CursorTarget::MatchTarget) => data.key.clone(),
(BlockDoc::Match { data, .. }, CursorTarget::MatchValue { id }) => {
data.arms.iter().find(|a| a.id == *id)?.value.clone()
+773
View File
@@ -0,0 +1,773 @@
//! A document as an endpoint: whether it serves one, and the JSON Schemas
//! (draft-07) of its request and response. One place for what the Agent's
//! OpenAPI document, BRMS API docs, MCP tools and the simulator describe.
//!
//! The request has two audiences. The contract is what a caller sends to a
//! host with a feature store: what the host supplies is left out and a
//! reference is the id of what it names. The evaluated request is what the
//! rules are given once the host has filled it in, as a decision log
//! records it: everything the request holds, the host's values included.
use std::collections::BTreeSet;
use std::sync::Arc;
use ahash::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use zen_expression::variable::VariableType;
use crate::model::{DecisionContent, DecisionNodeKind};
use crate::policy::ir::{DataModelIr, PropertyTypeIr};
use crate::policy::raw::BlockDoc;
use crate::workspace::db::Db;
use crate::workspace::types::{InputProperty, ScopeRequest, SuppliedBy};
const DRAFT: &str = "http://json-schema.org/draft-07/schema#";
/// What a document serves.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EndpointKind {
Graph,
Policy,
}
/// Who a request schema is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SchemaAudience {
/// What a caller sends: no host-supplied fields, references as ids.
Contract,
/// What the rules are given: the request as the host filled it in
/// (features, model outputs, computes, the referenced records).
Evaluated,
}
impl Db {
/// A graph, or a policy with at least one rule. A document of data
/// models and dictionaries only serves nothing; nor does an unknown path.
pub(crate) fn endpoint(&self, path: &str) -> Option<EndpointKind> {
match self.raw_document(path)?.as_ref() {
DecisionContent::Graph(_) => Some(EndpointKind::Graph),
DecisionContent::Policy(_) => {
let parsed = self.parsed(&Arc::from(path))?;
(!parsed.policy.rules.is_empty()).then_some(EndpointKind::Policy)
}
}
}
/// The request's JSON Schema, without `$id` (the caller names it). A
/// graph's declared input schema wins; a request nothing is known of is
/// an open object.
pub(crate) fn request_schema(&self, req: &ScopeRequest, audience: SchemaAudience) -> Value {
if let Some(declared) = self.declared_graph_schema(&req.policy_path, true) {
return declared;
}
let mut inputs = self.inputs(req);
if inputs.is_empty() {
return self.signature_schema(&req.policy_path, true);
}
let shape = self.request_shape(&req.policy_path);
for input in &mut inputs {
if let Some(pool) = shape.pools.get(&input.path) {
input.record_references = pool.references.clone();
}
}
from_inputs(&inputs, audience, &shape)
}
/// The response's JSON Schema, without `$id`: what the rules write. A
/// graph's declared output schema wins.
pub(crate) fn response_schema(&self, req: &ScopeRequest) -> Value {
if let Some(declared) = self.declared_graph_schema(&req.policy_path, false) {
return declared;
}
let outputs = self.outputs(req);
if outputs.is_empty() {
return self.signature_schema(&req.policy_path, false);
}
from_properties(
outputs
.iter()
.map(|output| (output.path.as_ref(), &output.resolved_type)),
)
}
/// The schema on a graph's Request (`input`) or Response node, its
/// dictionaries resolved; `None` when it declares none or names a
/// dictionary no import makes visible.
fn declared_graph_schema(&self, path: &str, input: bool) -> Option<Value> {
let document = self.raw_document(path)?;
let graph = document.as_graph()?;
let schema = graph.nodes.iter().find_map(|node| match &node.kind {
DecisionNodeKind::InputNode { content } if input => content.schema.clone(),
DecisionNodeKind::OutputNode { content } if !input => content.schema.clone(),
_ => None,
})?;
if !crate::decision_graph::schema_dict::schema_references_dictionary(&schema) {
return Some(schema.as_ref().clone());
}
let dictionaries = self
.graph_dictionary_blocks(&graph.imports)
.into_iter()
.map(|entry| (entry.ir.name.clone(), entry.ir.values().cloned().collect()))
.collect();
crate::decision_graph::schema_dict::resolve_schema(&schema, &dictionaries)
.ok()
.map(|(resolved, _)| resolved)
}
/// A graph's whole input or output type, as its analysis has it; an open
/// object when that says nothing.
fn signature_schema(&self, path: &str, input: bool) -> Value {
self.graph_analysis(&Arc::from(path))
.and_then(|analysis| {
let signature = &analysis.signature;
from_type(if input {
&signature.input
} else {
&signature.output
})
})
.unwrap_or_else(|| json!({ "$schema": DRAFT, "type": "object" }))
}
/// What the request's entities are beyond their types: their keys, the
/// pools of referenced records beside a policy's request, and the stored
/// relationships no request carries.
fn request_shape(&self, path: &Arc<str>) -> RequestShape {
if self.is_graph(path) {
let imports = self.graph_imports(path);
let blocks = self.graph_entity_blocks(&imports);
let entities = self.graph_entities(&imports);
let target = self
.raw_document(path)
.and_then(|document| document.as_graph()?.request_target());
let stored = target
.and_then(|target| entities.get(&target).cloned())
.map(|entity| {
entity
.properties
.iter()
.filter(|p| p.is_stored())
.map(|p| p.name.clone())
.collect()
})
.unwrap_or_default();
let paths: Vec<Arc<str>> = blocks.into_iter().map(|b| b.policy_path).collect();
return RequestShape {
ids: self.id_schemas(&paths, &entities),
pools: HashMap::default(),
stored,
};
}
let unit = self.unit(path);
let mut members: Vec<Arc<str>> = unit.members.iter().cloned().collect();
members.sort();
let targets: HashSet<&Arc<str>> = unit
.entities
.values()
.flat_map(|dm| &dm.properties)
.filter_map(|p| match &p.kind {
PropertyTypeIr::Reference { target } => Some(target),
_ => None,
})
.collect();
// A pool holds the referenced entity's records: their own references
// are ids, as anywhere in a policy's request.
let pools = targets
.into_iter()
.filter_map(|target| {
let dm = unit.entities.get(target)?;
let references = dm
.properties
.iter()
.filter_map(|p| match &p.kind {
PropertyTypeIr::Reference { target } => {
Some((p.name.clone(), target.clone()))
}
_ => None,
})
.collect();
let optional = dm
.properties
.iter()
.filter(|p| p.optional || p.default.is_some())
.map(|p| p.name.to_string())
.collect();
Some((
target.clone(),
Pool {
references,
optional,
},
))
})
.collect();
let stored = self
.walk_visible_properties(path)
.into_iter()
.filter(|vp| vp.property.is_stored())
.map(|vp| vp.dotted_path())
.collect();
RequestShape {
ids: self.id_schemas(&members, &unit.entities),
pools,
stored,
}
}
/// Each entity's id as a reference carries it: a string (ZEN reads
/// references by string id; a composite key's parts are joined), or the
/// values of a single enum key. Declared in `paths`, first wins.
fn id_schemas(
&self,
paths: &[Arc<str>],
entities: &HashMap<Arc<str>, Arc<DataModelIr>>,
) -> HashMap<Arc<str>, Value> {
let mut out: HashMap<Arc<str>, Value> = HashMap::default();
for path in paths {
let Some(policy) = self.raw_policy(path) else {
continue;
};
for block in &policy.blocks {
let BlockDoc::DataModel { data, .. } = block else {
continue;
};
if out.contains_key(&data.name) {
continue;
}
let key = match &data.key {
Some(Value::String(key)) => Some(key.as_str()),
Some(Value::Array(_)) => None,
_ => Some("id"),
};
let property = key.and_then(|key| {
entities
.get(&data.name)?
.properties
.iter()
.find(|p| p.name.as_ref() == key)
});
let schema = match property.map(|p| (&p.kind, p.array)) {
Some((PropertyTypeIr::Enum(values), false)) => json!({ "enum": values }),
_ => json!({ "type": "string" }),
};
out.insert(data.name.clone(), schema);
}
}
out
}
}
/// What [`from_inputs`] needs beyond the inputs.
#[derive(Default)]
pub(crate) struct RequestShape {
/// Each entity's id schema (a string when unknown).
ids: HashMap<Arc<str>, Value>,
/// The pools beside a policy's request, by entity.
pools: HashMap<Arc<str>, Pool>,
/// Stored relationships: the host finds their members; never sent.
stored: HashSet<Arc<str>>,
}
/// A pool of a referenced entity's records.
struct Pool {
/// The reference fields of its records.
references: std::collections::BTreeMap<Arc<str>, Arc<str>>,
/// The fields its records may leave out (optional, or with a default).
optional: HashSet<String>,
}
impl RequestShape {
/// The schema of a reference: the id of the entity it names.
fn id_schema(&self, target: &str, nullable: bool) -> Value {
let mut id = self
.ids
.get(target)
.cloned()
.unwrap_or_else(|| json!({ "type": "string" }));
id["description"] = json!(format!("{target} id"));
if nullable {
json!({ "anyOf": [id, { "type": "null" }] })
} else {
id
}
}
}
/// A request schema from the engine's input properties. The contract
/// leaves out what the host supplies; the evaluated request keeps it (but
/// not a stored relationship's members, which no request holds). A field
/// is required unless it is optional, has a default or is nullable; its
/// default is published. A reference sent as an id (always in the
/// contract, and in a policy's request, where pools hold the records) is
/// that id, at the top and inside a relationship's records.
pub(crate) fn from_inputs(
inputs: &[InputProperty],
audience: SchemaAudience,
shape: &RequestShape,
) -> Value {
let sent: Vec<&InputProperty> = inputs
.iter()
.filter(|input| match audience {
SchemaAudience::Contract => input.supplied_by == SuppliedBy::Request,
SchemaAudience::Evaluated => !shape.stored.contains(&input.path),
})
.collect();
let mut schema = nested(sent.iter().map(|input| {
let required = !input.optional && !matches!(input.resolved_type, VariableType::Nullable(_));
(
input.path.as_ref(),
&input.resolved_type,
required,
input.default.as_ref(),
)
}));
let as_id = |leaf: &Value| audience == SchemaAudience::Contract || is_string(leaf);
for input in &sent {
let pointer = format!(
"/properties/{}",
input
.path
.split('.')
.collect::<Vec<_>>()
.join("/properties/")
);
let Some(leaf) = schema.pointer_mut(&pointer) else {
continue;
};
if let Some(target) = &input.reference {
if as_id(leaf) {
let nullable =
input.optional || matches!(input.resolved_type, VariableType::Nullable(_));
let default = leaf.get("default").cloned();
*leaf = shape.id_schema(target, nullable);
if let Some(default) = default {
leaf["default"] = default;
}
}
}
if let Some(pool) = shape.pools.get(&input.path) {
pool_items(leaf, pool, audience);
}
for (field, target) in &input.record_references {
let Some(property) = record_schema(leaf)
.and_then(|record| record.get_mut("properties")?.get_mut(field.as_ref()))
else {
continue;
};
if as_id(property) {
let nullable = property.get("anyOf").is_some();
*property = shape.id_schema(target, nullable);
}
}
}
schema
}
/// A pool's records are found by their `id`, and may leave out what their
/// entity says is optional; the evaluated request's records carry what the
/// host keeps beside it (its key column), so they stay open.
fn pool_items(schema: &mut Value, pool: &Pool, audience: SchemaAudience) {
let Some(items) = record_schema(schema) else {
return;
};
if items["properties"].get("id").is_none() {
items["properties"]["id"] = json!({ "type": "string" });
}
let mut required: BTreeSet<String> = items["required"]
.as_array()
.into_iter()
.flatten()
.filter_map(|r| r.as_str().map(str::to_string))
.filter(|r| !pool.optional.contains(r))
.collect();
required.insert("id".to_string());
items["required"] = json!(required.into_iter().collect::<Vec<_>>());
if audience == SchemaAudience::Evaluated {
if let Some(items) = items.as_object_mut() {
items.remove("additionalProperties");
}
}
}
/// A string, or a nullable one.
fn is_string(schema: &Value) -> bool {
match schema.get("anyOf").and_then(Value::as_array) {
Some(options) => options.iter().any(is_string),
None => schema["type"] == "string",
}
}
/// The record object of a relationship's schema: itself, its items, or
/// either inside a nullable `anyOf`.
fn record_schema(schema: &mut Value) -> Option<&mut Value> {
if schema.get("anyOf").is_some() {
return schema["anyOf"]
.as_array_mut()?
.iter_mut()
.find(|s| s["type"] != "null")
.and_then(record_schema);
}
match schema["type"].as_str() {
Some("object") => Some(schema),
Some("array") => record_schema(schema.get_mut("items")?),
_ => None,
}
}
/// The schema of an engine type.
pub(crate) fn leaf_schema(variable_type: &VariableType) -> Value {
match variable_type {
VariableType::Any => json!({}),
VariableType::Null => json!({ "type": "null" }),
VariableType::Bool => json!({ "type": "boolean" }),
VariableType::String => json!({ "type": "string" }),
VariableType::Number => json!({ "type": "number" }),
VariableType::Date => json!({ "type": "string", "format": "date-time" }),
VariableType::Interval => json!({ "type": "string" }),
VariableType::Const(value) => json!({ "const": value.as_ref() }),
VariableType::Enum(name, values) => {
let mut schema = json!({
"enum": values.iter().map(|v| v.as_ref()).collect::<Vec<_>>()
});
if let Some(name) = name {
schema["title"] = json!(name.as_ref());
}
schema
}
VariableType::Array(items) => json!({ "type": "array", "items": leaf_schema(items) }),
VariableType::Object(fields) => {
let fields = fields.borrow();
let mut properties = Map::new();
let mut required = BTreeSet::new();
for (key, field) in fields.iter() {
properties.insert(key.to_string(), leaf_schema(field));
if !matches!(field, VariableType::Nullable(_)) {
required.insert(key.to_string());
}
}
let mut schema = json!({
"type": "object",
"properties": properties,
"additionalProperties": false,
});
if !required.is_empty() {
schema["required"] = json!(required.into_iter().collect::<Vec<_>>());
}
schema
}
VariableType::Nullable(inner) => {
json!({ "anyOf": [leaf_schema(inner), { "type": "null" }] })
}
}
}
fn set_at_path(root: &mut Value, path: &[&str], leaf: Value) {
let Some((last, parents)) = path.split_last() else {
return;
};
let mut cursor = root;
for segment in parents {
if cursor.get("type").and_then(Value::as_str) != Some("object") {
cursor["type"] = json!("object");
cursor["additionalProperties"] = json!(false);
}
if !cursor["properties"].is_object() {
cursor["properties"] = json!({});
}
let properties = &mut cursor["properties"];
if !properties[*segment].is_object() {
properties[*segment] = json!({
"type": "object",
"properties": {},
"additionalProperties": false,
});
}
cursor = &mut properties[*segment];
}
if !cursor["properties"].is_object() {
cursor["properties"] = json!({});
}
cursor["properties"][*last] = leaf;
}
/// A whole type as a root schema; `None` when it says nothing (`any`, or
/// an object without fields), rather than an object that forbids every key.
pub(crate) fn from_type(variable_type: &VariableType) -> Option<Value> {
match variable_type {
VariableType::Any => return None,
VariableType::Object(fields) if fields.borrow().is_empty() => return None,
_ => {}
}
let mut schema = leaf_schema(variable_type);
schema
.as_object_mut()?
.insert("$schema".to_string(), json!(DRAFT));
Some(schema)
}
/// Dotted property paths stitched into one object schema (as BRMS
/// `buildSchemaFromProperties`); a property is required unless nullable.
pub(crate) fn from_properties<'a>(
properties: impl IntoIterator<Item = (&'a str, &'a VariableType)>,
) -> Value {
nested(
properties
.into_iter()
.map(|(path, ty)| (path, ty, !matches!(ty, VariableType::Nullable(_)), None)),
)
}
/// Dotted paths nested into one object schema: (path, type, required,
/// default). A top-level field is required when a property under it is.
fn nested<'a>(
properties: impl IntoIterator<Item = (&'a str, &'a VariableType, bool, Option<&'a Value>)>,
) -> Value {
let mut root = json!({
"$schema": DRAFT,
"type": "object",
"properties": {},
"additionalProperties": false,
});
let mut required = BTreeSet::new();
for (path, variable_type, is_required, default) in properties {
let segments: Vec<&str> = path.split('.').collect();
let mut leaf = leaf_schema(variable_type);
if let Some(default) = default {
leaf["default"] = default.clone();
}
set_at_path(&mut root, &segments, leaf);
if let (Some(first), true) = (segments.first(), is_required) {
required.insert(first.to_string());
}
}
if !required.is_empty() {
root["required"] = json!(required.into_iter().collect::<Vec<_>>());
}
root
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::rc::Rc;
fn object(fields: &[(&str, VariableType)]) -> VariableType {
let map = fields
.iter()
.map(|(key, value)| (Rc::from(*key), value.clone()))
.collect();
VariableType::Object(Rc::new(RefCell::new(map)))
}
fn input(
path: &str,
optional: bool,
supplied_by: SuppliedBy,
default: Option<Value>,
) -> InputProperty {
InputProperty {
path: path.into(),
resolved_type: VariableType::Number,
optional,
supplied_by,
default,
reference: None,
record_references: Default::default(),
}
}
#[test]
fn dotted_paths_nest_into_objects() {
let cart = VariableType::Number;
let name = VariableType::String;
let schema = from_properties([("customer.name", &name), ("cart.total", &cart)]);
assert!(schema.get("$id").is_none());
assert_eq!(schema["$schema"], json!(DRAFT));
assert_eq!(schema["required"], json!(["cart", "customer"]));
assert_eq!(
schema["properties"]["customer"]["properties"]["name"],
json!({ "type": "string" })
);
assert_eq!(
schema["properties"]["cart"]["properties"]["total"],
json!({ "type": "number" })
);
assert_eq!(
schema["properties"]["customer"]["additionalProperties"],
json!(false)
);
}
#[test]
fn nullable_top_level_properties_are_not_required() {
let optional = VariableType::Nullable(Rc::new(VariableType::String));
let required = VariableType::Number;
let schema = from_properties([("note", &optional), ("amount", &required)]);
assert_eq!(schema["required"], json!(["amount"]));
assert_eq!(
schema["properties"]["note"],
json!({ "anyOf": [{ "type": "string" }, { "type": "null" }] })
);
}
#[test]
fn object_leaf_marks_non_nullable_fields_required() {
let value = object(&[
("id", VariableType::Number),
(
"note",
VariableType::Nullable(Rc::new(VariableType::String)),
),
]);
let schema = from_properties([("customer", &value)]);
let customer = &schema["properties"]["customer"];
assert_eq!(customer["required"], json!(["id"]));
assert_eq!(customer["properties"]["id"], json!({ "type": "number" }));
}
#[test]
fn any_becomes_an_open_schema() {
let any = VariableType::Any;
let schema = from_properties([("passthrough", &any)]);
assert_eq!(schema["properties"]["passthrough"], json!({}));
}
#[test]
fn uninformative_types_have_no_schema() {
assert_eq!(from_type(&VariableType::Any), None);
assert_eq!(from_type(&object(&[])), None);
let typed = from_type(&object(&[("total", VariableType::Number)])).unwrap();
assert_eq!(typed["$schema"], json!(DRAFT));
assert_eq!(typed["required"], json!(["total"]));
}
#[test]
fn requests_leave_out_what_the_host_supplies() {
let inputs = [
input("transaction.amount", false, SuppliedBy::Request, None),
input("transaction.txn_count_7d", false, SuppliedBy::Host, None),
input(
"customer.limit",
true,
SuppliedBy::Request,
Some(json!(100)),
),
input("note", true, SuppliedBy::Request, None),
];
let shape = RequestShape::default();
let schema = from_inputs(&inputs, SchemaAudience::Contract, &shape);
assert_eq!(schema["required"], json!(["transaction"]), "{schema}");
let transaction = &schema["properties"]["transaction"]["properties"];
assert!(transaction.get("amount").is_some());
assert!(
transaction.get("txn_count_7d").is_none(),
"a feature is not a request field: {schema}"
);
assert_eq!(
schema["properties"]["customer"]["properties"]["limit"]["default"],
json!(100)
);
assert!(schema["properties"].get("note").is_some());
// The rules are given the host's values too.
let evaluated = from_inputs(&inputs, SchemaAudience::Evaluated, &shape);
assert_eq!(
evaluated["properties"]["transaction"]["properties"]["txn_count_7d"],
json!({ "type": "number" })
);
}
#[test]
fn references_are_sent_as_ids() {
let record = object(&[("id", VariableType::Number), ("note", VariableType::String)]);
let line = object(&[("qty", VariableType::Number), ("product", record.clone())]);
let customer = InputProperty {
path: "customer".into(),
resolved_type: record,
optional: false,
supplied_by: SuppliedBy::Request,
default: None,
reference: Some("customer".into()),
record_references: Default::default(),
};
let lines = InputProperty {
path: "lines".into(),
resolved_type: VariableType::Array(Rc::new(line)),
optional: false,
supplied_by: SuppliedBy::Request,
default: None,
reference: None,
record_references: [("product".into(), "product".into())].into_iter().collect(),
};
let inputs = [customer, lines];
let shape = RequestShape::default();
let schema = from_inputs(&inputs, SchemaAudience::Contract, &shape);
assert_eq!(
schema["properties"]["customer"],
json!({ "type": "string", "description": "customer id" }),
"{schema}"
);
let item = &schema["properties"]["lines"]["items"]["properties"];
assert_eq!(
item["product"],
json!({ "type": "string", "description": "product id" }),
"{schema}"
);
assert_eq!(item["qty"], json!({ "type": "number" }));
// Evaluated: a reference holding its record stays the record.
let evaluated = from_inputs(&inputs, SchemaAudience::Evaluated, &shape);
assert_eq!(evaluated["properties"]["customer"]["type"], json!("object"));
assert_eq!(
evaluated["properties"]["lines"]["items"]["properties"]["product"]["type"],
json!("object")
);
}
#[test]
fn a_nullable_record_inside_a_relationship_is_found() {
let record = object(&[(
"product",
VariableType::Nullable(Rc::new(VariableType::String)),
)]);
let lines = InputProperty {
path: "lines".into(),
resolved_type: VariableType::Nullable(Rc::new(VariableType::Array(Rc::new(record)))),
optional: true,
supplied_by: SuppliedBy::Request,
default: None,
reference: None,
record_references: [("product".into(), "product".into())].into_iter().collect(),
};
let schema = from_inputs(
&[lines],
SchemaAudience::Evaluated,
&RequestShape::default(),
);
assert_eq!(
schema["properties"]["lines"]["anyOf"][0]["items"]["properties"]["product"],
json!({ "anyOf": [{ "type": "string", "description": "product id" }, { "type": "null" }] }),
"{schema}"
);
}
}
+166 -1
View File
@@ -25,6 +25,7 @@ use crate::policy::linter::{AstOps, RedundantParentheses};
use crate::policy::queries::scope::VariableTypeScope;
use crate::workspace::db::Db;
use crate::workspace::graph::function::FunctionTypeOutcome;
use crate::workspace::graph::request::{RequestTarget, RequestTypes};
use crate::workspace::types::{
CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, DiagnosticLocation, ExpressionKind,
Severity,
@@ -107,6 +108,8 @@ pub(crate) struct GraphAnalyzer<'a> {
unchecked: bool,
nodes_scope: VariableType,
dictionary_types: HashMap<Arc<str>, VariableType>,
/// The Request node's entity, when it names one (`target`).
request: RequestTarget,
constraints: PathConstraints,
rewritten: Option<Vec<Arc<str>>>,
}
@@ -152,7 +155,8 @@ impl GraphTopology {
impl<'a> GraphAnalyzer<'a> {
pub(crate) fn new(db: &'a Db, path: Arc<str>, content: &'a GraphContent) -> Self {
let dictionary_types = db.graph_dictionary_types(&content.imports);
let dictionary_types = db.graph_dictionary_types(content);
let request = Self::request_target(db, content);
Self {
db,
path,
@@ -162,11 +166,40 @@ impl<'a> GraphAnalyzer<'a> {
unchecked: false,
nodes_scope: VariableType::Any,
dictionary_types,
request,
constraints: PathConstraints::default(),
rewritten: None,
}
}
/// The Request node's entity, resolved through the graph's imports (as
/// an entity property's `target` is). The imports are recorded as read by
/// `graph_dictionary_types`, entities with them.
fn request_target(db: &Db, content: &GraphContent) -> RequestTarget {
let Some(target) = content.nodes.iter().find_map(|node| match &node.kind {
DecisionNodeKind::InputNode { content } => content.target.clone(),
_ => None,
}) else {
return RequestTarget::None;
};
let entities = db.graph_entities(&content.imports);
if !entities.contains_key(&target) {
return RequestTarget::Missing(target);
}
let dictionaries: HashMap<Arc<str>, Arc<crate::policy::ir::DictionaryIr>> = db
.graph_dictionary_blocks(&content.imports)
.into_iter()
.map(|b| (b.ir.name.clone(), b.ir))
.collect();
let types = RequestTypes {
entities: &entities,
dictionaries: &dictionaries,
outcomes: true,
};
let (input, roots) = types.input(&target);
RequestTarget::Entity { input, roots }
}
pub(crate) fn analyze(mut self) -> GraphAnalysis {
self.check_imports();
let topology = self.build_topology();
@@ -227,7 +260,13 @@ impl<'a> GraphAnalyzer<'a> {
let inferred_inputs = self.inferred_inputs(&topology, &nodes, &graph_input);
self.lint_output_any(&topology, &nodes, &graph_input);
self.lint_unreachable(&topology);
self.check_outcome_reads();
self.lint_expressions();
Db::drop_refused_unknowns(&mut self.diagnostics);
if let Some(target) = self.content.request_target() {
let entities = self.db.graph_entities(&self.content.imports);
Db::explain_unknown_members(&mut self.diagnostics, &entities, |_| Some(target.clone()));
}
self.locate_nullable_sources(&topology);
self.sort_diagnostics(&topology);
@@ -240,6 +279,83 @@ impl<'a> GraphAnalyzer<'a> {
}
}
/// A node reading an outcome of the Request node's entity (`fraud`,
/// through a reference `customer.claims_after`): known only after the
/// decision, so never in the request. An error, so a compile fails too.
fn check_outcome_reads(&mut self) {
use crate::policy::ir::{outcome_read_message, DataModelIr, OutcomeReader};
use crate::workspace::graph::editor::{NodePaths, ReadBase};
let Some(target) = self.content.request_target() else {
return;
};
let entities = self.db.graph_entities(&self.content.imports);
let Some(entity) = entities.get(&target) else {
return;
};
if !entities
.values()
.any(|dm| dm.properties.iter().any(|p| p.is_outcome()))
{
return;
}
let intellisense = self.db.graph_intellisense();
for node in &self.content.nodes {
if !matches!(
node.kind,
DecisionNodeKind::ExpressionNode { .. }
| DecisionNodeKind::DecisionTableNode { .. }
| DecisionNodeKind::SwitchNode { .. }
) {
continue;
}
let paths = NodePaths::new(node);
for site in Self::node_sites(node) {
let deps = match site.kind {
ExpressionKind::Standard => intellisense.borrow_mut().reads(&site.source),
ExpressionKind::Unary => intellisense.borrow_mut().reads_unary(&site.source),
};
let mut reads = Vec::new();
ReadFlattener::extend_from_deps(&deps, &site.expression_id, &mut reads);
for read in reads.iter().filter(|read| !read.unresolved) {
let path = read.path.as_ref();
if path.starts_with('$') {
continue;
}
// What the node reads from the request: its input, or
// under its `inputField`.
let global = match (&paths.read_base, &site.target) {
(_, CursorTarget::TransformInput) | (ReadBase::NodeInput, _) => {
path.to_string()
}
(ReadBase::Prefixed(prefix), _) => format!("{}.{path}", prefix.join(".")),
(ReadBase::Opaque, _) => continue,
};
let first = global.split('.').next().unwrap_or_default();
if !entity.properties.iter().any(|p| *p.name == *first)
&& !entity.is_maturity_flag(first)
{
continue;
}
let Some(field) = DataModelIr::outcome_at(&entities, Some(&target), &global)
else {
continue;
};
self.diagnostics.push(Diagnostic::error(
DiagnosticCode::OutcomeRead,
DiagnosticLocation {
policy_path: self.path.clone(),
block_id: Some(node.id.clone()),
expression_id: site.expression_id.clone(),
span: read.span,
target: Some(site.target.clone()),
},
outcome_read_message(&field, OutcomeReader::Rules),
));
}
}
}
}
fn check_imports(&mut self) {
let snap = self.db.snapshot();
let mut seen: HashSet<&str> = HashSet::default();
@@ -627,6 +743,9 @@ impl<'a> GraphAnalyzer<'a> {
}
fn graph_input_type(&self) -> VariableType {
if let Some(input) = self.request.input() {
return input.shallow_clone();
}
self.content
.nodes
.iter()
@@ -639,6 +758,9 @@ impl<'a> GraphAnalyzer<'a> {
}
fn graph_input_signature(&self) -> VariableType {
if let Some(input) = self.request.input() {
return input.shallow_clone();
}
self.content
.nodes
.iter()
@@ -650,6 +772,25 @@ impl<'a> GraphAnalyzer<'a> {
.unwrap_or(VariableType::Any)
}
/// A Request node typed by an entity: not with a schema too, and the
/// entity visible through the graph's imports.
fn check_request_target(&mut self, node: &DecisionNode, with_schema: bool) {
let location = || DiagnosticLocation::block(self.path.clone(), node.id.clone());
if with_schema {
self.diagnostics.push(Diagnostic::error(
DiagnosticCode::InvalidGraphStructure,
location(),
"the request is typed twice: by a schema and by an entity (`target`); keep one",
));
}
if let RequestTarget::Missing(target) = &self.request {
let message = format!(
"no entity `{target}` visible from this document; import the policy that defines it"
);
self.diagnostics.push(Diagnostic::error(DiagnosticCode::UnknownDataModelTarget, location(), message));
}
}
fn check_schema_dictionaries(&mut self, node: &DecisionNode, schema: &serde_json::Value) {
let mut names: Vec<Arc<str>> = Vec::new();
super::SchemaType::dictionary_names(schema, &mut names);
@@ -711,6 +852,14 @@ impl<'a> GraphAnalyzer<'a> {
};
match &node.kind {
DecisionNodeKind::InputNode { content } if content.target.is_some() => {
self.check_request_target(node, content.schema.is_some());
analysis.output = graph_input.shallow_clone();
if matches!(graph_input, VariableType::Any) {
analysis.opaque = true;
analysis.open = true;
}
}
DecisionNodeKind::InputNode { content } => {
if let Some(schema) = content.schema.as_ref() {
self.check_schema_dictionaries(node, schema);
@@ -2378,6 +2527,14 @@ impl<'a> GraphAnalyzer<'a> {
matches!(kind, ExpressionKind::Unary),
on_error,
);
if self.diagnostics[first..]
.iter()
.any(|d| d.code == DiagnosticCode::UndefinedVariable)
{
let mut reads = Vec::new();
ReadFlattener::extend_from_deps(&analysis.reads, &expression_id, &mut reads);
Db::locate_unknown_members(&mut self.diagnostics[first..], &reads);
}
if self.validate {
self.validate_read_paths(node_id, &expression_id, &target, &analysis.reads, scope);
}
@@ -2643,6 +2800,10 @@ impl<'a> GraphAnalyzer<'a> {
}
fn locate_nullable_sources(&mut self, topology: &GraphTopology) {
let request_roots: Vec<Arc<str>> = match &self.request {
RequestTarget::Entity { roots, .. } => roots.clone(),
_ => Vec::new(),
};
let covers = |written: &str, field: &str| {
field == written
|| field
@@ -2668,6 +2829,10 @@ impl<'a> GraphAnalyzer<'a> {
&& covers(&prefixed(&content.transform_attributes, written), field)
})
}
DecisionNodeKind::InputNode { content } if content.target.is_some() => {
let root = field.split('.').next().unwrap_or_default();
request_roots.iter().any(|r| r.as_ref() == root)
}
DecisionNodeKind::InputNode { content } => {
let mut schema = content.schema.as_deref();
for segment in field.split('.') {
@@ -36,6 +36,65 @@ impl DepWalk {
}
impl Db {
/// The paths a document reads from its request (`transaction.amount`,
/// `card.txn_count_7d`), or None when that can't be known: a read of
/// `$`/`$root` or of something unresolved, or a node whose reads aren't
/// followed (a function, a custom node, a sub-decision, an input field
/// that isn't a plain path). A policy includes the rules of what it
/// imports; a graph typed by an entity reads under the entity's name.
pub(crate) fn document_reads(&self, document: &Arc<str>) -> Option<std::collections::BTreeSet<String>> {
let mut out = std::collections::BTreeSet::new();
if !self.is_graph(document) {
if !self.snapshot().all_parsed.contains_key(document) {
return None;
}
let unit = self.unit(document);
let shallow = self.shallow();
for rule in shallow.per_rule.iter().filter(|r| unit.members.contains(&r.policy_path)) {
for read in &rule.reads {
let path = read.path.as_ref();
// `$`, `$root`, `$root.x`, `$.x`: not a field of an entity. Unknown.
if path.starts_with('$') || read.unresolved {
return None;
}
if !read.via_alias {
out.insert(path.to_string());
}
}
}
return Some(out);
}
let snap = self.snapshot();
let content = snap.graphs.get(document).cloned()?;
let content = content.as_graph()?;
let root = content.request_target();
for node in &content.nodes {
match &node.kind {
DecisionNodeKind::InputNode { .. } | DecisionNodeKind::OutputNode { .. } => continue,
DecisionNodeKind::ExpressionNode { .. }
| DecisionNodeKind::DecisionTableNode { .. }
| DecisionNodeKind::SwitchNode { .. } => {}
_ => return None,
}
let paths = NodePaths::new(node);
if matches!(paths.read_base, ReadBase::Opaque) {
return None;
}
let mut whole = false;
let reads = self.node_global_reads_checked(node, &paths, None, &mut whole);
if whole {
return None;
}
for read in reads {
out.insert(match &root {
Some(target) => format!("{target}.{read}"),
None => read.to_string(),
});
}
}
Some(out)
}
pub(crate) fn graph_dependencies(&self, document: &Arc<str>, target: &str) -> DependencyNode {
self.graph_dep_node(document, target, &mut DepWalk::new())
}
@@ -366,6 +425,21 @@ impl Db {
node: &DecisionNode,
paths: &NodePaths,
expression_filter: Option<&[Arc<str>]>,
) -> Vec<Arc<str>> {
self.node_global_reads_checked(node, paths, expression_filter, &mut false)
}
/// The node's reads, as [`Self::node_global_reads`]; `whole` set when it
/// also reads something they can't follow: its whole input (`$`,
/// `$root`), the request through `$root.x`, another node's output
/// (`$nodes.x`), or something unresolved. (`$.x`, the node's own output
/// so far, is followed.)
fn node_global_reads_checked(
&self,
node: &DecisionNode,
paths: &NodePaths,
expression_filter: Option<&[Arc<str>]>,
whole: &mut bool,
) -> Vec<Arc<str>> {
let intellisense = self.graph_intellisense();
let mut is = intellisense.borrow_mut();
@@ -415,10 +489,13 @@ impl Db {
let mut flat: Vec<PropertyRead> = Vec::new();
ReadFlattener::extend_from_deps(&deps, &None, &mut flat);
for read in flat {
let path = read.path.as_ref();
if read.unresolved || (path.starts_with('$') && !path.starts_with("$.")) {
*whole = true;
}
if read.via_alias || read.unresolved {
continue;
}
let path = read.path.as_ref();
if path == "$" || path == "$root" {
continue;
}
+3
View File
@@ -5,11 +5,14 @@ mod editor;
mod enhance;
pub(crate) mod function;
mod queries;
mod request;
mod schema;
mod ts_type;
pub use analysis::{GraphAnalysis, GraphNodeAnalysis, GraphSignature};
pub(crate) use analysis::{GraphAnalyzer, SignatureResolution};
pub(crate) use queries::EntityUnitEntry;
pub(crate) use request::{merge_entities, with_inline_references};
pub use enhance::GraphTraceMap;
pub use function::{FunctionResolutionRequest, FunctionTypeResolver};
pub(crate) use schema::SchemaType;
+118 -11
View File
@@ -4,10 +4,13 @@ use std::sync::Arc;
use ahash::{HashMap, HashMapExt, HashSet};
use zen_expression::variable::VariableType;
use crate::model::GraphContent;
use crate::policy::ir::{DataModelIr, ParsedPolicy};
use crate::workspace::db::{Db, DictionaryUnitEntry};
use crate::workspace::graph::analysis::{
GraphAnalysis, GraphAnalyzer, GraphSignature, SignatureResolution,
};
use crate::workspace::graph::request::{merge_entities, RequestTypes};
use crate::workspace::reads::ReadView;
use crate::policy::queries::scope::VariableTypeScope;
@@ -46,12 +49,14 @@ impl Db {
.unwrap_or_default()
}
pub(crate) fn graph_dictionary_blocks(&self, imports: &[Arc<str>]) -> Vec<DictionaryUnitEntry> {
/// The policies a graph's imports make visible: the imports and what
/// they import, breadth-first, each import in the order listed (as the
/// runtime loads them).
fn graph_import_closure(&self, imports: &[Arc<str>]) -> Vec<(Arc<str>, Arc<ParsedPolicy>)> {
let snap = self.snapshot();
let mut seen: HashSet<Arc<str>> = HashSet::default();
let mut visited: HashSet<Arc<str>> = HashSet::default();
let mut queue: VecDeque<Arc<str>> = imports.iter().cloned().collect();
let mut out: Vec<DictionaryUnitEntry> = Vec::new();
let mut out: Vec<(Arc<str>, Arc<ParsedPolicy>)> = Vec::new();
while let Some(path) = queue.pop_front() {
if !visited.insert(path.clone()) {
continue;
@@ -59,6 +64,16 @@ impl Db {
let Some(parsed) = snap.all_parsed.get(&path) else {
continue;
};
queue.extend(parsed.policy.imports().iter().cloned());
out.push((path, parsed.clone()));
}
out
}
pub(crate) fn graph_dictionary_blocks(&self, imports: &[Arc<str>]) -> Vec<DictionaryUnitEntry> {
let mut seen: HashSet<Arc<str>> = HashSet::default();
let mut out: Vec<DictionaryUnitEntry> = Vec::new();
for (path, parsed) in self.graph_import_closure(imports) {
for block in &parsed.policy.dictionaries {
if !seen.insert(block.ir.name.clone()) {
continue;
@@ -69,17 +84,50 @@ impl Db {
ir: block.ir.clone(),
});
}
queue.extend(parsed.policy.imports().iter().cloned());
}
out
}
pub(crate) fn graph_dictionary_types(
/// The entity blocks a graph's imports make visible, each with the
/// policy that declares it, in the order they're walked.
pub(crate) fn graph_entity_blocks(&self, imports: &[Arc<str>]) -> Vec<EntityUnitEntry> {
let mut out: Vec<EntityUnitEntry> = Vec::new();
for (path, parsed) in self.graph_import_closure(imports) {
for block in &parsed.policy.data_models {
if block.ir.scope.is_global() || block.ir.name.is_empty() {
continue;
}
out.push(EntityUnitEntry {
policy_path: path.clone(),
block_id: block.id.clone(),
ir: block.ir.clone(),
});
}
}
out
}
/// The entities a graph's imports make visible: one declared in several
/// policies is one entity, as in a policy's unit (and at runtime).
pub(crate) fn graph_entities(
&self,
imports: &[Arc<str>],
) -> HashMap<Arc<str>, Arc<DataModelIr>> {
let blocks = self.graph_entity_blocks(imports);
merge_entities(blocks.iter().map(|b| b.ir.as_ref()))
}
/// The dictionaries a graph's imports make visible, by name; the read is
/// recorded, with the entities when the graph's request is one.
pub(crate) fn graph_dictionary_types(
&self,
content: &GraphContent,
) -> HashMap<Arc<str>, VariableType> {
let imports = &content.imports;
let mut out = HashMap::new();
let view = ReadView::Dictionaries(self.dictionary_view(imports));
let view = ReadView::Dictionaries(
self.dictionary_view(imports, content.request_target().is_some()),
);
for import in imports {
self.graph_dep_record_view(import, view.clone());
}
@@ -126,6 +174,9 @@ impl Db {
pub(crate) fn graph_inputs(&self, path: &str) -> Vec<InputProperty> {
let path_arc: Arc<str> = Arc::from(path);
if let Some(properties) = self.graph_entity_inputs(&path_arc) {
return properties;
}
let Some(analysis) = self.graph_analysis(&path_arc) else {
return Vec::new();
};
@@ -134,26 +185,65 @@ impl Db {
let mut properties: Vec<InputProperty> = fields
.borrow()
.iter()
.map(|(key, resolved_type)| InputProperty {
path: Arc::from(key.as_ref()),
resolved_type: resolved_type.shallow_clone(),
.map(|(key, resolved_type)| {
InputProperty::request(Arc::from(key.as_ref()), resolved_type.shallow_clone())
})
.collect();
properties.sort_by(|a, b| a.path.cmp(&b.path));
properties
}
// What the graph reads, untyped: required, since nothing says
// the request may leave it out.
VariableType::Any => analysis
.inferred_inputs
.iter()
.map(|path| InputProperty {
path: path.clone(),
resolved_type: VariableType::Any,
optional: false,
..InputProperty::request(path.clone(), VariableType::Any)
})
.collect(),
_ => Vec::new(),
}
}
/// A request typed by an entity, as the caller sends it and nodes read
/// it: the entity's fields, a reference as the record it names (as are
/// the references inside it); what the host supplies marked so.
fn graph_entity_inputs(&self, path: &Arc<str>) -> Option<Vec<InputProperty>> {
let snap = self.snapshot();
let content = snap.graphs.get(path).cloned()?;
let content = content.as_graph()?;
let target = content.request_target()?;
let entities = self.graph_entities(&content.imports);
let dictionaries: HashMap<Arc<str>, Arc<crate::policy::ir::DictionaryIr>> = self
.graph_dictionary_blocks(&content.imports)
.into_iter()
.map(|b| (b.ir.name.clone(), b.ir))
.collect();
let entity = entities.get(&target)?;
let types = RequestTypes {
entities: &entities,
dictionaries: &dictionaries,
outcomes: false,
};
let mut properties: Vec<InputProperty> = entity
.properties
.iter()
// An outcome is known only after the decision: never an input.
.filter(|property| !property.is_outcome())
.map(|property| {
InputProperty::of_property(
property.name.clone(),
property,
types.field(property, 0),
&entities,
)
})
.collect();
properties.sort_by(|a, b| a.path.cmp(&b.path));
Some(properties)
}
pub(crate) fn graph_outputs(&self, path: &str) -> Vec<OutputProperty> {
let path_arc: Arc<str> = Arc::from(path);
let Some(analysis) = self.graph_analysis(&path_arc) else {
@@ -206,3 +296,20 @@ impl Db {
nodes
}
}
/// An entity a graph sees through its imports, and where it is defined.
#[derive(Clone)]
pub(crate) struct EntityUnitEntry {
pub policy_path: Arc<str>,
pub block_id: Arc<str>,
pub ir: Arc<DataModelIr>,
}
impl PartialEq for EntityUnitEntry {
// The same parsed block: a policy's blocks are parsed again only when it changes.
fn eq(&self, other: &Self) -> bool {
self.policy_path == other.policy_path
&& self.block_id == other.block_id
&& Arc::ptr_eq(&self.ir, &other.ir)
}
}
+169
View File
@@ -0,0 +1,169 @@
//! A Request node typed by an entity (`inputNode.content.target`): the
//! graph's input is that entity itself, flat (`{ txn_id, amount, customer }`),
//! as a schema-typed request is. A reference holds the record it names
//! (`customer: { … }`): the host places it; there are no pools. A request of
//! several entities is an entity of them.
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use ahash::{HashMap, HashSet};
use zen_expression::variable::VariableType;
use crate::policy::ir::{DataModelIr, DictionaryIr, Property, PropertyTypeIr, Records, Scope};
/// What a graph's Request node takes, as far as its target goes.
#[derive(Clone)]
pub(crate) enum RequestTarget {
/// A schema, or nothing declared.
None,
/// An entity no import makes visible.
Missing(Arc<str>),
Entity {
/// The graph's input: the entity, references opened.
input: VariableType,
/// The names at the input's root: the entity's fields.
roots: Vec<Arc<str>>,
},
}
impl RequestTarget {
pub(crate) fn input(&self) -> Option<&VariableType> {
match self {
RequestTarget::Entity { input, .. } => Some(input),
_ => None,
}
}
}
pub(crate) struct RequestTypes<'a> {
pub entities: &'a HashMap<Arc<str>, Arc<DataModelIr>>,
pub dictionaries: &'a HashMap<Arc<str>, Arc<DictionaryIr>>,
/// Whether outcomes are fields: as nodes read the request (so a read of
/// one is found and refused), not as a request schema has it (known
/// only after the decision, never sent).
pub outcomes: bool,
}
/// How many links (references, relationships) a request's type opens from
/// its root: a host fills in the records a few levels deep, so past that a
/// link reads as unknown (`any`). It also bounds the type when entities
/// reference each other in a cycle (each level opens every link again).
pub(crate) const REQUEST_LINK_DEPTH: usize = 4;
impl RequestTypes<'_> {
/// The graph's input for a request of `target`: the entity's fields,
/// its references and relationships typed as the entities they reach.
pub(crate) fn input(&self, target: &Arc<str>) -> (VariableType, Vec<Arc<str>>) {
let roots = self
.entities
.get(target)
.map(|dm| dm.properties.iter().map(|p| p.name.clone()).collect())
.unwrap_or_default();
(self.hydrated(target, 0), roots)
}
/// An entity `depth` links from the request's root, as expressions read
/// it: each field as [`Self::field`] types it.
fn hydrated(&self, name: &Arc<str>, depth: usize) -> VariableType {
let Some(dm) = self.entities.get(name) else {
return VariableType::Any;
};
let fields: HashMap<Rc<str>, VariableType> = dm
.properties
.iter()
.filter(|prop| self.outcomes || !prop.is_outcome())
.map(|prop| (Rc::from(prop.name.as_ref()), self.field(prop, depth)))
.collect();
VariableType::Object(Rc::new(RefCell::new(fields)))
}
/// A field of an entity `depth` links from the request's root: a link
/// to an entity holds its record (or records), opened up to
/// [`REQUEST_LINK_DEPTH`]; an optional field is nullable.
pub(crate) fn field(&self, prop: &Property, depth: usize) -> VariableType {
let ty = match &prop.kind {
PropertyTypeIr::Reference { target } | PropertyTypeIr::Relationship { target }
if self.entities.contains_key(target) =>
{
let inner = if depth < REQUEST_LINK_DEPTH {
self.hydrated(target, depth + 1)
} else {
VariableType::Any
};
if prop.array {
inner.array()
} else {
inner
}
}
_ => DataModelIr::wire_property_type(
prop,
self.entities,
self.dictionaries,
&mut HashSet::default(),
),
};
if prop.optional {
super::wrap_optional(ty)
} else {
ty
}
}
}
/// Entities of one name declared in several policies are one entity: each
/// property once (the first declared wins) and the first kind of records
/// that isn't plain. `models` come in the order their policies are walked.
pub(crate) fn merge_entities<'a>(
models: impl IntoIterator<Item = &'a DataModelIr>,
) -> HashMap<Arc<str>, Arc<DataModelIr>> {
let mut merged: HashMap<Arc<str>, DataModelIr> = HashMap::default();
for dm in models {
let entity = merged
.entry(dm.name.clone())
.or_insert_with(|| DataModelIr {
name: dm.name.clone(),
scope: Scope::Entity,
properties: Vec::new(),
records: Records::Plain,
});
if entity.records == Records::Plain {
entity.records = dm.records;
}
for prop in &dm.properties {
if !entity.properties.iter().any(|p| p.name == prop.name) {
entity.properties.push(prop.clone());
}
}
}
merged
.into_iter()
.map(|(name, dm)| (name, Arc::new(dm)))
.collect()
}
/// The entities with each reference read as the record it names (a
/// relationship), as a flat request carries it: what its checks and date
/// conversion go by.
pub(crate) fn with_inline_references(
entities: &HashMap<Arc<str>, Arc<DataModelIr>>,
) -> HashMap<Arc<str>, Arc<DataModelIr>> {
entities
.iter()
.map(|(name, dm)| {
let mut inline = dm.as_ref().clone();
for prop in &mut inline.properties {
if let PropertyTypeIr::Reference { target } = &prop.kind {
if entities.contains_key(target) {
prop.kind = PropertyTypeIr::Relationship {
target: target.clone(),
};
}
}
}
(name.clone(), Arc::new(inline))
})
.collect()
}
+30 -2
View File
@@ -2,6 +2,7 @@ pub(crate) mod affected;
pub(crate) mod db;
pub mod document_dependencies;
pub(crate) mod editor;
pub(crate) mod endpoint;
pub(crate) mod graph;
pub(crate) mod reads;
pub(crate) mod search;
@@ -26,12 +27,14 @@ pub use types::{
CursorTarget, DecisionTableExtras, DependencyNode, Diagnostic, DiagnosticCode,
DiagnosticLocation, Dictionary, DictionaryEntryInfo, DiscriminantVariant, DiscriminatedUnion,
EngineEdit, Entity, EntityField, EvaluateRequest, EvaluationError, EvaluationResult,
ExpressionKind, FieldOrigin, GuardedProperty, InputProperty, InputValidationError,
ExpressionKind, FieldOrigin, GuardedProperty, InputProperty, InputValidationError, SuppliedBy,
InspectResult, OutputProperty, PrepareRename, PropertyKind, ReferenceKind, ReferenceSite,
RenameTarget, SchemaFieldKind, SchemaGroup, ScopeRequest, SearchHit, SearchHitKind, Severity,
SlotRole, Span, Trace, WriteConflict, WriteTrace,
};
pub use endpoint::{EndpointKind, SchemaAudience};
use types::Global;
pub struct Workspace {
@@ -102,8 +105,9 @@ impl Workspace {
policy_path: &Arc<str>,
goals: &[Arc<str>],
columns: &'a zen_expression::lane::Columns<'a>,
store: &'a crate::compiled::policy::ColumnStore<'a>,
) -> Result<crate::compiled::policy::PolicyColumnarOutput<'a>, EvaluationError> {
self.db.evaluate_columns(policy_path, goals, columns)
self.db.evaluate_columns(policy_path, goals, columns, store)
}
#[cfg(feature = "driver")]
@@ -132,6 +136,11 @@ impl Workspace {
self.db.enhance_graph_trace(document, trace)
}
/// What a document reads from its request; None when it can't be known.
pub fn reads(&self, path: &str) -> Option<std::collections::BTreeSet<String>> {
self.db.document_reads(&Arc::from(path))
}
pub(crate) fn eval_artifact(&self, policy: &str) -> Arc<EvalArtifact> {
self.db.eval_artifact(policy)
}
@@ -162,6 +171,25 @@ impl Workspace {
self.db.outputs(req)
}
/// What `path` serves: a graph, a policy with rules, or nothing.
pub fn endpoint(&self, path: &str) -> Option<EndpointKind> {
self.db.endpoint(path)
}
/// The request's JSON Schema for `audience`, without `$id`.
pub fn request_schema(
&self,
req: &ScopeRequest,
audience: SchemaAudience,
) -> serde_json::Value {
self.db.request_schema(req, audience)
}
/// The response's JSON Schema, without `$id`.
pub fn response_schema(&self, req: &ScopeRequest) -> serde_json::Value {
self.db.response_schema(req)
}
pub fn conditional_schema(&self, req: &ScopeRequest) -> ConditionalSchema {
self.db.conditional_schema(req)
}
+11 -3
View File
@@ -2,7 +2,7 @@ use std::sync::Arc;
use crate::policy::ir::DictionaryIr;
use crate::workspace::db::Db;
use crate::workspace::graph::SignatureResolution;
use crate::workspace::graph::{EntityUnitEntry, SignatureResolution};
#[derive(Clone, PartialEq)]
pub(crate) enum ReadView {
@@ -21,10 +21,17 @@ pub(crate) enum ImportKind {
pub(crate) struct DictionaryView {
imports: Vec<(Arc<str>, ImportKind)>,
entries: Vec<(Arc<str>, Arc<str>, Arc<DictionaryIr>)>,
/// The entities seen through the same imports, when the graph's Request
/// node is typed by one (else a data model edit leaves the graph be).
entities: Option<Vec<EntityUnitEntry>>,
}
impl Db {
pub(crate) fn dictionary_view(&self, imports: &[Arc<str>]) -> DictionaryView {
pub(crate) fn dictionary_view(
&self,
imports: &[Arc<str>],
with_entities: bool,
) -> DictionaryView {
let snap = self.snapshot();
DictionaryView {
imports: imports
@@ -46,6 +53,7 @@ impl Db {
.into_iter()
.map(|entry| (entry.policy_path, entry.block_id, entry.ir))
.collect(),
entities: with_entities.then(|| self.graph_entity_blocks(imports)),
}
}
@@ -57,7 +65,7 @@ impl Db {
.iter()
.map(|(import, _)| import.clone())
.collect();
self.dictionary_view(&imports) == *recorded
self.dictionary_view(&imports, recorded.entities.is_some()) == *recorded
}
ReadView::Signature(recorded) => {
self.graph_dep_frame_push(path);
+46 -1
View File
@@ -177,8 +177,53 @@ impl Db {
}
}
}
BlockDoc::DataModel { .. } | BlockDoc::Dictionary { .. } | BlockDoc::Ignored(_) => {
// The expressions on a data model's properties (features, per
// event values, model inputs and `when`): facts like any other
// expression, so business mode shows their pills unfocused.
BlockDoc::DataModel { data, .. } => {
for prop in &data.properties {
if let Some(feature) = prop.feature.as_ref().filter(|f| !f.expr.is_empty()) {
push(CursorTarget::FeatureExpr { id: prop.id.clone() }, &feature.expr);
}
if let Some(expr) = prop.outcome.as_ref().and_then(|o| o.expr.as_ref()) {
push(
CursorTarget::OutcomeExpr {
id: prop.id.clone(),
},
expr,
);
}
if let Some(compute) = prop.compute.as_ref().filter(|c| !c.is_empty()) {
push(CursorTarget::ComputeExpr { id: prop.id.clone() }, compute);
}
let Some(model) = prop.model.as_ref() else {
continue;
};
if let Some(inputs) = crate::policy::raw::call_inputs(model).and_then(serde_json::Value::as_object) {
for (input, expr) in inputs {
if let Some(expr) = expr.as_str().filter(|e| !e.is_empty()) {
push(
CursorTarget::ModelInput {
id: prop.id.clone(),
input: Arc::from(input.as_str()),
},
&Arc::from(expr),
);
}
}
}
if let Some(when) = model.get("when").and_then(serde_json::Value::as_str).filter(|w| !w.is_empty()) {
push(CursorTarget::ModelWhen { id: prop.id.clone() }, &Arc::from(when));
}
if let Some(request) = model.get("request").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty() && crate::policy::raw::call_inputs(model).is_none()) {
push(CursorTarget::ModelRequest { id: prop.id.clone() }, &Arc::from(request));
}
if let Some(response) = model.get("response").and_then(serde_json::Value::as_str).filter(|a| !a.is_empty()) {
push(CursorTarget::ModelResponse { id: prop.id.clone() }, &Arc::from(response));
}
}
}
BlockDoc::Dictionary { .. } | BlockDoc::Ignored(_) => {}
}
}
sites
+2
View File
@@ -295,6 +295,8 @@ impl Db {
}
if self.is_graph(&cursor.policy_path) {
self.graph_cursor_scope(cursor, cache)
} else if cursor.target.is_data_model_expression() {
self.data_model_cursor_scope(cursor)
} else {
self.policy_cursor_scope(cursor, cache)
}
+220 -3
View File
@@ -1,6 +1,9 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use ahash::HashMap;
use zen_expression::variable::VariableType;
use zen_types::decision::{
DecisionNodeKind, DecisionTableContent, DecisionTableHitPolicy, OutputNodeContent,
@@ -13,7 +16,8 @@ use crate::model::GraphContent;
use crate::policy::blocks::{
BlockKind, DecisionTableIr, IntelliSenseSource, SharedIntelliSense, ROW_ID_KEY,
};
use crate::policy::ir::PropertyTypeIr;
use crate::policy::ir::{DataModelIr, PropertyTypeIr, Records, MATURE_SUFFIX};
use crate::policy::raw::BlockDoc;
use crate::policy::queries::scope::VariableTypeScope;
use crate::workspace::db::{Db, Unit};
use crate::workspace::graph::{GraphAnalyzer, GraphNodeAnalysis, SchemaType};
@@ -54,6 +58,219 @@ impl Db {
}
}
/// Expressions on a data model property, read by the host rather than
/// run by the policy. A windowed feature aggregates the records of an
/// events (or reference) entity: `count(transaction)`. A derived feature
/// and a per-event `compute` read the entity's own properties (and
/// through references, other entities' features). A model's inputs and
/// `when` read the request.
pub(crate) fn data_model_cursor_scope(&self, cursor: &Cursor) -> Option<CursorScope> {
let unit = self.unit(&cursor.policy_path);
let entry = unit
.data_models
.iter()
.find(|e| e.policy_path == cursor.policy_path && e.block_id == cursor.block_id)?;
let enriched = self.enriched_of_unit(&unit);
let own = || -> HashMap<Rc<str>, VariableType> {
match enriched.declared_at(&entry.ir.name) {
VariableType::Object(obj) => obj.borrow().clone(),
_ => HashMap::default(),
}
};
let object = |fields: HashMap<Rc<str>, VariableType>| {
VariableType::Object(Rc::new(RefCell::new(fields)))
};
// The records a windowed feature (or an outcome) aggregates: each
// events or reference entity by name, as a list (all entities when
// there are none).
let sources = || -> HashMap<Rc<str>, VariableType> {
let mut sources: Vec<&Arc<DataModelIr>> = unit
.entities
.values()
.filter(|dm| dm.records != Records::Plain)
.collect();
if sources.is_empty() {
sources = unit.entities.values().collect();
}
sources
.into_iter()
.map(|dm| {
(
Rc::from(dm.name.as_ref()),
enriched.declared_at(&dm.name).array(),
)
})
.collect()
};
match &cursor.target {
CursorTarget::FeatureExpr { id } => {
let BlockDoc::DataModel { data, .. } = self.block_doc(&BlockRef {
policy_path: cursor.policy_path.clone(),
block_id: cursor.block_id.clone(),
})?
else {
return None;
};
let feature = data.properties.iter().find(|p| p.id == *id)?.feature.as_ref()?;
let windowed = feature.window.as_ref().is_some_and(|w| !w.list().is_empty());
let mut fields = if windowed {
sources()
} else {
// Derived at read time: the instant read for.
let mut fields = own();
fields.entry(Rc::from("asOf")).or_insert(VariableType::Date);
fields
};
// A name the scope has already is the real one: never shadowed.
fields
.entry(Rc::from("params"))
.or_insert_with(|| self.feature_params(&unit));
Some(CursorScope::value(object(fields), None))
}
// An outcome: what is known after the decision. The entity's
// fields, features and other outcomes; the records that
// reference it (`count(chargeback as c, ..)`); through a
// reference, the records referencing the same entity
// (`customer.claim`: the claims of this entity's customer); and
// `decidedAt`, the decision's time. Never a decision's result.
CursorTarget::OutcomeExpr { .. } => {
let mut fields = own();
for prop in &entry.ir.properties {
let PropertyTypeIr::Reference { target } = &prop.kind else {
continue;
};
let key: Rc<str> = Rc::from(prop.name.as_ref());
let Some(declared) = fields.get(&key) else {
continue;
};
let (base, nullable) = match declared {
VariableType::Nullable(inner) => (inner.as_ref().shallow_clone(), true),
other => (other.shallow_clone(), false),
};
let VariableType::Object(target_fields) = base else {
continue;
};
let mut through = target_fields.borrow().clone();
for dm in unit.entities.values() {
let references = dm.properties.iter().any(|p| {
matches!(&p.kind, PropertyTypeIr::Reference { target: t } if t == target)
});
if references {
through
.entry(Rc::from(dm.name.as_ref()))
.or_insert_with(|| enriched.declared_at(&dm.name).array());
}
}
let through = object(through);
fields.insert(
key,
if nullable {
VariableType::Nullable(Rc::new(through))
} else {
through
},
);
}
// Each outcome with `maturity`: whether the decision is old
// enough to trust a "no" (`fraud_mature`).
for prop in &entry.ir.properties {
if prop.outcome_maturity().is_some() {
fields
.entry(Rc::from(format!("{}{MATURE_SUFFIX}", prop.name)))
.or_insert(VariableType::Bool);
}
}
// A name the scope has already is the real one: never shadowed.
for (name, records) in sources() {
fields.entry(name).or_insert(records);
}
fields
.entry(Rc::from("decidedAt"))
.or_insert(VariableType::Date);
fields
.entry(Rc::from("params"))
.or_insert_with(|| self.feature_params(&unit));
Some(CursorScope::value(object(fields), None))
}
CursorTarget::ComputeExpr { .. } => Some(CursorScope::value(object(own()), None)),
CursorTarget::ModelInput { .. } => {
Some(CursorScope::value(enriched.declared_scope(), None))
}
// What a call sends: the instance, as its derived features read
// it; `$root` the whole request (a parent the instance can't reach).
CursorTarget::ModelRequest { .. } => {
let mut fields = own();
fields.insert(Rc::from("$root"), enriched.declared_scope());
Some(CursorScope::value(object(fields), None))
}
// The call's value: the reply (`response`) beside the instance.
CursorTarget::ModelResponse { .. } => {
let mut fields = own();
fields.entry(Rc::from("response")).or_insert(VariableType::Any);
fields.insert(Rc::from("$root"), enriched.declared_scope());
Some(CursorScope::value(object(fields), None))
}
// `when` reads the instance; a call written with named `inputs`
// (the earlier format) reads the request and those names.
CursorTarget::ModelWhen { id } => {
let BlockDoc::DataModel { data, .. } = self.block_doc(&BlockRef {
policy_path: cursor.policy_path.clone(),
block_id: cursor.block_id.clone(),
})?
else {
return None;
};
let model = data.properties.iter().find(|p| p.id == *id)?.model.as_ref()?;
if crate::policy::raw::call_inputs(model).is_some() {
Some(CursorScope::condition(enriched.declared_scope()))
} else {
let mut fields = own();
fields.insert(Rc::from("$root"), enriched.declared_scope());
Some(CursorScope::condition(object(fields)))
}
}
_ => None,
}
}
/// `params` in feature expressions: the constants of a `featureSettings`
/// block in the policy or its imports (`{ name, type, value }`).
fn feature_params(&self, unit: &Unit) -> VariableType {
let mut fields: HashMap<Rc<str>, VariableType> = HashMap::default();
let mut members: Vec<&Arc<str>> = unit.members.iter().collect();
members.sort();
for member in members {
let Some(policy) = self.raw_policy(member) else {
continue;
};
for block in &policy.blocks {
let BlockDoc::Ignored(value) = block else {
continue;
};
if value.get("type").and_then(serde_json::Value::as_str) != Some("featureSettings") {
continue;
}
let params = value
.pointer("/props/data/params")
.and_then(serde_json::Value::as_array);
for param in params.into_iter().flatten() {
let Some(name) = param.get("name").and_then(serde_json::Value::as_str) else {
continue;
};
let kind = match param.get("type").and_then(serde_json::Value::as_str) {
Some("number" | "decimal" | "integer") => VariableType::Number,
Some("string") => VariableType::String,
Some("boolean") => VariableType::Bool,
Some("date" | "timestamp") => VariableType::Date,
_ => VariableType::Any,
};
fields.entry(Rc::from(name)).or_insert(kind);
}
}
}
VariableType::Object(Rc::new(RefCell::new(fields)))
}
fn policy_table_scope(
&self,
unit: &Unit,
@@ -251,7 +468,7 @@ impl Db {
});
}
let column = table.outputs.iter().find(|c| c.id == *col)?;
let dictionaries = self.graph_dictionary_types(&content.imports);
let dictionaries = self.graph_dictionary_types(content);
let expected =
GraphAnalyzer::output_expected(table, col, &dictionaries).or_else(|| {
(!column.field.is_empty())
@@ -294,7 +511,7 @@ impl Db {
key: &str,
output_path: Option<&str>,
) -> Option<VariableType> {
let dictionaries = self.graph_dictionary_types(&content.imports);
let dictionaries = self.graph_dictionary_types(content);
let key = match output_path.filter(|p| !p.is_empty()) {
Some(path) => format!("{path}.{key}"),
None => key.to_string(),
+46
View File
@@ -46,6 +46,52 @@ pub enum CursorTarget {
id: Arc<str>,
},
TransformInput,
/// A data model property's `feature.expr`.
FeatureExpr {
id: Arc<str>,
},
/// A data model property's `outcome.expr`.
OutcomeExpr {
id: Arc<str>,
},
/// A data model property's `compute`.
ComputeExpr {
id: Arc<str>,
},
/// The request path of a model input (`model.inputs[input]`).
ModelInput {
id: Arc<str>,
input: Arc<str>,
},
/// A model's `model.when`.
ModelWhen {
id: Arc<str>,
},
/// What a call sends (`model.request`): empty sends the whole entity.
ModelRequest {
id: Arc<str>,
},
/// The call's value from its reply (`model.response`, reading `response`).
ModelResponse {
id: Arc<str>,
},
}
impl CursorTarget {
/// On an expression of a data model property (feature, outcome,
/// compute, model).
pub fn is_data_model_expression(&self) -> bool {
matches!(
self,
CursorTarget::FeatureExpr { .. }
| CursorTarget::OutcomeExpr { .. }
| CursorTarget::ComputeExpr { .. }
| CursorTarget::ModelInput { .. }
| CursorTarget::ModelWhen { .. }
| CursorTarget::ModelRequest { .. }
| CursorTarget::ModelResponse { .. }
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
+37 -2
View File
@@ -156,6 +156,10 @@ pub enum DiagnosticCode {
UndefinedVariable,
TypeMismatch,
/// A value that may be null (`bool?`) where a bool is required: a
/// condition, an operand of `and`/`or`/`not`, a callback's condition.
/// A null fails at run time: an error in outcomes, else a warning.
NullableCondition,
InvalidExpression,
EmptyBlock,
@@ -177,6 +181,16 @@ pub enum DiagnosticCode {
DuplicateProperty,
DuplicateEnumValue,
InvalidName,
InvalidRelationship,
InvalidDuration,
DeprecatedType,
FeatureShape,
IgnoredAttribute,
/// A property with an outcome written wrong (no `expr`, also a feature).
InvalidOutcome,
/// A rule, graph node, feature, compute or call reading an outcome:
/// known only after the decision.
OutcomeRead,
ImportNotFound,
CircularImport,
@@ -213,6 +227,9 @@ impl DiagnosticCode {
match diag.source {
DiagnosticSource::Lexer | DiagnosticSource::Parser => DiagnosticCode::ParseError,
DiagnosticSource::Compiler => DiagnosticCode::InvalidExpression,
DiagnosticSource::TypeCheck if diag.code == Some("type.nullable-condition") => {
DiagnosticCode::NullableCondition
}
DiagnosticSource::TypeCheck => {
let msg = diag.message.to_lowercase();
if msg.contains("left-hand side of `??`") {
@@ -293,8 +310,26 @@ impl Diagnostic {
zen_expression::intellisense::diagnostic::Severity::Warning => Severity::Warning,
zen_expression::intellisense::diagnostic::Severity::Hint => Severity::Hint,
};
let code = DiagnosticCode::from_expression_diagnostic(diag);
// A nullable condition fails when null, wherever it is (a rule at the
// decision, an outcome offline): an error, as its type mismatch was.
let mut args = diag.args.clone();
if code == DiagnosticCode::NullableCondition {
if let Some(path) = args
.get("operand")
.filter(|p| {
!p.starts_with(['$', '#'])
&& p.split('.').all(|s| {
!s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '_')
})
})
.cloned()
{
args.insert("nullablePath", path);
}
}
Self {
code: DiagnosticCode::from_expression_diagnostic(diag),
code,
message: diag.message.clone(),
severity,
location: DiagnosticLocation {
@@ -302,7 +337,7 @@ impl Diagnostic {
..location
},
expr_code: diag.code,
args: diag.args.clone(),
args,
}
}
+1
View File
@@ -22,6 +22,7 @@ pub use result::{
DecisionTableExtras, DependencyNode, Dictionary, DictionaryEntryInfo, DiscriminantVariant,
DiscriminatedUnion, Entity, EntityField, EvaluationResult, FieldOrigin, Global,
GuardedProperty, InputProperty, InstanceTarget, OutputProperty, PropertyKind, SchemaFieldKind,
SuppliedBy,
SchemaGroup, Trace, WriteConflict, WriteTrace,
};
pub use search::{SearchHit, SearchHitKind};
+92
View File
@@ -113,6 +113,91 @@ pub struct WriteConflict {
pub struct InputProperty {
pub path: Arc<str>,
pub resolved_type: VariableType,
/// The caller may leave it out: it is optional or has a default.
pub optional: bool,
/// Who supplies it: the request, or the host (a feature, a call, a
/// value computed per event, an entity read from the store or a source).
pub supplied_by: SuppliedBy,
/// Filled in when the caller leaves it out.
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<serde_json::Value>,
/// A reference: the entity it names. The engine reads the record; a
/// host that fills records in from ids can take the id instead.
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<Arc<str>>,
/// A relationship: the reference fields of its records, each with the
/// entity it names (one level: the records' own fields).
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub record_references: std::collections::BTreeMap<Arc<str>, Arc<str>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SuppliedBy {
Request,
Host,
}
impl InputProperty {
/// A value the request carries, required unless its type is nullable.
pub fn request(path: Arc<str>, resolved_type: VariableType) -> Self {
let optional = matches!(resolved_type, VariableType::Nullable(_) | VariableType::Any);
Self {
path,
resolved_type,
optional,
supplied_by: SuppliedBy::Request,
default: None,
reference: None,
record_references: Default::default(),
}
}
/// A data model property at `path`: optional when declared so or when
/// it has a default; the host's when something supplies it.
pub(crate) fn of_property<S: std::hash::BuildHasher>(
path: Arc<str>,
property: &crate::policy::ir::Property,
resolved_type: VariableType,
entities: &std::collections::HashMap<Arc<str>, Arc<crate::policy::ir::DataModelIr>, S>,
) -> Self {
use crate::policy::ir::PropertyTypeIr;
let reference = match &property.kind {
PropertyTypeIr::Reference { target } => Some(target.clone()),
_ => None,
};
let record_references = match &property.kind {
PropertyTypeIr::Relationship { target } => entities
.get(target)
.map(|records| {
records
.properties
.iter()
.filter_map(|field| match &field.kind {
PropertyTypeIr::Reference { target } => {
Some((field.name.clone(), target.clone()))
}
_ => None,
})
.collect()
})
.unwrap_or_default(),
_ => Default::default(),
};
Self {
reference,
record_references,
path,
resolved_type,
optional: property.optional || property.default.is_some(),
supplied_by: if property.supply.is_some() {
SuppliedBy::Host
} else {
SuppliedBy::Request
},
default: property.default.as_deref().cloned(),
}
}
}
#[derive(Debug, Clone, Serialize)]
@@ -260,6 +345,13 @@ pub enum FieldOrigin {
source: Arc<str>,
#[serde(rename = "fieldKind")]
kind: SchemaFieldKind,
/// The type as written when checked as another (`integer`, `timestamp`).
#[serde(skip_serializing_if = "Option::is_none")]
exact_type: Option<Arc<str>>,
/// Supplied by the host: a feature (one field per window), a value
/// computed per event, or a model's output.
#[serde(skip_serializing_if = "Option::is_none")]
supply: Option<Arc<crate::policy::ir::Supply>>,
},
Computed {
written_by: BlockRef,
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -274,7 +274,8 @@ impl Policies {
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);
let store = zen_engine::ColumnStore::new();
let output = ws.evaluate_columns(&Arc::from(path), &targets, columns, &store);
for row in 0..columns.rows {
let input = columns.row(row);
let key = Canon::key(id, goals, &input);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,296 @@
{"key":"analysis — excellent tier, high revenue → 20% discount | | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — excellent tier, high revenue → 20% discount","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | 3e23c4d5ea193885f330c4e9a2983f25","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"ok":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"creditTier":"excellent","discount":0.2,"name":"Alice","totalRevenue":550000}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | 5ab43f4342431b3cb0b11e8c11a67d27","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":{"age":"text","companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | 64d345bd2997534827893e6c19a73a11","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | 7e58fcb7bfcd36dd58162fbeac57cef4","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":null,"name":"Alice"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | 821418efc03340d73c74ecfdb5392775","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | 86924166f3c1249af222d00ede5bf082","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":{"age":35,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"ok":{"customer":{"age":35,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"creditTier":"excellent","discount":0.15,"name":"Alice","totalRevenue":0}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | | b14725903e8800e437b7894e15fde953","suite":"analysis — excellent tier, high revenue → 20% discount","input":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":7,"creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | customer.creditTier | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — excellent tier, high revenue → 20% discount","goals":["customer.creditTier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.creditTier\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.creditTier"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | customer.creditTier | 64d345bd2997534827893e6c19a73a11","suite":"analysis — excellent tier, high revenue → 20% discount","goals":["customer.creditTier"],"input":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | customer.creditTier,customer.discount | 86924166f3c1249af222d00ede5bf082","suite":"analysis — excellent tier, high revenue → 20% discount","goals":["customer.creditTier","customer.discount"],"input":{"customer":{"age":35,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"ok":{"customer":{"age":35,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"creditTier":"excellent","discount":0.15,"name":"Alice","totalRevenue":0}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | customer.discount | 821418efc03340d73c74ecfdb5392775","suite":"analysis — excellent tier, high revenue → 20% discount","goals":["customer.discount"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | customer.discount,customer.totalRevenue | b14725903e8800e437b7894e15fde953","suite":"analysis — excellent tier, high revenue → 20% discount","goals":["customer.discount","customer.totalRevenue"],"input":{"customer":{"age":35,"companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":7,"creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, high revenue → 20% discount | customer.totalRevenue | 5ab43f4342431b3cb0b11e8c11a67d27","suite":"analysis — excellent tier, high revenue → 20% discount","goals":["customer.totalRevenue"],"input":{"customer":{"age":"text","companies":[{"iban":"DE123","id":"c1","name":"ACME","revenue":300000},{"iban":"DE456","id":"c2","name":"Globex","revenue":250000}],"country":"US","creditReport":{"delinquencies":0,"score":800,"totalDebt":5000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — excellent tier, low revenue → 15% discount","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 23b7ccfc26d56d3fa21bee57ec4b080d","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":7,"creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 27e7a0aa4cb3c31242d0f9dca690a3f4","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 2fc62c43f4d9dce914d50163eb20e9a0","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":null,"name":"Bob"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 75ed11b950fdc52e867eb4aa32ec664b","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":{"age":40,"companies":[],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"ok":{"customer":{"age":40,"companies":[],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"creditTier":"excellent","discount":0.15,"name":"Bob","totalRevenue":0}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 760b1ec348602d4072b296a566f3c37f","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":{"age":"text","companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 821418efc03340d73c74ecfdb5392775","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | | 822f4543d145c5ce3693305b2a3e0a39","suite":"analysis — excellent tier, low revenue → 15% discount","input":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"ok":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"creditTier":"excellent","discount":0.15,"name":"Bob","totalRevenue":50000}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | customer.creditTier | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — excellent tier, low revenue → 15% discount","goals":["customer.creditTier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.creditTier\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.creditTier"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | customer.creditTier | 27e7a0aa4cb3c31242d0f9dca690a3f4","suite":"analysis — excellent tier, low revenue → 15% discount","goals":["customer.creditTier"],"input":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | customer.creditTier,customer.discount | 75ed11b950fdc52e867eb4aa32ec664b","suite":"analysis — excellent tier, low revenue → 15% discount","goals":["customer.creditTier","customer.discount"],"input":{"customer":{"age":40,"companies":[],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"ok":{"customer":{"age":40,"companies":[],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"creditTier":"excellent","discount":0.15,"name":"Bob","totalRevenue":0}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | customer.discount | 821418efc03340d73c74ecfdb5392775","suite":"analysis — excellent tier, low revenue → 15% discount","goals":["customer.discount"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | customer.discount,customer.totalRevenue | 23b7ccfc26d56d3fa21bee57ec4b080d","suite":"analysis — excellent tier, low revenue → 15% discount","goals":["customer.discount","customer.totalRevenue"],"input":{"customer":{"age":40,"companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":7,"creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — excellent tier, low revenue → 15% discount | customer.totalRevenue | 760b1ec348602d4072b296a566f3c37f","suite":"analysis — excellent tier, low revenue → 15% discount","goals":["customer.totalRevenue"],"input":{"customer":{"age":"text","companies":[{"iban":"GB123","id":"c1","name":"SmallCo","revenue":50000}],"country":"UK","creditReport":{"delinquencies":0,"score":760,"totalDebt":2000},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — good tier, any revenue → 5% discount","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | 0ef305c2189db9a7894cc3e032fc6170","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":null,"name":"Carol"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | 2e3122064a565767160bd47e16e20bea","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"ok":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"creditTier":"good","discount":0.05,"name":"Carol","totalRevenue":100000}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | 821418efc03340d73c74ecfdb5392775","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | 9355347b27af04e78aa41aa8d8e4b985","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":{"age":28,"companies":[],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"ok":{"customer":{"age":28,"companies":[],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"creditTier":"good","discount":0.05,"name":"Carol","totalRevenue":0}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | 95b5f8bb2365fb51db41565a50a00d51","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | ac713ebcc8c8acbd8b6255e037efb432","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":{"age":"text","companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | | cd22fd38650f1e10187174ba30906abd","suite":"analysis — good tier, any revenue → 5% discount","input":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":7,"creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | customer.creditTier | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — good tier, any revenue → 5% discount","goals":["customer.creditTier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.creditTier\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.creditTier"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | customer.creditTier | 95b5f8bb2365fb51db41565a50a00d51","suite":"analysis — good tier, any revenue → 5% discount","goals":["customer.creditTier"],"input":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | customer.creditTier,customer.discount | 9355347b27af04e78aa41aa8d8e4b985","suite":"analysis — good tier, any revenue → 5% discount","goals":["customer.creditTier","customer.discount"],"input":{"customer":{"age":28,"companies":[],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"ok":{"customer":{"age":28,"companies":[],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"creditTier":"good","discount":0.05,"name":"Carol","totalRevenue":0}}}}
{"key":"analysis — good tier, any revenue → 5% discount | customer.discount | 821418efc03340d73c74ecfdb5392775","suite":"analysis — good tier, any revenue → 5% discount","goals":["customer.discount"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | customer.discount,customer.totalRevenue | cd22fd38650f1e10187174ba30906abd","suite":"analysis — good tier, any revenue → 5% discount","goals":["customer.discount","customer.totalRevenue"],"input":{"customer":{"age":28,"companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":7,"creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, any revenue → 5% discount | customer.totalRevenue | ac713ebcc8c8acbd8b6255e037efb432","suite":"analysis — good tier, any revenue → 5% discount","goals":["customer.totalRevenue"],"input":{"customer":{"age":"text","companies":[{"iban":"DE789","id":"c1","name":"MidCo","revenue":100000}],"country":"DE","creditReport":{"delinquencies":1,"score":650,"totalDebt":15000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — good tier, no companies → 5% discount","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 1acb0247d6d3acdb8f3954f8da5943b3","suite":"analysis — good tier, no companies → 5% discount","input":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Dave"}},"plain":{"ok":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"creditTier":"good","discount":0.05,"name":"Dave","totalRevenue":0}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 5ee4869cf66da5dabd80d3156324fd13","suite":"analysis — good tier, no companies → 5% discount","input":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 6ca0069358ae1880b8f6feeb51dfe390","suite":"analysis — good tier, no companies → 5% discount","input":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":null,"name":"Dave"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 821418efc03340d73c74ecfdb5392775","suite":"analysis — good tier, no companies → 5% discount","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 8fe2478dc085c8fd1f2c93f654a24458","suite":"analysis — good tier, no companies → 5% discount","input":{"customer":{"age":"text","companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | | 9f63c212ad57f413cb49d124e35b7721","suite":"analysis — good tier, no companies → 5% discount","input":{"customer":{"age":50,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | customer.creditTier | 0880955dd2ab1be95aa0733055c655b5","suite":"analysis — good tier, no companies → 5% discount","goals":["customer.creditTier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.creditTier\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.creditTier"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | customer.creditTier | 5ee4869cf66da5dabd80d3156324fd13","suite":"analysis — good tier, no companies → 5% discount","goals":["customer.creditTier"],"input":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | customer.creditTier,customer.discount | 1acb0247d6d3acdb8f3954f8da5943b3","suite":"analysis — good tier, no companies → 5% discount","goals":["customer.creditTier","customer.discount"],"input":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Dave"}},"plain":{"ok":{"customer":{"age":50,"companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"creditTier":"good","discount":0.05,"name":"Dave","totalRevenue":0}}}}
{"key":"analysis — good tier, no companies → 5% discount | customer.discount | 821418efc03340d73c74ecfdb5392775","suite":"analysis — good tier, no companies → 5% discount","goals":["customer.discount"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.discount\"], missing: [\"customer.companies\", \"customer.companies.revenue\", \"customer.creditReport.score\"] }","value":{"goals":["customer.discount"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | customer.discount,customer.totalRevenue | 9f63c212ad57f413cb49d124e35b7721","suite":"analysis — good tier, no companies → 5% discount","goals":["customer.discount","customer.totalRevenue"],"input":{"customer":{"age":50,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"analysis — good tier, no companies → 5% discount | customer.totalRevenue | 8fe2478dc085c8fd1f2c93f654a24458","suite":"analysis — good tier, no companies → 5% discount","goals":["customer.totalRevenue"],"input":{"customer":{"age":"text","companies":[],"country":"FR","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — both conditions fail","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | | 24f3cf70b34662e87ffe0e5f366b9c50","suite":"assertion — both conditions fail","input":{"customer":{"age":15,"companies":[],"country":"DE","creditReport":null,"name":"Dave"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | | 26398873a33d209a6f003dfffaf1d2ee","suite":"assertion — both conditions fail","input":{"customer":{"age":15,"companies":[],"country":"DE","creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | | 6991795f77dfbae2164e2d82fcd23d48","suite":"assertion — both conditions fail","input":{"customer":{"age":15,"companies":[],"country":"DE","creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":"Dave"}},"plain":{"ok":{"customer":{"age":15,"companies":[],"country":"DE","creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"isEligible":false,"name":"Dave"}}}}
{"key":"assertion — both conditions fail | | 821418efc03340d73c74ecfdb5392775","suite":"assertion — both conditions fail","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | | 998789c045853ad5bffbad57372d76ac","suite":"assertion — both conditions fail","input":{"customer":{"age":"text","companies":[],"country":"DE","creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | | f40039c39fbe49053781a439aa03a3cb","suite":"assertion — both conditions fail","input":{"customer":{"age":15,"companies":[],"country":7,"creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | customer.isEligible | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — both conditions fail","goals":["customer.isEligible"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | customer.isEligible | 26398873a33d209a6f003dfffaf1d2ee","suite":"assertion — both conditions fail","goals":["customer.isEligible"],"input":{"customer":{"age":15,"companies":[],"country":"DE","creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | customer.isEligible | 998789c045853ad5bffbad57372d76ac","suite":"assertion — both conditions fail","goals":["customer.isEligible"],"input":{"customer":{"age":"text","companies":[],"country":"DE","creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — both conditions fail | customer.isEligible | f40039c39fbe49053781a439aa03a3cb","suite":"assertion — both conditions fail","goals":["customer.isEligible"],"input":{"customer":{"age":15,"companies":[],"country":7,"creditReport":{"delinquencies":5,"score":400,"totalDebt":10000},"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — eligible customer (both conditions true)","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | | 35b10db2e5897966249a62cf922e668f","suite":"assertion — eligible customer (both conditions true)","input":{"customer":{"age":25,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":"Alice"}},"plain":{"ok":{"customer":{"age":25,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"isEligible":true,"name":"Alice"}}}}
{"key":"assertion — eligible customer (both conditions true) | | 3aed40ad818a614f09da4894d2854494","suite":"assertion — eligible customer (both conditions true)","input":{"customer":{"age":"text","companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | | 712167396099ca0c9633a1fec5ab5215","suite":"assertion — eligible customer (both conditions true)","input":{"customer":{"age":25,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | | 821418efc03340d73c74ecfdb5392775","suite":"assertion — eligible customer (both conditions true)","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | | 839634a6d8487521cd3d7ab4ff9f0c52","suite":"assertion — eligible customer (both conditions true)","input":{"customer":{"age":25,"companies":[],"country":"US","creditReport":null,"name":"Alice"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | | f71c24f6b6d01173a176dc7e2b009ba3","suite":"assertion — eligible customer (both conditions true)","input":{"customer":{"age":25,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | customer.isEligible | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — eligible customer (both conditions true)","goals":["customer.isEligible"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | customer.isEligible | 3aed40ad818a614f09da4894d2854494","suite":"assertion — eligible customer (both conditions true)","goals":["customer.isEligible"],"input":{"customer":{"age":"text","companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | customer.isEligible | 712167396099ca0c9633a1fec5ab5215","suite":"assertion — eligible customer (both conditions true)","goals":["customer.isEligible"],"input":{"customer":{"age":25,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — eligible customer (both conditions true) | customer.isEligible | f71c24f6b6d01173a176dc7e2b009ba3","suite":"assertion — eligible customer (both conditions true)","goals":["customer.isEligible"],"input":{"customer":{"age":25,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":1000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — low credit score fails","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | | 3f7e1fb4ae597873d35baa1290708c60","suite":"assertion — low credit score fails","input":{"customer":{"age":"text","companies":[],"country":"UK","creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | | 534a893b1384d07f8b41e245e1c81417","suite":"assertion — low credit score fails","input":{"customer":{"age":30,"companies":[],"country":7,"creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | | 821418efc03340d73c74ecfdb5392775","suite":"assertion — low credit score fails","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | | c788c46bb6ada20feec2d09b88f76165","suite":"assertion — low credit score fails","input":{"customer":{"age":30,"companies":[],"country":"UK","creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":"Carol"}},"plain":{"ok":{"customer":{"age":30,"companies":[],"country":"UK","creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"isEligible":false,"name":"Carol"}}}}
{"key":"assertion — low credit score fails | | dd80dc2195107ba3a145f669509e9d6f","suite":"assertion — low credit score fails","input":{"customer":{"age":30,"companies":[],"country":"UK","creditReport":null,"name":"Carol"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | | e70ddd74b26277bc0dd15b2d3c1f5c0e","suite":"assertion — low credit score fails","input":{"customer":{"age":30,"companies":[],"country":"UK","creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | customer.isEligible | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — low credit score fails","goals":["customer.isEligible"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | customer.isEligible | 3f7e1fb4ae597873d35baa1290708c60","suite":"assertion — low credit score fails","goals":["customer.isEligible"],"input":{"customer":{"age":"text","companies":[],"country":"UK","creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | customer.isEligible | 534a893b1384d07f8b41e245e1c81417","suite":"assertion — low credit score fails","goals":["customer.isEligible"],"input":{"customer":{"age":30,"companies":[],"country":7,"creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — low credit score fails | customer.isEligible | e70ddd74b26277bc0dd15b2d3c1f5c0e","suite":"assertion — low credit score fails","goals":["customer.isEligible"],"input":{"customer":{"age":30,"companies":[],"country":"UK","creditReport":{"delinquencies":2,"score":500,"totalDebt":5000},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — underage customer fails","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | | 468eec199fa113f5980705c0fd01944d","suite":"assertion — underage customer fails","input":{"customer":{"age":16,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":"Bob"}},"plain":{"ok":{"customer":{"age":16,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"isEligible":false,"name":"Bob"}}}}
{"key":"assertion — underage customer fails | | 6cf0193c3fc413db77aafda7f3f99c79","suite":"assertion — underage customer fails","input":{"customer":{"age":16,"companies":[],"country":"US","creditReport":null,"name":"Bob"}},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | | 8107d39e78def8d4bed3cf677f038adb","suite":"assertion — underage customer fails","input":{"customer":{"age":16,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | | 821418efc03340d73c74ecfdb5392775","suite":"assertion — underage customer fails","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | | 9a6798a60ce960900dabd6b4c4168b92","suite":"assertion — underage customer fails","input":{"customer":{"age":"text","companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | | ff4e7b8e9844b426b2c425b19cf2cc20","suite":"assertion — underage customer fails","input":{"customer":{"age":16,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | customer.isEligible | 0880955dd2ab1be95aa0733055c655b5","suite":"assertion — underage customer fails","goals":["customer.isEligible"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\"], missing: [\"customer.age\", \"customer.creditReport.score\"] }","value":{"goals":["customer.isEligible"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.creditReport.score"],"type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | customer.isEligible | 8107d39e78def8d4bed3cf677f038adb","suite":"assertion — underage customer fails","goals":["customer.isEligible"],"input":{"customer":{"age":16,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | customer.isEligible | 9a6798a60ce960900dabd6b4c4168b92","suite":"assertion — underage customer fails","goals":["customer.isEligible"],"input":{"customer":{"age":"text","companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"assertion — underage customer fails | customer.isEligible | ff4e7b8e9844b426b2c425b19cf2cc20","suite":"assertion — underage customer fails","goals":["customer.isEligible"],"input":{"customer":{"age":16,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":750,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | | 0880955dd2ab1be95aa0733055c655b5","suite":"collect table — adult gets adult + minor tags","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | | 69f0f6a482754d80a7eaf203c2a7ae90","suite":"collect table — adult gets adult + minor tags","input":{"customer":{"age":"text","companies":[],"country":"US","name":"Frank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | | 6aafd11cf509e693ef85d5f2fa734f47","suite":"collect table — adult gets adult + minor tags","input":{"customer":{"age":30,"companies":[],"country":"US","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | | 821418efc03340d73c74ecfdb5392775","suite":"collect table — adult gets adult + minor tags","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | | c85c53564edcebf86900e9a591cbb6d3","suite":"collect table — adult gets adult + minor tags","input":{"customer":{"age":30,"companies":[],"country":"US","name":"Frank"}},"plain":{"ok":{"customer":{"age":30,"companies":[],"country":"US","name":"Frank","tags":["adult","minor"]}}}}
{"key":"collect table — adult gets adult + minor tags | | fcb72a6320b58a1d60aff94cd50af585","suite":"collect table — adult gets adult + minor tags","input":{"customer":{"age":30,"companies":[],"country":7,"name":"Frank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | customer.tags | 0880955dd2ab1be95aa0733055c655b5","suite":"collect table — adult gets adult + minor tags","goals":["customer.tags"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | customer.tags | 69f0f6a482754d80a7eaf203c2a7ae90","suite":"collect table — adult gets adult + minor tags","goals":["customer.tags"],"input":{"customer":{"age":"text","companies":[],"country":"US","name":"Frank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — adult gets adult + minor tags | customer.tags | fcb72a6320b58a1d60aff94cd50af585","suite":"collect table — adult gets adult + minor tags","goals":["customer.tags"],"input":{"customer":{"age":30,"companies":[],"country":7,"name":"Frank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | | 0880955dd2ab1be95aa0733055c655b5","suite":"collect table — child gets only minor tag","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | | 1d4c3d21ef754d881cde6620a9a3d2c4","suite":"collect table — child gets only minor tag","input":{"customer":{"age":"text","companies":[],"country":"US","name":"Grace"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | | 21cb768e3572d6bc6726f904f8a9b2c9","suite":"collect table — child gets only minor tag","input":{"customer":{"age":10,"companies":[],"country":"US","name":"Grace"}},"plain":{"ok":{"customer":{"age":10,"companies":[],"country":"US","name":"Grace","tags":["minor"]}}}}
{"key":"collect table — child gets only minor tag | | 821418efc03340d73c74ecfdb5392775","suite":"collect table — child gets only minor tag","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | | 9c9d45427b79ffd6a45b522a553c6d33","suite":"collect table — child gets only minor tag","input":{"customer":{"age":10,"companies":[],"country":7,"name":"Grace"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | | d5fb92245d2cb35097909e3eec81d0b9","suite":"collect table — child gets only minor tag","input":{"customer":{"age":10,"companies":[],"country":"US","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | customer.tags | 0880955dd2ab1be95aa0733055c655b5","suite":"collect table — child gets only minor tag","goals":["customer.tags"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | customer.tags | 1d4c3d21ef754d881cde6620a9a3d2c4","suite":"collect table — child gets only minor tag","goals":["customer.tags"],"input":{"customer":{"age":"text","companies":[],"country":"US","name":"Grace"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — child gets only minor tag | customer.tags | 9c9d45427b79ffd6a45b522a553c6d33","suite":"collect table — child gets only minor tag","goals":["customer.tags"],"input":{"customer":{"age":10,"companies":[],"country":7,"name":"Grace"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | | 0880955dd2ab1be95aa0733055c655b5","suite":"collect table — senior gets senior + adult + minor tags","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | | 585c2f0e997086575ba5207b9d03e2a8","suite":"collect table — senior gets senior + adult + minor tags","input":{"customer":{"age":"text","companies":[],"country":"US","name":"Edna"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | | 7f13c2b7bbe2a3a4ec022be840a3cd43","suite":"collect table — senior gets senior + adult + minor tags","input":{"customer":{"age":70,"companies":[],"country":"US","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | | 821418efc03340d73c74ecfdb5392775","suite":"collect table — senior gets senior + adult + minor tags","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | | ec4452db03a88e32a42ed3d468a2c36b","suite":"collect table — senior gets senior + adult + minor tags","input":{"customer":{"age":70,"companies":[],"country":7,"name":"Edna"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | | f1ecaee44c6056990dc76b605a93d631","suite":"collect table — senior gets senior + adult + minor tags","input":{"customer":{"age":70,"companies":[],"country":"US","name":"Edna"}},"plain":{"ok":{"customer":{"age":70,"companies":[],"country":"US","name":"Edna","tags":["senior","adult","minor"]}}}}
{"key":"collect table — senior gets senior + adult + minor tags | customer.tags | 0880955dd2ab1be95aa0733055c655b5","suite":"collect table — senior gets senior + adult + minor tags","goals":["customer.tags"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tags\"], missing: [\"customer.age\"] }","value":{"goals":["customer.tags"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | customer.tags | 585c2f0e997086575ba5207b9d03e2a8","suite":"collect table — senior gets senior + adult + minor tags","goals":["customer.tags"],"input":{"customer":{"age":"text","companies":[],"country":"US","name":"Edna"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"collect table — senior gets senior + adult + minor tags | customer.tags | ec4452db03a88e32a42ed3d468a2c36b","suite":"collect table — senior gets senior + adult + minor tags","goals":["customer.tags"],"input":{"customer":{"age":70,"companies":[],"country":7,"name":"Edna"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"company block — computes profit margin per instance | | 030c0e1b0a48e157772ac7ccab763a4c","suite":"company block — computes profit margin per instance","input":{"customer":{"age":30,"companies":[{"iban":"US123","id":"c1","name":"BigCo","revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","revenue":50000}],"country":"US","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Ivy"}},"plain":{"ok":{"customer":{"age":30,"companies":[{"iban":"US123","id":"c1","name":"BigCo","profitMargin":100000,"revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","profitMargin":5000,"revenue":50000}],"country":"US","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Ivy"}}}}
{"key":"company block — computes profit margin per instance | | 0880955dd2ab1be95aa0733055c655b5","suite":"company block — computes profit margin per instance","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.profitMargin\"], missing: [\"company.revenue\"] }","value":{"goals":["company.profitMargin"],"kind":"MissingRequiredInputs","missing":["company.revenue"],"type":"PolicyError"}}}}
{"key":"company block — computes profit margin per instance | | 3b099c1108dce1fb6b0823bdc04d0d37","suite":"company block — computes profit margin per instance","input":{"customer":{"age":30,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Ivy"}},"plain":{"ok":{"customer":{"age":30,"companies":[],"country":"US","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Ivy"}}}}
{"key":"company block — computes profit margin per instance | | 3d69c15b6e5c48c86bfb808b350bdfbf","suite":"company block — computes profit margin per instance","input":{"customer":{"age":30,"companies":[{"iban":"US123","id":"c1","name":"BigCo","revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","revenue":50000}],"country":"US","creditReport":null,"name":"Ivy"}},"plain":{"ok":{"customer":{"age":30,"companies":[{"iban":"US123","id":"c1","name":"BigCo","profitMargin":100000,"revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","profitMargin":5000,"revenue":50000}],"country":"US","creditReport":null,"name":"Ivy"}}}}
{"key":"company block — computes profit margin per instance | | 5a2dfddafd9d985dc5e4579bca05466b","suite":"company block — computes profit margin per instance","input":{"customer":{"age":"text","companies":[{"iban":"US123","id":"c1","name":"BigCo","revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","revenue":50000}],"country":"US","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Ivy"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"company block — computes profit margin per instance | | 821418efc03340d73c74ecfdb5392775","suite":"company block — computes profit margin per instance","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.profitMargin\"], missing: [\"company.revenue\"] }","value":{"goals":["company.profitMargin"],"kind":"MissingRequiredInputs","missing":["company.revenue"],"type":"PolicyError"}}}}
{"key":"company block — computes profit margin per instance | | f5e8a4a02e83eae996e609cc9ad86878","suite":"company block — computes profit margin per instance","input":{"customer":{"age":30,"companies":[{"iban":"US123","id":"c1","name":"BigCo","revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","revenue":50000}],"country":7,"creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Ivy"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"company block — computes profit margin per instance | | fa50b29ae1f44e325db87553ed480536","suite":"company block — computes profit margin per instance","input":{"customer":{"age":30,"companies":[{"iban":"US123","id":"c1","name":"BigCo","revenue":1000000},{"iban":"US456","id":"c2","name":"Smol","revenue":50000}],"country":"US","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — eligible high-income → platinum","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | | 15e51844ff6730c5450283d94fe79fb1","suite":"cross-policy — eligible high-income → platinum","input":{"customer":{"age":30,"income":120000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — eligible high-income → platinum","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | | cf1c3d474f27dcd1a4470c63f0192a6a","suite":"cross-policy — eligible high-income → platinum","input":{"customer":{"age":"text","income":120000,"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | | ebe27a80caa0be2bcd2a0d09d24ef4f0","suite":"cross-policy — eligible high-income → platinum","input":{"customer":{"age":30,"income":"text","name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.income\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.income': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | | f3e6573b7d93112d14c15e62ebbc2005","suite":"cross-policy — eligible high-income → platinum","input":{"customer":{"age":30,"income":120000,"name":"Alice"}},"plain":{"ok":{"customer":{"age":30,"income":120000,"isEligible":true,"name":"Alice","tier":"platinum"}}}}
{"key":"cross-policy — eligible high-income → platinum | customer.isEligible | cf1c3d474f27dcd1a4470c63f0192a6a","suite":"cross-policy — eligible high-income → platinum","goals":["customer.isEligible"],"input":{"customer":{"age":"text","income":120000,"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | customer.isEligible,customer.tier | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — eligible high-income → platinum","goals":["customer.isEligible","customer.tier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\", \"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.isEligible","customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | customer.isEligible,customer.tier | 15e51844ff6730c5450283d94fe79fb1","suite":"cross-policy — eligible high-income → platinum","goals":["customer.isEligible","customer.tier"],"input":{"customer":{"age":30,"income":120000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible high-income → platinum | customer.tier | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — eligible high-income → platinum","goals":["customer.tier"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | | 054dba0a424dee88e41246cdc342dd30","suite":"cross-policy — eligible low-income → silver","input":{"customer":{"age":"text","income":35000,"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — eligible low-income → silver","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | | 4a7a6b550940557565a29822ef3e3b15","suite":"cross-policy — eligible low-income → silver","input":{"customer":{"age":40,"income":35000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | | 567652f6e46fa3646b6c818354bee82e","suite":"cross-policy — eligible low-income → silver","input":{"customer":{"age":40,"income":35000,"name":"Carol"}},"plain":{"ok":{"customer":{"age":40,"income":35000,"isEligible":true,"name":"Carol","tier":"silver"}}}}
{"key":"cross-policy — eligible low-income → silver | | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — eligible low-income → silver","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | | fb342195039e70b42aec9ba48c6901c2","suite":"cross-policy — eligible low-income → silver","input":{"customer":{"age":40,"income":"text","name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.income\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.income': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | customer.isEligible | 054dba0a424dee88e41246cdc342dd30","suite":"cross-policy — eligible low-income → silver","goals":["customer.isEligible"],"input":{"customer":{"age":"text","income":35000,"name":"Carol"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | customer.isEligible,customer.tier | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — eligible low-income → silver","goals":["customer.isEligible","customer.tier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\", \"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.isEligible","customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | customer.isEligible,customer.tier | 4a7a6b550940557565a29822ef3e3b15","suite":"cross-policy — eligible low-income → silver","goals":["customer.isEligible","customer.tier"],"input":{"customer":{"age":40,"income":35000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible low-income → silver | customer.tier | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — eligible low-income → silver","goals":["customer.tier"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — eligible mid-income → gold","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | | 2540f4d62787f40d4e575c962ed368b4","suite":"cross-policy — eligible mid-income → gold","input":{"customer":{"age":"text","income":60000,"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — eligible mid-income → gold","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | | 8316d94fd6959b83075517b24c279d93","suite":"cross-policy — eligible mid-income → gold","input":{"customer":{"age":25,"income":60000,"name":"Bob"}},"plain":{"ok":{"customer":{"age":25,"income":60000,"isEligible":true,"name":"Bob","tier":"gold"}}}}
{"key":"cross-policy — eligible mid-income → gold | | 8fbda76d3f24015fbc2585d823ae87ef","suite":"cross-policy — eligible mid-income → gold","input":{"customer":{"age":25,"income":"text","name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.income\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.income': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | | f950dce7cf28e952881bca5b7ce1616e","suite":"cross-policy — eligible mid-income → gold","input":{"customer":{"age":25,"income":60000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | customer.isEligible | 2540f4d62787f40d4e575c962ed368b4","suite":"cross-policy — eligible mid-income → gold","goals":["customer.isEligible"],"input":{"customer":{"age":"text","income":60000,"name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | customer.isEligible,customer.tier | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — eligible mid-income → gold","goals":["customer.isEligible","customer.tier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\", \"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.isEligible","customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | customer.isEligible,customer.tier | f950dce7cf28e952881bca5b7ce1616e","suite":"cross-policy — eligible mid-income → gold","goals":["customer.isEligible","customer.tier"],"input":{"customer":{"age":25,"income":60000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — eligible mid-income → gold | customer.tier | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — eligible mid-income → gold","goals":["customer.tier"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | | 0845148c188365c64d092a67ed074fef","suite":"cross-policy — ineligible (low income) → rejected","input":{"customer":{"age":"text","income":20000,"name":"Eve"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — ineligible (low income) → rejected","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | | 70cd976ef209af0f0251f681d9b92152","suite":"cross-policy — ineligible (low income) → rejected","input":{"customer":{"age":25,"income":20000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — ineligible (low income) → rejected","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | | 961570c8ddfdf8248985975d08957150","suite":"cross-policy — ineligible (low income) → rejected","input":{"customer":{"age":25,"income":20000,"name":"Eve"}},"plain":{"ok":{"customer":{"age":25,"income":20000,"isEligible":false,"name":"Eve","tier":"rejected"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | | d6084eef1624015fbc3d473a1ef496a0","suite":"cross-policy — ineligible (low income) → rejected","input":{"customer":{"age":25,"income":"text","name":"Eve"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.income\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.income': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | customer.isEligible | 0845148c188365c64d092a67ed074fef","suite":"cross-policy — ineligible (low income) → rejected","goals":["customer.isEligible"],"input":{"customer":{"age":"text","income":20000,"name":"Eve"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | customer.isEligible,customer.tier | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — ineligible (low income) → rejected","goals":["customer.isEligible","customer.tier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\", \"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.isEligible","customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | customer.isEligible,customer.tier | 70cd976ef209af0f0251f681d9b92152","suite":"cross-policy — ineligible (low income) → rejected","goals":["customer.isEligible","customer.tier"],"input":{"customer":{"age":25,"income":20000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (low income) → rejected | customer.tier | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — ineligible (low income) → rejected","goals":["customer.tier"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — ineligible (underage) → rejected","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | | 320fb6f1b8dd05ac7e3e80f129d613d2","suite":"cross-policy — ineligible (underage) → rejected","input":{"customer":{"age":"text","income":50000,"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | | 4e40fc8e6d69979c80edaf381d208596","suite":"cross-policy — ineligible (underage) → rejected","input":{"customer":{"age":16,"income":"text","name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.income\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.income': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — ineligible (underage) → rejected","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | | 855ed24f4e0242a6814652d867913be9","suite":"cross-policy — ineligible (underage) → rejected","input":{"customer":{"age":16,"income":50000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | | ad063cd9d0262cab580a361512430a75","suite":"cross-policy — ineligible (underage) → rejected","input":{"customer":{"age":16,"income":50000,"name":"Dave"}},"plain":{"ok":{"customer":{"age":16,"income":50000,"isEligible":false,"name":"Dave","tier":"rejected"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | customer.isEligible | 320fb6f1b8dd05ac7e3e80f129d613d2","suite":"cross-policy — ineligible (underage) → rejected","goals":["customer.isEligible"],"input":{"customer":{"age":"text","income":50000,"name":"Dave"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | customer.isEligible,customer.tier | 0880955dd2ab1be95aa0733055c655b5","suite":"cross-policy — ineligible (underage) → rejected","goals":["customer.isEligible","customer.tier"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.isEligible\", \"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.isEligible","customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | customer.isEligible,customer.tier | 855ed24f4e0242a6814652d867913be9","suite":"cross-policy — ineligible (underage) → rejected","goals":["customer.isEligible","customer.tier"],"input":{"customer":{"age":16,"income":50000,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"cross-policy — ineligible (underage) → rejected | customer.tier | 821418efc03340d73c74ecfdb5392775","suite":"cross-policy — ineligible (underage) → rejected","goals":["customer.tier"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.tier\"], missing: [\"customer.age\", \"customer.income\"] }","value":{"goals":["customer.tier"],"kind":"MissingRequiredInputs","missing":["customer.age","customer.income"],"type":"PolicyError"}}}}
{"key":"inverse relationship — company reads company.customer.age | | 0880955dd2ab1be95aa0733055c655b5","suite":"inverse relationship — company reads company.customer.age","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.ownerAge\"], missing: [\"company.customer.age\"] }","value":{"goals":["company.ownerAge"],"kind":"MissingRequiredInputs","missing":["company.customer.age"],"type":"PolicyError"}}}}
{"key":"inverse relationship — company reads company.customer.age | | 0c916e83be9f0e6a518502473fb97a3e","suite":"inverse relationship — company reads company.customer.age","input":{"customer":{"age":42,"companies":[{"name":"Acme"},{"name":"Smol"}],"name":"Alice"}},"plain":{"ok":{"customer":{"age":42,"companies":[{"name":"Acme","ownerAge":42},{"name":"Smol","ownerAge":42}],"name":"Alice"}}}}
{"key":"inverse relationship — company reads company.customer.age | | 821418efc03340d73c74ecfdb5392775","suite":"inverse relationship — company reads company.customer.age","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.ownerAge\"], missing: [\"company.customer.age\"] }","value":{"goals":["company.ownerAge"],"kind":"MissingRequiredInputs","missing":["company.customer.age"],"type":"PolicyError"}}}}
{"key":"inverse relationship — company reads company.customer.age | | a8c8db304675ff29f231f190715d7e89","suite":"inverse relationship — company reads company.customer.age","input":{"customer":{"age":42,"companies":[],"name":"Alice"}},"plain":{"ok":{"customer":{"age":42,"companies":[],"name":"Alice"}}}}
{"key":"inverse relationship — company reads company.customer.age | | af82542ed21574aaaad26693c4c8d93a","suite":"inverse relationship — company reads company.customer.age","input":{"customer":{"age":42,"companies":[{"name":"Acme"},{"name":"Smol"}],"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"inverse relationship — company reads company.customer.age | | e4e7e433d55caef938811fc6068fea2e","suite":"inverse relationship — company reads company.customer.age","input":{"customer":{"age":"text","companies":[{"name":"Acme"},{"name":"Smol"}],"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | | 0d120f6e3f6ea267d8569fa882d9392e","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | | 2f64d262c35720557ca5d6e407f7e58a","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":7,"name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":7,"name":"TechCo","revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | 4b39a4d608dc359c3028e218d239d731","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | 705ae5299f52238d45f04c65698788ef","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":null,"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":null,"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | 7641a5fd754ee8fe6fb776c986bf84df","suite":"multi-entity table — writes to customer and company","input":{"company":null,"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":null,"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | 7913961613118e1e169ec932d96b2ddf","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":7,"id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":7,"id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | 96e1431a4700628f858e19acb2dc3e31","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":null},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":null}}}
{"key":"multi-entity table — writes to customer and company | | 9b6d105e712a86127f6b5f0d48e6aa0f","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":"text"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":"text","status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | a99320adff73bad72a613e3c6dfafe58","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":7,"revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":7,"revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | aa2be18abbc4be9f09f8dbe1a1d84498","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":"text","companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | | d5b073c9b14709466052ec96917d0df6","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | d9cae3e1378d7d9132e6430033d477aa","suite":"multi-entity table — writes to customer and company","input":{"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | | f2046de517d3dd01df5e29b8458b8b50","suite":"multi-entity table — writes to customer and company","input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | company.status | 4b39a4d608dc359c3028e218d239d731","suite":"multi-entity table — writes to customer and company","goals":["company.status"],"input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | company.status | 7913961613118e1e169ec932d96b2ddf","suite":"multi-entity table — writes to customer and company","goals":["company.status"],"input":{"company":{"iban":7,"id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":7,"id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | company.status | f2046de517d3dd01df5e29b8458b8b50","suite":"multi-entity table — writes to customer and company","goals":["company.status"],"input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":7,"creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | company.status,customer.status | 0d120f6e3f6ea267d8569fa882d9392e","suite":"multi-entity table — writes to customer and company","goals":["company.status","customer.status"],"input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | company.status,customer.status | a99320adff73bad72a613e3c6dfafe58","suite":"multi-entity table — writes to customer and company","goals":["company.status","customer.status"],"input":{"company":{"iban":"NL001","id":"c1","name":7,"revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":7,"revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | company.status,customer.status | aa2be18abbc4be9f09f8dbe1a1d84498","suite":"multi-entity table — writes to customer and company","goals":["company.status","customer.status"],"input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":"text","companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-entity table — writes to customer and company | company.status,customer.status | d9cae3e1378d7d9132e6430033d477aa","suite":"multi-entity table — writes to customer and company","goals":["company.status","customer.status"],"input":{"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | customer.status | 7641a5fd754ee8fe6fb776c986bf84df","suite":"multi-entity table — writes to customer and company","goals":["customer.status"],"input":{"company":null,"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":null,"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | customer.status | 9b6d105e712a86127f6b5f0d48e6aa0f","suite":"multi-entity table — writes to customer and company","goals":["customer.status"],"input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":"text"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":"text","status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-entity table — writes to customer and company | customer.status | d5b073c9b14709466052ec96917d0df6","suite":"multi-entity table — writes to customer and company","goals":["customer.status"],"input":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank"}},"plain":{"ok":{"company":{"iban":"NL001","id":"c1","name":"TechCo","revenue":500000,"status":"verified"},"customer":{"age":40,"companies":[],"country":"NL","creditReport":{"delinquencies":0,"score":700,"totalDebt":0},"name":"Hank","status":"active"}}}}
{"key":"multi-policy import — both policies write to customer | | 0880955dd2ab1be95aa0733055c655b5","suite":"multi-policy import — both policies write to customer","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\"], missing: [\"customer.country\", \"customer.name\"] }","value":{"goals":["customer.greeting","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.name"],"type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | | 186a1faad0d58a2d09e70ff0b76b8935","suite":"multi-policy import — both policies write to customer","input":{"customer":{"age":30,"country":"France","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | | 286243c575798fc9203ebf57a16986c9","suite":"multi-policy import — both policies write to customer","input":{"customer":{"age":30,"country":"France","name":"Alice"}},"plain":{"ok":{"customer":{"age":30,"country":"France","greeting":"Alice","label":"France","name":"Alice"}}}}
{"key":"multi-policy import — both policies write to customer | | 2aa537dc88b3c5f25429f7a829d04c28","suite":"multi-policy import — both policies write to customer","input":{"customer":{"age":"text","country":"France","name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | | 6bb27d220f715963a0f047e6573e190c","suite":"multi-policy import — both policies write to customer","input":{"customer":{"age":30,"country":7,"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | | 821418efc03340d73c74ecfdb5392775","suite":"multi-policy import — both policies write to customer","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\"], missing: [\"customer.country\", \"customer.name\"] }","value":{"goals":["customer.greeting","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.name"],"type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | customer.greeting | 2aa537dc88b3c5f25429f7a829d04c28","suite":"multi-policy import — both policies write to customer","goals":["customer.greeting"],"input":{"customer":{"age":"text","country":"France","name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | customer.greeting,customer.label | 0880955dd2ab1be95aa0733055c655b5","suite":"multi-policy import — both policies write to customer","goals":["customer.greeting","customer.label"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\"], missing: [\"customer.country\", \"customer.name\"] }","value":{"goals":["customer.greeting","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.name"],"type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | customer.greeting,customer.label | 186a1faad0d58a2d09e70ff0b76b8935","suite":"multi-policy import — both policies write to customer","goals":["customer.greeting","customer.label"],"input":{"customer":{"age":30,"country":"France","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"multi-policy import — both policies write to customer | customer.label | 821418efc03340d73c74ecfdb5392775","suite":"multi-policy import — both policies write to customer","goals":["customer.label"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.country\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country"],"type":"PolicyError"}}}}
{"key":"per-instance — company-risk runs per company | | 0880955dd2ab1be95aa0733055c655b5","suite":"per-instance — company-risk runs per company","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.riskLevel\"], missing: [\"company.revenue\"] }","value":{"goals":["company.riskLevel"],"kind":"MissingRequiredInputs","missing":["company.revenue"],"type":"PolicyError"}}}}
{"key":"per-instance — company-risk runs per company | | 3f38eb048dc4dbaac59bf12851c7dcef","suite":"per-instance — company-risk runs per company","input":{"customer":{"companies":[{"name":"Acme","revenue":300000},{"name":"Smol","revenue":50000}],"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"per-instance — company-risk runs per company | | 821418efc03340d73c74ecfdb5392775","suite":"per-instance — company-risk runs per company","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.riskLevel\"], missing: [\"company.revenue\"] }","value":{"goals":["company.riskLevel"],"kind":"MissingRequiredInputs","missing":["company.revenue"],"type":"PolicyError"}}}}
{"key":"per-instance — company-risk runs per company | | cf245082bb96f8a3cca7d1b4bb403aa8","suite":"per-instance — company-risk runs per company","input":{"customer":{"companies":[],"name":"Alice"}},"plain":{"ok":{"customer":{"companies":[],"name":"Alice"}}}}
{"key":"per-instance — company-risk runs per company | | e7c09977b0943e20c2d1f2b12683c4ab","suite":"per-instance — company-risk runs per company","input":{"customer":{"companies":[{"name":"Acme","revenue":300000},{"name":"Smol","revenue":50000}],"name":"Alice"}},"plain":{"ok":{"customer":{"companies":[{"name":"Acme","revenue":300000,"riskLevel":"low"},{"name":"Smol","revenue":50000,"riskLevel":"high"}],"name":"Alice"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | 1065c8dc34c8f2a7e01417e4e8c15993","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}],"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.riskLevel\", \"customer.totalRevenue\"], missing: [\"customer.companies\", \"customer.companies.revenue\"] }","value":{"goals":["company.riskLevel","customer.totalRevenue"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue"],"type":"PolicyError"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | 433e065450601c5ef888b36161c26612","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}],"customer":{"companies":[],"name":"Alice"}},"plain":{"ok":{"company":[{"id":"c1","revenue":300000,"riskLevel":"low"},{"id":"c2","revenue":50000,"riskLevel":"high"}],"customer":{"companies":[],"name":"Alice","totalRevenue":0}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | 6ea7cc672a3a618c14d13f574d4e4d09","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}],"customer":{"companies":["c1","c2"],"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | 825015860859cbc4907b86c36aa90dfb","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"customer":{"companies":["c1","c2"],"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.companies[0]\", expected: \"reference id present in 'company' pool\", got: \"'c1' (not found)\" }, InputValidationError { path: \"customer.companies[1]\", expected: \"reference id present in 'company' pool\", got: \"'c2' (not found)\" }] }","value":{"errors":["'customer.companies[0]': expected reference id present in 'company' pool, got 'c1' (not found)","'customer.companies[1]': expected reference id present in 'company' pool, got 'c2' (not found)"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | b3623301d9c6694048fc15a140d9616d","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}],"customer":{"companies":["c1","c2"],"name":"Alice"}},"plain":{"ok":{"company":[{"id":"c1","revenue":300000,"riskLevel":"low"},{"id":"c2","revenue":50000,"riskLevel":"high"}],"customer":{"companies":[{"id":"c1","revenue":300000,"riskLevel":"low"},{"id":"c2","revenue":50000,"riskLevel":"high"}],"name":"Alice","totalRevenue":350000}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | d8b9f807376f659c1adc074f932445ca","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"company":null,"customer":{"companies":["c1","c2"],"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.companies[0]\", expected: \"reference id present in 'company' pool\", got: \"'c1' (not found)\" }, InputValidationError { path: \"customer.companies[1]\", expected: \"reference id present in 'company' pool\", got: \"'c2' (not found)\" }] }","value":{"errors":["'customer.companies[0]': expected reference id present in 'company' pool, got 'c1' (not found)","'customer.companies[1]': expected reference id present in 'company' pool, got 'c2' (not found)"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | | e05771aee35387287abd9977305e0747","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}]},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"company.riskLevel\", \"customer.totalRevenue\"], missing: [\"customer.companies\", \"customer.companies.revenue\"] }","value":{"goals":["company.riskLevel","customer.totalRevenue"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue"],"type":"PolicyError"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | customer.totalRevenue | 433e065450601c5ef888b36161c26612","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","goals":["customer.totalRevenue"],"input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}],"customer":{"companies":[],"name":"Alice"}},"plain":{"ok":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}],"customer":{"companies":[],"name":"Alice","totalRevenue":0}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | customer.totalRevenue | 825015860859cbc4907b86c36aa90dfb","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","goals":["customer.totalRevenue"],"input":{"customer":{"companies":["c1","c2"],"name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.companies[0]\", expected: \"reference id present in 'company' pool\", got: \"'c1' (not found)\" }, InputValidationError { path: \"customer.companies[1]\", expected: \"reference id present in 'company' pool\", got: \"'c2' (not found)\" }] }","value":{"errors":["'customer.companies[0]': expected reference id present in 'company' pool, got 'c1' (not found)","'customer.companies[1]': expected reference id present in 'company' pool, got 'c2' (not found)"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"reference iteration — customer.companies ids hydrated from top-level company[] | customer.totalRevenue | e05771aee35387287abd9977305e0747","suite":"reference iteration — customer.companies ids hydrated from top-level company[]","goals":["customer.totalRevenue"],"input":{"company":[{"id":"c1","revenue":300000},{"id":"c2","revenue":50000}]},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.totalRevenue\"], missing: [\"customer.companies\", \"customer.companies.revenue\"] }","value":{"goals":["customer.totalRevenue"],"kind":"MissingRequiredInputs","missing":["customer.companies","customer.companies.revenue"],"type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | | 0880955dd2ab1be95aa0733055c655b5","suite":"scope enrichment — s2 reads computed value from s1","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | | 821418efc03340d73c74ecfdb5392775","suite":"scope enrichment — s2 reads computed value from s1","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | | 8f212f69f4b1a86926ebf13d82039429","suite":"scope enrichment — s2 reads computed value from s1","input":{"customer":{"age":45,"name":"Alice"}},"plain":{"ok":{"customer":{"age":45,"ageGroup":true,"label":true,"name":"Alice"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | | a814fbac0e4373ac837977408d7c6d55","suite":"scope enrichment — s2 reads computed value from s1","input":{"customer":{"age":45,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | | c30e91b8a923554672ca5770b060cb98","suite":"scope enrichment — s2 reads computed value from s1","input":{"customer":{"age":"text","name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | customer.ageGroup | c30e91b8a923554672ca5770b060cb98","suite":"scope enrichment — s2 reads computed value from s1","goals":["customer.ageGroup"],"input":{"customer":{"age":"text","name":"Alice"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | customer.ageGroup,customer.label | 0880955dd2ab1be95aa0733055c655b5","suite":"scope enrichment — s2 reads computed value from s1","goals":["customer.ageGroup","customer.label"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.ageGroup\", \"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.ageGroup","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — s2 reads computed value from s1 | customer.label | 821418efc03340d73c74ecfdb5392775","suite":"scope enrichment — s2 reads computed value from s1","goals":["customer.label"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | | 0880955dd2ab1be95aa0733055c655b5","suite":"scope enrichment — young customer","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | | 09884c42a3c74efa6a4dfa0da2fccc91","suite":"scope enrichment — young customer","input":{"customer":{"age":20,"name":"Bob"}},"plain":{"ok":{"customer":{"age":20,"ageGroup":false,"label":false,"name":"Bob"}}}}
{"key":"scope enrichment — young customer | | 1b812b0ab6726082e0c5c7405b19be8c","suite":"scope enrichment — young customer","input":{"customer":{"age":20,"name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | | 821418efc03340d73c74ecfdb5392775","suite":"scope enrichment — young customer","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | | fb946bf53d398e0cdb5b0295e46a39a1","suite":"scope enrichment — young customer","input":{"customer":{"age":"text","name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | customer.ageGroup | fb946bf53d398e0cdb5b0295e46a39a1","suite":"scope enrichment — young customer","goals":["customer.ageGroup"],"input":{"customer":{"age":"text","name":"Bob"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | customer.ageGroup,customer.label | 0880955dd2ab1be95aa0733055c655b5","suite":"scope enrichment — young customer","goals":["customer.ageGroup","customer.label"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.ageGroup\", \"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.ageGroup","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"scope enrichment — young customer | customer.label | 821418efc03340d73c74ecfdb5392775","suite":"scope enrichment — young customer","goals":["customer.label"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.age\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.age"],"type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | | 0880955dd2ab1be95aa0733055c655b5","suite":"sibling A writes greeting from its own data","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\"], missing: [\"customer.country\", \"customer.name\"] }","value":{"goals":["customer.greeting","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.name"],"type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | | 1c0eb99057c5fb727c56d8120b318425","suite":"sibling A writes greeting from its own data","input":{"customer":{"age":30,"country":7,"name":"Ann"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | | 6ce0d1d0273d2f1f5dd8028f8f6510ea","suite":"sibling A writes greeting from its own data","input":{"customer":{"age":30,"country":"NL","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | | 821418efc03340d73c74ecfdb5392775","suite":"sibling A writes greeting from its own data","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\"], missing: [\"customer.country\", \"customer.name\"] }","value":{"goals":["customer.greeting","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.name"],"type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | | 903f2393ed823e5e831781470b7e6fb2","suite":"sibling A writes greeting from its own data","input":{"customer":{"age":"text","country":"NL","name":"Ann"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | | 909a235716869b05b55b868bad1613eb","suite":"sibling A writes greeting from its own data","input":{"customer":{"age":30,"country":"NL","name":"Ann"}},"plain":{"ok":{"customer":{"age":30,"country":"NL","greeting":"Ann","label":"NL","name":"Ann"}}}}
{"key":"sibling A writes greeting from its own data | customer.greeting | 903f2393ed823e5e831781470b7e6fb2","suite":"sibling A writes greeting from its own data","goals":["customer.greeting"],"input":{"customer":{"age":"text","country":"NL","name":"Ann"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.age\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'customer.age': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | customer.greeting,customer.label | 0880955dd2ab1be95aa0733055c655b5","suite":"sibling A writes greeting from its own data","goals":["customer.greeting","customer.label"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\"], missing: [\"customer.country\", \"customer.name\"] }","value":{"goals":["customer.greeting","customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.name"],"type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | customer.greeting,customer.label | 6ce0d1d0273d2f1f5dd8028f8f6510ea","suite":"sibling A writes greeting from its own data","goals":["customer.greeting","customer.label"],"input":{"customer":{"age":30,"country":"NL","name":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling A writes greeting from its own data | customer.label | 821418efc03340d73c74ecfdb5392775","suite":"sibling A writes greeting from its own data","goals":["customer.label"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.country\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country"],"type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | | 0880955dd2ab1be95aa0733055c655b5","suite":"sibling C writes greeting from the shared import","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\", \"customer.tag\"], missing: [\"customer.country\", \"customer.segment\"] }","value":{"goals":["customer.greeting","customer.label","customer.tag"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.segment"],"type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | | 2049a834c9c8ab24311491c31e45468e","suite":"sibling C writes greeting from the shared import","input":{"customer":{"country":7,"name":"Ann","segment":"retail"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | | 5e55a0d2a2013e911972a6ceb1c688eb","suite":"sibling C writes greeting from the shared import","input":{"customer":{"country":"NL","name":"Ann","segment":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.segment\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.segment': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | | 6904ea431333c9541bfe649bb0ff9395","suite":"sibling C writes greeting from the shared import","input":{"customer":{"country":"NL","name":7,"segment":"retail"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | | 821418efc03340d73c74ecfdb5392775","suite":"sibling C writes greeting from the shared import","input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\", \"customer.label\", \"customer.tag\"], missing: [\"customer.country\", \"customer.segment\"] }","value":{"goals":["customer.greeting","customer.label","customer.tag"],"kind":"MissingRequiredInputs","missing":["customer.country","customer.segment"],"type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | | fb047142ab822773e2c18a33850c9a20","suite":"sibling C writes greeting from the shared import","input":{"customer":{"country":"NL","name":"Ann","segment":"retail"}},"plain":{"ok":{"customer":{"country":"NL","greeting":"NL","label":"NL","name":"Ann","segment":"retail","tag":"retail"}}}}
{"key":"sibling C writes greeting from the shared import | customer.greeting | 0880955dd2ab1be95aa0733055c655b5","suite":"sibling C writes greeting from the shared import","goals":["customer.greeting"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.greeting\"], missing: [\"customer.country\"] }","value":{"goals":["customer.greeting"],"kind":"MissingRequiredInputs","missing":["customer.country"],"type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | customer.greeting,customer.label | 6904ea431333c9541bfe649bb0ff9395","suite":"sibling C writes greeting from the shared import","goals":["customer.greeting","customer.label"],"input":{"customer":{"country":"NL","name":7,"segment":"retail"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.name\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.name': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | customer.label | 821418efc03340d73c74ecfdb5392775","suite":"sibling C writes greeting from the shared import","goals":["customer.label"],"input":{"customer":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"customer.label\"], missing: [\"customer.country\"] }","value":{"goals":["customer.label"],"kind":"MissingRequiredInputs","missing":["customer.country"],"type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | customer.label,customer.tag | 5e55a0d2a2013e911972a6ceb1c688eb","suite":"sibling C writes greeting from the shared import","goals":["customer.label","customer.tag"],"input":{"customer":{"country":"NL","name":"Ann","segment":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.segment\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.segment': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"sibling C writes greeting from the shared import | customer.tag | 2049a834c9c8ab24311491c31e45468e","suite":"sibling C writes greeting from the shared import","goals":["customer.tag"],"input":{"customer":{"country":7,"name":"Ann","segment":"retail"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"customer.country\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'customer.country': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — EU small order | | 0880955dd2ab1be95aa0733055c655b5","suite":"strict table — EU small order","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — EU small order | | 63b9e6111d8c598853feba1db62b728a","suite":"strict table — EU small order","input":{"order":{"amount":"text","region":"EU"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.amount\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'order.amount': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — EU small order | | 81df8f6b95ae4413597c4f787bd562a7","suite":"strict table — EU small order","input":{"order":{"amount":50,"region":"EU"}},"plain":{"ok":{"order":{"amount":50,"region":"EU","shippingCost":15}}}}
{"key":"strict table — EU small order | | cd42eab6975029ae157f3bddcbf9046d","suite":"strict table — EU small order","input":{"order":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — EU small order | | eae1c6b045bfd47b91e2c8f66c9a7843","suite":"strict table — EU small order","input":{"order":{"amount":50,"region":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.region\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'order.region': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — EU small order | order.shippingCost | 0880955dd2ab1be95aa0733055c655b5","suite":"strict table — EU small order","goals":["order.shippingCost"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — EU small order | order.shippingCost | 63b9e6111d8c598853feba1db62b728a","suite":"strict table — EU small order","goals":["order.shippingCost"],"input":{"order":{"amount":"text","region":"EU"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.amount\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'order.amount': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — US large order, free shipping | | 0880955dd2ab1be95aa0733055c655b5","suite":"strict table — US large order, free shipping","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — US large order, free shipping | | 185fd3a9398c598853fee66745f484b8","suite":"strict table — US large order, free shipping","input":{"order":{"amount":"text","region":"US"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.amount\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'order.amount': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — US large order, free shipping | | 2a4079b784f49d70ad4d569e5ab1face","suite":"strict table — US large order, free shipping","input":{"order":{"amount":200,"region":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.region\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'order.region': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — US large order, free shipping | | 617585bc3348c0ba87c9508fe9513222","suite":"strict table — US large order, free shipping","input":{"order":{"amount":200,"region":"US"}},"plain":{"ok":{"order":{"amount":200,"region":"US","shippingCost":0}}}}
{"key":"strict table — US large order, free shipping | | cd42eab6975029ae157f3bddcbf9046d","suite":"strict table — US large order, free shipping","input":{"order":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — US large order, free shipping | order.shippingCost | 0880955dd2ab1be95aa0733055c655b5","suite":"strict table — US large order, free shipping","goals":["order.shippingCost"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — US large order, free shipping | order.shippingCost | 185fd3a9398c598853fee66745f484b8","suite":"strict table — US large order, free shipping","goals":["order.shippingCost"],"input":{"order":{"amount":"text","region":"US"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.amount\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'order.amount': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — unknown region, no rows match writes null | | 0880955dd2ab1be95aa0733055c655b5","suite":"strict table — unknown region, no rows match writes null","input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — unknown region, no rows match writes null | | a32e7c8e30ae4413597c5799f13cdb73","suite":"strict table — unknown region, no rows match writes null","input":{"order":{"amount":50,"region":"JP"}},"plain":{"ok":{"order":{"amount":50,"region":"JP","shippingCost":null}}}}
{"key":"strict table — unknown region, no rows match writes null | | cd42eab6975029ae157f3bddcbf9046d","suite":"strict table — unknown region, no rows match writes null","input":{"order":null},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — unknown region, no rows match writes null | | e5c9a1b8ea8c598853fe9b21b0c12e86","suite":"strict table — unknown region, no rows match writes null","input":{"order":{"amount":"text","region":"JP"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.amount\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'order.amount': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — unknown region, no rows match writes null | | eae1c6b045bfd47b91e2c8f66c9a7843","suite":"strict table — unknown region, no rows match writes null","input":{"order":{"amount":50,"region":7}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.region\", expected: \"string\", got: \"number\" }] }","value":{"errors":["'order.region': expected string, got number"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
{"key":"strict table — unknown region, no rows match writes null | order.shippingCost | 0880955dd2ab1be95aa0733055c655b5","suite":"strict table — unknown region, no rows match writes null","goals":["order.shippingCost"],"input":{},"plain":{"err":{"debug":"MissingRequiredInputs { goals: [\"order.shippingCost\"], missing: [\"order.amount\", \"order.region\"] }","value":{"goals":["order.shippingCost"],"kind":"MissingRequiredInputs","missing":["order.amount","order.region"],"type":"PolicyError"}}}}
{"key":"strict table — unknown region, no rows match writes null | order.shippingCost | e5c9a1b8ea8c598853fe9b21b0c12e86","suite":"strict table — unknown region, no rows match writes null","goals":["order.shippingCost"],"input":{"order":{"amount":"text","region":"JP"}},"plain":{"err":{"debug":"InputValidationFailed { errors: [InputValidationError { path: \"order.amount\", expected: \"number\", got: \"string\" }] }","value":{"errors":["'order.amount': expected number, got string"],"kind":"InputValidationFailed","type":"PolicyError"}}}}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+14
View File
@@ -597,3 +597,17 @@ async fn unknown_relationship_target_in_import_refuses_importer() {
assert!(reported.contains(&("main", "policy")), "{failures:#?}");
assert!(reported.contains(&("child", "policy")), "{failures:#?}");
}
#[tokio::test]
async fn compiled_documents_say_what_they_read() {
let loader = Arc::new(MemoryLoader::default());
loader.add("policy", make_policy_content(simple_policy_json()));
let engine = engine_with(loader);
assert_eq!(engine.reads("policy"), None, "nothing is known before compile()");
engine.compile();
let reads = engine.reads("policy").expect("known after compile");
assert!(reads.contains("customer.age"), "{reads:?}");
// Found with or without `.json`, as evaluate finds it.
assert_eq!(engine.reads("policy.json"), Some(reads));
assert_eq!(engine.reads("missing"), None);
}
@@ -0,0 +1,170 @@
//! Stored relationships: a `relationship` with `on` (members sharing this
//! entity's key) or `through` (counterparties in an events entity). The host
//! finds the members; features on the owner aggregate their features.
use serde_json::{json, Value};
use zen_engine::policy::{PolicyWorkspace, ScopeRequest, Severity, SuppliedBy};
fn prop(name: &str, ty: &str, extra: Value) -> Value {
let mut p = json!({ "id": name, "name": name, "type": ty });
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
p
}
fn entity(id: &str, data: Value) -> Value {
json!({ "id": id, "type": "dataModel", "props": { "data": data } })
}
/// Merchants with a monthly sales feature, a peer group of merchants by
/// (mcc, postal_code), and transfers between customers.
fn doc(rollup: &str, merchant_extra: Vec<Value>, senders: Value, rule: &str) -> PolicyWorkspace {
let mut merchant_props = vec![
prop("id", "string", json!({})),
prop("mcc", "string", json!({})),
prop("postal_code", "string", json!({})),
prop("risk", "string", json!({})),
prop("sales", "number", json!({ "feature": { "expr": "sum(txn as t, t.amount)", "window": ["30d"] } })),
prop("peer_group", "reference", json!({ "target": "peer_group" })),
];
merchant_props.extend(merchant_extra);
let blocks = json!([
entity("b-txn", json!({
"name": "txn", "events": { "id": "id", "time": "at" },
"properties": [
prop("id", "string", json!({})), prop("at", "date", json!({})), prop("amount", "number", json!({})),
prop("merchant", "reference", json!({ "target": "merchant" })),
prop("sender", "reference", json!({ "target": "customer" })),
prop("receiver", "reference", json!({ "target": "customer" }))
]
})),
entity("b-merchant", json!({ "name": "merchant", "key": "id", "reference": {}, "properties": merchant_props })),
entity("b-group", json!({
"name": "peer_group", "key": ["mcc", "postal_code"], "reference": {},
"properties": [
prop("mcc", "string", json!({})), prop("postal_code", "string", json!({})),
prop("merchants", "relationship", json!({ "target": "merchant", "array": true, "on": { "mcc": "mcc", "postal_code": "postal_code" } })),
prop("avg_sales", "number", json!({ "feature": { "expr": rollup } }))
]
})),
entity("b-customer", json!({
"name": "customer", "key": "id", "reference": {},
"properties": [
prop("id", "string", json!({})),
prop("sent", "number", json!({ "feature": { "expr": "sum(txn as t, t.amount)", "window": ["30d"] } })),
prop("senders", "relationship", json!({ "target": "customer", "array": true, "through": senders })),
prop("big_senders", "number", json!({ "feature": { "expr": "count(senders as s, s.sent_30d > 1000 and s.id != id)" } }))
]
})),
{ "id": "r", "type": "expression", "props": { "data": { "key": "txn.flag", "value": rule } } }
]);
let mut ws = PolicyWorkspace::new();
ws.set_policy("p", serde_json::from_value(json!({ "blocks": blocks })).unwrap());
ws
}
fn errors(ws: &PolicyWorkspace) -> Vec<String> {
ws.diagnostics("p")
.into_iter()
.filter(|d| d.severity == Severity::Error)
.map(|d| d.message)
.collect()
}
fn through() -> Value {
json!({ "events": "txn", "self": "receiver", "member": "sender", "window": "30d", "where": "amount >= 100" })
}
#[test]
fn rollups_aggregate_the_members_features() {
let ws = doc("avg(merchants as m, m.sales_30d)", vec![], through(), "(txn.merchant.peer_group.avg_sales ?? 0) > 0");
assert!(errors(&ws).is_empty(), "{:#?}", errors(&ws));
// A member property that doesn't exist; a condition on the member.
let ws = doc("avg(merchants as m, m.salez_30d)", vec![], through(), "true");
assert_eq!(errors(&ws), vec!["`merchant` has no `salez_30d`"]);
// A member's windowed feature as written: its windows.
let ws = doc("avg(merchants as m, m.sales)", vec![], through(), "true");
assert_eq!(errors(&ws), vec!["`sales` has windows: read `sales_30d`"]);
let ws = doc("count(merchants as m, m.risk == 'High')", vec![], through(), "true");
assert!(errors(&ws).is_empty(), "{:#?}", errors(&ws));
}
#[test]
fn the_targets_stay_roots_and_the_members_are_the_hosts() {
// Only the stored relationship points at merchant: it stays a root (the request is `{ merchant }`).
let blocks = json!([
entity("b-merchant", json!({ "name": "merchant", "key": "id", "reference": {}, "properties": [
prop("id", "string", json!({})), prop("mcc", "string", json!({})), prop("postal_code", "string", json!({})),
prop("peer_avg", "number", json!({ "feature": { "expr": "peer_group.avg_sales" } })),
prop("peer_group", "reference", json!({ "target": "peer_group" }))
] })),
entity("b-group", json!({ "name": "peer_group", "key": ["mcc", "postal_code"], "reference": {}, "properties": [
prop("mcc", "string", json!({})), prop("postal_code", "string", json!({})),
prop("merchants", "relationship", json!({ "target": "merchant", "array": true, "on": { "mcc": "mcc", "postal_code": "postal_code" } })),
prop("avg_sales", "number", json!({ "feature": { "expr": "count(merchants as m, m.mcc != '')" } }))
] })),
{ "id": "r", "type": "expression", "props": { "data": { "key": "merchant.flag", "value": "merchant.mcc == '5411'" } } }
]);
let mut ws = PolicyWorkspace::new();
ws.set_policy("p", serde_json::from_value(json!({ "blocks": blocks })).unwrap());
assert!(errors(&ws).is_empty(), "{:#?}", errors(&ws));
let inputs = ws.inputs(&ScopeRequest::for_policy("p"));
let path = |p: &str| inputs.iter().find(|i| i.path.as_ref() == p);
let mcc = path("merchant.mcc").unwrap_or_else(|| panic!("merchant is a root: {inputs:#?}"));
assert_eq!(mcc.supplied_by, SuppliedBy::Request);
// The members never come with the request.
assert!(
inputs.iter().all(|i| !i.path.contains("merchants") || i.supplied_by == SuppliedBy::Host),
"{inputs:#?}"
);
}
#[test]
fn on_and_through_are_checked() {
let ok = doc("avg(merchants as m, m.sales_30d)", vec![], through(), "true");
assert!(errors(&ok).is_empty(), "{:#?}", errors(&ok));
let found = errors(&doc(
"avg(merchants as m, m.sales_30d)",
vec![],
json!({ "events": "merchant", "self": "receiver", "member": "nobody", "window": "a month" }),
"true",
));
for expected in ["`merchant` isn't an events entity", "a duration like 10m, 1h or 30d"] {
assert!(found.iter().any(|m| m.contains(expected)), "{expected}: {found:#?}");
}
let found = errors(&doc(
"avg(merchants as m, m.sales_30d)",
vec![],
json!({ "events": "txn", "self": "merchant", "member": "amount", "window": "30d" }),
"true",
));
for expected in ["`self` is `merchant`", "`member` is `amount`"] {
assert!(found.iter().any(|m| m.contains(expected)), "{expected}: {found:#?}");
}
}
#[test]
fn a_missing_through_attribute_is_named() {
let ws = doc("avg(merchants as m, m.sales_30d)", vec![], json!({ "self": "receiver" }), "true");
let found = errors(&ws);
for expected in ["`through.events` is missing", "`through.window` is missing"] {
assert!(found.iter().any(|m| m.contains(expected)), "{expected}: {found:#?}");
}
let found = errors(&doc("avg(merchants as m, m.sales_30d)", vec![], json!({ "events": "txn", "window": "30d" }), "true"));
for expected in ["`through.self` is missing", "`through.member` is missing"] {
assert!(found.iter().any(|m| m.contains(expected)), "{expected}: {found:#?}");
}
assert!(!found.iter().any(|m| m.contains("``")), "{found:#?}");
// Its own code, not a parse error.
let codes: Vec<_> = ws
.diagnostics("p")
.into_iter()
.filter(|d| d.message.contains("through."))
.map(|d| serde_json::to_value(d.code).unwrap())
.collect();
assert!(!codes.is_empty() && codes.iter().all(|c| c == "INVALID_RELATIONSHIP"), "{codes:?}");
}
+250
View File
@@ -0,0 +1,250 @@
//! An unknown member of an entity names the entity, and a windowed
//! feature's name as written lists the windows to read instead: in rules,
//! graph nodes, features, computes, calls and outcomes; through references
//! and closure aliases. Other objects keep the generic message.
use serde_json::{json, Value};
use std::sync::Arc;
use zen_engine::model::DecisionContent;
use zen_engine::policy::{
CursorTarget, Diagnostic, DiagnosticCode, PolicyWorkspace, Severity, Workspace,
};
const TWO: &str = "`txn_count` has windows: read `txn_count_7d` or `txn_count_30d`";
const THREE: &str = "`spend` has windows: read `spend_1d`, `spend_7d` or `spend_30d`";
/// Transactions (events) reference a card and a customer; the card has
/// windowed features; the customer's feature aggregates transactions.
fn models(customer_feature: &str) -> Vec<Value> {
vec![
json!({ "id": "dm-transaction", "type": "dataModel", "props": { "data": {
"name": "transaction",
"events": { "id": "txn_id", "time": "authorized_at" },
"properties": [
{ "id": "t1", "name": "txn_id", "type": "string" },
{ "id": "t2", "name": "amount", "type": "number" },
{ "id": "t3", "name": "card", "type": "reference", "target": "card" },
{ "id": "t4", "name": "customer", "type": "reference", "target": "customer" }
]
} } }),
json!({ "id": "dm-card", "type": "dataModel", "props": { "data": {
"name": "card",
"reference": {},
"properties": [
{ "id": "c1", "name": "id", "type": "string" },
{ "id": "c2", "name": "txn_count", "type": "number",
"feature": { "expr": "count(transaction)", "window": ["7d", "30d"], "default": 0 } },
{ "id": "c3", "name": "spend", "type": "number",
"feature": { "expr": "sum(transaction as t, t.amount)", "window": ["1d", "7d", "30d"], "default": 0 } }
]
} } }),
json!({ "id": "dm-customer", "type": "dataModel", "props": { "data": {
"name": "customer",
"reference": {},
"properties": [
{ "id": "u1", "name": "id", "type": "string" },
{ "id": "u2", "name": "card_txns", "type": "number",
"feature": { "expr": customer_feature, "window": "7d", "default": 0 } }
]
} } }),
]
}
fn policy(rule: &str, customer_feature: &str) -> Value {
let mut blocks = models(customer_feature);
blocks.push(
json!({ "id": "rule", "type": "expression", "props": { "data": {
"key": "transaction.flag", "value": rule
} } }),
);
json!({ "blocks": blocks })
}
fn workspace(doc: Value) -> PolicyWorkspace {
let mut ws = PolicyWorkspace::new();
ws.set_policy("p", serde_json::from_value(doc).unwrap());
ws
}
fn rule(expr: &str) -> PolicyWorkspace {
workspace(policy(expr, "count(transaction)"))
}
fn unknowns(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
diagnostics
.into_iter()
.filter(|d| d.code == DiagnosticCode::UndefinedVariable)
.collect()
}
fn messages(ws: &PolicyWorkspace) -> Vec<String> {
unknowns(ws.diagnostics("p"))
.into_iter()
.map(|d| d.message)
.collect()
}
#[test]
fn a_rule_reading_a_windowed_feature_as_written_lists_its_windows() {
let source = "transaction.card.txn_count > 3";
let found = unknowns(rule(source).diagnostics("p"));
assert_eq!(found.len(), 1, "{found:#?}");
let d = &found[0];
assert_eq!(d.message, TWO);
assert_eq!(d.severity, Severity::Error);
assert_eq!(d.location.block_id.as_deref(), Some("rule"));
let (start, end) = d.location.span.expect("at the read");
assert_eq!(
&source[start as usize..end as usize],
"transaction.card.txn_count"
);
// Three windows; `$root`.
assert_eq!(messages(&rule("transaction.card.spend > 3")), vec![THREE]);
assert_eq!(
messages(&rule("$root.transaction.card.txn_count > 3")),
vec![TWO]
);
}
#[test]
fn any_other_unknown_member_of_an_entity_names_it() {
assert_eq!(
messages(&rule("transaction.card.foo > 3")),
vec!["`card` has no `foo`"]
);
assert_eq!(
messages(&rule("transaction.amout > 3")),
vec!["`transaction` has no `amout`"]
);
// Not an entity: the generic message.
let mut doc = policy("risk.levl > 0", "count(transaction)");
doc["blocks"].as_array_mut().unwrap().insert(
3,
json!({ "id": "risk", "type": "expression",
"props": { "data": { "key": "risk", "value": "{ level: 1 }" } } }),
);
let found = messages(&workspace(doc));
assert_eq!(found, vec!["'levl' is not a valid member of `object`."]);
}
#[test]
fn feature_compute_and_call_expressions_are_explained_too() {
// Through a closure alias in a feature: `t.card` is the card.
let ws = workspace(policy("true", "sum(transaction as t, t.card.txn_count)"));
let found = unknowns(ws.diagnostics("p"));
assert_eq!(found.len(), 1, "{found:#?}");
assert_eq!(found[0].message, TWO);
assert_eq!(
serde_json::to_value(found[0].location.target.as_ref().unwrap()).unwrap(),
serde_json::to_value(CursorTarget::FeatureExpr {
id: Arc::from("u2")
})
.unwrap()
);
// A compute and a call on the transaction, from its own fields.
let mut doc = policy("true", "count(transaction)");
let props = doc["blocks"][0]["props"]["data"]["properties"]
.as_array_mut()
.unwrap();
props.push(
json!({ "id": "t6", "name": "scaled", "type": "number", "compute": "card.spend * 2" }),
);
props.push(json!({ "id": "t7", "name": "score", "type": "number",
"model": { "datasource": "fraud", "request": "{ n: card.txn_count }", "when": "card.bar > 0" } }));
let mut found = messages(&workspace(doc));
found.sort();
assert_eq!(found, vec!["`card` has no `bar`", THREE, TWO], "{found:?}");
}
#[test]
fn an_outcome_expression_is_explained_too() {
let mut doc = policy("true", "count(transaction)");
doc["blocks"][0]["props"]["data"]["properties"]
.as_array_mut()
.unwrap()
.push(json!({ "id": "t6", "name": "heavy", "type": "boolean",
"outcome": { "expr": "card.txn_count > 5" } }));
let found = unknowns(workspace(doc).diagnostics("p"));
assert_eq!(found.len(), 1, "{found:#?}");
assert_eq!(found[0].message, TWO);
assert_eq!(
serde_json::to_value(found[0].location.target.as_ref().unwrap()).unwrap(),
serde_json::to_value(CursorTarget::OutcomeExpr {
id: Arc::from("t6")
})
.unwrap()
);
}
#[test]
fn a_graph_node_on_an_entity_request_is_explained_too() {
let node = |id: &str, kind: &str, content: Value| json!({ "id": id, "name": id, "type": kind, "content": content });
let edge = |id: &str, source: &str, target: &str| json!({ "id": id, "sourceId": source, "targetId": target, "sourceHandle": null });
let graph = json!({
"imports": ["models"],
"nodes": [
node("in", "inputNode", json!({ "target": "transaction" })),
node("ex", "expressionNode", json!({ "expressions": [
{ "id": "x0", "key": "a", "value": "card.txn_count > 3" },
{ "id": "x1", "key": "b", "value": "card.foo" },
{ "id": "x2", "key": "c", "value": "$root.card.spend > 1" }
] })),
node("out", "outputNode", json!({}))
],
"edges": [edge("e1", "in", "ex"), edge("e2", "ex", "out")]
});
let document = |value: Value| -> DecisionContent { serde_json::from_value(value).unwrap() };
let mut ws = Workspace::new();
ws.set_document(
"models",
document(json!({ "imports": [], "blocks": models("count(transaction)") })),
);
ws.set_document("g", document(graph));
let mut found: Vec<(String, String)> = unknowns(ws.diagnostics("g"))
.into_iter()
.map(|d| {
(
d.location
.expression_id
.as_deref()
.unwrap_or_default()
.to_string(),
d.message,
)
})
.collect();
found.sort();
assert_eq!(found.len(), 3, "{found:#?}");
assert_eq!(found[0], ("x0".to_string(), TWO.to_string()));
assert_eq!(
found[1],
("x1".to_string(), "`card` has no `foo`".to_string())
);
assert_eq!(found[2], ("x2".to_string(), THREE.to_string()));
// A request typed by a schema: no entity, the generic message.
let schema = json!({
"type": "object",
"properties": { "customer": { "type": "object", "properties": { "age": { "type": "number" } }, "required": ["age"] } },
"required": ["customer"]
});
let graph = json!({
"nodes": [
node("in", "inputNode", json!({ "schema": schema.to_string() })),
node("ex", "expressionNode", json!({ "expressions": [
{ "id": "x0", "key": "a", "value": "customer.agee > 3" }
] })),
node("out", "outputNode", json!({}))
],
"edges": [edge("e1", "in", "ex"), edge("e2", "ex", "out")]
});
let mut ws = Workspace::new();
ws.set_document("g", document(graph));
let found: Vec<String> = unknowns(ws.diagnostics("g"))
.into_iter()
.map(|d| d.message)
.collect();
assert_eq!(found, vec!["'agee' is not a valid member of `object`."]);
}
+4 -2
View File
@@ -273,7 +273,8 @@ impl Engines {
}
fn policy_columns(&mut self, suite: &Suite, run: &PolicyRun, cases: &[&Case], goals: &[String], targets: &[Arc<str>], columns: &zen_expression::lane::Columns) {
let Ok(output) = run.workspace.evaluate_columns(&Arc::from(PolicyRun::MAIN), targets, columns) else {
let store = zen_engine::ColumnStore::new();
let Ok(output) = run.workspace.evaluate_columns(&Arc::from(PolicyRun::MAIN), targets, columns, &store) else {
return;
};
self.hosted += output.hosted;
@@ -531,7 +532,8 @@ impl Snapshot {
false => built.columns(),
};
for call in 1..=Self::CALLS {
let line = match run.workspace.evaluate_columns(&Arc::from(PolicyRun::MAIN), &targets, &columns) {
let store = zen_engine::ColumnStore::new();
let line = match run.workspace.evaluate_columns(&Arc::from(PolicyRun::MAIN), &targets, &columns, &store) {
Ok(output) => format!(
"rows={}\ttyped={}\tlaned={}\thosted={}\terrors=[{}]\tpaths={:016x}\torder={:016x}",
output.rows,
@@ -350,7 +350,7 @@
{
name: "null-safe guard inside one condition",
diagnostics: ["TYPE_MISMATCH"],
diagnostics: [],
policy: {
models: {x: {n: "number?"}},
blocks: [{assertion: "x.ok", conditions: ["x.n != null and x.n > 1"]}],
@@ -542,7 +542,7 @@
{
name: "a computed null flows into the next block",
diagnostics: ["INVALID_EXPRESSION"],
diagnostics: [],
policy: {
models: {customer: {email: "string?"}},
blocks: [
@@ -78,7 +78,7 @@
{
name: "optional dates",
diagnostics: ["INVALID_EXPRESSION"],
diagnostics: [],
policy: {
models: {customer: {joined: "date?"}},
blocks: [
@@ -103,7 +103,7 @@
// still evaluates it correctly.
{
name: "null-guarded optional expiry",
diagnostics: ["TYPE_MISMATCH"],
diagnostics: [],
policy: {
models: {customer: {documents: "document[]"}, document: {expires: "date?"}},
blocks: [
@@ -114,8 +114,7 @@
cases: [
{
input: {customer: {documents: [{expires: "2020-01-01"}, {expires: null}, {}]}},
output: {customer: {anyExpired: true, documents: [{expires: "2020-01-01", expired: true}, {expires: null, expired: false}, {expired: false}]}},
note: "question: `x != null and x < d()` is a TYPE_MISMATCH error, so DecisionEngine refuses the policy; the left operand guards the right one, so narrowing looks intended",
output: {customer: {anyExpired: true, documents: [{expires: "2020-01-01", expired: true}, {expires: null, expired: false}, {expired: false}]}}
},
[{customer: {documents: [{expires: "2030-01-01"}]}}, {customer: {anyExpired: false, documents: [{expires: "2030-01-01", expired: false}]}}],
[{customer: {documents: []}}, {customer: {anyExpired: false, documents: []}}],
@@ -445,14 +445,14 @@
}
{
name: "a null check does not narrow an optional date inside `or`",
diagnostics: ["TYPE_MISMATCH"],
name: "a null check narrows an optional date inside `or`",
diagnostics: [],
policy: {
models: {contract: {start: "date", end: "date?"}},
blocks: [{expression: "contract.active", value: "contract.start <= d() and (contract.end == null or contract.end >= d())"}],
},
cases: [
{input: {contract: {start: "2025-01-01"}}, output: {contract: {start: "2025-01-01", active: true}}, note: "question: the type checker reports TYPE_MISMATCH for `end >= d()` although `end == null or` guards it, so DecisionEngine refuses the policy"},
{input: {contract: {start: "2025-01-01"}}, output: {contract: {start: "2025-01-01", active: true}}},
[{contract: {start: "2025-01-01", end: "2025-02-01"}}, {contract: {start: "2025-01-01", end: "2025-02-01", active: false}}],
[{contract: {start: "2025-01-01", end: "2025-12-31"}}, {contract: {start: "2025-01-01", end: "2025-12-31", active: true}}],
],
@@ -692,13 +692,13 @@
{
name: "an and-guard before an ordering comparison",
diagnostics: ["TYPE_MISMATCH"],
diagnostics: [],
policy: {
models: {customer: {score: "number?"}},
blocks: [{expression: "customer.high", value: "customer.score != null and customer.score > 700"}],
},
cases: [
{input: {customer: {score: 800}}, output: {customer: {score: 800, high: true}}, note: "question: `score != null and score > 700` is reported as TYPE_MISMATCH although the guard makes the comparison safe, so DecisionEngine refuses the policy"},
{input: {customer: {score: 800}}, output: {customer: {score: 800, high: true}}},
[{customer: {score: 600}}, {customer: {score: 600, high: false}}],
[{customer: {}}, {customer: {high: false}}],
[{customer: {score: null}}, {customer: {score: null, high: false}}],
@@ -707,7 +707,7 @@
{
name: "a guard through an optional relationship",
diagnostics: ["TYPE_MISMATCH"],
diagnostics: [],
policy: {
models: {customer: {report: "creditReport?"}, creditReport: {score: "number"}},
blocks: [{expression: "customer.band", value: "customer.report == null ? 'none' : customer.report.score >= 700 ? 'good' : 'poor'"}],
+348
View File
@@ -0,0 +1,348 @@
//! A document as an endpoint: whether it serves one, and the JSON Schemas of
//! its request (as a caller sends it, and as the rules are given it once the
//! host has filled it in) and of its response.
use serde_json::{json, Value};
use zen_engine::model::DecisionContent;
use zen_engine::policy::{EndpointKind, SchemaAudience, ScopeRequest, Workspace};
fn document(value: Value) -> DecisionContent {
serde_json::from_value(value).expect("valid decision content")
}
fn entity(name: &str, extra: Value, properties: Value) -> Value {
let mut data = json!({ "name": name, "properties": properties });
for (key, value) in extra.as_object().unwrap() {
data[key] = value.clone();
}
json!({ "id": format!("dm-{name}"), "type": "dataModel", "props": { "data": data } })
}
fn prop(name: &str, ty: &str) -> Value {
json!({ "id": name, "name": name, "type": ty })
}
fn link(name: &str, ty: &str, target: &str) -> Value {
json!({ "id": name, "name": name, "type": ty, "target": target })
}
/// `models/fraud`, data models only: a transaction (events) references its
/// card (reference data with features), an optional merchant (plain, sent
/// by the caller as a pool), a country keyed by an enum code and a
/// card × merchant pair (a composite key); its lines reference products.
fn models() -> Value {
json!({ "blocks": [
entity("transaction", json!({ "events": { "id": "txn_id", "time": "at" } }), json!([
prop("txn_id", "string"),
prop("at", "date"),
prop("amount", "number"),
{ "id": "currency", "name": "currency", "type": "string", "default": "GBP" },
{ "id": "amount_x2", "name": "amount_x2", "type": "number", "compute": "amount * 2" },
link("card", "reference", "card"),
{ "id": "merchant", "name": "merchant", "type": "reference", "target": "merchant", "optional": true },
link("country", "reference", "country"),
link("pair", "reference", "card_merchant"),
{ "id": "lines", "name": "lines", "type": "relationship", "target": "line_item", "array": true }
])),
entity("line_item", json!({}), json!([
prop("qty", "number"),
link("product", "reference", "product")
])),
entity("card", json!({ "reference": { "validFrom": "valid_from" } }), json!([
prop("id", "string"),
prop("valid_from", "date"),
prop("holder_country", "string"),
{ "id": "txn_count", "name": "txn_count", "type": "number",
"feature": { "expr": "count(transaction)", "window": ["1h", "7d"] } },
{ "id": "spend_1d", "name": "spend_1d", "type": "number",
"feature": { "expr": "sum(transaction as t, t.amount)", "window": "1d", "default": 0 } }
])),
entity("merchant", json!({}), json!([prop("id", "string"), prop("name", "string")])),
entity("country", json!({ "key": "code" }), json!([
{ "id": "code", "name": "code", "type": "string", "enum": ["GB", "US"] },
prop("risky", "boolean")
])),
entity("card_merchant", json!({ "key": ["card", "merchant"] }), json!([
link("card", "reference", "card"),
link("merchant", "reference", "merchant")
])),
entity("product", json!({}), json!([prop("id", "string"), prop("sku", "string")])),
{ "id": "fs", "type": "featureSettings", "props": { "data": {} } }
] })
}
fn rules() -> Value {
json!({
"imports": ["models/fraud"],
"blocks": [
{ "id": "flag", "type": "expression", "props": { "data": {
"key": "transaction.flag",
"value": "transaction.amount > 100 and (transaction.card.txn_count_1h ?? 0) > 3 and transaction.country.risky"
} } }
]
})
}
fn graph(imports: &[&str], input: Value, output: Value, expression: &str) -> Value {
json!({
"imports": imports,
"nodes": [
{ "id": "in", "name": "request", "type": "inputNode", "content": input },
{ "id": "ex", "name": "compute", "type": "expressionNode", "content": { "expressions": [
{ "id": "e1", "key": "total", "value": expression }
] } },
{ "id": "out", "name": "response", "type": "outputNode", "content": output }
],
"edges": [
{ "id": "a", "sourceId": "in", "targetId": "ex" },
{ "id": "b", "sourceId": "ex", "targetId": "out" }
]
})
}
fn workspace() -> Workspace {
let mut ws = Workspace::new();
ws.set_document("models/fraud", document(models()));
ws.set_document("fraud", document(rules()));
ws.set_document(
"screen",
document(graph(
&["models/fraud"],
json!({ "target": "transaction" }),
json!({}),
"amount * 2",
)),
);
ws.set_document(
"pricing",
document(graph(
&[],
json!({}),
json!({}),
"cart.price * cart.quantity",
)),
);
ws
}
fn request(ws: &Workspace, path: &str, audience: SchemaAudience) -> Value {
ws.request_schema(&ScopeRequest::for_policy(path), audience)
}
#[test]
fn endpoints_are_graphs_and_policies_with_rules() {
let ws = workspace();
assert_eq!(ws.endpoint("screen"), Some(EndpointKind::Graph));
assert_eq!(ws.endpoint("pricing"), Some(EndpointKind::Graph));
assert_eq!(ws.endpoint("fraud"), Some(EndpointKind::Policy));
assert_eq!(ws.endpoint("models/fraud"), None, "data models only");
assert_eq!(ws.endpoint("missing"), None);
assert_eq!(
serde_json::to_value(EndpointKind::Policy).unwrap(),
json!("policy")
);
assert_eq!(
serde_json::to_value(SchemaAudience::Evaluated).unwrap(),
json!("evaluated")
);
}
#[test]
fn contract_is_what_the_caller_sends() {
let ws = workspace();
let schema = request(&ws, "fraud", SchemaAudience::Contract);
assert_eq!(
schema["$schema"],
json!("http://json-schema.org/draft-07/schema#")
);
assert!(schema.get("$id").is_none(), "{schema}");
let transaction = &schema["properties"]["transaction"]["properties"];
assert_eq!(transaction["amount"], json!({ "type": "number" }));
assert_eq!(
transaction["currency"],
json!({ "type": "string", "default": "GBP" })
);
assert!(
transaction.get("amount_x2").is_none(),
"a compute is the host's: {schema}"
);
assert_eq!(
transaction["card"],
json!({ "type": "string", "description": "card id" })
);
assert_eq!(
transaction["merchant"],
json!({ "anyOf": [{ "type": "string", "description": "merchant id" }, { "type": "null" }] }),
"an optional reference may be null"
);
assert_eq!(
transaction["country"],
json!({ "enum": ["GB", "US"], "description": "country id" }),
"an enum key"
);
assert_eq!(
transaction["pair"],
json!({ "type": "string", "description": "card_merchant id" }),
"a composite key is one joined string"
);
assert_eq!(
transaction["lines"]["items"]["properties"]["product"],
json!({ "type": "string", "description": "product id" })
);
assert_eq!(
transaction["lines"]["items"]["properties"]["qty"],
json!({ "type": "number" })
);
// The card's records come from the store; the merchant's are sent.
let properties = schema["properties"].as_object().unwrap();
assert!(!properties.contains_key("card"), "{schema}");
let merchant = &schema["properties"]["merchant"]["items"];
assert_eq!(merchant["required"], json!(["id", "name"]));
assert_eq!(merchant["additionalProperties"], json!(false));
let required = schema["required"].as_array().unwrap();
assert!(required.contains(&json!("transaction")), "{schema}");
assert!(!required.contains(&json!("card")), "{schema}");
}
#[test]
fn evaluated_is_what_the_rules_are_given() {
let ws = workspace();
let schema = request(&ws, "fraud", SchemaAudience::Evaluated);
let transaction = &schema["properties"]["transaction"]["properties"];
assert_eq!(
transaction["amount_x2"],
json!({ "type": "number" }),
"{schema}"
);
assert_eq!(
transaction["card"],
json!({ "type": "string", "description": "card id" }),
"a policy's reference is an id; its record is in the pool"
);
// The card's pool, with its features; its records carry the host's
// own fields beside them.
let card = &schema["properties"]["card"]["items"];
for feature in ["txn_count_1h", "txn_count_7d", "spend_1d"] {
assert!(
card["properties"].get(feature).is_some(),
"{feature}: {schema}"
);
}
let required = card["required"].as_array().unwrap();
assert!(required.contains(&json!("id")), "{card}");
assert!(required.contains(&json!("holder_country")), "{card}");
assert!(
!required.contains(&json!("spend_1d")),
"a default fills it in"
);
assert!(
!required.contains(&json!("txn_count_1h")),
"absent when unknown"
);
assert!(card.get("additionalProperties").is_none(), "{card}");
let pair = &schema["properties"]["card_merchant"]["items"]["properties"];
assert_eq!(
pair["card"],
json!({ "type": "string", "description": "card id" })
);
assert!(
!schema["required"]
.as_array()
.unwrap()
.contains(&json!("card")),
"the host's pool may be absent: {schema}"
);
}
#[test]
fn a_graph_typed_by_an_entity() {
let ws = workspace();
let contract = request(&ws, "screen", SchemaAudience::Contract);
assert_eq!(
contract["properties"]["card"],
json!({ "type": "string", "description": "card id" }),
"{contract}"
);
assert_eq!(
contract["properties"]["lines"]["items"]["properties"]["product"],
json!({ "type": "string", "description": "product id" })
);
assert!(contract["properties"].get("amount_x2").is_none());
// Evaluated: the reference is the record it names, its features in it.
let evaluated = request(&ws, "screen", SchemaAudience::Evaluated);
let card = &evaluated["properties"]["card"];
assert_eq!(card["type"], json!("object"), "{evaluated}");
assert!(
card["properties"].get("txn_count_1h").is_some(),
"{evaluated}"
);
assert_eq!(
evaluated["properties"]["lines"]["items"]["properties"]["product"]["properties"]["sku"],
json!({ "type": "string" })
);
assert_eq!(
evaluated["properties"]["amount_x2"],
json!({ "type": "number" })
);
}
#[test]
fn untyped_and_declared_graphs() {
let mut ws = workspace();
let inferred = request(&ws, "pricing", SchemaAudience::Contract);
assert_eq!(inferred["required"], json!(["cart"]), "{inferred}");
assert!(inferred["properties"]["cart"]["properties"]
.get("price")
.is_some());
assert_eq!(request(&ws, "pricing", SchemaAudience::Evaluated), inferred);
let declared = json!({ "type": "object", "properties": { "cart": { "type": "object", "description": "Cart" } } });
ws.set_document(
"declared",
document(graph(
&[],
json!({ "schema": declared.to_string() }),
json!({ "schema": "{\"type\":\"object\",\"properties\":{\"total\":{\"type\":\"number\",\"minimum\":0}}}" }),
"cart.price",
)),
);
assert_eq!(request(&ws, "declared", SchemaAudience::Contract), declared);
assert_eq!(
ws.response_schema(&ScopeRequest::for_policy("declared"))["properties"]["total"]["minimum"],
json!(0)
);
}
#[test]
fn responses_are_what_the_rules_write() {
let ws = workspace();
let response = ws.response_schema(&ScopeRequest::for_policy("fraud"));
assert_eq!(response["required"], json!(["transaction"]), "{response}");
assert_eq!(
response["properties"]["transaction"]["properties"]["flag"],
json!({ "type": "boolean" })
);
let graph = ws.response_schema(&ScopeRequest::for_policy("pricing"));
assert_eq!(
graph["properties"]["total"],
json!({ "type": "number" }),
"{graph}"
);
assert_eq!(graph["required"], json!(["total"]));
}
#[test]
fn unknown_paths_are_open_objects() {
let ws = workspace();
let open = json!({ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object" });
assert_eq!(request(&ws, "missing", SchemaAudience::Contract), open);
assert_eq!(
ws.response_schema(&ScopeRequest::for_policy("missing")),
open
);
}
+2
View File
@@ -693,6 +693,8 @@ fn inputs_inferred_from_reads_without_schema() {
let inputs = ws.inputs(&ScopeRequest::for_policy("g"));
let paths: Vec<&str> = inputs.iter().map(|i| i.path.as_ref()).collect();
assert_eq!(paths, vec!["customer.age", "factor"]);
// Nothing says the request may leave them out.
assert!(inputs.iter().all(|i| !i.optional), "{inputs:?}");
}
#[test]
@@ -0,0 +1,632 @@
//! A graph's Request node typed by an entity (`inputNode.content.target`)
//! instead of a schema: the entity is visible through the graph's imports,
//! and the request is that entity, flat; a reference holds its record.
use serde_json::{json, Value};
use zen_engine::model::DecisionContent;
use zen_engine::policy::{DiagnosticCode, ScopeRequest, Severity, Workspace};
use zen_expression::variable::VariableType;
fn document(value: Value) -> DecisionContent {
serde_json::from_value(value).expect("valid decision content")
}
fn node(id: &str, kind: &str, content: Value) -> Value {
json!({ "id": id, "name": id, "type": kind, "content": content })
}
fn edge(id: &str, source: &str, target: &str) -> Value {
json!({ "id": id, "sourceId": source, "targetId": target, "sourceHandle": null })
}
fn entity(id: &str, name: &str, properties: Value) -> Value {
json!({ "id": id, "type": "dataModel", "props": { "data": { "name": name, "properties": properties } } })
}
fn prop(name: &str, ty: &str) -> Value {
json!({ "id": name, "name": name, "type": ty, "array": false, "optional": false })
}
/// `models/aml`: a transaction referencing its customer; a channel dictionary.
fn models(transaction_fields: Value) -> Value {
json!({
"imports": [],
"blocks": [
entity("b-txn", "transaction", transaction_fields),
entity("b-cust", "customer", json!([
prop("id", "string"),
{ "id": "risk", "name": "risk_rating", "type": "string", "enum": ["low", "high"], "array": false, "optional": false }
])),
{ "id": "b-ch", "type": "dictionary", "props": { "data": {
"name": "channel",
"entries": [{ "id": "c1", "value": "cash", "label": "Cash" }, { "id": "c2", "value": "wire", "label": "Wire" }]
} } }
]
})
}
fn transaction_fields() -> Value {
json!([
prop("txn_id", "string"),
prop("amount", "number"),
{ "id": "channel", "name": "channel", "type": "relationship", "target": "channel", "array": false, "optional": false },
{ "id": "customer", "name": "customer", "type": "reference", "target": "customer", "array": false, "optional": false }
])
}
fn graph(imports: &[&str], request: Value, expressions: &[(&str, &str)]) -> Value {
let expressions: Vec<Value> = expressions
.iter()
.enumerate()
.map(|(i, (key, value))| json!({ "id": format!("x{i}"), "key": key, "value": value }))
.collect();
json!({
"imports": imports,
"nodes": [
node("in", "inputNode", request),
node("ex", "expressionNode", json!({ "expressions": expressions })),
node("out", "outputNode", json!({}))
],
"edges": [edge("e1", "in", "ex"), edge("e2", "ex", "out")]
})
}
fn codes(ws: &Workspace, path: &str, severity: Severity) -> Vec<DiagnosticCode> {
ws.diagnostics(path)
.into_iter()
.filter(|d| d.severity == severity)
.map(|d| d.code)
.collect()
}
fn workspace(request: Value, expressions: &[(&str, &str)]) -> Workspace {
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models(transaction_fields())));
ws.set_document("g", document(graph(&["models/aml"], request, expressions)));
ws
}
#[test]
fn nodes_read_the_entity_flat_and_its_references_as_records() {
let ws = workspace(
json!({ "target": "transaction" }),
&[
("big", "amount > 9000"),
("cash", "channel == 'cash'"),
("risky", "customer.risk_rating == 'high'"),
("customer_id", "customer.id"),
],
);
let diagnostics = ws.diagnostics("g");
assert!(diagnostics.is_empty(), "{diagnostics:?}");
}
#[test]
fn a_field_the_entity_does_not_have_is_flagged() {
let ws = workspace(
json!({ "target": "transaction" }),
&[("big", "amout > 9000")],
);
let errors = codes(&ws, "g", Severity::Error);
assert!(
errors.contains(&DiagnosticCode::UndefinedVariable),
"{errors:?}"
);
}
#[test]
fn a_value_outside_the_dictionary_is_flagged() {
let ws = workspace(
json!({ "target": "transaction" }),
&[("gold", "channel == 'gold'")],
);
let diagnostics = ws.diagnostics("g");
assert!(!diagnostics.is_empty(), "expected a diagnostic for 'gold'");
}
#[test]
fn an_entity_no_import_makes_visible_is_an_error() {
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models(transaction_fields())));
ws.set_document(
"g",
document(graph(
&[],
json!({ "target": "transaction" }),
&[("x", "1")],
)),
);
let diagnostics = ws.diagnostics("g");
let missing = diagnostics
.iter()
.find(|d| d.code == DiagnosticCode::UnknownDataModelTarget)
.unwrap_or_else(|| panic!("{diagnostics:?}"));
assert_eq!(missing.severity, Severity::Error);
assert!(
missing.message.contains("no entity `transaction` visible"),
"{}",
missing.message
);
}
#[test]
fn a_schema_and_an_entity_together_is_an_error() {
let schema =
json!({ "type": "object", "properties": { "amount": { "type": "number" } } }).to_string();
let ws = workspace(
json!({ "schema": schema, "target": "transaction" }),
&[("x", "1")],
);
let errors = codes(&ws, "g", Severity::Error);
assert!(
errors.contains(&DiagnosticCode::InvalidGraphStructure),
"{errors:?}"
);
}
#[test]
fn an_entity_is_a_declared_request() {
let ws = workspace(json!({ "target": "transaction" }), &[("x", "amount")]);
let warnings = codes(&ws, "g", Severity::Warning);
assert!(
!warnings.contains(&DiagnosticCode::MissingInputSchema),
"{warnings:?}"
);
}
#[test]
fn an_empty_target_is_no_target() {
let ws = workspace(json!({ "target": "" }), &[("x", "1")]);
let warnings = codes(&ws, "g", Severity::Warning);
assert!(
warnings.contains(&DiagnosticCode::MissingInputSchema),
"{warnings:?}"
);
}
#[test]
fn a_change_to_the_entity_in_its_policy_reaches_the_graph() {
let mut ws = workspace(
json!({ "target": "transaction" }),
&[("big", "amout > 9000")],
);
assert!(codes(&ws, "g", Severity::Error).contains(&DiagnosticCode::UndefinedVariable));
let mut fields = transaction_fields();
fields.as_array_mut().unwrap().push(prop("amout", "number"));
ws.set_document("models/aml", document(models(fields)));
let diagnostics = ws.diagnostics("g");
assert!(diagnostics.is_empty(), "{diagnostics:?}");
}
async fn run(imports: &[&str], input: Value) -> Result<Value, String> {
use zen_engine::loader::MemoryLoader;
use zen_engine::DecisionEngine;
let loader = std::sync::Arc::new(MemoryLoader::default());
loader.add("models/aml", document(models(transaction_fields())));
loader.add(
"g",
document(graph(
imports,
json!({ "target": "transaction" }),
&[
("big", "amount > 9000"),
("risky", "customer.risk_rating == 'high'"),
("customer_id", "customer.id"),
],
)),
);
let engine = DecisionEngine::default().with_loader(loader);
engine
.evaluate("g", input.into())
.await
.map(|response| response.result.to_value())
.map_err(|error| format!("{error:?}"))
}
#[tokio::test]
async fn runtime_reads_the_entity_flat_with_its_reference_as_a_record() {
let output = run(
&["models/aml"],
json!({ "txn_id": "X1", "amount": 9500, "channel": "cash", "customer": { "id": "C1", "risk_rating": "high" } }),
)
.await
.expect("evaluates");
assert_eq!(output["big"], json!(true), "{output}");
assert_eq!(output["risky"], json!(true), "{output}");
assert_eq!(output["customer_id"], json!("C1"), "{output}");
}
#[tokio::test]
async fn runtime_rejects_a_request_that_is_not_the_entity() {
let error = run(
&["models/aml"],
json!({ "txn_id": "X1", "amount": "a lot", "channel": "cash", "customer": { "id": "C1", "risk_rating": "high" } }),
)
.await
.expect_err("must fail");
assert!(error.contains("not a valid `transaction`"), "{error}");
assert!(error.contains("'amount'"), "{error}");
}
#[tokio::test]
async fn runtime_rejects_a_reference_sent_as_an_id_alone() {
let error = run(
&["models/aml"],
json!({ "txn_id": "X1", "amount": 1, "channel": "cash", "customer": "C1" }),
)
.await
.expect_err("must fail");
assert!(
error.contains("'customer' is the id \\\"C1\\\", but a reference carries its record: send the `customer` itself"),
"{error}"
);
}
#[tokio::test]
async fn runtime_errors_when_no_import_makes_the_entity_visible() {
let error = run(&[], json!({ "txn_id": "X1" }))
.await
.expect_err("must fail");
assert!(error.contains("no entity `transaction` visible"), "{error}");
}
#[test]
fn a_document_says_what_it_reads_from_its_request() {
let set = |reads: Option<std::collections::BTreeSet<String>>| {
reads.map(|r| r.into_iter().collect::<Vec<_>>())
};
// A graph typed by an entity: its fields under the entity's name, through references.
let ws = workspace(
json!({ "target": "transaction" }),
&[("big", "amount > 9000"), ("risky", "customer.risk_rating == 'high'")],
);
assert_eq!(
set(ws.reads("g")),
Some(vec!["transaction.amount".to_string(), "transaction.customer.risk_rating".to_string()])
);
// A read of the whole request can't be followed.
let ws = workspace(json!({ "target": "transaction" }), &[("all", "$")]);
assert_eq!(ws.reads("g"), None);
// Nor can a function node's.
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models(transaction_fields())));
ws.set_document(
"f",
document(json!({
"imports": ["models/aml"],
"nodes": [
node("in", "inputNode", json!({ "target": "transaction" })),
node("fn", "functionNode", json!({ "source": "export const handler = (input) => input;" })),
node("out", "outputNode", json!({}))
],
"edges": [edge("e1", "in", "fn"), edge("e2", "fn", "out")]
})),
);
assert_eq!(ws.reads("f"), None);
// A policy: what its rules read, including those of what it imports.
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models(transaction_fields())));
ws.set_document(
"p",
document(json!({
"imports": ["models/aml"],
"blocks": [{ "id": "r", "type": "expression", "props": { "data": {
"key": "transaction.big", "value": "transaction.amount > 9000 and transaction.customer.risk_rating == 'high'"
} } }]
})),
);
let reads = set(ws.reads("p")).expect("known");
assert!(reads.contains(&"transaction.amount".to_string()), "{reads:?}");
assert!(reads.iter().any(|r| r.starts_with("transaction.customer")), "{reads:?}");
}
#[test]
fn a_read_it_cant_follow_reads_everything() {
// `$root.x` and another node's output (`$nodes.x`): the request, but not
// as a field of the entity it's typed by. Unknown, so everything.
for expression in ["$root.amount > 9000", "$nodes.in.amount > 9000"] {
let ws = workspace(json!({ "target": "transaction" }), &[("big", expression)]);
assert_eq!(ws.reads("g"), None, "{expression}");
}
}
#[test]
fn reads_through_an_index_or_alias_are_never_lost() {
// Each is either followed (the entity's field is listed) or unknown
// (None: everything is computed); never silently left out.
for expression in [
"customer['risk_rating'] == 'high'",
"some([customer] as c, c.risk_rating == 'high')",
"count([amount] as a, a > 9000) > 0",
] {
let ws = workspace(json!({ "target": "transaction" }), &[("x", expression)]);
if let Some(reads) = ws.reads("g") {
assert!(!reads.is_empty(), "{expression}: reads nothing");
}
}
}
fn input<'a>(
inputs: &'a [zen_engine::policy::InputProperty],
path: &str,
) -> &'a zen_engine::policy::InputProperty {
inputs
.iter()
.find(|i| i.path.as_ref() == path)
.unwrap_or_else(|| panic!("{path} in {inputs:?}"))
}
fn object_fields(ty: &VariableType) -> Vec<String> {
let VariableType::Object(fields) = ty else {
panic!("expected an object, got {ty:?}");
};
let mut keys: Vec<String> = fields.borrow().keys().map(|k| k.to_string()).collect();
keys.sort();
keys
}
#[test]
fn inputs_carry_a_reference_as_its_record() {
// As nodes read it and the runtime takes it: `customer` is the record,
// and so is a reference inside a relationship's records.
let mut fields = transaction_fields();
fields.as_array_mut().unwrap().push(
json!({ "id": "lines", "name": "lines", "type": "relationship", "target": "line", "array": true, "optional": false }),
);
let mut models = models(fields);
models["blocks"].as_array_mut().unwrap().push(entity(
"b-line",
"line",
json!([
prop("qty", "number"),
{ "id": "product", "name": "product", "type": "reference", "target": "customer", "array": false, "optional": false }
]),
));
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models));
ws.set_document(
"g",
document(graph(&["models/aml"], json!({ "target": "transaction" }), &[("x", "amount")])),
);
let inputs = ws.inputs(&ScopeRequest::for_policy("g"));
let customer = input(&inputs, "customer");
assert_eq!(object_fields(&customer.resolved_type), vec!["id", "risk_rating"]);
assert!(!customer.optional);
let VariableType::Array(line) = &input(&inputs, "lines").resolved_type else {
panic!("lines: {inputs:?}");
};
let VariableType::Object(line) = line.as_ref() else {
panic!("line: {line:?}");
};
let product = line.borrow().get("product").cloned().expect("product");
assert_eq!(object_fields(&product), vec!["id", "risk_rating"]);
// Which inputs are references, and to what: a host that fills records
// in from ids takes the id there.
assert_eq!(customer.reference.as_deref(), Some("customer"));
let lines = input(&inputs, "lines");
assert_eq!(lines.reference, None);
assert_eq!(
lines.record_references.get("product").map(|t| t.as_ref()),
Some("customer")
);
assert_eq!(input(&inputs, "amount").reference, None);
assert!(input(&inputs, "amount").record_references.is_empty());
}
#[test]
fn an_optional_field_is_nullable_in_a_graph() {
let mut fields = transaction_fields();
fields.as_array_mut().unwrap().push(
json!({ "id": "fee", "name": "fee", "type": "number", "array": false, "optional": true }),
);
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models(fields)));
for (expression, flagged) in [("fee * 2", true), ("(fee ?? 0) * 2", false)] {
ws.set_document(
"g",
document(graph(&["models/aml"], json!({ "target": "transaction" }), &[("x", expression)])),
);
let errors = codes(&ws, "g", Severity::Error);
assert_eq!(!errors.is_empty(), flagged, "{expression}: {errors:?}");
}
let inputs = ws.inputs(&ScopeRequest::for_policy("g"));
let fee = input(&inputs, "fee");
assert!(fee.optional);
assert!(matches!(fee.resolved_type, VariableType::Nullable(_)), "{:?}", fee.resolved_type);
}
/// `g` imports `a` and `b`, both import `d` (a diamond). `b` declares
/// `transaction.amount` a string, `d` a number with `txn_id`; `e`, imported
/// by `b`, adds `flag` to it. Walked breadth-first (a, b, d, e), `b`'s
/// `amount` comes first; every declaration's fields are merged.
fn diamond() -> Vec<(&'static str, Value)> {
let policy = |imports: Value, blocks: Value| json!({ "imports": imports, "blocks": blocks });
vec![
("a", policy(json!(["d"]), json!([]))),
("b", policy(json!(["d", "e"]), json!([entity("b-t", "transaction", json!([prop("amount", "string")]))]))),
(
"d",
policy(json!([]), json!([entity("d-t", "transaction", json!([prop("amount", "number"), prop("txn_id", "string")]))])),
),
("e", policy(json!([]), json!([entity("e-t", "transaction", json!([prop("flag", "boolean")]))]))),
]
}
fn diamond_graph() -> Value {
graph(
&["a", "b"],
json!({ "target": "transaction" }),
&[("shout", "amount + '!'"), ("id", "txn_id"), ("flagged", "flag == true")],
)
}
#[test]
fn imports_are_walked_and_entities_merged_as_at_runtime() {
let mut ws = Workspace::new();
for (path, policy) in diamond() {
ws.set_document(path, document(policy));
}
ws.set_document("g", document(diamond_graph()));
let diagnostics = ws.diagnostics("g");
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let inputs = ws.inputs(&ScopeRequest::for_policy("g"));
let paths: Vec<&str> = inputs.iter().map(|i| i.path.as_ref()).collect();
assert_eq!(paths, vec!["amount", "flag", "txn_id"]);
assert!(matches!(input(&inputs, "amount").resolved_type, VariableType::String));
}
#[tokio::test]
async fn runtime_walks_imports_and_merges_entities_as_the_editor() {
use zen_engine::loader::MemoryLoader;
use zen_engine::DecisionEngine;
let loader = std::sync::Arc::new(MemoryLoader::default());
for (path, policy) in diamond() {
loader.add(path, document(policy));
}
loader.add("g", document(diamond_graph()));
let engine = DecisionEngine::default().with_loader(loader);
let output = engine
.evaluate("g", json!({ "amount": "high", "txn_id": "X1", "flag": true }).into())
.await
.map(|response| response.result.to_value())
.map_err(|error| format!("{error:?}"))
.expect("a string amount is the entity's");
assert_eq!(output["shout"], json!("high!"), "{output}");
assert_eq!(output["flagged"], json!(true), "{output}");
let error = engine
.evaluate("g", json!({ "amount": 1, "txn_id": "X1", "flag": "yes" }).into())
.await
.map_err(|error| format!("{error:?}"))
.expect_err("must fail");
assert!(error.contains("'amount'") && error.contains("'flag'"), "{error}");
}
#[test]
fn entities_referencing_each_other_type_quickly() {
// Eight entities, each referencing every other: opened a few links deep,
// not along every path through them.
let names: Vec<String> = (0..8).map(|i| format!("e{i}")).collect();
let blocks: Vec<Value> = names
.iter()
.map(|name| {
let mut fields = vec![prop("id", "string")];
for other in names.iter().filter(|o| *o != name) {
fields.push(json!({ "id": other, "name": other, "type": "reference", "target": other, "array": false, "optional": false }));
}
entity(&format!("b-{name}"), name, json!(fields))
})
.collect();
let started = std::time::Instant::now();
let mut ws = Workspace::new();
ws.set_document("models/ring", document(json!({ "imports": [], "blocks": blocks })));
ws.set_document(
"g",
document(graph(
&["models/ring"],
json!({ "target": "e0" }),
&[("deep", "e1.e2.e3.e4.id"), ("far", "e1.e2.e3.e4.e5.id")],
)),
);
let diagnostics = ws.diagnostics("g");
let inputs = ws.inputs(&ScopeRequest::for_policy("g"));
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
// Four links are records; a fifth is unknown.
let errors: Vec<_> = diagnostics.iter().filter(|d| d.severity == Severity::Error).collect();
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(errors[0].code == DiagnosticCode::ImplicitAny && errors[0].message.contains("`far`"), "{errors:?}");
assert_eq!(inputs.len(), 8);
}
#[test]
fn a_graph_without_an_entity_request_ignores_entity_edits() {
let schema =
json!({ "type": "object", "properties": { "amount": { "type": "number" } } }).to_string();
for (request, affected) in [(json!({ "schema": schema }), false), (json!({ "target": "transaction" }), true)] {
let mut ws = Workspace::new();
ws.set_document("models/aml", document(models(transaction_fields())));
ws.set_document("g", document(graph(&["models/aml"], request.clone(), &[("x", "amount")])));
let _ = ws.diagnostics("g");
let (cursor, _) = ws.changes_since(0);
let mut fields = transaction_fields();
fields.as_array_mut().unwrap().push(prop("extra", "number"));
ws.set_document("models/aml", document(models(fields)));
let (_, changed) = ws.changes_since(cursor);
assert_eq!(
changed.iter().any(|p| p.as_ref() == "g"),
affected,
"{request}: {changed:?}"
);
}
}
#[tokio::test]
async fn a_decision_loads_its_request_entity_once() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use zen_engine::loader::ClosureLoader;
use zen_engine::model::GraphContent;
use zen_engine::Decision;
let loads = Arc::new(AtomicUsize::new(0));
let counted = loads.clone();
let models = Arc::new(document(models(transaction_fields())));
let loader = ClosureLoader::new(move |_key: String| {
counted.fetch_add(1, Ordering::SeqCst);
let models = models.clone();
async move { Ok(models) }
});
let content: GraphContent = serde_json::from_value(graph(
&["models/aml"],
json!({ "target": "transaction" }),
&[("big", "amount > 9000")],
))
.unwrap();
let decision = Decision::from(content).with_loader(Arc::new(loader));
let request = json!({ "txn_id": "X1", "amount": 9500, "channel": "cash", "customer": { "id": "C1", "risk_rating": "low" } });
for _ in 0..3 {
let output = decision.evaluate(request.clone().into()).await.expect("evaluates");
assert_eq!(output.result.to_value()["big"], json!(true));
}
assert_eq!(loads.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn runtime_rejects_a_schema_and_an_entity_together() {
use zen_engine::loader::MemoryLoader;
use zen_engine::DecisionEngine;
let schema =
json!({ "type": "object", "properties": { "amount": { "type": "number" } } }).to_string();
let loader = std::sync::Arc::new(MemoryLoader::default());
loader.add("models/aml", document(models(transaction_fields())));
loader.add(
"g",
document(graph(
&["models/aml"],
json!({ "schema": schema, "target": "transaction" }),
&[("x", "1")],
)),
);
let engine = DecisionEngine::default().with_loader(loader);
let error = engine
.evaluate("g", json!({ "amount": 1 }).into())
.await
.map_err(|error| format!("{error:?}"))
.expect_err("must fail");
assert!(
error.contains("the request is typed twice: by a schema and by an entity (`target`); keep one"),
"{error}"
);
}
#[test]
fn reads_of_an_unknown_document_are_unknown() {
let ws = workspace(json!({ "target": "transaction" }), &[("x", "amount")]);
assert_eq!(ws.reads("missing"), None);
}
+1
View File
@@ -30,6 +30,7 @@ rust_decimal_macros = { workspace = true }
nohash-hasher = { workspace = true }
strsim = "0.11"
iana-time-zone = "0.1"
xxhash-rust = { version = "0.8", features = ["xxh3"] }
zen-macros = { path = "../macros", version = "2.1.2" }
zen-types = { path = "../types", version = "2.1.2" }
+152
View File
@@ -109,6 +109,14 @@ impl<'arena, 'bytecode_ref> CompilerInner<'arena, 'bytecode_ref> {
let _ = std::mem::replace(&mut self.bytecode[at - 1], op);
}
/// Points the jump emitted at `at` to the next instruction.
fn land(&mut self, at: usize) {
if let Opcode::Jump(kind, _) = self.bytecode[at - 1] {
let to = self.bytecode.len();
self.replace(at, Opcode::Jump(kind, (to - at) as u32));
}
}
fn calc_backward_jump(&self, to: usize) -> usize {
self.bytecode.len() + 1 - to
}
@@ -554,6 +562,150 @@ impl<'arena, 'bytecode_ref> CompilerInner<'arena, 'bytecode_ref> {
self.emit(Opcode::Array);
Ok(self.emit(Opcode::Flatten))
}
ClosureFunction::Count if arguments.len() == 1 => {
self.compile_argument(kind, arguments, 0)?;
self.emit(Opcode::Begin);
self.emit(Opcode::GetLen);
Ok(self.emit(Opcode::End))
}
// `first(items, cb)`: per item, a `bool` is a condition
// (`true` keeps the item), any other value the
// projection; null is skipped (see `ClosureFunction::First`).
ClosureFunction::First | ClosureFunction::Last if arguments.len() == 2 => {
self.compile_argument(kind, arguments, 0)?;
self.emit(Opcode::Begin);
self.emit_loop(|c| {
c.compile_argument(kind, arguments, 1)?;
let projected = c.emit(Opcode::Jump(Jump::IfNotBool, 0));
let rejected = c.emit(Opcode::Jump(Jump::IfFalse, 0));
c.emit(Opcode::Pop);
c.emit(Opcode::Pointer(0));
let matched = c.emit(Opcode::Jump(Jump::Forward, 0));
c.land(rejected);
c.emit(Opcode::Pop);
let skipped = c.emit(Opcode::Jump(Jump::Forward, 0));
c.land(projected);
c.land(matched);
let keep = c.emit(Opcode::Jump(Jump::IfNotNull, 0));
c.emit(Opcode::Pop);
let null = c.emit(Opcode::Jump(Jump::Forward, 0));
c.land(keep);
c.emit(Opcode::IncrementCount);
c.land(skipped);
c.land(null);
Ok(())
})?;
self.emit(Opcode::GetCount);
self.emit(Opcode::End);
self.emit(Opcode::Array);
Ok(self.emit(Opcode::CallFunction {
kind: kind.clone(),
arg_count: 1,
}))
}
ClosureFunction::Sum
| ClosureFunction::Avg
| ClosureFunction::Min
| ClosureFunction::Max
| ClosureFunction::Median
| ClosureFunction::Mode
| ClosureFunction::Stddev
| ClosureFunction::Variance
| ClosureFunction::TopK
| ClosureFunction::LastN
| ClosureFunction::Percentile
| ClosureFunction::CountDistinct
| ClosureFunction::Unique
| ClosureFunction::First
| ClosureFunction::Last
| ClosureFunction::ArgMax
| ClosureFunction::ArgMin
| ClosureFunction::Skew
| ClosureFunction::Kurtosis
| ClosureFunction::CountDistinctApprox
| ClosureFunction::PercentileApprox => {
let (_, maximum) = c.callbacks();
if arguments.len() > maximum + 1 {
return Err(CompilerError::InvalidFunctionCall {
name: kind.to_string(),
message: "Invalid number of arguments".to_string(),
});
}
// A parameter (`topK`'s count) sits between the
// projections and the filter.
let parameter = c.parameter();
let filter_at = c.filter_position();
let projections = c.projections();
self.compile_argument(kind, arguments, 0)?;
self.emit(Opcode::Begin);
self.emit_loop(|c| {
let filtered = arguments.len() > filter_at;
let mut noop = 0;
if filtered {
c.compile_argument(kind, arguments, filter_at)?;
noop = c.emit(Opcode::Jump(Jump::IfFalse, 0));
c.emit(Opcode::Pop);
}
// The item (or its projection) joins the result
// unless it is null. With two projections
// (`argMax`), the pair `[value, by]` joins unless
// either is null; with one callback
// (`argMax(items, #.amount)`) the value is the item.
let missing = projections - (arguments.len() - 1).min(projections);
let mut skips = Vec::with_capacity(projections);
for at in 1..=projections {
if at > missing {
c.compile_argument(kind, arguments, at - missing)?;
} else {
c.emit(Opcode::Pointer(0));
}
let keep = c.emit(Opcode::Jump(Jump::IfNotNull, 0));
for _ in 0..at {
c.emit(Opcode::Pop);
}
skips.push(c.emit(Opcode::Jump(Jump::Forward, 0)));
let kept = c.bytecode.len();
c.replace(
keep,
Opcode::Jump(Jump::IfNotNull, (kept - keep) as u32),
);
}
if projections > 1 {
c.emit(Opcode::PushNumber(projections.into()));
c.emit(Opcode::Array);
}
c.emit(Opcode::IncrementCount);
let skipped = c.bytecode.len();
for skip in skips {
c.replace(
skip,
Opcode::Jump(Jump::Forward, (skipped - skip) as u32),
);
}
if filtered {
let jmp = c.emit(Opcode::Jump(Jump::Forward, 0));
c.replace(noop, Opcode::Jump(Jump::IfFalse, (jmp - noop) as u32));
let e = c.emit(Opcode::Pop);
c.replace(jmp, Opcode::Jump(Jump::Forward, (e - jmp) as u32));
}
Ok(())
})?;
self.emit(Opcode::GetCount);
self.emit(Opcode::End);
self.emit(Opcode::Array);
let mut arg_count = 1;
if let Some(at) = parameter {
self.compile_argument(kind, arguments, at)?;
arg_count = 2;
}
Ok(self.emit(Opcode::CallFunction {
kind: kind.clone(),
arg_count,
}))
}
ClosureFunction::Count => {
self.compile_argument(kind, arguments, 0)?;
self.emit(Opcode::Begin);
+2
View File
@@ -76,6 +76,8 @@ pub enum Jump {
IfTrue,
IfFalse,
IfNotNull,
/// Jumps when the top of the stack is no `bool` (it stays).
IfNotBool,
IfEnd,
}
+20 -1
View File
@@ -1,5 +1,7 @@
use crate::variable::Variable;
use crate::vm::date::VmDate;
use crate::vm::date::{DurationUnit, VmDate};
use rust_decimal::Decimal;
use rust_decimal::prelude::FromPrimitive;
use std::rc::Rc;
pub struct DateValue;
@@ -18,6 +20,23 @@ impl DateValue {
Some(Variable::String(text.into()))
}
/// `d(a).diff(d(b), unit)` as ZEN evaluates it, for hosts that compile
/// it: whole units, truncated toward zero (milliseconds without a unit);
/// null when either is not a date or the unit is unknown.
pub fn diff(a: &Variable, b: &Variable, unit: Option<&str>) -> Variable {
let unit = match unit {
None => None,
Some(unit) => match DurationUnit::parse(unit) {
Some(unit) => Some(unit),
None => return Variable::Null,
},
};
VmDate::new(a.clone(), None)
.diff(&VmDate::new(b.clone(), None), unit)
.and_then(Decimal::from_i64)
.map_or(Variable::Null, Variable::Number)
}
pub fn is(value: &Variable) -> bool {
matches!(value, Variable::Dynamic(dynamic) if dynamic.type_name() == "date")
}
+70
View File
@@ -1,4 +1,10 @@
use std::collections::BTreeSet;
use std::rc::Rc;
use crate::expression::{Standard, Unary};
use crate::intellisense::dependency::{DependencyResolutionWalker, ReadDependency};
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::variable::Variable;
use crate::{Expression, Isolate, IsolateError};
@@ -24,6 +30,70 @@ pub fn evaluate_unary_expression(
Isolate::with_environment(context).run_unary(expression)
}
/// Root-level context keys a standard expression can read, in stable order —
/// `None` when the expression addresses the whole context (`$root` and
/// friends) or cannot be analyzed, meaning no projection is safe. Callers use
/// this to avoid materialising data the expression provably never touches;
/// the set may over-include (harmless), never under-include.
pub fn expression_root_references(expression: &str) -> Option<Vec<String>> {
let arena = bumpalo::Bump::new();
let tokens = Lexer::new().tokenize(&arena, expression).ok()?;
let parser = Parser::try_new(&tokens, &arena).ok()?;
let result = parser.standard().with_metadata().parse();
if !result.is_complete || result.root.has_error() {
return None;
}
let metadata = result.metadata.unwrap_or_default();
let dependencies = DependencyResolutionWalker::walk(result.root, &metadata);
let mut roots = BTreeSet::new();
if !collect_read_roots(&dependencies.reads, &mut roots) {
return None;
}
for reference in &dependencies.references {
if let Some(root) = reference.path.first() {
if !insert_root(root, &mut roots) {
return None;
}
}
}
Some(roots.into_iter().collect())
}
fn collect_read_roots(reads: &[ReadDependency], roots: &mut BTreeSet<String>) -> bool {
for read in reads {
match read {
ReadDependency::Direct { path, .. } | ReadDependency::Unresolved { path, .. } => {
let Some(root) = path.first() else {
return false;
};
if !insert_root(root, roots) {
return false;
}
}
ReadDependency::Iteration {
collection, reads, ..
} => {
let Some(root) = collection.first() else {
return false;
};
if !insert_root(root, roots) || !collect_read_roots(reads, roots) {
return false;
}
}
}
}
true
}
fn insert_root(root: &Rc<str>, roots: &mut BTreeSet<String>) -> bool {
if matches!(root.as_ref(), "$root" | "$" | "$nodes") {
return false;
}
roots.insert(root.to_string());
true
}
/// Compiles a standard expression
pub fn compile_expression(expression: &str) -> Result<Expression<Standard>, IsolateError> {
Isolate::new().compile_standard(expression)
+6 -4
View File
@@ -154,10 +154,12 @@ impl FunctionDefinition for CompositeFunction {
}
for signature in &self.signatures {
let all_match = args
.iter()
.zip(signature.parameters.iter())
.all(|(arg, param)| arg.satisfies(param));
// A signature shorter than the call can't take its extra arguments.
let all_match = signature.parameters.len() >= args.len()
&& args
.iter()
.zip(signature.parameters.iter())
.all(|(arg, param)| arg.satisfies(param));
if all_match {
typecheck.return_type = signature.return_type.clone();
return typecheck;
+274 -9
View File
@@ -24,6 +24,7 @@ pub enum InternalFunction {
Extract,
FuzzyMatch,
Split,
Join,
// Math
Abs,
@@ -34,6 +35,12 @@ pub enum InternalFunction {
Rand,
Median,
Mode,
Stddev,
Variance,
Percentile,
PercentileApprox,
TopK,
LastN,
Floor,
Ceil,
Round,
@@ -161,6 +168,25 @@ impl From<&InternalFunction> for Rc<dyn FunctionDefinition> {
},
}),
// `join(list, separator?)`: the inverse of `split`. Strings, numbers,
// bools and dates join; null items are skipped.
IF::Join => Rc::new(CompositeFunction {
implementation: Rc::new(imp::join),
signatures: [VT::String, VT::Number, VT::Bool, VT::Date]
.into_iter()
.flat_map(|item| {
let list = VT::Nullable(Rc::new(item)).array();
[
FunctionSignature::single(list.clone(), VT::String),
FunctionSignature {
parameters: vec![list, VT::String],
return_type: VT::String,
},
]
})
.collect(),
}),
IF::FuzzyMatch => Rc::new(CompositeFunction {
implementation: Rc::new(imp::fuzzy_match),
signatures: vec![
@@ -254,11 +280,56 @@ impl From<&InternalFunction> for Rc<dyn FunctionDefinition> {
signature: FunctionSignature::single(VT::Number.array(), VT::Number),
}),
IF::Mode => Rc::new(StaticFunction {
IF::Mode => Rc::new(CompositeFunction {
implementation: Rc::new(imp::mode),
signatures: vec![
FunctionSignature::single(VT::Number.array(), VT::Number),
FunctionSignature::single(VT::String.array(), VT::String),
],
}),
IF::Stddev => Rc::new(StaticFunction {
implementation: Rc::new(imp::stddev),
signature: FunctionSignature::single(VT::Number.array(), VT::Number),
}),
IF::Variance => Rc::new(StaticFunction {
implementation: Rc::new(imp::variance),
signature: FunctionSignature::single(VT::Number.array(), VT::Number),
}),
IF::Percentile => Rc::new(StaticFunction {
implementation: Rc::new(imp::percentile),
signature: FunctionSignature {
parameters: vec![VT::Number.array(), VT::Number],
return_type: VT::Number,
},
}),
IF::PercentileApprox => Rc::new(StaticFunction {
implementation: Rc::new(imp::percentile_approx),
signature: FunctionSignature {
parameters: vec![VT::Number.array(), VT::Number],
return_type: VT::Number,
},
}),
IF::TopK => Rc::new(StaticFunction {
implementation: Rc::new(imp::top_k),
signature: FunctionSignature {
parameters: vec![VT::Any.array(), VT::Number],
return_type: VT::Any.array(),
},
}),
IF::LastN => Rc::new(StaticFunction {
implementation: Rc::new(imp::last_n),
signature: FunctionSignature {
parameters: vec![VT::Any.array(), VT::Number],
return_type: VT::Any.array(),
},
}),
IF::Type => Rc::new(StaticFunction {
implementation: Rc::new(imp::to_type),
signature: FunctionSignature::single(VT::Any, VT::String),
@@ -456,6 +527,35 @@ pub(crate) mod imp {
Ok(V::from_array(arr))
}
/// The items as text, between separators (`,` by default): strings as
/// they are, numbers normalized (`1.50` is `1.5`), bools and dates as
/// `string()` renders them; null items are skipped. Lists and objects
/// fail.
pub fn join(args: Arguments) -> anyhow::Result<V> {
let array = args.array(0)?;
let separator = args.ostr(1)?.unwrap_or(",");
let items = array.borrow();
let mut out = String::new();
let mut first = true;
for item in items.iter() {
let text: std::borrow::Cow<str> = match item {
V::Null => continue,
V::String(s) => std::borrow::Cow::Borrowed(s.as_str()),
V::Number(n) => n.normalize().to_string().into(),
V::Bool(b) => b.to_string().into(),
V::Dynamic(d) if d.as_date().is_some() => d.to_string().into(),
other => anyhow::bail!("Cannot join type {}", other.type_name()),
};
if !first {
out.push_str(separator);
}
first = false;
out.push_str(&text);
}
Ok(V::String(out.into()))
}
pub fn flatten(args: Arguments) -> anyhow::Result<V> {
let a = args.array(0)?;
@@ -702,20 +802,185 @@ pub(crate) mod imp {
}
}
/// The most common value of numbers or strings; ties go to the largest.
pub fn mode(args: Arguments) -> anyhow::Result<V> {
let a = __internal_number_array(&args, 0)?;
let mut counts = BTreeMap::new();
for num in a {
*counts.entry(num).or_insert(0) += 1;
let array = args.array(0)?;
let items = array.borrow();
if items.iter().all(|item| matches!(item, V::Number(_))) {
let mut counts = BTreeMap::new();
for item in items.iter() {
if let V::Number(n) = item {
*counts.entry(*n).or_insert(0) += 1;
}
}
return counts
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(num, _)| V::Number(num))
.context("Empty array");
}
let most_common = counts
let mut counts = BTreeMap::new();
for item in items.iter() {
let V::String(s) = item else {
anyhow::bail!("Expected an array of numbers or strings");
};
*counts.entry(s.clone()).or_insert(0usize) += 1;
}
counts
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(num, _)| num)
.context("Empty array")?;
.map(|(s, _)| V::String(s))
.context("Empty array")
}
Ok(V::Number(most_common))
/// Sample variance, exact in decimals: `(Σx² − (Σx)²/n) / (n − 1)`;
/// `None` below two values. Callers merging `(n, Σx, Σx²)` across
/// partial sums use the same formula and get the same digits.
pub fn sample_variance(values: &[Decimal]) -> anyhow::Result<Option<Decimal>> {
let mut sum = Decimal::ZERO;
let mut squares = Decimal::ZERO;
for x in values {
sum = sum.checked_add(*x).context("Number overflow")?;
squares = x
.checked_mul(*x)
.and_then(|sq| squares.checked_add(sq))
.context("Number overflow")?;
}
variance_of(values.len() as i64, sum, squares)
}
pub fn variance_of(n: i64, sum: Decimal, squares: Decimal) -> anyhow::Result<Option<Decimal>> {
if n < 2 {
return Ok(None);
}
let n = Decimal::from(n);
let spread = sum
.checked_mul(sum)
.and_then(|s2| s2.checked_div(n))
.and_then(|s2n| squares.checked_sub(s2n))
.context("Number overflow")?;
let variance = spread
.checked_div(n - Decimal::ONE)
.context("Number overflow")?;
Ok(Some(variance.max(Decimal::ZERO).normalize()))
}
pub fn sqrt_of(value: Decimal) -> anyhow::Result<Decimal> {
use rust_decimal::MathematicalOps;
Ok(value.sqrt().context("Square root of a negative number")?.normalize())
}
pub fn variance(args: Arguments) -> anyhow::Result<V> {
let a = __internal_number_array(&args, 0)?;
Ok(sample_variance(&a)?.map_or(V::Null, V::Number))
}
pub fn stddev(args: Arguments) -> anyhow::Result<V> {
let a = __internal_number_array(&args, 0)?;
match sample_variance(&a)? {
None => Ok(V::Null),
Some(variance) => Ok(V::Number(sqrt_of(variance)?)),
}
}
/// Linear interpolation between the closest ranks of sorted values
/// (`q` in 0..=1): `x[⌊p⌋] + (p − ⌊p⌋)·(x[⌊p⌋+1] − x[⌊p⌋])`, `p = q·(n − 1)`.
pub fn percentile_of(sorted: &[Decimal], q: Decimal) -> anyhow::Result<Option<Decimal>> {
if !(Decimal::ZERO..=Decimal::ONE).contains(&q) {
anyhow::bail!("Percentile must be between 0 and 1, got {q}");
}
if sorted.is_empty() {
return Ok(None);
}
let position = q
.checked_mul(Decimal::from(sorted.len() - 1))
.context("Number overflow")?;
let low = position.floor();
let index = low.to_usize().context("Index out of bounds")?;
let fraction = position - low;
let value = if fraction.is_zero() {
sorted[index]
} else {
let (a, b) = (sorted[index], sorted[index + 1]);
b.checked_sub(a)
.and_then(|d| d.checked_mul(fraction))
.and_then(|d| a.checked_add(d))
.context("Number overflow")?
};
Ok(Some(value.normalize()))
}
fn __internal_count(args: &Arguments, pos: usize) -> anyhow::Result<usize> {
let n = args.number(pos)?;
if n.is_sign_negative() || !n.fract().is_zero() {
anyhow::bail!("Expected a whole number of items, got {n}");
}
n.to_usize().context("Number of items is too large")
}
/// The `k` most frequent non-null values (numbers or strings), most
/// frequent first; equal counts go to the smaller value.
pub fn top_k(args: Arguments) -> anyhow::Result<V> {
let k = __internal_count(&args, 1)?;
let array = args.array(0)?;
let items = array.borrow();
let mut numbers: BTreeMap<Decimal, usize> = BTreeMap::new();
let mut strings = BTreeMap::new();
for item in items.iter() {
match item {
V::Null => {}
V::Number(n) => *numbers.entry(n.normalize()).or_insert(0) += 1,
V::String(s) => *strings.entry(s.clone()).or_insert(0) += 1,
_ => anyhow::bail!("Expected an array of numbers or strings"),
}
}
let mut ranked: Vec<(usize, V)> = numbers
.into_iter()
.map(|(n, c)| (c, V::Number(n)))
.chain(strings.into_iter().map(|(s, c)| (c, V::String(s))))
.collect();
// Stable: within a count, numbers then strings, each ascending.
ranked.sort_by(|a, b| b.0.cmp(&a.0));
Ok(V::from_array(ranked.into_iter().take(k).map(|(_, v)| v).collect()))
}
/// The last `n` non-null items, the last one first.
pub fn last_n(args: Arguments) -> anyhow::Result<V> {
let n = __internal_count(&args, 1)?;
let array = args.array(0)?;
let items = array.borrow();
Ok(V::from_array(
items
.iter()
.rev()
.filter(|item| !matches!(item, V::Null))
.take(n)
.cloned()
.collect(),
))
}
pub fn percentile(args: Arguments) -> anyhow::Result<V> {
let mut a = __internal_number_array(&args, 0)?;
let q = args.number(1)?;
a.sort();
Ok(percentile_of(&a, q)?.map_or(V::Null, V::Number))
}
/// The DDSketch estimate (1% relative accuracy) of the value at a
/// fraction `q` (0 to 1) of the numbers: no interpolation.
pub fn percentile_approx(args: Arguments) -> anyhow::Result<V> {
let values = __internal_number_array(&args, 0)?;
let q = args.number(1)?;
if !(Decimal::ZERO..=Decimal::ONE).contains(&q) {
anyhow::bail!("Percentile must be between 0 and 1, got {q}");
}
let mut sketch = crate::functions::sketch::DdSketch::new();
for x in values {
sketch.insert(x);
}
Ok(sketch.quantile(q).map_or(V::Null, V::Number))
}
pub fn to_type(args: Arguments) -> anyhow::Result<V> {
+173
View File
@@ -14,7 +14,9 @@ pub(crate) mod defs;
mod deprecated;
pub(crate) mod internal;
mod method;
pub mod moments;
pub(crate) mod registry;
pub mod sketch;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum FunctionKind {
@@ -55,4 +57,175 @@ pub enum ClosureFunction {
Map,
FlatMap,
Count,
// Aggregates over the items, optionally projected and filtered:
// `sum(arr, #.amount, #.kind == 'in')`. Null projections are skipped.
Sum,
Avg,
Min,
Max,
Median,
Mode,
Stddev,
Variance,
// With a parameter after the projection, then the optional filter:
// `topK(items as t, t.merchant, 3 [, t.kind == 'in'])`.
TopK,
LastN,
Percentile,
CountDistinct,
Unique,
/// Selectors return an item, or a projection of it.
///
/// - `first(items)`: the first non-null item.
/// - `first(items, cb)`: per item, a `bool` callback value is a
/// condition (`true`: the item is a candidate, `false`: skipped); any
/// other non-null value is the projection (as in
/// `first(items, value, cond)`); null is skipped. The first candidate
/// wins. Analysis follows the same rule: a `bool` callback types the
/// result as the item, else as the projection.
/// - `first(items, value, cond)`: the first non-null `value` at a
/// matching item, even when `value` is a `bool`.
///
/// `last` is the same from the end.
First,
Last,
/// The item (or a projection of it) with the greatest (smallest) `by`,
/// a number or date; ties go to the last, a null `by` is skipped:
///
/// - `argMax(items as t, t.amount)`: the item;
/// - `argMax(items as t, t.merchant, t.amount [, t.kind == 'in'])`: its
/// `merchant`.
///
/// Three arguments are always `(value, by)`: a condition on the item
/// form needs the four-argument form (`argMax(items as t, t, t.amount,
/// cond)`) or `argMax(filter(items, cond), #.amount)`.
ArgMax,
ArgMin,
Skew,
Kurtosis,
CountDistinctApprox,
// With a parameter (the fraction) like `percentile`.
PercentileApprox,
}
impl ClosureFunction {
/// Callbacks accepted after the array: `(required, maximum)`.
pub fn callbacks(&self) -> (usize, usize) {
match self {
ClosureFunction::All
| ClosureFunction::None
| ClosureFunction::Some
| ClosureFunction::One
| ClosureFunction::Filter
| ClosureFunction::Map
| ClosureFunction::FlatMap => (1, 1),
ClosureFunction::Count => (0, 1),
ClosureFunction::Sum
| ClosureFunction::Avg
| ClosureFunction::Min
| ClosureFunction::Max
| ClosureFunction::Median
| ClosureFunction::Mode
| ClosureFunction::Stddev
| ClosureFunction::Variance => (1, 2),
ClosureFunction::TopK
| ClosureFunction::LastN
| ClosureFunction::Percentile
| ClosureFunction::PercentileApprox => (2, 3),
ClosureFunction::ArgMax | ClosureFunction::ArgMin => (1, 3),
ClosureFunction::CountDistinct
| ClosureFunction::Unique
| ClosureFunction::First
| ClosureFunction::Last
| ClosureFunction::Skew
| ClosureFunction::Kurtosis
| ClosureFunction::CountDistinctApprox => (0, 2),
}
}
/// How many projections an aggregate reads per item: two for `argMax`
/// and `argMin` (the value, then what ranks it), else one. With a
/// single callback (`argMax(items, #.amount)`) the value is the item.
pub fn projections(&self) -> usize {
match self {
ClosureFunction::ArgMax | ClosureFunction::ArgMin => 2,
_ => 1,
}
}
/// The argument position of an aggregate's optional filter: after the
/// projections and the parameter.
pub fn filter_position(&self) -> usize {
1 + self.projections() + usize::from(self.parameter().is_some())
}
/// Aggregates: the first callback projects an item, the second filters.
/// The others take one predicate (or mapping) callback.
pub fn is_aggregate(&self) -> bool {
!matches!(
self,
ClosureFunction::All
| ClosureFunction::None
| ClosureFunction::Some
| ClosureFunction::One
| ClosureFunction::Filter
| ClosureFunction::Map
| ClosureFunction::FlatMap
| ClosureFunction::Count
)
}
/// Whether callback `index` (1-based argument position) must return a bool.
pub fn is_predicate(&self, index: usize) -> bool {
match self {
ClosureFunction::Map | ClosureFunction::FlatMap => false,
c if c.is_aggregate() => index == c.filter_position(),
_ => index == 1,
}
}
/// The argument position of a plain parameter (a count or fraction),
/// evaluated once rather than per item.
pub fn parameter(&self) -> Option<usize> {
matches!(
self,
ClosureFunction::TopK
| ClosureFunction::LastN
| ClosureFunction::Percentile
| ClosureFunction::PercentileApprox
)
.then_some(2)
}
}
impl InternalFunction {
/// The callback form of an array aggregate: `sum([1, 2])` stays internal,
/// `sum(items, #.amount)` is [`ClosureFunction::Sum`].
pub fn closure_form(&self) -> Option<ClosureFunction> {
Some(match self {
InternalFunction::Sum => ClosureFunction::Sum,
InternalFunction::Avg => ClosureFunction::Avg,
InternalFunction::Min => ClosureFunction::Min,
InternalFunction::Max => ClosureFunction::Max,
InternalFunction::Median => ClosureFunction::Median,
InternalFunction::Mode => ClosureFunction::Mode,
InternalFunction::Stddev => ClosureFunction::Stddev,
InternalFunction::Variance => ClosureFunction::Variance,
_ => return None,
})
}
/// The callback form of a built-in that already takes a second argument
/// (`topK(arr, 3)`): used only with three or more arguments, so every
/// two-argument call stays the built-in, with or without an alias
/// (`lastN(items as t, 5)` is `lastN(items, 5)`).
pub fn parameterized_closure_form(&self) -> Option<ClosureFunction> {
Some(match self {
InternalFunction::TopK => ClosureFunction::TopK,
InternalFunction::LastN => ClosureFunction::LastN,
InternalFunction::Percentile => ClosureFunction::Percentile,
InternalFunction::PercentileApprox => ClosureFunction::PercentileApprox,
_ => return None,
})
}
}
+169
View File
@@ -0,0 +1,169 @@
//! Shape of a distribution (skewness, excess kurtosis) from exact decimal
//! power sums, so partial sums `(n, Σx, Σx², Σx³, Σx⁴)` can be merged
//! (added) anywhere and still give the same digits.
//!
//! With `mean = s1/n`, the population central moments are
//!
//! ```text
//! m2 = s2/n − mean²
//! m3 = s3/n − 3·mean·(s2/n) + 2·mean³
//! m4 = s4/n − 4·mean·(s3/n) + 6·mean²·(s2/n) − 3·mean⁴
//! ```
//!
//! Every step is a checked `rust_decimal` operation (28 significant
//! digits); an overflow gives `None`, never a panic.
use rust_decimal::{Decimal, MathematicalOps};
/// The power sums `(n, [Σx, Σx², Σx³, Σx⁴])` of `values`; `None` on overflow.
pub fn power_sums<I>(values: I) -> Option<(i64, [Decimal; 4])>
where
I: IntoIterator<Item = Decimal>,
{
let mut n = 0i64;
let mut s = [Decimal::ZERO; 4];
for x in values {
n = n.checked_add(1)?;
let mut power = Decimal::ONE;
for sum in s.iter_mut() {
power = power.checked_mul(x)?;
*sum = sum.checked_add(power)?;
}
}
Some((n, s))
}
/// `(n, mean, s2/n, m2)` when there are at least two values and `m2 > 0`.
fn spread(n: i64, s: &[Decimal; 4]) -> Option<(Decimal, Decimal, Decimal, Decimal)> {
if n < 2 {
return None;
}
let n = Decimal::from(n);
let mean = s[0].checked_div(n)?;
let s2n = s[1].checked_div(n)?;
let m2 = s2n.checked_sub(mean.checked_mul(mean)?)?;
if m2 <= Decimal::ZERO {
return None;
}
Some((n, mean, s2n, m2))
}
/// Decimal places of `skew` and `kurtosis`: Σx⁴ of large values rounds at
/// each add, so a sum taken in another order (a feature store merging time
/// buckets) differs in the last digits; at 12 places both agree.
pub const MOMENT_SCALE: u32 = 12;
fn finish(value: Decimal) -> Decimal {
value
.round_dp_with_strategy(MOMENT_SCALE, rust_decimal::RoundingStrategy::MidpointNearestEven)
.normalize()
}
/// Population skewness `g1 = m3 / m2^(3/2)` (`m2^(3/2)` as `m2·√m2`) from
/// `s = [Σx, Σx², Σx³, Σx⁴]` over `n` values. `None` when `n < 2`, when
/// `m2 ≤ 0` (all values equal) or on overflow.
/// Rounded to [`MOMENT_SCALE`] places.
pub fn skew(n: i64, s: [Decimal; 4]) -> Option<Decimal> {
let (nd, mean, s2n, m2) = spread(n, &s)?;
let s3n = s[2].checked_div(nd)?;
let mean2 = mean.checked_mul(mean)?;
let mean3 = mean2.checked_mul(mean)?;
let m3 = s3n
.checked_sub(Decimal::from(3).checked_mul(mean)?.checked_mul(s2n)?)?
.checked_add(Decimal::TWO.checked_mul(mean3)?)?;
let denominator = m2.checked_mul(m2.sqrt()?)?;
Some(finish(m3.checked_div(denominator)?))
}
/// Excess kurtosis `g2 = m4 / m2² − 3` from `s = [Σx, Σx², Σx³, Σx⁴]` over
/// `n` values. `None` when `n < 2`, when `m2 ≤ 0` or on overflow. Rounded
/// to [`MOMENT_SCALE`] places.
pub fn kurtosis(n: i64, s: [Decimal; 4]) -> Option<Decimal> {
let (nd, mean, s2n, m2) = spread(n, &s)?;
let s3n = s[2].checked_div(nd)?;
let s4n = s[3].checked_div(nd)?;
let mean2 = mean.checked_mul(mean)?;
let mean4 = mean2.checked_mul(mean2)?;
let m4 = s4n
.checked_sub(Decimal::from(4).checked_mul(mean)?.checked_mul(s3n)?)?
.checked_add(Decimal::from(6).checked_mul(mean2)?.checked_mul(s2n)?)?
.checked_sub(Decimal::from(3).checked_mul(mean4)?)?;
let g2 = m4
.checked_div(m2.checked_mul(m2)?)?
.checked_sub(Decimal::from(3))?;
Some(finish(g2))
}
#[cfg(test)]
mod tests {
use super::*;
use rust_decimal_macros::dec;
fn sums(values: &[Decimal]) -> (i64, [Decimal; 4]) {
power_sums(values.iter().copied()).unwrap()
}
fn close(a: Decimal, b: Decimal, tolerance: Decimal) -> bool {
(a - b).abs() <= tolerance
}
#[test]
fn hand_computed() {
// Deviations from the mean 4: −3, −2, −1, 0, 6.
// m2 = 50/5 = 10, m3 = 180/5 = 36, m4 = 1394/5 = 278.8.
let (n, s) = sums(&[dec!(1), dec!(2), dec!(3), dec!(4), dec!(10)]);
assert_eq!(n, 5);
assert_eq!(s, [dec!(20), dec!(130), dec!(1100), dec!(10354)]);
// 36 / (10·√10) = 1.13841995766062...
let g1 = skew(n, s).unwrap();
// 1.13841995766061655952… at 12 places.
assert_eq!(g1, dec!(1.138419957661));
// 278.8 / 100 − 3, exactly.
assert_eq!(kurtosis(n, s), Some(dec!(-0.212)));
}
#[test]
fn symmetric() {
let (n, s) = sums(&[dec!(1), dec!(2), dec!(3)]);
assert_eq!(skew(n, s), Some(Decimal::ZERO));
// m2 = 2/3, m4 = 2/3: (2/3)/(4/9) − 3 = −1.5.
let g2 = kurtosis(n, s).unwrap();
assert!(close(g2, dec!(-1.5), dec!(0.000000000000000000001)), "{g2}");
}
#[test]
fn negative_skew_and_decimals() {
let (n, s) = sums(&[dec!(-1), dec!(-2), dec!(-3), dec!(-4), dec!(-10)]);
let g1 = skew(n, s).unwrap();
assert_eq!(g1, dec!(-1.138419957661));
assert_eq!(kurtosis(n, s), Some(dec!(-0.212)));
// Scaling does not change the shape.
let (n, s) = sums(&[dec!(0.1), dec!(0.2), dec!(0.3), dec!(0.4), dec!(1.0)]);
let g1 = skew(n, s).unwrap();
assert_eq!(g1, dec!(1.138419957661));
// At 12 places the rounding of the scaled sums is gone.
assert_eq!(kurtosis(n, s), Some(dec!(-0.212)));
}
#[test]
fn too_little_or_flat() {
assert_eq!(skew(0, [Decimal::ZERO; 4]), None);
let (n, s) = sums(&[dec!(5)]);
assert_eq!(skew(n, s), None);
assert_eq!(kurtosis(n, s), None);
let (n, s) = sums(&[dec!(5), dec!(5), dec!(5)]);
assert_eq!(skew(n, s), None);
assert_eq!(kurtosis(n, s), None);
}
#[test]
fn overflow_is_none() {
assert_eq!(power_sums([Decimal::MAX]), None);
let big = dec!(10000000000000000000000);
assert_eq!(power_sums([big, Decimal::ONE]), None);
let huge = [Decimal::MAX, Decimal::MAX, Decimal::MAX, Decimal::MAX];
assert_eq!(skew(2, huge), None);
assert_eq!(kurtosis(2, huge), None);
}
}
+320 -3
View File
@@ -1,5 +1,5 @@
use crate::functions::defs::FunctionDefinition;
use crate::functions::{DeprecatedFunction, FunctionKind, InternalFunction};
use crate::functions::defs::{FunctionDefinition, FunctionSignature, StaticFunction};
use crate::functions::{ClosureFunction, DeprecatedFunction, FunctionKind, InternalFunction};
use nohash_hasher::{BuildNoHashHasher, IsEnabled};
use std::cell::RefCell;
use std::collections::HashMap;
@@ -17,6 +17,7 @@ pub struct FunctionRegistry {
Rc<dyn FunctionDefinition>,
BuildNoHashHasher<DeprecatedFunction>,
>,
closure_aggregates: HashMap<ClosureFunction, Rc<dyn FunctionDefinition>>,
}
impl FunctionRegistry {
@@ -32,7 +33,9 @@ impl FunctionRegistry {
FunctionKind::Deprecated(deprecated) => {
Self::INSTANCE.with_borrow(|i| i.deprecated_functions.get(&deprecated).cloned())
}
FunctionKind::Closure(_) => None,
FunctionKind::Closure(closure) => {
Self::INSTANCE.with_borrow(|i| i.closure_aggregates.get(closure).cloned())
}
}
}
@@ -45,9 +48,323 @@ impl FunctionRegistry {
.map(|i| (i.clone(), (&i).into()))
.collect();
let closure_aggregates = ClosureFunction::iter()
.filter_map(|c| Some((c, aggregate::definition(c)?)))
.collect();
Self {
internal_functions,
deprecated_functions,
closure_aggregates,
}
}
}
/// What the callback forms of the aggregates do with the values they
/// collected (projected, filtered, nulls skipped). Empty input: `sum`,
/// `countDistinct` and `countDistinctApprox` are `0`, `unique` is `[]`,
/// the others are `null`. `argMax` and `argMin` collect `[value, by]` pairs.
mod aggregate {
use super::*;
use crate::functions::arguments::Arguments;
use crate::functions::internal::imp;
use crate::functions::moments::{self, power_sums};
use crate::functions::sketch::Hll;
use crate::variable::VariableType as VT;
use crate::vm::date::DynamicVariableExt;
use crate::vm::VmDate;
use crate::Variable;
use anyhow::Context;
use rust_decimal::Decimal;
use std::collections::HashSet;
type Implementation = fn(Arguments) -> anyhow::Result<Variable>;
/// `None` for the callbacks that are no aggregate (`map`, `filter`...).
pub(super) fn definition(kind: ClosureFunction) -> Option<Rc<dyn FunctionDefinition>> {
let (return_type, implementation): (VT, Implementation) = match kind {
ClosureFunction::Sum => (VT::Number, imp::sum),
ClosureFunction::Avg => (VT::Number, avg),
ClosureFunction::Min => (VT::Any, min),
ClosureFunction::Max => (VT::Any, max),
ClosureFunction::Median => (VT::Number, median),
ClosureFunction::Mode => (VT::Any, mode),
ClosureFunction::Stddev => (VT::Number, imp::stddev),
ClosureFunction::Variance => (VT::Number, imp::variance),
ClosureFunction::TopK
| ClosureFunction::LastN
| ClosureFunction::Percentile
| ClosureFunction::PercentileApprox => {
let (return_type, implementation): (VT, Implementation) = match kind {
ClosureFunction::TopK => (VT::Any.array(), imp::top_k),
ClosureFunction::LastN => (VT::Any.array(), imp::last_n),
ClosureFunction::PercentileApprox => (VT::Number, imp::percentile_approx),
_ => (VT::Number, imp::percentile),
};
return Some(Rc::new(StaticFunction {
signature: FunctionSignature {
parameters: vec![VT::Any.array(), VT::Number],
return_type,
},
implementation: Rc::new(implementation),
}));
}
ClosureFunction::CountDistinct => (VT::Number, count_distinct),
ClosureFunction::Unique => (VT::Any.array(), unique),
ClosureFunction::First => (VT::Any, first),
ClosureFunction::Last => (VT::Any, last),
ClosureFunction::ArgMax => (VT::Any, arg_max),
ClosureFunction::ArgMin => (VT::Any, arg_min),
ClosureFunction::Skew => (VT::Number, skew),
ClosureFunction::Kurtosis => (VT::Number, kurtosis),
ClosureFunction::CountDistinctApprox => (VT::Number, count_distinct_approx),
ClosureFunction::All
| ClosureFunction::None
| ClosureFunction::Some
| ClosureFunction::One
| ClosureFunction::Filter
| ClosureFunction::Map
| ClosureFunction::FlatMap
| ClosureFunction::Count => return None,
};
Some(Rc::new(StaticFunction {
signature: FunctionSignature::single(VT::Any.array(), return_type),
implementation: Rc::new(implementation),
}))
}
fn null_if_empty(args: Arguments, f: Implementation) -> anyhow::Result<Variable> {
if args.array(0)?.borrow().is_empty() {
return Ok(Variable::Null);
}
f(args)
}
fn avg(args: Arguments) -> anyhow::Result<Variable> {
null_if_empty(args, imp::avg)
}
fn min(args: Arguments) -> anyhow::Result<Variable> {
null_if_empty(args, imp::min)
}
fn max(args: Arguments) -> anyhow::Result<Variable> {
null_if_empty(args, imp::max)
}
fn median(args: Arguments) -> anyhow::Result<Variable> {
null_if_empty(args, imp::median)
}
/// The most common value (numbers or strings); ties go to the largest.
fn mode(args: Arguments) -> anyhow::Result<Variable> {
null_if_empty(args, imp::mode)
}
/// What `countDistinct` and `unique` compare: scalars as they are
/// (numbers normalized), objects and arrays by a canonical text with
/// object keys sorted, so `{a: 1, b: 2}` and `{b: 2, a: 1}` are one.
#[derive(PartialEq, Eq, Hash)]
enum Key<'a> {
Bool(bool),
Number(rust_decimal::Decimal),
String(&'a str),
Canonical(String),
}
fn key(value: &Variable) -> Key<'_> {
match value {
Variable::Bool(b) => Key::Bool(*b),
Variable::Number(n) => Key::Number(n.normalize()),
Variable::String(s) => Key::String(s.as_str()),
other => {
let mut text = String::new();
canonical(other, &mut text);
Key::Canonical(text)
}
}
}
fn canonical(value: &Variable, out: &mut String) {
use std::fmt::Write;
match value {
Variable::Null => out.push_str("null"),
Variable::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Variable::Number(n) => {
let _ = write!(out, "{}", n.normalize());
}
Variable::String(s) => {
let _ = write!(out, "{:?}", s.as_str());
}
Variable::Array(items) => {
out.push('[');
for (i, item) in items.borrow().iter().enumerate() {
if i > 0 {
out.push(',');
}
canonical(item, out);
}
out.push(']');
}
Variable::Object(fields) => {
let fields = fields.borrow();
let mut entries: Vec<_> = fields.iter().collect();
entries.sort_by(|a, b| a.0.cmp(b.0));
out.push('{');
for (i, (name, item)) in entries.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
let _ = write!(out, "{:?}:", name.as_str());
canonical(item, out);
}
out.push('}');
}
Variable::Dynamic(dynamic) => {
let _ = write!(out, "{}:{dynamic}", dynamic.type_name());
}
}
}
fn distinct(args: &Arguments) -> anyhow::Result<Vec<Variable>> {
let array = args.array(0)?;
let items = array.borrow();
let mut seen = HashSet::with_capacity(items.len());
Ok(items
.iter()
.filter(|item| !matches!(item, Variable::Null) && seen.insert(key(item)))
.cloned()
.collect())
}
fn count_distinct(args: Arguments) -> anyhow::Result<Variable> {
Ok(Variable::Number(distinct(&args)?.len().into()))
}
fn unique(args: Arguments) -> anyhow::Result<Variable> {
Ok(Variable::from_array(distinct(&args)?))
}
fn first(args: Arguments) -> anyhow::Result<Variable> {
Ok(args
.array(0)?
.borrow()
.first()
.cloned()
.unwrap_or(Variable::Null))
}
fn last(args: Arguments) -> anyhow::Result<Variable> {
Ok(args
.array(0)?
.borrow()
.last()
.cloned()
.unwrap_or(Variable::Null))
}
fn numbers(args: &Arguments) -> anyhow::Result<Vec<Decimal>> {
let array = args.array(0)?;
let items = array.borrow();
items
.iter()
.map(|item| item.as_number())
.collect::<Option<Vec<_>>>()
.context("Expected a number array")
}
/// What `argMax` and `argMin` rank by: numbers, or dates (as `min` and
/// `max` compare them).
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Rank {
Number(Decimal),
Date(VmDate),
}
fn rank(value: &Variable) -> anyhow::Result<Rank> {
match value {
Variable::Number(n) => Ok(Rank::Number(*n)),
Variable::Dynamic(d) => match d.as_date() {
Some(date) => Ok(Rank::Date(date.clone())),
None => anyhow::bail!("Expected numbers or dates to rank by"),
},
_ => anyhow::bail!("Expected numbers or dates to rank by"),
}
}
/// The value paired with the greatest (`greatest`) or smallest rank;
/// ties go to the last pair. `null` without pairs.
fn arg_extreme(args: Arguments, greatest: bool) -> anyhow::Result<Variable> {
let array = args.array(0)?;
let items = array.borrow();
let mut best: Option<(Rank, Variable)> = None;
for item in items.iter() {
let Variable::Array(pair) = item else {
anyhow::bail!("Expected [value, by] pairs");
};
let pair = pair.borrow();
let [value, by] = pair.as_slice() else {
anyhow::bail!("Expected [value, by] pairs");
};
let by = rank(by)?;
let replaces = match &best {
None => true,
Some((current, _)) => {
if std::mem::discriminant(current) != std::mem::discriminant(&by) {
anyhow::bail!("Cannot rank numbers and dates together");
}
if greatest {
by >= *current
} else {
by <= *current
}
}
};
if replaces {
best = Some((by, value.clone()));
}
}
Ok(best.map_or(Variable::Null, |(_, value)| value))
}
fn arg_max(args: Arguments) -> anyhow::Result<Variable> {
arg_extreme(args, true)
}
fn arg_min(args: Arguments) -> anyhow::Result<Variable> {
arg_extreme(args, false)
}
/// Population skewness and excess kurtosis from exact power sums;
/// `null` below two values, for equal values or on overflow.
fn shape(
args: Arguments,
f: fn(i64, [Decimal; 4]) -> Option<Decimal>,
) -> anyhow::Result<Variable> {
let values = numbers(&args)?;
Ok(power_sums(values)
.and_then(|(n, s)| f(n, s))
.map_or(Variable::Null, Variable::Number))
}
fn skew(args: Arguments) -> anyhow::Result<Variable> {
shape(args, moments::skew)
}
fn kurtosis(args: Arguments) -> anyhow::Result<Variable> {
shape(args, moments::kurtosis)
}
/// HyperLogLog estimate of the distinct scalars (see [`Hll`]); arrays
/// and objects have no stable hash and are skipped.
fn count_distinct_approx(args: Arguments) -> anyhow::Result<Variable> {
let array = args.array(0)?;
let mut hll = Hll::new();
for item in array.borrow().iter() {
hll.insert(item);
}
Ok(Variable::Number(hll.estimate()))
}
}
+683
View File
@@ -0,0 +1,683 @@
//! Mergeable approximate summaries, computed in exact decimals (no floats)
//! so every implementation that follows these rules gets the same digits:
//!
//! - [`Hll`]: HyperLogLog distinct counting (`countDistinctApprox`),
//! - [`DdSketch`]: relative-accuracy quantiles (`percentileApprox`),
//! - [`hash_value`]: the stable value hash both [`Hll`] and hosts use.
use crate::vm::date::DynamicVariableExt;
use crate::Variable;
use chrono::{SecondsFormat, Utc};
use once_cell::sync::Lazy;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::{Decimal, MathematicalOps, RoundingStrategy};
use std::collections::BTreeMap;
use xxhash_rust::xxh3::xxh3_64;
/// Type tag of a number in [`canonical_bytes`].
pub const TAG_NUMBER: u8 = 0x01;
/// Type tag of a string in [`canonical_bytes`].
pub const TAG_STRING: u8 = 0x02;
/// Type tag of a bool in [`canonical_bytes`].
pub const TAG_BOOL: u8 = 0x03;
/// Type tag of a date in [`canonical_bytes`].
pub const TAG_DATE: u8 = 0x04;
/// The canonical bytes of a scalar value: one type-tag byte, then the
/// payload, with nothing in between and no terminator.
///
/// | value | tag | payload |
/// |--------|--------|---------------------------------------------------------------|
/// | number | `0x01` | ASCII of the normalized decimal (see below) |
/// | string | `0x02` | the string's UTF-8 bytes, as they are (no normalization) |
/// | bool | `0x03` | ASCII `true` or `false` |
/// | date | `0x04` | ASCII RFC 3339 in UTC with milliseconds (see below) |
///
/// - **Number**: `rust_decimal`'s `Decimal::normalize()` (trailing fractional
/// zeros stripped, `-0` becomes `0`) printed with `Display`: plain
/// notation, never an exponent, `-` for negatives, no `+`, no leading
/// zeros beyond a single `0` before the point. So `1`, `1.0` and `1.000`
/// are all `1`; `-0.50` is `-0.5`; `0.0001` is `0.0001`; `1e3` is `1000`.
/// - **Date**: the instant converted to UTC and printed as
/// `YYYY-MM-DDTHH:MM:SS.mmmZ` (chrono's `to_rfc3339_opts(Millis, true)`):
/// always exactly three fractional digits, finer precision truncated
/// (not rounded), `Z` for the offset. A date written with any offset or
/// time zone hashes as its UTC instant. An invalid date has no bytes.
/// - **Record** (an object, as a reference reads: `t.merchant`): the bytes
/// of its `id` field, so a record hashes exactly as its id (the key a
/// feature store aggregates). No `id`, or an object `id`: no bytes.
/// - **Null, arrays** and other dynamic values have no canonical bytes
/// (`None`): aggregates skip them.
///
/// The tags keep types apart: the string `"1"`, the number `1` and the
/// bool `true` never collide, nor does a date with its own text.
pub fn canonical_bytes(value: &Variable) -> Option<Vec<u8>> {
let (tag, payload) = match value {
Variable::Number(n) => (TAG_NUMBER, n.normalize().to_string()),
Variable::String(s) => (TAG_STRING, s.as_str().to_string()),
Variable::Bool(b) => (TAG_BOOL, b.to_string()),
Variable::Dynamic(dynamic) => {
let date_time = dynamic.as_date()?.0?;
let text = date_time
.with_timezone(&Utc)
.to_rfc3339_opts(SecondsFormat::Millis, true);
(TAG_DATE, text)
}
// A record (what a reference reads, `t.merchant`) is its `id`: the
// key a feature store aggregates.
Variable::Object(object) => {
let id = object.borrow().get_str("id").cloned()?;
return match id {
Variable::Object(_) => None,
id => canonical_bytes(&id),
};
}
Variable::Null | Variable::Array(_) => return None,
};
let mut bytes = Vec::with_capacity(1 + payload.len());
bytes.push(tag);
bytes.extend_from_slice(payload.as_bytes());
Some(bytes)
}
/// A stable 64-bit hash of a scalar: XXH3-64 (seed 0) of its
/// [`canonical_bytes`]. `None` for null, arrays, records without an `id`
/// and invalid dates.
pub fn hash_value(value: &Variable) -> Option<u64> {
canonical_bytes(value).map(|bytes| xxh3_64(&bytes))
}
/// HyperLogLog precision: the top 12 bits of a hash pick the register.
pub const HLL_PRECISION: u32 = 12;
/// Number of HyperLogLog registers, `2^12`.
pub const HLL_REGISTERS: u32 = 1 << HLL_PRECISION;
/// Largest register value: the 52 low bits all zero.
pub const HLL_MAX_RANK: u8 = (64 - HLL_PRECISION + 1) as u8;
/// HyperLogLog with `p = 12` (`m = 4096` registers), kept sparse: only the
/// registers that saw a value, `index → rank`.
///
/// A hash `h` goes to register `h >> 52`; its rank is the number of
/// leading zeros of the remaining 52 bits (as a 52-bit field) plus one, so
/// 1..=53. A register keeps the largest rank it saw. Merging takes the
/// larger of each register, so merged sketches equal one fed every value.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Hll {
registers: BTreeMap<u16, u8>,
}
impl Hll {
pub fn new() -> Self {
Self::default()
}
/// Restores a sketch from its registers (as [`Hll::registers`] gives
/// them). Rank-0 entries are dropped (an absent register is 0). `None`
/// for an index outside `0..4096` or a rank above 53.
pub fn from_registers(registers: BTreeMap<u16, u8>) -> Option<Self> {
if registers
.iter()
.any(|(&index, &rank)| u32::from(index) >= HLL_REGISTERS || rank > HLL_MAX_RANK)
{
return None;
}
Some(Self {
registers: registers
.into_iter()
.filter(|&(_, rank)| rank > 0)
.collect(),
})
}
/// The registers that saw a value, `index → rank` (rank ≥ 1).
pub fn registers(&self) -> &BTreeMap<u16, u8> {
&self.registers
}
pub fn insert_hash(&mut self, hash: u64) {
let index = (hash >> (64 - HLL_PRECISION)) as u16;
let rest = hash & ((1u64 << (64 - HLL_PRECISION)) - 1);
// The 52-bit field's leading zeros, plus one: 53 when all are zero.
let rank = (rest.leading_zeros() - HLL_PRECISION + 1) as u8;
let register = self.registers.entry(index).or_insert(0);
*register = (*register).max(rank);
}
/// Adds a value by its [`hash_value`]; `false` (and no change) for the
/// values without one (null, arrays, objects).
pub fn insert(&mut self, value: &Variable) -> bool {
match hash_value(value) {
Some(hash) => {
self.insert_hash(hash);
true
}
None => false,
}
}
pub fn merge(&mut self, other: &Hll) {
for (&index, &rank) in &other.registers {
let register = self.registers.entry(index).or_insert(0);
*register = (*register).max(rank);
}
}
/// The estimated number of distinct values, a whole number:
///
/// ```text
/// α = 0.7213 / (1 + 1.079/m)
/// Z = Σ_j 2^−M[j] over all m registers (an absent register is 2^0 = 1)
/// E = α·m² / Z
/// if E ≤ 2.5·m and V > 0: E = m·ln(m/V) (V: registers still 0)
/// ```
///
/// `Z` is summed exactly as the integer `Z·2^53 = Σ_j 2^(53−M[j])`, so
/// `E = (α·m²)·2^53 / (Z·2^53)`. `ln` is `rust_decimal`'s. The result
/// is rounded to an integer half to even (banker's rounding,
/// `RoundingStrategy::MidpointNearestEven`). Empty: `0`.
pub fn estimate(&self) -> Decimal {
self.raw_estimate()
.unwrap_or(Decimal::ZERO)
.round_dp_with_strategy(0, RoundingStrategy::MidpointNearestEven)
.normalize()
}
fn raw_estimate(&self) -> Option<Decimal> {
let m = Decimal::from(HLL_REGISTERS);
let zeros = HLL_REGISTERS - self.registers.len() as u32;
let shift = u32::from(HLL_MAX_RANK);
let scaled_z: u128 = (u128::from(zeros) << shift)
+ self
.registers
.values()
.map(|&rank| 1u128 << (shift - u32::from(rank)))
.sum::<u128>();
let alpha = Decimal::new(7213, 4)
.checked_div(Decimal::ONE.checked_add(Decimal::new(1079, 3).checked_div(m)?)?)?;
let estimate = alpha
.checked_mul(m.checked_mul(m)?)?
.checked_mul(Decimal::from(1u64 << shift))?
.checked_div(Decimal::from_u128(scaled_z)?)?;
if estimate <= Decimal::new(25, 1).checked_mul(m)? && zeros > 0 {
let ratio = m.checked_div(Decimal::from(zeros))?;
return m.checked_mul(ratio.checked_ln()?);
}
Some(estimate)
}
}
/// DDSketch relative accuracy `α`: `0.01`.
pub const DDSKETCH_ACCURACY: Decimal = Decimal::from_parts(1, 0, 0, false, 2);
/// Most buckets per sign before the lowest ones collapse.
pub const DDSKETCH_MAX_BUCKETS: usize = 2048;
/// `γ = (1 + α) / (1 − α) = 101/99`.
static GAMMA: Lazy<Decimal> = Lazy::new(|| Decimal::from(101) / Decimal::from(99));
static LN_GAMMA: Lazy<Decimal> = Lazy::new(|| GAMMA.checked_ln().unwrap_or(Decimal::ONE));
/// DDSketch with relative accuracy `α = 0.01` (`γ = 101/99`, in decimals).
///
/// A positive `x` lands in bucket `i = ceil(ln(x) / ln(γ))` (`ln` is
/// `rust_decimal`'s, `γ` the decimal `101/99`); a negative `x` in the
/// negative store by `|x|`; an exact zero in a separate count. Each store
/// keeps at most 2048 buckets: past that, the lowest-index buckets fold
/// into the lowest kept one. Merging adds the counts (then folds), so
/// merged sketches equal one fed every value.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DdSketch {
positive: BTreeMap<i32, u64>,
negative: BTreeMap<i32, u64>,
zero: u64,
count: u64,
}
impl DdSketch {
pub fn new() -> Self {
Self::default()
}
/// Restores a sketch from its buckets and zero count (as the accessors
/// give them); empty buckets are dropped and the stores fold to 2048.
pub fn from_parts(
positive: BTreeMap<i32, u64>,
negative: BTreeMap<i32, u64>,
zero: u64,
) -> Self {
let mut sketch = Self {
positive: positive.into_iter().filter(|&(_, c)| c > 0).collect(),
negative: negative.into_iter().filter(|&(_, c)| c > 0).collect(),
zero,
count: 0,
};
sketch.count = sketch
.positive
.values()
.chain(sketch.negative.values())
.fold(zero, |total, &c| total.saturating_add(c));
collapse(&mut sketch.positive);
collapse(&mut sketch.negative);
sketch
}
/// Buckets of the positive values, `index → count`.
pub fn positive(&self) -> &BTreeMap<i32, u64> {
&self.positive
}
/// Buckets of the negative values by `|x|`, `index → count`.
pub fn negative(&self) -> &BTreeMap<i32, u64> {
&self.negative
}
/// How many exact zeros were inserted.
pub fn zero_count(&self) -> u64 {
self.zero
}
/// How many values were inserted.
pub fn count(&self) -> u64 {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
/// The bucket of a positive `x`: `ceil(ln(x) / ln(γ))`; `None` for
/// `x ≤ 0`.
pub fn bucket_index(x: Decimal) -> Option<i32> {
if x <= Decimal::ZERO {
return None;
}
x.checked_ln()?.checked_div(*LN_GAMMA)?.ceil().to_i32()
}
/// The value a bucket stands for: `2·γ^i / (γ + 1)`, which for
/// `γ = 101/99` is exactly `0.99·γ^i` (`γ^i` by `rust_decimal`'s
/// `checked_powi`). Saturates at `Decimal::MAX` past the decimal range.
pub fn bucket_value(index: i32) -> Decimal {
GAMMA
.checked_powi(i64::from(index))
.and_then(|power| power.checked_mul(Decimal::new(99, 2)))
.map_or(Decimal::MAX, |value| value.normalize())
}
pub fn insert(&mut self, x: Decimal) {
if x.is_zero() {
self.zero = self.zero.saturating_add(1);
self.count = self.count.saturating_add(1);
return;
}
// `ln` of a positive decimal always exists: no value is lost.
let Some(index) = Self::bucket_index(x.abs()) else {
return;
};
let store = if x.is_sign_negative() {
&mut self.negative
} else {
&mut self.positive
};
let bucket = store.entry(index).or_insert(0);
*bucket = bucket.saturating_add(1);
self.count = self.count.saturating_add(1);
collapse(store);
}
pub fn merge(&mut self, other: &DdSketch) {
for (store, theirs) in [
(&mut self.positive, &other.positive),
(&mut self.negative, &other.negative),
] {
for (&index, &c) in theirs {
let bucket = store.entry(index).or_insert(0);
*bucket = bucket.saturating_add(c);
}
collapse(store);
}
self.zero = self.zero.saturating_add(other.zero);
self.count = self.count.saturating_add(other.count);
}
/// The value at quantile `q` (`0..=1`): with `rank = q·(n − 1)`, walk
/// the negatives from the most negative (highest index) up, then the
/// zeros, then the positives ascending; the first bucket whose running
/// count exceeds `rank` gives the answer (its [`bucket_value`],
/// negated for negatives; zeros give `0`). That is the sketch's
/// estimate of the `⌊rank⌋`-th smallest value (no interpolation).
/// `None` when empty or `q` is outside `0..=1`.
///
/// [`bucket_value`]: DdSketch::bucket_value
pub fn quantile(&self, q: Decimal) -> Option<Decimal> {
if self.count == 0 || q < Decimal::ZERO || q > Decimal::ONE {
return None;
}
let rank = q.checked_mul(Decimal::from(self.count - 1))?;
let mut seen: u64 = 0;
let mut exceeds = |c: u64| {
seen = seen.saturating_add(c);
Decimal::from(seen) > rank
};
for (&index, &c) in self.negative.iter().rev() {
if exceeds(c) {
return Some(-Self::bucket_value(index));
}
}
if self.zero > 0 && exceeds(self.zero) {
return Some(Decimal::ZERO);
}
for (&index, &c) in &self.positive {
if exceeds(c) {
return Some(Self::bucket_value(index));
}
}
// Counts past `u64` saturate: the largest bucket.
match self.positive.last_key_value() {
Some((&index, _)) => Some(Self::bucket_value(index)),
None if self.zero > 0 => Some(Decimal::ZERO),
None => self
.negative
.first_key_value()
.map(|(&index, _)| -Self::bucket_value(index)),
}
}
}
/// Folds the lowest-index buckets into the lowest kept one until at most
/// [`DDSKETCH_MAX_BUCKETS`] remain.
fn collapse(store: &mut BTreeMap<i32, u64>) {
while store.len() > DDSKETCH_MAX_BUCKETS {
let Some((_, c)) = store.pop_first() else {
return;
};
if let Some(mut lowest) = store.first_entry() {
*lowest.get_mut() = lowest.get().saturating_add(c);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DateValue;
use rust_decimal_macros::dec;
fn number(n: Decimal) -> Variable {
Variable::Number(n)
}
#[test]
fn a_record_hashes_as_its_id() {
let record: Variable = serde_json::json!({ "id": "M7", "mcc": "5411" }).into();
let id: Variable = serde_json::json!("M7").into();
assert_eq!(hash_value(&record), hash_value(&id));
let no_id: Variable = serde_json::json!({ "mcc": "5411" }).into();
assert_eq!(hash_value(&no_id), None);
}
#[test]
fn canonical_bytes_rule() {
assert_eq!(canonical_bytes(&number(dec!(1.000))).unwrap(), b"\x011");
assert_eq!(canonical_bytes(&number(dec!(-0.50))).unwrap(), b"\x01-0.5");
assert_eq!(canonical_bytes(&number(dec!(-0.0))).unwrap(), b"\x010");
assert_eq!(canonical_bytes(&number(dec!(1e3))).unwrap(), b"\x011000");
assert_eq!(
canonical_bytes(&number(dec!(0.0001))).unwrap(),
b"\x010.0001"
);
assert_eq!(
canonical_bytes(&Variable::String("héllo".into())).unwrap(),
"\x02héllo".as_bytes()
);
assert_eq!(canonical_bytes(&Variable::Bool(true)).unwrap(), b"\x03true");
assert_eq!(
canonical_bytes(&Variable::Bool(false)).unwrap(),
b"\x03false"
);
let date = DateValue::from_text("2024-03-01T10:20:30.123456+02:00").unwrap();
assert_eq!(
canonical_bytes(&date).unwrap(),
b"\x042024-03-01T08:20:30.123Z"
);
let date = DateValue::from_text("2024-03-01T08:20:30Z").unwrap();
assert_eq!(
canonical_bytes(&date).unwrap(),
b"\x042024-03-01T08:20:30.000Z"
);
assert_eq!(canonical_bytes(&Variable::Null), None);
assert_eq!(
canonical_bytes(&Variable::from_array(vec![number(dec!(1))])),
None
);
}
#[test]
fn hash_stability() {
// XXH3-64, seed 0, of the canonical bytes: fixed across releases.
// The reference vector of XXH3-64 for no input:
assert_eq!(xxh3_64(b""), 0x2d06800538d394c2);
assert_eq!(hash_value(&number(dec!(1))), Some(xxh3_64(b"\x011")));
assert_eq!(hash_value(&number(dec!(1))), Some(HASH_NUMBER_1));
assert_eq!(
hash_value(&Variable::String("1".into())),
Some(HASH_STRING_1)
);
assert_eq!(hash_value(&Variable::Bool(true)), Some(HASH_TRUE));
assert_eq!(
hash_value(&Variable::String("".into())),
Some(HASH_EMPTY_STRING)
);
assert_eq!(hash_value(&number(dec!(1))), hash_value(&number(dec!(1.0))));
assert_eq!(
hash_value(&number(dec!(0))),
hash_value(&number(dec!(-0.00)))
);
let one = hash_value(&number(dec!(1)));
assert_ne!(one, hash_value(&Variable::String("1".into())));
assert_ne!(one, hash_value(&Variable::Bool(true)));
assert_ne!(
hash_value(&Variable::String("true".into())),
hash_value(&Variable::Bool(true))
);
assert_eq!(hash_value(&Variable::Null), None);
}
const HASH_NUMBER_1: u64 = 0x3fdad128b7dfd3e3; // 0x01 '1'
const HASH_STRING_1: u64 = 0x534a116932758ab1; // 0x02 '1'
const HASH_TRUE: u64 = 0x6b7690728bda8e6a; // 0x03 't' 'r' 'u' 'e'
const HASH_EMPTY_STRING: u64 = 0xc9f42e6c9e93dfff; // 0x02
fn hll_of(range: std::ops::Range<i64>) -> Hll {
let mut hll = Hll::new();
for i in range {
assert!(hll.insert(&number(Decimal::from(i))));
}
hll
}
#[test]
fn hll_rank_and_index() {
let mut hll = Hll::new();
hll.insert_hash(0);
hll.insert_hash(u64::MAX);
hll.insert_hash((5u64 << 52) | (1u64 << 51));
hll.insert_hash((5u64 << 52) | 1);
assert_eq!(
hll.registers()
.iter()
.map(|(&i, &r)| (i, r))
.collect::<Vec<_>>(),
vec![(0, 53), (5, 52), (4095, 1)]
);
}
#[test]
fn hll_small_cardinalities() {
assert_eq!(Hll::new().estimate(), dec!(0));
for n in [1i64, 2, 3, 10, 50, 100, 500] {
let estimate = hll_of(0..n).estimate();
let error = (estimate - Decimal::from(n)).abs();
assert!(
error <= Decimal::from(n) / dec!(50) + dec!(1),
"n = {n}: {estimate}"
);
}
assert_eq!(hll_of(0..1).estimate(), dec!(1));
assert_eq!(hll_of(0..10).estimate(), dec!(10));
// Duplicates do not count.
let mut hll = hll_of(0..10);
hll.insert(&number(dec!(3.0)));
hll.insert(&number(dec!(4)));
assert_eq!(hll, hll_of(0..10));
}
#[test]
fn hll_large_cardinality() {
let n = 100_000i64;
let estimate = hll_of(0..n).estimate();
let error = (estimate - Decimal::from(n)).abs() / Decimal::from(n);
assert!(error <= dec!(0.03), "{estimate}");
}
#[test]
fn hll_merge_equals_insert_all() {
let mut merged = hll_of(0..3000);
merged.merge(&hll_of(2000..7000));
assert_eq!(merged, hll_of(0..7000));
assert_eq!(merged.estimate(), hll_of(0..7000).estimate());
let restored = Hll::from_registers(merged.registers().clone()).unwrap();
assert_eq!(restored, merged);
assert_eq!(Hll::from_registers(BTreeMap::from([(4096, 1)])), None);
assert_eq!(Hll::from_registers(BTreeMap::from([(1, 54)])), None);
}
/// `α`, plus the last digits a decimal `γ^i` may round.
const TOLERANCE: Decimal = dec!(0.01000000000000000001);
fn exact_quantile(values: &[Decimal], q: Decimal) -> Decimal {
let mut sorted = values.to_vec();
sorted.sort();
let rank = (q * Decimal::from(sorted.len() - 1)).floor();
sorted[rank.to_usize().unwrap()]
}
fn sketch_of(values: &[Decimal]) -> DdSketch {
let mut sketch = DdSketch::new();
for &x in values {
sketch.insert(x);
}
sketch
}
fn spread() -> Vec<Decimal> {
let mut values = Vec::new();
for i in 1..=500i64 {
// 0.01 .. ~5000, mixed magnitudes.
values.push(Decimal::from(i * i) / dec!(50));
values.push(-Decimal::from(i * 7 % 113) / dec!(3));
if i % 25 == 0 {
values.push(Decimal::ZERO);
}
}
values.push(dec!(123456789.123));
values.push(dec!(0.000001));
values
}
#[test]
fn ddsketch_relative_accuracy() {
let values = spread();
let sketch = sketch_of(&values);
assert_eq!(sketch.count(), values.len() as u64);
assert_eq!(sketch.zero_count(), 24);
for q in 0..=100i64 {
let q = Decimal::new(q, 2);
let exact = exact_quantile(&values, q);
let approx = sketch.quantile(q).unwrap();
if exact.is_zero() {
assert_eq!(approx, Decimal::ZERO, "q = {q}");
continue;
}
let error = ((approx - exact) / exact).abs();
assert!(error <= TOLERANCE, "q = {q}: {approx} vs {exact}");
}
assert_eq!(sketch.quantile(dec!(1.5)), None);
assert_eq!(sketch.quantile(dec!(-0.1)), None);
assert_eq!(DdSketch::new().quantile(dec!(0.5)), None);
}
#[test]
fn ddsketch_buckets() {
assert_eq!(DdSketch::bucket_index(dec!(1)), Some(0));
assert_eq!(DdSketch::bucket_index(dec!(1.01)), Some(1));
assert_eq!(DdSketch::bucket_index(dec!(0)), None);
assert_eq!(DdSketch::bucket_value(0), dec!(0.99));
let one_bucket = DdSketch::bucket_value(1);
assert!((one_bucket - dec!(1.01)).abs() < dec!(0.000000000000000000000001));
assert!(DdSketch::bucket_index(Decimal::MAX).is_some());
assert!(DdSketch::bucket_index(dec!(0.0000000000000000000000000001)).is_some());
for x in [Decimal::MAX, dec!(0.0000000000000000000000000001)] {
let approx = sketch_of(&[x]).quantile(dec!(0.5)).unwrap();
assert!(((approx - x) / x).abs() <= TOLERANCE, "{x}: {approx}");
}
let five = DdSketch::bucket_value(DdSketch::bucket_index(dec!(5)).unwrap());
assert_eq!(sketch_of(&[dec!(-5)]).quantile(dec!(0)), Some(-five));
}
#[test]
fn ddsketch_merge_equals_insert_all() {
let values = spread();
let (left, right) = values.split_at(values.len() / 3);
let mut merged = sketch_of(left);
merged.merge(&sketch_of(right));
assert_eq!(merged, sketch_of(&values));
let restored = DdSketch::from_parts(
merged.positive().clone(),
merged.negative().clone(),
merged.zero_count(),
);
assert_eq!(restored, merged);
}
#[test]
fn ddsketch_collapses_lowest_buckets() {
// γ^i for 3000 consecutive buckets: 1e-13 .. 1e13.
let mut sketch = DdSketch::new();
let mut values = Vec::new();
for i in -1500..1500i32 {
let x = DdSketch::bucket_value(i);
values.push(x);
sketch.insert(x);
sketch.insert(-x);
}
assert_eq!(sketch.positive().len(), DDSKETCH_MAX_BUCKETS);
assert_eq!(sketch.negative().len(), DDSKETCH_MAX_BUCKETS);
assert_eq!(sketch.count(), 6000);
let lowest = *sketch.positive().keys().next().unwrap();
assert_eq!(sketch.positive()[&lowest], 3000 - 2047);
// The upper quantiles stay accurate.
let all: Vec<Decimal> = values.iter().flat_map(|&x| [x, -x]).collect();
for q in [dec!(0.75), dec!(0.9), dec!(0.99), dec!(1)] {
let exact = exact_quantile(&all, q);
let approx = sketch.quantile(q).unwrap();
let error = ((approx - exact) / exact).abs();
assert!(error <= TOLERANCE, "q = {q}: {approx} vs {exact}");
}
// Folding is the same whether merged or inserted.
let mut merged = DdSketch::new();
for chunk in values.chunks(700) {
let mut part = DdSketch::new();
for &x in chunk {
part.insert(x);
part.insert(-x);
}
merged.merge(&part);
}
assert_eq!(merged.positive(), sketch.positive());
}
}
+86 -4
View File
@@ -189,6 +189,11 @@ impl Completions {
if let VariableType::Object(obj) = resolved_data {
for (key, val) in Self::sorted_fields(&obj.borrow()) {
// A `$root` key types `$root` (completed below), it is no variable.
if key.as_ref() == "$root" {
continue;
}
completions.push(Completion {
label: key.to_string(),
kind: CompletionKind::Variable,
@@ -213,8 +218,11 @@ impl Completions {
follow: None,
});
// The callback forms of `sum`, `avg`, ... share the built-in's name:
// one completion each, described with its callback form.
completions.extend(
InternalFunction::iter()
.filter(|f| f.closure_form().is_none() && f.parameterized_closure_form().is_none())
.map(FunctionKind::Internal)
.chain(ClosureFunction::iter().map(FunctionKind::Closure))
.map(|fk| Self::function(fk, None)),
@@ -246,7 +254,9 @@ impl Completions {
let info = function_info(&fk);
let detail = function_signature(&fk);
let boost = boost_override.or(match &fk {
// Aggregates rank with the built-ins, most of which they extend.
FunctionKind::Internal(_) => Some(10),
FunctionKind::Closure(c) if c.is_aggregate() => Some(10),
FunctionKind::Closure(_) => None,
FunctionKind::Deprecated(_) => Some(-20),
});
@@ -340,6 +350,9 @@ fn function_info(fk: &FunctionKind) -> String {
InternalFunction::Split => {
"Splits a string into an array of substrings using the specified delimiter"
}
InternalFunction::Join => {
"Joins the items into a string with the separator (default `,`); null items are skipped"
}
InternalFunction::Abs => "Returns the absolute value of a number",
InternalFunction::Sum => "Returns the sum of all elements in the input array",
InternalFunction::Avg => "Calculates the average of all elements in the input array",
@@ -351,7 +364,17 @@ fn function_info(fk: &FunctionKind) -> String {
InternalFunction::Median => {
"Calculates the median value of all elements in the input array"
}
InternalFunction::Mode => "Finds the mode(s) of the input array",
InternalFunction::Mode => "Most common value (number or string) of the input array",
InternalFunction::Stddev => "Sample standard deviation of the input array",
InternalFunction::Variance => "Sample variance of the input array",
InternalFunction::Percentile => {
"Value at a percentile (0 to 1) of the input array, interpolated"
}
InternalFunction::PercentileApprox => {
"Approximate value at a percentile (0 to 1) of the input array (1% relative error)"
}
InternalFunction::TopK => "The k most frequent values, most frequent first",
InternalFunction::LastN => "The last n values, the last one first",
InternalFunction::Floor => "Rounds a number down to the nearest integer",
InternalFunction::Ceil => "Rounds a number up to the nearest integer",
InternalFunction::Round => "Rounds a number to a specified number of decimal places",
@@ -411,7 +434,32 @@ fn function_info(fk: &FunctionKind) -> String {
}
ClosureFunction::Map => "Creates a new array by transforming each element",
ClosureFunction::FlatMap => "Maps each element then flattens the result",
ClosureFunction::Count => "Counts elements that satisfy the condition",
ClosureFunction::Count => "Counts elements, or those that satisfy the condition",
ClosureFunction::Sum => "Sums the numbers, or a projection of matching elements",
ClosureFunction::Avg => "Averages the numbers, or a projection of matching elements",
ClosureFunction::Min => "Smallest value, or of a projection of matching elements",
ClosureFunction::Max => "Largest value, or of a projection of matching elements",
ClosureFunction::Median => "Median, or of a projection of matching elements",
ClosureFunction::Mode => "Most common value, or of a projection of matching elements",
ClosureFunction::Stddev => {
"Sample standard deviation, or of a projection of matching elements"
}
ClosureFunction::Variance => "Sample variance, or of a projection of matching elements",
ClosureFunction::TopK => "The k most frequent values, or of a projection of matching elements",
ClosureFunction::LastN => "The last n values, or of a projection of matching elements, the last one first",
ClosureFunction::Percentile => {
"Value at a percentile (0 to 1) of the numbers, or of a projection of matching elements"
}
ClosureFunction::CountDistinct => "Counts distinct non-null values",
ClosureFunction::Unique => "Distinct non-null values, in first-seen order",
ClosureFunction::First => "first(items) — first non-null item; first(items, cond) — first matching item; first(items, value) — first non-null value; first(items, value, cond) — its value at the first matching item",
ClosureFunction::Last => "last(items) — last non-null item; last(items, cond) — last matching item; last(items, value) — last non-null value; last(items, value, cond) — its value at the last matching item",
ClosureFunction::ArgMax => "argMax(items, by) — the item with the greatest by (number or date); argMax(items, value, by, cond?) — its value; ties go to the last",
ClosureFunction::ArgMin => "argMin(items, by) — the item with the smallest by (number or date); argMin(items, value, by, cond?) — its value; ties go to the last",
ClosureFunction::Skew => "Population skewness, or of a projection of matching elements",
ClosureFunction::Kurtosis => "Excess kurtosis (population), or of a projection of matching elements",
ClosureFunction::CountDistinctApprox => "Approximate count of distinct non-null values (HyperLogLog, ~1.6% error)",
ClosureFunction::PercentileApprox => "Approximate value at a percentile (0 to 1) of the numbers, or of a projection of matching elements (1% relative error)",
},
};
s.to_string()
@@ -431,6 +479,7 @@ fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> {
InternalFunction::Matches | InternalFunction::Extract => vec!["str", "pattern"],
InternalFunction::FuzzyMatch => vec!["haystack", "needle"],
InternalFunction::Split => vec!["str", "delimiter"],
InternalFunction::Join => vec!["arr", "separator"],
InternalFunction::Abs | InternalFunction::Floor | InternalFunction::Ceil => {
vec!["num"]
}
@@ -439,7 +488,12 @@ fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> {
| InternalFunction::Min
| InternalFunction::Max
| InternalFunction::Median
| InternalFunction::Mode => vec!["arr"],
| InternalFunction::Mode
| InternalFunction::Stddev
| InternalFunction::Variance => vec!["arr"],
InternalFunction::Percentile | InternalFunction::PercentileApprox => vec!["arr", "q"],
InternalFunction::TopK => vec!["arr", "k"],
InternalFunction::LastN => vec!["arr", "n"],
InternalFunction::Rand => vec!["max"],
InternalFunction::Round | InternalFunction::Trunc => vec!["num", "digits"],
InternalFunction::IsNumeric
@@ -512,8 +566,36 @@ fn function_signature(fk: &FunctionKind) -> String {
"<T, U>(array: T[], callback: Callback<T, U[]>) -> U[]".to_string()
}
ClosureFunction::Count => {
"<T>(array: T[], callback: Callback<T, boolean>) -> number".to_string()
"<T>(array: T[], callback?: Callback<T, boolean>) -> number".to_string()
}
ClosureFunction::Sum
| ClosureFunction::Avg
| ClosureFunction::Median
| ClosureFunction::Stddev
| ClosureFunction::Variance => "<T>(array: number[] | T[], projection?: Callback<T, number>, filter?: Callback<T, boolean>) -> number".to_string(),
ClosureFunction::Mode => "<T, U>(array: U[] | T[], projection?: Callback<T, U>, filter?: Callback<T, boolean>) -> U".to_string(),
ClosureFunction::TopK | ClosureFunction::LastN => "<T, U>(array: U[] | T[], projection?: Callback<T, U>, n: number, filter?: Callback<T, boolean>) -> U[]".to_string(),
ClosureFunction::Percentile => "<T>(array: number[] | T[], projection?: Callback<T, number>, q: number, filter?: Callback<T, boolean>) -> number".to_string(),
ClosureFunction::Min | ClosureFunction::Max => "<T, U>(array: U[] | T[], projection?: Callback<T, U>, filter?: Callback<T, boolean>) -> U".to_string(),
ClosureFunction::CountDistinct => {
"<T, U>(array: T[], projection?: Callback<T, U>, filter?: Callback<T, boolean>) -> number".to_string()
}
ClosureFunction::Unique => {
"<T, U>(array: T[], projection?: Callback<T, U>, filter?: Callback<T, boolean>) -> U[]".to_string()
}
ClosureFunction::First | ClosureFunction::Last => {
"<T, U>(array: T[], conditionOrProjection?: Callback<T, boolean | U>, filter?: Callback<T, boolean>) -> T | U".to_string()
}
ClosureFunction::ArgMax | ClosureFunction::ArgMin => {
"<T, U>(array: T[], projection?: Callback<T, U>, by: Callback<T, number | date>, filter?: Callback<T, boolean>) -> T | U".to_string()
}
ClosureFunction::Skew | ClosureFunction::Kurtosis => {
"<T>(array: number[] | T[], projection?: Callback<T, number>, filter?: Callback<T, boolean>) -> number".to_string()
}
ClosureFunction::CountDistinctApprox => {
"<T, U>(array: T[], projection?: Callback<T, U>, filter?: Callback<T, boolean>) -> number".to_string()
}
ClosureFunction::PercentileApprox => "<T>(array: number[] | T[], projection?: Callback<T, number>, q: number, filter?: Callback<T, boolean>) -> number".to_string(),
},
}
}
+42 -31
View File
@@ -679,7 +679,6 @@ impl<'a> DependencyResolutionWalker<'a> {
if let FunctionKind::Closure(_) = kind {
if arguments.len() >= 2 {
let collection_node = arguments[0];
let closure_node = arguments[1];
let collection_info = self.extract_path_with_spans(collection_node);
let collection_source = collection_info
@@ -687,44 +686,52 @@ impl<'a> DependencyResolutionWalker<'a> {
.map(|(p, _)| p.clone())
.or_else(|| Self::collection_source_path(collection_node));
let (alias, inner_reads, inner_refs) = match closure_node {
Node::Closure { body, alias } => {
let mut inner_scope = scope.clone();
inner_scope.locals.insert(Variable::dollar_key_rc());
inner_scope.pointer_collection = collection_source
.as_ref()
.filter(|source| !scope.is_local(source))
.map(|source| scope.expand_alias_root(source));
// Every callback (an aggregate's projection and its
// filter) reads through the same items.
let mut alias_found: Option<Rc<str>> = None;
let mut inner_reads = Vec::new();
let mut inner_refs = Vec::new();
// A parameter (`topK`'s count) reads the outer scope,
// once; resolved after the iteration.
let mut parameters = Vec::new();
for &closure_node in &arguments[1..] {
let Node::Closure { body, alias } = closure_node else {
parameters.push(closure_node);
continue;
};
match (alias, collection_source.as_ref()) {
(Some(alias_name), Some(source)) => {
let expanded = scope.expand_alias_root(source);
if scope.is_local(&expanded) {
inner_scope
.unresolved_aliases
.insert(Rc::from(*alias_name));
} else {
inner_scope
.aliases
.insert(Rc::from(*alias_name), expanded);
}
}
(Some(alias_name), None) => {
let mut inner_scope = scope.clone();
inner_scope.locals.insert(Variable::dollar_key_rc());
inner_scope.pointer_collection = collection_source
.as_ref()
.filter(|source| !scope.is_local(source))
.map(|source| scope.expand_alias_root(source));
match (alias, collection_source.as_ref()) {
(Some(alias_name), Some(source)) => {
let expanded = scope.expand_alias_root(source);
if scope.is_local(&expanded) {
inner_scope
.unresolved_aliases
.insert(Rc::from(*alias_name));
} else {
inner_scope.aliases.insert(Rc::from(*alias_name), expanded);
}
_ => {}
}
let (reads, refs) =
Self::walk_inner(body, &mut inner_scope, self.metadata);
(alias.map(|a| Rc::from(a)), reads, refs)
(Some(alias_name), None) => {
inner_scope.unresolved_aliases.insert(Rc::from(*alias_name));
}
_ => {}
}
_ => {
self.resolve(closure_node, scope);
return;
let (reads, refs) =
Self::walk_inner(body, &mut inner_scope, self.metadata);
if alias_found.is_none() {
alias_found = alias.map(Rc::from);
}
};
inner_reads.extend(reads);
inner_refs.extend(refs);
}
let alias = alias_found;
match collection_info {
Some((collection, spans)) if !scope.is_local(&collection) => {
@@ -765,6 +772,10 @@ impl<'a> DependencyResolutionWalker<'a> {
}
}
}
for parameter in parameters {
self.resolve(parameter, scope);
}
} else {
for arg in arguments.iter() {
self.resolve(arg, scope);
+15 -1
View File
@@ -1,5 +1,7 @@
use crate::compiler::CompilerError;
use crate::intellisense::type_provider::TypesProvider;
use crate::intellisense::type_provider::{
nullable_condition_message, TypesProvider, NULLABLE_CONDITION,
};
use crate::lexer::{LexerError, Operator};
use crate::parser::AstNodeError;
use crate::parser::Node;
@@ -239,6 +241,7 @@ pub(crate) fn collect_parser_diagnostics(ast: &Node, diagnostics: &mut Vec<Diagn
}
pub(crate) fn collect_type_diagnostics(
source: &str,
ast: &Node,
type_data: &TypesProvider,
metadata: &HashMap<usize, NodeMetadata, BuildNoHashHasher<usize>>,
@@ -273,6 +276,17 @@ pub(crate) fn collect_type_diagnostics(
diagnostic.code = Some(code);
diagnostic.args = args.clone();
}
// Named as written (`(a or b)`, `x["k"]`), not only as a path.
if diagnostic.code == Some(NULLABLE_CONDITION) {
let written = source
.get(span.0 as usize..span.1 as usize)
.map(str::trim)
.filter(|text| !text.is_empty());
if let (Some(written), Some(ty)) = (written, diagnostic.args.get("type")) {
diagnostic.message = nullable_condition_message(Some(written), ty);
diagnostic.args.insert("operand", written.to_string());
}
}
collected.borrow_mut().push(diagnostic);
});
diagnostics.extend(collected.into_inner());
+2 -2
View File
@@ -219,7 +219,7 @@ impl IntelliSense {
.map(|t| t.kind.clone())
.unwrap_or(VariableType::Any);
collect_type_diagnostics(ast, &type_data, &metadata, &mut diagnostics);
collect_type_diagnostics(source, ast, &type_data, &metadata, &mut diagnostics);
let dep_result = DependencyResolutionWalker::walk(ast, &metadata);
@@ -466,7 +466,7 @@ impl IntelliSense {
};
let type_data = TypesProvider::generate(ast, scope, self.strict);
collect_type_diagnostics(ast, &type_data, &metadata, &mut diagnostics);
collect_type_diagnostics(source, ast, &type_data, &metadata, &mut diagnostics);
let dep_result = DependencyResolutionWalker::walk_with_locals(ast, &metadata, &["$"]);
+352 -38
View File
@@ -65,16 +65,36 @@ pub struct TypesProvider {
types: HashMap<usize, TypeInfo>,
codes: HashMap<usize, ErrorCode>,
strict: bool,
/// Paths known not to be null here (`x` in `x != null and x`, in the
/// `else` of `x == null ? … : x`).
narrowed: Vec<String>,
}
pub(crate) type ErrorCode = (&'static str, DiagnosticArgs);
/// A `bool?` where a bool is required: a null condition fails at run time.
pub(crate) const NULLABLE_CONDITION: &str = "type.nullable-condition";
/// The message for a `bool?` condition, naming the operand (its source
/// text, else its path) when known.
pub(crate) fn nullable_condition_message(operand: Option<&str>, ty: &str) -> String {
match operand {
Some(x) => format!(
"`{x}` may be null (`{ty}`): a null condition fails; write `{x} == true`, `{x} ?? false`, or `{x} == null ? … : …`."
),
None => format!(
"Condition may be null (`{ty}`): a null condition fails; compare with `== true` or add `?? false`."
),
}
}
impl TypesProvider {
pub fn generate(root: &Node, scope: IntelliSenseScope, strict: bool) -> Self {
let mut s = Self {
types: HashMap::new(),
codes: HashMap::new(),
strict,
narrowed: Vec::new(),
};
s.determine(root, scope);
@@ -135,6 +155,104 @@ impl TypesProvider {
)
}
/// A `bool?` where a bool is required (a condition, an operand of
/// `and`/`or`/`not`, a callback's condition): a null fails at run time.
fn nullable_condition(&mut self, operand: &Node, ty: &VariableType) -> bool {
let VariableType::Nullable(inner) = ty else {
return false;
};
if !matches!(inner.as_ref(), VariableType::Bool) {
return false;
}
let target = match operand {
Node::Closure { body, .. } => *body,
other => other,
};
let path = Self::path_of(target);
let ty = ty.to_string();
let message = nullable_condition_message(path.as_deref(), &ty);
let mut args = DiagnosticArgs::from([("type", ty)]);
if let Some(path) = path {
args.insert("operand", path);
}
self.set_coded_error(target, message, (NULLABLE_CONDITION, args));
true
}
/// The data path a node reads (`a.b`, `#.c`, `$root.d`), if it is one.
fn path_of(node: &Node) -> Option<String> {
match node {
Node::Parenthesized(inner) => Self::path_of(inner),
Node::Identifier(name) => Some(name.to_string()),
Node::Pointer => Some("#".to_string()),
Node::Root => Some("$root".to_string()),
Node::Member {
node,
property: Node::String(key),
} => Some(format!("{}.{key}", Self::path_of(node)?)),
_ => None,
}
}
/// The paths not null when `node` is `truthy`: `x != null`,
/// `x == true`, through `and` (when true), `or` (when false) and `not`.
fn non_null_when(node: &Node, truthy: bool, out: &mut Vec<String>) {
match node {
Node::Parenthesized(inner) => Self::non_null_when(inner, truthy, out),
Node::Unary {
node,
operator: Operator::Logical(LogicalOperator::Not),
} => Self::non_null_when(node, !truthy, out),
Node::Binary {
left,
operator: Operator::Logical(logical),
right,
} => match (logical, truthy) {
(LogicalOperator::And, true) | (LogicalOperator::Or, false) => {
Self::non_null_when(left, truthy, out);
Self::non_null_when(right, truthy, out);
}
_ => {}
},
Node::Binary {
left,
operator: Operator::Comparison(comparison),
right,
} => {
let (value, other) = match (left, right) {
(value, other @ (Node::Null | Node::Bool(_))) => (value, other),
(other @ (Node::Null | Node::Bool(_)), value) => (value, other),
_ => return,
};
let holds = match (comparison, other) {
(ComparisonOperator::NotEqual, Node::Null) => truthy,
(ComparisonOperator::Equal, Node::Null) => !truthy,
(ComparisonOperator::Equal, Node::Bool(_)) => truthy,
_ => false,
};
if let Some(path) = holds.then(|| Self::path_of(value)).flatten() {
out.push(path);
}
}
_ => {}
}
}
/// `determine` with the paths `condition` proves not null when `truthy`.
fn determine_narrowed(
&mut self,
node: &Node,
scope: IntelliSenseScope,
condition: &Node,
truthy: bool,
) -> TypeInfo {
let depth = self.narrowed.len();
Self::non_null_when(condition, truthy, &mut self.narrowed);
let ty = self.determine(node, scope);
self.narrowed.truncate(depth);
ty
}
fn maybe_nullable(kind: VariableType, nullable: bool) -> TypeInfo {
if nullable
&& !matches!(
@@ -176,7 +294,16 @@ impl TypesProvider {
}
Node::Pointer => V(scope.pointer_data.clone()),
Node::Root => V(scope.root_data.clone()),
// A host may give `$root` its own type: a `$root` key in the data
// (no expression can name such a key, `$root` being its own token).
Node::Root => V(match &scope.root_data {
VariableType::Object(fields) => fields
.borrow()
.get("$root")
.cloned()
.unwrap_or_else(|| scope.root_data.clone()),
_ => scope.root_data.clone(),
}),
Node::Slice { node, from, to } => {
let node_type = self.determine(node, scope.clone());
@@ -340,7 +467,15 @@ impl TypesProvider {
operator,
} => {
let left_type = self.determine(left, scope.clone());
let right_type = self.determine(right, scope.clone());
let right_type = match operator {
Operator::Logical(LogicalOperator::And) => {
self.determine_narrowed(right, scope.clone(), left, true)
}
Operator::Logical(LogicalOperator::Or) => {
self.determine_narrowed(right, scope.clone(), left, false)
}
_ => self.determine(right, scope.clone()),
};
match operator {
Operator::Arithmetic(arith) => match arith {
@@ -367,7 +502,16 @@ impl TypesProvider {
},
Operator::Logical(l) => match l {
LogicalOperator::And | LogicalOperator::Or | LogicalOperator::Not => {
match (left_type.deref(), right_type.deref()) {
let left_null = self.nullable_condition(left, &left_type);
let right_null = self.nullable_condition(right, &right_type);
// Reported above: checked as the bool it holds.
let held = |ty: &TypeInfo, null: bool| match (&ty.kind, null) {
(VariableType::Nullable(inner), true) => inner.as_ref().clone(),
(kind, _) => kind.clone(),
};
let left_held = held(&left_type, left_null);
let right_held = held(&right_type, right_null);
match (left_held, right_held) {
(VariableType::Bool | VariableType::Any, VariableType::Bool | VariableType::Any) => V(VariableType::Bool),
_ => Error(format!(
"Operator `{operator}` cannot be applied to types `{left_type}` and `{right_type}`."
@@ -484,15 +628,17 @@ impl TypesProvider {
on_false,
} => {
let condition_type = self.determine(condition, scope.clone());
if !condition_type.satisfies(&VariableType::Bool) {
if !self.nullable_condition(condition, &condition_type)
&& !condition_type.satisfies(&VariableType::Bool)
{
self.set_error(
condition,
format!("Ternary operator cannot be applied to type `{condition_type}`."),
);
}
let true_type = self.determine(on_true, scope.clone());
let false_type = self.determine(on_false, scope.clone());
let true_type = self.determine_narrowed(on_true, scope.clone(), condition, true);
let false_type = self.determine_narrowed(on_false, scope.clone(), condition, false);
V(true_type.kind.merge(&false_type.kind))
}
@@ -515,7 +661,9 @@ impl TypesProvider {
},
Operator::Logical(logical) => match logical {
LogicalOperator::Not => {
if !node_type.satisfies(&VariableType::Bool) {
if !self.nullable_condition(node, &node_type)
&& !node_type.satisfies(&VariableType::Bool)
{
self.set_error(node, format!("Operator `{operator}` cannot be applied to type `{node_type}`."))
}
@@ -565,7 +713,7 @@ impl TypesProvider {
let mut type_list: Vec<VariableType> = arguments
.iter()
.enumerate()
.map(|(i, n)| match is_closure_kind && i == 1 {
.map(|(i, n)| match is_closure_kind && i >= 1 {
true => VariableType::Any,
false => self.determine(n, scope.clone()).kind,
})
@@ -577,26 +725,41 @@ impl TypesProvider {
.unwrap_or_else(|| Rc::new(VariableType::Any));
let ptr_type_inner = ptr_type.deref().clone();
let alias = match arguments[1] {
Node::Closure { alias, .. } => *alias,
_ => None,
};
for i in 1..arguments.len() {
// A parameter (`topK`'s count) is no callback: it
// reads the outer scope.
let alias = match arguments[i] {
Node::Closure { alias, .. } => *alias,
_ => {
type_list[i] = self.determine(arguments[i], scope.clone()).kind;
continue;
}
};
let mut closure_scope = IntelliSenseScope {
pointer_data: ptr_type_inner.clone(),
current_data: scope.current_data.clone(),
root_data: scope.root_data.clone(),
aliases: scope.aliases.clone(),
};
let mut closure_scope = IntelliSenseScope {
pointer_data: ptr_type_inner.clone(),
current_data: scope.current_data.clone(),
root_data: scope.root_data.clone(),
aliases: scope.aliases.clone(),
};
if let Some(alias_name) = alias {
closure_scope
.aliases
.insert(Rc::from(alias_name), ptr_type_inner);
if let Some(alias_name) = alias {
closure_scope
.aliases
.insert(Rc::from(alias_name), ptr_type_inner.clone());
}
// `#` and the alias are the item here, not what
// they were outside.
let outer = self.narrowed.clone();
self.narrowed.retain(|path| {
let root = path.split('.').next().unwrap_or_default();
root != "#" && alias.is_none_or(|alias| root != alias)
});
let new_type = self.determine(arguments[i], closure_scope);
self.narrowed = outer;
type_list[i] = new_type.kind;
}
let new_type = self.determine(arguments[1], closure_scope);
type_list[1] = new_type.kind;
}
match kind {
@@ -623,8 +786,23 @@ impl TypesProvider {
self.set_coded_error(arguments[i], arg_error, code);
}
// These return null on too little input (`stddev([5])`,
// `percentile([], q)`): nullable in strict mode.
let may_be_null = matches!(
kind,
FunctionKind::Internal(
InternalFunction::Stddev
| InternalFunction::Variance
| InternalFunction::Percentile
| InternalFunction::PercentileApprox
)
);
TypeInfo {
kind: typecheck.return_type,
kind: if may_be_null {
Self::maybe_nullable(typecheck.return_type, self.strict).kind
} else {
typecheck.return_type
},
error: typecheck.general,
}
}
@@ -644,26 +822,131 @@ impl TypesProvider {
);
}
if matches!(
c,
ClosureFunction::All
| ClosureFunction::None
| ClosureFunction::Some
| ClosureFunction::One
| ClosureFunction::Filter
| ClosureFunction::Count
) {
if !type_list[1].satisfies(&VariableType::Bool) {
for i in 1..arguments.len() {
if c.is_predicate(i)
&& !self.nullable_condition(arguments[i], &type_list[i])
&& !type_list[i].satisfies(&VariableType::Bool)
{
self.set_error(
arguments[1],
arguments[i],
format!(
"Callback must return a `bool`, but its return type is `{}`.",
type_list[1]
type_list[i]
),
);
}
}
if let Some(at) = c.parameter().filter(|&at| at < arguments.len()) {
let parameter = &type_list[at];
if !parameter
.satisfies(&VariableType::Nullable(Rc::new(VariableType::Number)))
{
self.set_error(
arguments[at],
format!("Argument of type `{parameter}` is not a `number`."),
);
}
}
// What an aggregate reads: the projection, else the
// items. Nulls are skipped, so never null. Selectors
// return the item itself with one callback that is a
// condition (`first(items, #.active)`) or ranks
// (`argMax(items, #.amount)`), as the VM decides.
let item_type = || {
type_list[0]
.iterator()
.map(|t| t.unwrap_nullable().0.clone())
.unwrap_or(VariableType::Any)
};
let selects_item = arguments.len() == 2
&& match c {
ClosureFunction::First | ClosureFunction::Last => {
matches!(type_list[1].unwrap_nullable().0, VariableType::Bool)
}
ClosureFunction::ArgMax | ClosureFunction::ArgMin => true,
_ => false,
};
let value_type = match type_list.get(1) {
Some(projection) if !selects_item => {
projection.unwrap_nullable().0.clone()
}
_ => item_type(),
};
// Numeric aggregates need numbers (`min`, `max` also dates).
let numeric = match c {
ClosureFunction::Sum
| ClosureFunction::Avg
| ClosureFunction::Median
| ClosureFunction::Stddev
| ClosureFunction::Variance
| ClosureFunction::Percentile
| ClosureFunction::Skew
| ClosureFunction::Kurtosis
| ClosureFunction::PercentileApprox => Some(false),
ClosureFunction::Min | ClosureFunction::Max => Some(true),
_ => None,
};
if let Some(dates) = numeric {
let accepted = match &value_type {
VariableType::Any | VariableType::Number => true,
VariableType::Date => dates,
_ => false,
};
if !accepted {
let expected = if dates {
"`number` or `date`"
} else {
"`number`"
};
self.set_error(
arguments.get(1).copied().unwrap_or(arguments[0]),
format!(
"Aggregate must read a {expected}, but its type is `{value_type}`."
),
);
}
}
// `argMax` and `argMin` rank by numbers or dates.
if c.projections() == 2 {
let by_at = arguments.len().min(3) - 1;
if let Some(by) = type_list.get(by_at).filter(|_| by_at > 0) {
let by = by.unwrap_nullable().0;
if !matches!(
by,
VariableType::Any | VariableType::Number | VariableType::Date
) {
self.set_error(
arguments[by_at],
format!(
"Aggregate must rank by a `number` or `date`, but its type is `{by}`."
),
);
}
}
}
// `countDistinctApprox` hashes scalars, and a record
// (a reference, `t.merchant`) as its id: not lists.
if c == &ClosureFunction::CountDistinctApprox
&& matches!(value_type, VariableType::Array(_))
{
self.set_error(
arguments.get(1).copied().unwrap_or(arguments[0]),
format!(
"Aggregate must read a scalar, but its type is `{value_type}`."
),
);
}
// Empty (or filtered-out) items: `sum` is 0, `count`,
// `countDistinct` and `countDistinctApprox` count, the
// others are null.
let nullable = |kind| Self::maybe_nullable(kind, self.strict);
match c {
ClosureFunction::All => V(VariableType::Bool),
ClosureFunction::Some => V(VariableType::Bool),
@@ -682,6 +965,28 @@ impl TypesProvider {
};
V(VariableType::Array(Rc::new(element)))
}
ClosureFunction::Sum
| ClosureFunction::CountDistinct
| ClosureFunction::CountDistinctApprox => V(VariableType::Number),
ClosureFunction::Avg
| ClosureFunction::Median
| ClosureFunction::Stddev
| ClosureFunction::Variance
| ClosureFunction::Percentile
| ClosureFunction::Skew
| ClosureFunction::Kurtosis
| ClosureFunction::PercentileApprox => nullable(VariableType::Number),
ClosureFunction::TopK | ClosureFunction::LastN => {
V(VariableType::Array(Rc::new(value_type)))
}
ClosureFunction::Mode
| ClosureFunction::Min
| ClosureFunction::Max
| ClosureFunction::First
| ClosureFunction::Last
| ClosureFunction::ArgMax
| ClosureFunction::ArgMin => nullable(value_type),
ClosureFunction::Unique => V(VariableType::Array(Rc::new(value_type))),
}
}
}
@@ -748,6 +1053,15 @@ impl TypesProvider {
node_type.error.replace(error);
}
// Proven not null (`x != null and x`): `x` is its inner type here.
if !self.narrowed.is_empty() && matches!(node, Node::Identifier(_) | Node::Member { .. }) {
if let VariableType::Nullable(inner) = &node_type.kind {
if Self::path_of(node).is_some_and(|path| self.narrowed.contains(&path)) {
node_type.kind = inner.as_ref().clone();
}
}
}
self.set_type(node, node_type.clone());
node_type
}
+11 -2
View File
@@ -6,6 +6,7 @@ use crate::lane::builtins::convert::Convert;
use crate::lane::builtins::dates::Dates;
use crate::lane::builtins::legacy::Legacy;
use crate::lane::builtins::math::Math;
use crate::lane::builtins::registered::Registered;
use crate::lane::builtins::text::Text;
use crate::lane::builtins::{Arg, Builtin, Fail, Out};
use crate::lane::exec::{CallFault, Fault};
@@ -38,7 +39,8 @@ impl Builtins {
D::EndOf => &Legacy::END_OF,
})
}
FunctionKind::Closure(_) => return None,
// A callback aggregate's final step (the collected values in).
FunctionKind::Closure(closure) => return Registered::aggregate(*closure),
};
Some(match function {
F::Len => &Text::LEN,
@@ -59,7 +61,7 @@ impl Builtins {
F::Max => &Math::MAX,
F::Rand => &Math::RAND,
F::Median => &Math::MEDIAN,
F::Mode => &Math::MODE,
F::Mode => &Registered::MODE,
F::Floor => &Math::FLOOR,
F::Ceil => &Math::CEIL,
F::Round => &Math::ROUND,
@@ -75,6 +77,13 @@ impl Builtins {
F::Bool => &Convert::BOOL,
F::Type => &Convert::TYPE,
F::Date => &Convert::DATE,
F::Join => &Registered::JOIN,
F::Stddev => &Registered::STDDEV,
F::Variance => &Registered::VARIANCE,
F::Percentile => &Registered::PERCENTILE,
F::PercentileApprox => &Registered::PERCENTILE_APPROX,
F::TopK => &Registered::TOP_K,
F::LastN => &Registered::LAST_N,
})
}
-18
View File
@@ -4,7 +4,6 @@ use crate::lane::date::DynamicVariableExt;
use crate::variable::Variable;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::{Decimal, RoundingStrategy};
use std::collections::BTreeMap;
pub(crate) struct Math;
@@ -145,23 +144,6 @@ impl Math {
fail: |args| Params::fail(args, Self::ARRAY),
};
pub(crate) const MODE: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
let mut counts = BTreeMap::new();
for n in Self::numbers(&a)? {
*counts.entry(n).or_insert(0usize) += 1;
}
counts
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(n, _)| n)
.ok_or_else(|| "Empty array".to_string())
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
fn extreme(a: &Array) -> Result<Extreme, Fail> {
a.with(|values| {
let numeric = values.first().and_then(Variable::as_number).is_some();

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