From 1a0b04d784c8a77d362ae3e86519faac2c2c9e86 Mon Sep 17 00:00:00 2001 From: Ivan Miletic Date: Thu, 8 Oct 2026 21:06:09 +0200 Subject: [PATCH] fix: continuation --- bindings/nodejs/index.d.ts | 6 ++ bindings/nodejs/src/policy.rs | 13 ++++ core/engine/src/policy/mod.rs | 2 +- core/engine/src/policy/queries/schema.rs | 22 ++++++- core/engine/src/workspace/graph/queries.rs | 60 +++++++++++++++--- core/engine/src/workspace/mod.rs | 2 +- core/engine/src/workspace/slot/scope.rs | 14 ++++- core/engine/src/workspace/types/mod.rs | 1 + core/engine/src/workspace/types/result.rs | 29 +++++++++ core/engine/tests/policy_features.rs | 62 ++++++++++++++++++- .../src/intellisense/type_provider.rs | 11 +++- 11 files changed, 205 insertions(+), 17 deletions(-) diff --git a/bindings/nodejs/index.d.ts b/bindings/nodejs/index.d.ts index aaaf72ab..9d37eed1 100644 --- a/bindings/nodejs/index.d.ts +++ b/bindings/nodejs/index.d.ts @@ -617,6 +617,12 @@ 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 } export interface PolicyInspectResult { diff --git a/bindings/nodejs/src/policy.rs b/bindings/nodejs/src/policy.rs index ccad4648..f002db33 100644 --- a/bindings/nodejs/src/policy.rs +++ b/bindings/nodejs/src/policy.rs @@ -142,6 +142,13 @@ 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, } #[napi(object)] @@ -780,6 +787,12 @@ 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, }) .collect()) } diff --git a/core/engine/src/policy/mod.rs b/core/engine/src/policy/mod.rs index 30f827ec..078cc4e0 100644 --- a/core/engine/src/policy/mod.rs +++ b/core/engine/src/policy/mod.rs @@ -19,7 +19,7 @@ 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, diff --git a/core/engine/src/policy/queries/schema.rs b/core/engine/src/policy/queries/schema.rs index 20fc89e7..c7d35f27 100644 --- a/core/engine/src/policy/queries/schema.rs +++ b/core/engine/src/policy/queries/schema.rs @@ -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 { @@ -159,14 +160,22 @@ impl Db { }) .map(|vp| { let mut visited: HashSet> = HashSet::default(); + let property = &vp.property; InputProperty { path: vp.dotted_path(), resolved_type: DataModelIr::wire_property_type( - &vp.property, + property, entities, &unit.dictionaries, &mut visited, ), + 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(), } }) .collect(); @@ -179,9 +188,18 @@ 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()) + }); result.push(InputProperty { path: target.clone(), resolved_type: entity_type.array(), + optional: hosted, + supplied_by: if hosted { SuppliedBy::Host } else { SuppliedBy::Request }, + default: None, }); } } diff --git a/core/engine/src/workspace/graph/queries.rs b/core/engine/src/workspace/graph/queries.rs index eb99de44..46c92d8f 100644 --- a/core/engine/src/workspace/graph/queries.rs +++ b/core/engine/src/workspace/graph/queries.rs @@ -12,7 +12,7 @@ use crate::workspace::graph::analysis::{ use crate::workspace::reads::ReadView; use crate::policy::queries::scope::VariableTypeScope; -use crate::workspace::types::{InputProperty, OutputProperty, PropertyKind, ScopeRequest}; +use crate::workspace::types::{InputProperty, OutputProperty, PropertyKind, ScopeRequest, SuppliedBy}; impl Db { pub(crate) fn graph_analysis(&self, path: &Arc) -> Option> { @@ -161,6 +161,9 @@ impl Db { pub(crate) fn graph_inputs(&self, path: &str) -> Vec { let path_arc: Arc = 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(); }; @@ -169,9 +172,8 @@ impl Db { let mut properties: Vec = 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)); @@ -180,15 +182,57 @@ impl Db { VariableType::Any => analysis .inferred_inputs .iter() - .map(|path| InputProperty { - path: path.clone(), - resolved_type: VariableType::Any, - }) + .map(|path| InputProperty::request(path.clone(), VariableType::Any)) .collect(), _ => Vec::new(), } } + /// A request typed by an entity, as the caller sends it: the entity's + /// fields, a reference as its id; what the host supplies marked so. + fn graph_entity_inputs(&self, path: &Arc) -> Option> { + let snap = self.snapshot(); + let content = snap.graphs.get(path).cloned()?; + let content = content.as_graph()?; + let target = content.request_target()?; + let entities: HashMap, Arc> = self + .graph_entity_blocks(&content.imports) + .into_iter() + .map(|b| (b.ir.name.clone(), b.ir)) + .collect(); + let dictionaries: HashMap, Arc> = self + .graph_dictionary_blocks(&content.imports) + .into_iter() + .map(|b| (b.ir.name.clone(), b.ir)) + .collect(); + let entity = entities.get(&target)?; + let mut properties: Vec = entity + .properties + .iter() + .map(|property| { + let mut visited: HashSet> = HashSet::default(); + InputProperty { + path: property.name.clone(), + resolved_type: DataModelIr::wire_property_type( + property, + &entities, + &dictionaries, + &mut visited, + ), + 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(), + } + }) + .collect(); + properties.sort_by(|a, b| a.path.cmp(&b.path)); + Some(properties) + } + pub(crate) fn graph_outputs(&self, path: &str) -> Vec { let path_arc: Arc = Arc::from(path); let Some(analysis) = self.graph_analysis(&path_arc) else { diff --git a/core/engine/src/workspace/mod.rs b/core/engine/src/workspace/mod.rs index 75c16cbe..7fdc8678 100644 --- a/core/engine/src/workspace/mod.rs +++ b/core/engine/src/workspace/mod.rs @@ -26,7 +26,7 @@ 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, diff --git a/core/engine/src/workspace/slot/scope.rs b/core/engine/src/workspace/slot/scope.rs index 13e729cc..993fca09 100644 --- a/core/engine/src/workspace/slot/scope.rs +++ b/core/engine/src/workspace/slot/scope.rs @@ -122,12 +122,18 @@ impl Db { CursorTarget::ModelInput { .. } => { Some(CursorScope::value(enriched.declared_scope(), None)) } - // What a call sends: the instance, as its derived features read it. - CursorTarget::ModelRequest { .. } => Some(CursorScope::value(object(own()), 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.insert(Rc::from("response"), 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` @@ -144,7 +150,9 @@ impl Db { if model.get("inputs").is_some() { Some(CursorScope::condition(enriched.declared_scope())) } else { - Some(CursorScope::condition(object(own()))) + let mut fields = own(); + fields.insert(Rc::from("$root"), enriched.declared_scope()); + Some(CursorScope::condition(object(fields))) } } _ => None, diff --git a/core/engine/src/workspace/types/mod.rs b/core/engine/src/workspace/types/mod.rs index 2a946dac..74122712 100644 --- a/core/engine/src/workspace/types/mod.rs +++ b/core/engine/src/workspace/types/mod.rs @@ -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}; diff --git a/core/engine/src/workspace/types/result.rs b/core/engine/src/workspace/types/result.rs index 712b6bea..9d252018 100644 --- a/core/engine/src/workspace/types/result.rs +++ b/core/engine/src/workspace/types/result.rs @@ -113,6 +113,35 @@ pub struct WriteConflict { pub struct InputProperty { pub path: Arc, 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, +} + +#[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, resolved_type: VariableType) -> Self { + let optional = matches!(resolved_type, VariableType::Nullable(_) | VariableType::Any); + Self { + path, + resolved_type, + optional, + supplied_by: SuppliedBy::Request, + default: None, + } + } } #[derive(Debug, Clone, Serialize)] diff --git a/core/engine/tests/policy_features.rs b/core/engine/tests/policy_features.rs index 57e986b6..b86ad2f9 100644 --- a/core/engine/tests/policy_features.rs +++ b/core/engine/tests/policy_features.rs @@ -5,7 +5,7 @@ use serde_json::json; use std::sync::Arc; use zen_engine::policy::{ - Cursor, CursorTarget, EvaluateRequest, EvaluationError, PolicyWorkspace, ScopeRequest, + Cursor, CursorTarget, EvaluateRequest, EvaluationError, PolicyWorkspace, ScopeRequest, SuppliedBy, Severity, }; use zen_expression::variable::{Variable, VariableType}; @@ -752,3 +752,63 @@ fn calls_and_derived_fields_are_ordered_by_what_they_read() { "{found:#?}" ); } + +#[test] +fn a_call_reads_a_parent_through_root() { + let doc = |request: &str, when: &str| { + let mut doc = fraud("true"); + let card = doc["blocks"][1]["props"]["data"]["properties"].as_array_mut().unwrap(); + card.push(json!({ "id": "c9", "name": "card_score", "type": "number", + "model": { "datasource": "fraud", "request": request, "when": when } })); + let mut ws = PolicyWorkspace::new(); + ws.set_policy("p", serde_json::from_value(doc).unwrap()); + ws + }; + let errors = |ws: &PolicyWorkspace| -> Vec { + ws.diagnostics("p") + .into_iter() + .filter(|d| d.severity == Severity::Error) + .map(|d| d.message) + .collect() + }; + + // The card has no way back to the transaction: `$root` is the request. + let ws = doc("{ holder_country, amount: $root.transaction.amount }", "$root.transaction.amount > 100"); + assert!(errors(&ws).is_empty(), "{:#?}", errors(&ws)); + + // A path the request doesn't have; and the parent without `$root`. + let found = errors(&doc("{ amount: $root.transaction.amout }", "")); + assert!(found.iter().any(|m| m.contains("amout")), "{found:#?}"); + let found = errors(&doc("{ amount: transaction.amount }", "")); + assert!(!found.is_empty(), "a bare parent read is not the instance's: {found:#?}"); + + // Completions after `$root.`: the request's entities; not offered as a field. + let ws = doc("$root.", ""); + let after_root = labels(&ws, &cursor("dm-card", "$root.".len(), CursorTarget::ModelRequest { id: Arc::from("c9") })); + assert!(after_root.iter().any(|l| l == "transaction"), "{after_root:?}"); + let ws = doc("", ""); + let fields = labels(&ws, &cursor("dm-card", 0, CursorTarget::ModelRequest { id: Arc::from("c9") })); + assert!(fields.iter().any(|l| l == "holder_country"), "{fields:?}"); + assert!(!fields.iter().any(|l| l == "$root"), "{fields:?}"); +} + +#[test] +fn inputs_say_who_supplies_them_and_whether_they_can_be_left_out() { + let mut doc = fraud("true"); + let txn = doc["blocks"][0]["props"]["data"]["properties"].as_array_mut().unwrap(); + txn.push(json!({ "id": "t7", "name": "channel", "type": "string", "default": "card" })); + txn.push(json!({ "id": "t8", "name": "note", "type": "string", "optional": true })); + let mut ws = PolicyWorkspace::new(); + ws.set_policy("p", serde_json::from_value(doc).unwrap()); + let inputs = ws.inputs(&ScopeRequest::for_policy("p")); + let find = |path: &str| inputs.iter().find(|p| p.path.as_ref() == path).unwrap_or_else(|| panic!("{path} in {inputs:#?}")); + + let amount = find("transaction.amount"); + assert!(!amount.optional && amount.supplied_by == SuppliedBy::Request); + let channel = find("transaction.channel"); + assert!(channel.optional && channel.default == Some(json!("card"))); + assert!(find("transaction.note").optional); + // The card is reference data with features: the host supplies it. + let card = find("card"); + assert!(card.supplied_by == SuppliedBy::Host && card.optional, "{card:#?}"); +} diff --git a/core/expression/src/intellisense/type_provider.rs b/core/expression/src/intellisense/type_provider.rs index 6624b3fd..36fd6a87 100644 --- a/core/expression/src/intellisense/type_provider.rs +++ b/core/expression/src/intellisense/type_provider.rs @@ -176,7 +176,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());