From 47f9f05aba8c496439b9835ac4b1e7d467350755 Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:32:37 +0000 Subject: [PATCH 1/5] feat(explain): model attempts, scopes and causal origins in reports Add optional invocation-use and logical-scope ownership, per-result and per-proof conditionality, bounded causal input identities and context paths. Preserve failed attempts separately from successful proof causes and distinguish uncaptured bindings from captured empty bindings. Document Rust and legacy JSON migrations and parameter-binding evidence; cover nested comprehension subjects and equal-valued helper arguments without inventing body predicates. These are report contracts, not a runtime producer. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/explain/fixtures.rs | 27 +- src/explain/mod.rs | 38 ++- src/explain/report.rs | 239 ++++++++++++- src/explain/settings.rs | 8 +- src/explain/tests.rs | 725 +++++++++++++++++++++++++++++++++++++++- 5 files changed, 999 insertions(+), 38 deletions(-) diff --git a/src/explain/fixtures.rs b/src/explain/fixtures.rs index 2d36fc5cf..237684b25 100644 --- a/src/explain/fixtures.rs +++ b/src/explain/fixtures.rs @@ -51,6 +51,9 @@ pub fn complete_rule_report() -> ExplanationReport { definition(1, 1, Outcome::Success, 7, vec![token]), ], results: None, + attempts: None, + scopes: None, + calls: None, }], checks: vec![ ConditionSite { @@ -101,6 +104,9 @@ pub fn partial_set_report() -> ExplanationReport { emissions: vec![emission(None, Value::from("bob"), vec![in_users.clone()])], definitions: vec![definition(0, 0, Outcome::Success, 3, vec![in_users])], results: None, + attempts: None, + scopes: None, + calls: None, }], checks: vec![ConditionSite { site_id: 0, @@ -149,6 +155,9 @@ pub fn partial_object_report() -> ExplanationReport { )], definitions: vec![definition(0, 0, Outcome::Success, 3, vec![in_tags])], results: None, + attempts: None, + scopes: None, + calls: None, }], checks: vec![ConditionSite { site_id: 0, @@ -187,6 +196,8 @@ pub fn attributed_report() -> ExplanationReport { let proof = Derivation { definition: 0, body: 0, + attempt: None, + conditionality: None, conditions: vec![ConditionExplanation { site_id: 2, owner: owner("data.test.deny", 0), @@ -196,7 +207,7 @@ pub fn attributed_report() -> ExplanationReport { witness: None, binding: None, }], - bindings: vec![ + bindings: Some(vec![ IterationBinding { site_id: 0, collection: 0, @@ -209,11 +220,12 @@ pub fn attributed_report() -> ExplanationReport { key: ReportedValue::Known(Value::from(0_u64)), value: ReportedValue::Known(Value::from("public")), }, - ], + ]), }; let result = ResultExplanation { key: None, value: ReportedValue::Known(Value::from("public")), + conditionality: None, derivations_total: Count::Exact(2), distinct_elements: vec![ distinct(0, "input.resources[_]", 0, 2), @@ -241,6 +253,9 @@ pub fn attributed_report() -> ExplanationReport { emissions: Vec::new(), definitions: Vec::new(), results: Some(vec![result]), + attempts: None, + scopes: None, + calls: None, }], checks: vec![ iteration(0, "some r in input.resources"), @@ -272,6 +287,7 @@ pub fn conflict_report() -> ExplanationReport { call_instance: 0, kind: RuleKind::Complete, outcome: RuleOutcome::Conflict { + key: None, values: vec![ ReportedValue::Known(Value::from(true)), ReportedValue::Known(Value::from(false)), @@ -281,6 +297,9 @@ pub fn conflict_report() -> ExplanationReport { emissions: Vec::new(), definitions: Vec::new(), results: None, + attempts: None, + scopes: None, + calls: None, }], checks: Vec::new(), } @@ -549,6 +568,7 @@ pub fn known(value: Value, path: Option<&str>) -> Operand { value: ReportedValue::Known(value), path: path.map(String::from), concrete_path: ConcretePath::NotCaptured, + origins: None, } } @@ -557,6 +577,7 @@ pub fn redacted(path: &str) -> Operand { value: ReportedValue::Redacted, path: Some(String::from(path)), concrete_path: ConcretePath::NotCaptured, + origins: None, } } @@ -574,6 +595,8 @@ pub fn owner(rule: &str, call_instance: u64) -> ConditionOwner { ConditionOwner { rule: String::from(rule), call_instance, + attempt: None, + scope: None, } } diff --git a/src/explain/mod.rs b/src/explain/mod.rs index 8db2c6eb2..c9e997dc0 100644 --- a/src/explain/mod.rs +++ b/src/explain/mod.rs @@ -19,8 +19,9 @@ //! location, kind, operand references and owning rule of each check. //! - [`ExplanationRecorder`] receives the RVM's evaluation events. //! -//! The report types are `#[non_exhaustive]` so that fields and variants can -//! be added without breaking callers. They implement [`serde::Serialize`]; +//! The report types are `#[non_exhaustive]` to permit new struct fields and +//! enum variants. This does not protect changes to existing field types or +//! fields of an exhaustive enum variant. They implement [`serde::Serialize`]; //! JSON is produced only by the language bindings. Consumers of an //! [`ExplanationReport`] should accept unknown fields and enum values. //! Consumers that enforce a [`PartialEvalResult`] must instead fail closed: @@ -62,11 +63,29 @@ //! ([`DistinctElements`]). Concrete operand paths are independently opt-in; //! [`ConcretePath`] distinguishes not captured, unrepresentable, and a //! captured absence of a direct path. +//! [`AttemptExplanation`] and call-local [`ScopeExplanation`] distinguish +//! producing attempts from failed alternatives. [`CallUse`] preserves caller +//! context for cached results used under different polarities. +//! Per-result and per-proof [`Conditionality`] is unknown when not captured; +//! bounded proofs cannot establish that omitted evidence was concrete. +//! Computed operands can name [`CausalOrigins`] without claiming that their +//! input sources held the computed value. //! //! A report for a successful evaluation is complete: it explains every rule //! within the selected scope. A report accompanying a failed evaluation //! covers rules only up to the error. //! Signalling a report that was cut short will come with bounded tracing. +//! +//! # WIP contract migration +//! +//! This contract update requires Rust callers to wrap captured +//! [`Derivation::bindings`] in `Some`, using `None` when capture was unavailable. +//! [`RuleOutcome::Conflict`] constructions now supply `key: None` when no +//! object key was captured; exact variant patterns must account for `key`. +//! These are source-breaking changes despite the outer `non_exhaustive`. +//! JSON schema version 2 is retained: omitted bindings remain unknown, including +//! older reports that omitted either empty or uncaptured bindings. Only an +//! explicit empty array certifies that no contributing loop bindings exist. mod error; mod provenance; @@ -87,12 +106,13 @@ pub use recorder::{ NotCapturedEvent, UncapturedConstruct, }; pub use report::{ - ConcretePath, ConditionExplanation, ConditionKind, ConditionOwner, ConditionSite, Count, - DefinitionExplanation, Derivation, DistinctElements, EmissionExplanation, ExplanationReport, - IterationBinding, LoopWitness, Operand, Operator, Outcome, PartialEvalResult, PathRoot, - PathSegment, QueryTarget, ReportedValue, ResidualAlternativeStatus, ResidualArgument, - ResidualCall, ResidualCondition, ResidualKind, ResidualQuery, ResidualStatus, - ResidualUnresolved, ResidualUnresolvedReason, ResultExplanation, RuleExplanation, RuleKind, - RuleOutcome, SourceLocation, + AttemptExplanation, CallUse, CausalOrigins, ConcretePath, ConditionExplanation, ConditionKind, + ConditionOwner, ConditionSite, Conditionality, Count, DefinitionExplanation, Derivation, + DistinctElements, EmissionExplanation, ExplanationReport, IterationBinding, LoopWitness, + Operand, Operator, Outcome, PartialEvalResult, PathRoot, PathSegment, QueryTarget, + ReportedValue, ResidualAlternativeStatus, ResidualArgument, ResidualCall, ResidualCondition, + ResidualKind, ResidualQuery, ResidualStatus, ResidualUnresolved, ResidualUnresolvedReason, + ResultExplanation, RuleExplanation, RuleKind, RuleOutcome, ScopeExplanation, ScopeKind, + SourceLocation, }; pub use settings::{ConditionMode, ExplanationScope, ExplanationSettings, ValueMode}; diff --git a/src/explain/report.rs b/src/explain/report.rs index 80b0a9787..fb8f6c0ba 100644 --- a/src/explain/report.rs +++ b/src/explain/report.rs @@ -167,7 +167,8 @@ impl Serialize for ExplanationReport { #[non_exhaustive] pub struct QueryTarget { /// The query or entry point as the caller gave it, for example - /// `data.test.allow`. Policy source, never redacted. + /// `data.test.allow`. Copied verbatim, including caller-supplied literals; + /// never redacted. Callers must not put secrets in this string. pub entry_point: String, /// Fully qualified rule or function the query names. `None` when the /// query is not a rule reference, such as an expression over several @@ -234,6 +235,17 @@ pub struct RuleExplanation { /// means captured with no defined results. Helpers never consume the /// queried rule's proof budget. Legacy `emissions` remain per contribution. pub results: Option>, + /// Body attempts, including failed parameter matches and failed bodies + /// before a successful `else`. `None` means not captured; an empty list + /// means no attempt ran, for example a default-only rule. + pub attempts: Option>, + /// Logical scopes entered within this invocation. `None` means not + /// captured, not that no nested scopes existed. + pub scopes: Option>, + /// Uses of callee results by this invocation, including cached results. + /// `None` means not captured. Each use retains its caller's scope: + /// a cached result can be used both positively and negatively. + pub calls: Option>, } impl Serialize for RuleExplanation { @@ -247,6 +259,9 @@ impl Serialize for RuleExplanation { !self.emissions.is_empty(), !self.definitions.is_empty(), self.results.is_some(), + self.attempts.is_some(), + self.scopes.is_some(), + self.calls.is_some(), ]); let mut state = serializer.serialize_struct("RuleExplanation", len)?; state.serialize_field("name", &self.name)?; @@ -274,6 +289,18 @@ impl Serialize for RuleExplanation { Some(ref results) => state.serialize_field("results", results)?, None => state.skip_field("results")?, } + match self.attempts { + Some(ref attempts) => state.serialize_field("attempts", attempts)?, + None => state.skip_field("attempts")?, + } + match self.scopes { + Some(ref scopes) => state.serialize_field("scopes", scopes)?, + None => state.skip_field("scopes")?, + } + match self.calls { + Some(ref calls) => state.serialize_field("calls", calls)?, + None => state.skip_field("calls")?, + } state.end() } } @@ -303,23 +330,31 @@ pub enum RuleOutcome { /// other value, so it can be redacted or elided. Each serializes as /// `{"value": ...}`, `{"redacted": true}` or `{"elided": true}`. values: Vec, + /// Conflicting partial-object key, subject to value redaction and + /// elision. Absent for complete rules/functions, or when not captured; + /// absence never means that every object key conflicted. + key: Option, }, } impl Serialize for RuleOutcome { fn serialize(&self, serializer: S) -> Result { - let (status, values) = match *self { - Self::Matched => ("matched", None), - Self::NoMatch => ("no_match", None), - Self::Conflict { ref values } => ("conflict", Some(values)), + let (status, values, key) = match *self { + Self::Matched => ("matched", None, None), + Self::NoMatch => ("no_match", None, None), + Self::Conflict { + ref values, + ref key, + } => ("conflict", Some(values), key.as_ref()), }; - let len = field_count(&[true, values.is_some()]); + let len = field_count(&[true, values.is_some(), is_reported(key)]); let mut state = serializer.serialize_struct("RuleOutcome", len)?; state.serialize_field("status", status)?; match values { Some(values) => state.serialize_field("values", &ReportedEntries(values))?, None => state.skip_field("values")?, } + serialize_reported(&mut state, "key", "key_redacted", "key_elided", key)?; state.end() } } @@ -480,6 +515,113 @@ pub struct ConditionOwner { /// Matches the owning [`RuleExplanation::call_instance`], not the /// caller's invocation even when they return equal values. pub call_instance: u64, + /// Dynamic body attempt in the owning invocation. Absent when not + /// captured or outside a body; inspect the invocation's `attempts` + /// capture state before concluding no attempt existed. + #[serde(skip_serializing_if = "Option::is_none")] + pub attempt: Option, + /// Innermost logical scope in that invocation, not the caller's scope. + /// Absent outside a scope or when scope capture was unavailable. + #[serde(skip_serializing_if = "Option::is_none")] + pub scope: Option, +} + +/// One dynamic try of a definition/body in a rule invocation. +/// +/// Attempts start before parameter matching. A rejected match has outcome +/// [`Outcome::Undefined`]; a body returning `false` successfully has outcome +/// [`Outcome::Success`]. Failed attempts are context, never independent causes +/// of a successful derivation. `else` bodies are separate attempts. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[non_exhaustive] +pub struct AttemptExplanation { + /// Evaluation-local identifier, assigned sequentially by the VM. + pub attempt: u64, + /// Definition within the enclosing [`RuleExplanation`]. + pub definition: usize, + /// Body within that definition, zero for the primary body. + pub body: usize, + /// Absent if evaluation aborted before this attempt completed. + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, + /// Checks evaluated in this attempt, including failed pre-`else` bodies + /// not retained by the deciding-body [`DefinitionExplanation`] summary. + /// Absent when not captured; captured empty can represent a parameter + /// match rejected before any body checks. These remain context unless + /// they belong to the successful producing path. + /// + /// Captured parameter bindings can use [`ConditionKind::Binding`] at + /// the parameter's source site: `binding` names the parameter and `left` + /// holds the actual argument, including its concrete path or causal + /// origins. The owner is the callee attempt. This records a real binding, + /// not a fabricated body predicate: binding a defined `false` succeeds. + /// It also works for a value-only function with no body checks. + #[serde(skip_serializing_if = "Option::is_none")] + pub conditions: Option>, +} + +/// Logical construct enclosing checks, emissions or nested scopes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum ScopeKind { + /// A `not` operand, entered before its evaluation. + Negation, + /// An `every` quantifier. + Every, + /// An array comprehension. + ArrayComprehension, + /// A set comprehension. + SetComprehension, + /// An object comprehension. + ObjectComprehension, +} + +/// One dynamic entry into a logical construct within a rule invocation. +/// +/// Scopes form call-local trees: a callee starts a new tree even when used +/// inside a caller's negation. Follow [`CallUse`] edges to recover polarity +/// for a particular use; do not assign one inherited polarity to a cached +/// callee used under several different scopes. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[non_exhaustive] +pub struct ScopeExplanation { + /// Evaluation-local identifier, assigned sequentially by the VM. + pub scope: u64, + /// Construct that was entered. + pub kind: ScopeKind, + /// Parent scope in the same invocation, absent at its local root. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// Attempt within the enclosing [`RuleExplanation`]. + pub attempt: u64, + /// Static construct site in [`ExplanationReport::checks`]. + pub site_id: u32, + /// Outcome of the enclosing construct, not of its inner checks. + /// Negation never has outcome `Undefined`; a comprehension succeeds + /// even when empty. Absent if evaluation aborted before the scope ended. + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, +} + +/// One use of a callee result by the enclosing rule invocation. +/// +/// The callee's checks retain their own owners/scopes. Local polarity is +/// the parity of negation scopes enclosing a check; logical polarity for +/// one use also follows the caller scope on each edge from the query. +/// A fresh call and each cached reuse have separate edges to the same +/// callee invocation. Equal returned values do not identify invocations. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[non_exhaustive] +pub struct CallUse { + /// Callee [`RuleExplanation::call_instance`]. + pub call_instance: u64, + /// Caller attempt, absent outside a body or when not captured. + #[serde(skip_serializing_if = "Option::is_none")] + pub attempt: Option, + /// Innermost caller scope, absent at its local root or when not captured. + #[serde(skip_serializing_if = "Option::is_none")] + pub scope: Option, } /// One evaluation of a condition, referencing text/semantics stored once @@ -503,7 +645,8 @@ pub struct ConditionExplanation { /// Iteration summary of a loop-backed condition. #[serde(skip_serializing_if = "Option::is_none")] pub witness: Option, - /// Variable bound by a binding condition, such as `x` in `x := ...`. + /// Variable bound by a binding condition, such as `x` in `x := ...`, + /// or a parameter binding in [`AttemptExplanation::conditions`]. #[serde(skip_serializing_if = "Option::is_none")] pub binding: Option, } @@ -527,7 +670,7 @@ pub enum ConditionKind { Existence, /// A negated expression, `not ...`. Negation, - /// A variable binding, `x := ...`. + /// A variable binding, `x := ...`, or captured parameter-binding evidence. Binding, } @@ -612,11 +755,21 @@ pub struct Operand { /// [`ExplanationSettings::capture_paths`](super::ExplanationSettings::capture_paths). /// A policy source template in `path` is not a captured concrete path. pub concrete_path: ConcretePath, + /// Inputs that influenced a computed operand; their values are not + /// asserted to equal this operand's value. Independently opt-in with + /// concrete path capture and subject to its redaction rules. `None` + /// means not captured, not no dependencies. + pub origins: Option, } impl Serialize for Operand { fn serialize(&self, serializer: S) -> Result { - let len = field_count(&[self.path.is_some(), true, is_reported(Some(&self.value))]); + let len = field_count(&[ + self.path.is_some(), + true, + is_reported(Some(&self.value)), + self.origins.is_some(), + ]); let mut state = serializer.serialize_struct("Operand", len)?; match self.path { Some(ref path) => state.serialize_field("path", path)?, @@ -624,10 +777,28 @@ impl Serialize for Operand { } state.serialize_field("concrete_path", &self.concrete_path)?; serialize_reported(&mut state, "value", "redacted", "elided", Some(&self.value))?; + match self.origins { + Some(ref origins) => state.serialize_field("origins", origins)?, + None => state.skip_field("origins")?, + } state.end() } } +/// Bounded causal input identities for a computed operand, not direct reads +/// of the operand's returned value. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[non_exhaustive] +pub struct CausalOrigins { + /// Captured identities; sensitive paths are withheld in their entirety + /// using [`ConcretePath::Redacted`], never replaced by fabricated keys. + pub paths: Vec, + /// Whether every contributing origin is represented. `false` means + /// some origins were omitted; an empty incomplete list proves nothing + /// about whether inputs contributed. + pub complete: bool, +} + /// Whether a concrete operand path was captured. /// /// Serializes as `{"status": ...}`, plus `root` and `segments` for @@ -673,6 +844,8 @@ pub enum PathRoot { Input, /// Policy data. Data, + /// Host-supplied ambient context, separate from evaluation input. + Context, } /// One path segment. Numeric-looking object keys remain keys, never indices. @@ -694,7 +867,8 @@ pub enum PathSegment { /// check's owner identifies the invocation that actually evaluated it. /// /// Serializes as `{"definition": ..., "body": ..., "conditions": [...], -/// "bindings": [...]}`, with `bindings` omitted when empty. +/// "bindings": [...]}`, with `bindings` omitted when not captured and an +/// empty array when capture established that no loops contributed. #[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] pub struct Derivation { @@ -702,14 +876,39 @@ pub struct Derivation { pub definition: usize, /// Producing body index (`0` is the primary body). pub body: usize, + /// Producing body attempt, resolving in the queried invocation's + /// [`RuleExplanation::attempts`]. Absent when not captured. + #[serde(skip_serializing_if = "Option::is_none")] + pub attempt: Option, + /// Whether this derivation depends on unknown information. Absent when + /// not established, including when a helper's evidence was not captured. + #[serde(skip_serializing_if = "Option::is_none")] + pub conditionality: Option, /// Evaluated checks on this producing path, in evaluation order. + /// Contributing parameter bindings may be copied from callee attempts, + /// retaining their callee owners. An argument's presence alone does not + /// establish that it contributed to the result. pub conditions: Vec, /// The loop iteration that produced this proof at each loop on its /// path, outermost first, unlike a condition's loop-wide - /// [`witness`](ConditionExplanation::witness). Empty when the path has - /// no loop or the producer did not capture its iterations. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub bindings: Vec, + /// [`witness`](ConditionExplanation::witness). `Some([])` means no loop + /// contributed; `None` means iteration bindings were not captured. + #[serde(skip_serializing_if = "Option::is_none")] + pub bindings: Option>, +} + +/// Whether unknown information is necessary for a particular derivation or +/// for the existence of a result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum Conditionality { + /// A derivation uses no assumption; a result has at least one such + /// derivation, even if other contributors remain conditional. + Concrete, + /// A derivation needs an assumption; all derivations of a result do. + /// Producers must establish this beyond retained evidence/capture caps. + Assumed, } /// The iteration of one loop that a [`Derivation`] went through. @@ -872,6 +1071,12 @@ pub struct ResultExplanation { pub key: Option, /// Complete/function result or emitted partial-rule value. pub value: ReportedValue, + /// Whether this result's existence depends on assumptions. One concrete + /// derivation suffices for `Concrete`, but does not make an assumed + /// contributor concrete. `None` means unknown, never concrete by default. + /// Computed independently of retained proofs, so a cap cannot certify + /// concreteness or hide a concrete derivation. + pub conditionality: Option, /// Successful derivations producing this result, as `{"exact": n}`, or /// `{"at_least": n}` when evaluation stopped early. pub derivations_total: Count, @@ -896,6 +1101,7 @@ impl ResultExplanation { let result = Self { key, value, + conditionality: None, derivations_total, distinct_elements, proofs, @@ -935,6 +1141,7 @@ impl Serialize for ResultExplanation { true, is_reported(self.key.as_ref()), is_reported(Some(&self.value)), + self.conditionality.is_some(), ]); let mut state = serializer.serialize_struct("ResultExplanation", len)?; serialize_reported( @@ -951,6 +1158,10 @@ impl Serialize for ResultExplanation { "value_elided", Some(&self.value), )?; + match self.conditionality { + Some(conditionality) => state.serialize_field("conditionality", &conditionality)?, + None => state.skip_field("conditionality")?, + } state.serialize_field("derivations_total", &self.derivations_total)?; state.serialize_field("derivations_shown", &self.derivations_shown())?; state.serialize_field("derivations_dropped", &dropped)?; diff --git a/src/explain/settings.rs b/src/explain/settings.rs index 3196ed3c3..b8af75bd4 100644 --- a/src/explain/settings.rs +++ b/src/explain/settings.rs @@ -28,6 +28,12 @@ pub enum ValueMode { /// written. Opted-in concrete paths can contain runtime-derived keys: /// sensitive paths are withheld in their entirety and marked /// [`ConcretePath::Redacted`](super::ConcretePath::Redacted). Redaction + /// also covers causal-origin paths and partial-object conflict keys. + /// The query's `entry_point` is copied verbatim, including caller literals; + /// callers must keep secrets out of it. Returned partial-rule collections + /// are no more secret than complete-rule results: the successful query + /// result itself is never sanitized. + /// Redaction /// is best effort, not a secrecy guarantee. Partial evaluation results /// are not affected. #[default] @@ -78,7 +84,7 @@ pub struct ExplanationSettings { pub condition_mode: ConditionMode, /// Which parts of each rule are reported. pub scope: ExplanationScope, - /// Capture concrete operand paths separately from policy-source + /// Capture concrete operand and causal-origin paths separately from policy-source /// templates. Off by default. Distinct-element counting is independent: /// when identity cannot be tracked, its count is unavailable, not zero. pub capture_paths: bool, diff --git a/src/explain/tests.rs b/src/explain/tests.rs index 0205d12ef..aa01aa520 100644 --- a/src/explain/tests.rs +++ b/src/explain/tests.rs @@ -490,6 +490,7 @@ fn every_reported_value_variant_has_a_json_form() -> Result<(), serde_json::Erro value: value.clone(), path: None, concrete_path: ConcretePath::NotCaptured, + origins: None, }; let expected = match value { ReportedValue::Known(_) => r#"{"concrete_path":{"status":"not_captured"},"value":1}"#, @@ -522,12 +523,12 @@ fn undefined_is_distinct_in_every_value_position() -> Result<(), serde_json::Err } fn binding(r: &mut ExplanationReport) -> Option<&mut IterationBinding> { let mut result = result_attribution(); - result.proofs.first_mut()?.bindings = alloc::vec![IterationBinding { + result.proofs.first_mut()?.bindings = Some(alloc::vec![IterationBinding { site_id: 0, collection: 0, key: ReportedValue::Known(Value::from(0)), value: ReportedValue::Known(Value::from(1)), - }]; + }]); let rule = rule(r)?; rule.results = Some(alloc::vec![result]); rule.results @@ -536,6 +537,7 @@ fn undefined_is_distinct_in_every_value_position() -> Result<(), serde_json::Err .proofs .first_mut()? .bindings + .as_mut()? .first_mut() } let positions: [(&str, Setter); 12] = [ @@ -796,6 +798,9 @@ fn empty_partial_rule_results_are_defined_not_omitted() -> Result<(), serde_json emissions: Vec::new(), definitions: Vec::new(), results: None, + attempts: None, + scopes: None, + calls: None, }; assert_eq!(serde_json::to_string(&rule)?, expected); } @@ -840,6 +845,7 @@ fn result_attribution() -> ResultExplanation { ResultExplanation { key: None, value: ReportedValue::Known(Value::from("same")), + conditionality: None, derivations_total: Count::Exact(200), distinct_elements: alloc::vec![DistinctElements { site_id: 0, @@ -850,8 +856,10 @@ fn result_attribution() -> ResultExplanation { proofs: alloc::vec![Derivation { definition: 0, body: 0, + attempt: None, + conditionality: None, conditions: Vec::new(), - bindings: Vec::new(), + bindings: None, }], } } @@ -985,8 +993,10 @@ fn proofs_reference_shared_sites_but_keep_helper_call_ownership() -> anyhow::Res let proof = Derivation { definition: 0, body: 0, + attempt: None, + conditionality: None, conditions: alloc::vec![check.clone(), condition], - bindings: Vec::new(), + bindings: None, }; result.proofs.push(proof); helper.call_instance = call_instance; @@ -1094,6 +1104,7 @@ fn sensitive_concrete_path_can_be_withheld_independently_of_source_template( value: ReportedValue::Redacted, path: Some(String::from("data.tokens[input.user.token]")), concrete_path: ConcretePath::Redacted, + origins: None, }; assert_eq!( serde_json::to_string(&operand)?, @@ -1146,18 +1157,20 @@ fn elided_is_distinct_from_undefined_and_redacted_in_all_reported_positions() -> let mut result = result_attribution(); result.key = Some(value.clone()); result.value = value.clone(); - result.proofs.first_mut().context("proof")?.bindings = alloc::vec![IterationBinding { - site_id: 0, - collection: 0, - key: value.clone(), - value: value.clone(), - }]; + result.proofs.first_mut().context("proof")?.bindings = + Some(alloc::vec![IterationBinding { + site_id: 0, + collection: 0, + key: value.clone(), + value: value.clone(), + }]); rule.results = Some(alloc::vec![result]); // A conflict has at least two distinct defined values; only withheld // ones are checked here. let withheld = !matches!(value, ReportedValue::Known(_)); if withheld { rule.outcome = RuleOutcome::Conflict { + key: None, values: alloc::vec![ReportedValue::Known(Value::from(1)), value.clone()], }; } @@ -1344,6 +1357,7 @@ fn every_rule_outcome_and_count_variant_has_a_json_form() -> Result<(), serde_js RuleOutcome::Matched, RuleOutcome::NoMatch, RuleOutcome::Conflict { + key: None, values: alloc::vec![ ReportedValue::Known(Value::from(1)), ReportedValue::Known(Value::from(2)), @@ -1493,6 +1507,7 @@ fn distinct_elements_of_different_collections_are_not_merged() -> anyhow::Result #[test] fn redacted_binding_conflict_and_result_key_json() -> Result<(), serde_json::Error> { let conflict = RuleOutcome::Conflict { + key: None, values: alloc::vec![ ReportedValue::Known(Value::from("a")), ReportedValue::Redacted @@ -1501,18 +1516,21 @@ fn redacted_binding_conflict_and_result_key_json() -> Result<(), serde_json::Err let result = ResultExplanation { key: Some(ReportedValue::Redacted), value: ReportedValue::Known(Value::from("prod")), + conditionality: None, derivations_total: Count::Exact(1), distinct_elements: Vec::new(), proofs: alloc::vec![Derivation { definition: 0, body: 0, + attempt: None, + conditionality: None, conditions: Vec::new(), - bindings: alloc::vec![IterationBinding { + bindings: Some(alloc::vec![IterationBinding { site_id: 0, collection: 3, key: ReportedValue::Redacted, value: ReportedValue::Redacted, - }], + }]), }], }; assert_eq!( @@ -1530,3 +1548,686 @@ fn redacted_binding_conflict_and_result_key_json() -> Result<(), serde_json::Err ); Ok(()) } + +#[test] +fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { + let mut report = complete_rule_report(); + let rule = report.rules.first_mut().context("queried rule")?; + rule.call_instance = 1; + let mut failed_conditions = rule + .definitions + .first() + .context("failed primary body")? + .conditions + .clone(); + for condition in &mut failed_conditions { + condition.owner.call_instance = 1; + condition.owner.attempt = Some(1); + } + let failed_context = serde_json::to_value(&failed_conditions)?; + rule.attempts = Some(alloc::vec![ + AttemptExplanation { + attempt: 1, + definition: 0, + body: 0, + outcome: Some(Outcome::Failure), + conditions: Some(failed_conditions), + }, + AttemptExplanation { + attempt: 2, + definition: 0, + body: 1, + outcome: Some(Outcome::Success), + conditions: None, + }, + ]); + rule.scopes = Some(alloc::vec![ + ScopeExplanation { + scope: 1, + kind: ScopeKind::Negation, + parent: None, + attempt: 2, + site_id: 2, + outcome: Some(Outcome::Success), + }, + ScopeExplanation { + scope: 2, + kind: ScopeKind::ArrayComprehension, + parent: Some(1), + attempt: 2, + site_id: 3, + outcome: Some(Outcome::Success), + }, + ]); + rule.calls = Some(alloc::vec![ + CallUse { + call_instance: 2, + attempt: Some(2), + scope: None + }, + CallUse { + call_instance: 2, + attempt: Some(2), + scope: Some(1) + }, + ]); + let mut helper = rule.clone(); + helper.name = String::from("data.test.helper"); + helper.call_instance = 2; + helper.result = ReportedValue::Known(Value::from(false)); + helper.attempts = Some(alloc::vec![ + AttemptExplanation { + attempt: 3, + definition: 0, + body: 0, + outcome: Some(Outcome::Undefined), + conditions: Some(Vec::new()), + }, + AttemptExplanation { + attempt: 4, + definition: 1, + body: 0, + outcome: Some(Outcome::Success), + conditions: None, + }, + ]); + helper.scopes = Some(Vec::new()); + helper.calls = Some(Vec::new()); + helper.definitions.clear(); + // The failed helper attempt is context; only attempt 4 owns its cause. + let mut helper_condition = rule + .definitions + .get(1) + .and_then(|definition| definition.conditions.first()) + .context("helper check fixture")? + .clone(); + helper_condition.owner = ConditionOwner { + rule: helper.name.clone(), + call_instance: 2, + attempt: Some(4), + scope: None, + }; + helper.definitions.push(DefinitionExplanation { + index: 1, + body: 0, + outcome: Outcome::Success, + location: Some(SourceLocation { + file: String::from("p.rego"), + line: 7, + column: 1, + }), + conditions: alloc::vec![helper_condition], + }); + let mut deciding_body = rule.definitions.get(1).context("else body")?.clone(); + deciding_body.index = 0; + for condition in &mut deciding_body.conditions { + condition.owner.call_instance = 1; + condition.owner.attempt = Some(2); + } + rule.definitions = alloc::vec![deciding_body]; + report.query.call_instance = Some(1); + for (site_id, kind) in [(2, ConditionKind::Negation), (3, ConditionKind::Binding)] { + report.checks.push(ConditionSite { + site_id, + text: String::from("nested construct"), + kind, + location: None, + operator: None, + }); + } + report.rules.push(helper); + let json = serde_json::to_value(&report)?; + assert_eq!( + json.pointer("/rules/0/attempts"), + Some(&serde_json::json!([ + {"attempt":1,"definition":0,"body":0,"outcome":"failure","conditions":failed_context}, + {"attempt":2,"definition":0,"body":1,"outcome":"success"} + ])) + ); + assert_eq!( + json.pointer("/rules/0/definitions/0/body"), + Some(&serde_json::json!(1)) + ); + assert_eq!( + report + .rules + .first() + .context("queried rule")? + .definitions + .len(), + 1 + ); + assert_eq!( + json.pointer("/rules/0/attempts/0/conditions/0/outcome"), + Some(&serde_json::json!("failure")) + ); + assert_eq!( + json.pointer("/rules/0/attempts/0/conditions/0/owner/attempt"), + Some(&serde_json::json!(1)) + ); + assert_eq!( + json.pointer("/rules/1/attempts/0/conditions"), + Some(&serde_json::json!([])) + ); + assert_eq!( + json.pointer("/rules/0/scopes"), + Some(&serde_json::json!([ + {"scope":1,"kind":"negation","attempt":2,"site_id":2,"outcome":"success"}, + {"scope":2,"kind":"array_comprehension","parent":1,"attempt":2,"site_id":3,"outcome":"success"} + ])) + ); + assert_eq!( + json.pointer("/rules/0/calls"), + Some(&serde_json::json!([ + {"call_instance":2,"attempt":2}, + {"call_instance":2,"attempt":2,"scope":1} + ])) + ); + assert_eq!( + json.pointer("/rules/1/definitions/0/conditions/0/owner"), + Some(&serde_json::json!({"rule":"data.test.helper","call_instance":2,"attempt":4})) + ); + assert_eq!( + json.pointer("/rules/1/result"), + Some(&serde_json::json!(false)) + ); + assert_eq!( + json.pointer("/rules/1/scopes"), + Some(&serde_json::json!([])) + ); + let uncaptured_helper = report.rules.get_mut(1).context("helper invocation")?; + uncaptured_helper.attempts = None; + uncaptured_helper.scopes = None; + uncaptured_helper.calls = None; + let uncaptured = serde_json::to_value(&report)?; + assert!(uncaptured.pointer("/rules/1/attempts").is_none()); + assert!(uncaptured.pointer("/rules/1/scopes").is_none()); + assert!(uncaptured.pointer("/rules/1/calls").is_none()); + Ok(()) +} + +#[test] +fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { + let proof = |conditionality| Derivation { + definition: 0, + body: 0, + attempt: Some(1), + conditionality: Some(conditionality), + conditions: Vec::new(), + bindings: Some(Vec::new()), + }; + let mut result = ResultExplanation::new( + None, + ReportedValue::Known(Value::from("finding")), + Count::Exact(2), + Vec::new(), + alloc::vec![ + proof(Conditionality::Concrete), + proof(Conditionality::Assumed) + ], + ) + .context("valid proof count")?; + result.conditionality = Some(Conditionality::Concrete); + assert_eq!( + serde_json::to_value(&result)?, + serde_json::json!({ + "value":"finding","conditionality":"concrete","derivations_total":{"exact":2}, + "derivations_shown":2,"derivations_dropped":{"exact":0},"distinct_elements":[], + "proofs":[ + {"definition":0,"body":0,"attempt":1,"conditionality":"concrete","conditions":[],"bindings":[]}, + {"definition":0,"body":0,"attempt":1,"conditionality":"assumed","conditions":[],"bindings":[]} + ] + }) + ); + result.proofs.remove(0); + let capped = serde_json::to_value(&result)?; + assert_eq!( + capped.get("conditionality"), + Some(&serde_json::json!("concrete")) + ); + assert_eq!( + capped.pointer("/proofs/0/conditionality"), + Some(&serde_json::json!("assumed")) + ); + result.proofs.clear(); + assert_eq!( + serde_json::to_value(&result)?.get("conditionality"), + Some(&serde_json::json!("concrete")) + ); + result.conditionality = None; + assert!(serde_json::to_value(&result)? + .get("conditionality") + .is_none()); + result.conditionality = Some(Conditionality::Assumed); + assert_eq!( + serde_json::to_value(&result)?.get("conditionality"), + Some(&serde_json::json!("assumed")) + ); + Ok(()) +} + +#[test] +fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyhow::Result<()> { + // deny contains name if { some name in input.users; not count([tag | + // some tag in input.tags; tag == "public"]) == 0 } + let mut report = partial_set_report(); + report.query.call_instance = Some(1); + let rule = report.rules.first_mut().context("queried rule")?; + rule.call_instance = 1; + let owner = |scope| ConditionOwner { + rule: String::from("data.test.deny"), + call_instance: 1, + attempt: Some(1), + scope, + }; + let subject = rule + .definitions + .first_mut() + .context("queried definition")? + .conditions + .first_mut() + .context("subject loop")?; + subject.owner = owner(None); + subject.witness = None; + let local = ConditionExplanation { + site_id: 3, + owner: owner(Some(2)), + outcome: Outcome::Success, + left: None, + right: None, + witness: Some(LoopWitness { + iterations: 1, + successes: 1, + sample_key: Some(known(Value::from(0), None)), + sample_value: Some(known(Value::from("public"), Some("input.tags"))), + }), + binding: Some(String::from("tag")), + }; + let predicate = ConditionExplanation { + site_id: 4, + owner: owner(Some(2)), + outcome: Outcome::Success, + left: Some(known(Value::from("public"), Some("tag"))), + right: Some(known(Value::from("public"), None)), + witness: None, + binding: None, + }; + let negation = ConditionExplanation { + site_id: 1, + owner: owner(Some(1)), + outcome: Outcome::Success, + left: Some(known(Value::from(1), None)), + right: Some(known(Value::from(0), None)), + witness: None, + binding: None, + }; + let conditions = vec![subject.clone(), local, predicate, negation]; + rule.definitions + .first_mut() + .context("queried definition")? + .conditions = conditions.clone(); + rule.emissions + .first_mut() + .context("queried emission")? + .conditions = conditions.clone(); + rule.attempts = Some(vec![AttemptExplanation { + attempt: 1, + definition: 0, + body: 0, + outcome: Some(Outcome::Success), + conditions: Some(conditions.clone()), + }]); + rule.scopes = Some(vec![ + ScopeExplanation { + scope: 1, + kind: ScopeKind::Negation, + parent: None, + attempt: 1, + site_id: 1, + outcome: Some(Outcome::Success), + }, + ScopeExplanation { + scope: 2, + kind: ScopeKind::ArrayComprehension, + parent: Some(1), + attempt: 1, + site_id: 2, + outcome: Some(Outcome::Success), + }, + ]); + rule.results = Some(vec![ResultExplanation::new( + None, + ReportedValue::Known(Value::from("bob")), + Count::Exact(1), + vec![DistinctElements { + site_id: 0, + loop_name: String::from("input.users[_]"), + collection: 1, + count: Some(Count::Exact(1)), + }], + vec![Derivation { + definition: 0, + body: 0, + attempt: Some(1), + conditionality: Some(Conditionality::Concrete), + conditions, + bindings: Some(vec![IterationBinding { + site_id: 0, + collection: 1, + key: ReportedValue::Known(Value::from(0)), + value: ReportedValue::Known(Value::from("bob")), + }]), + }], + ) + .context("valid proof count")?]); + for (site_id, text, kind, operator) in [ + ( + 1, + r#"not count([tag | some tag in input.tags; tag == "public"]) == 0"#, + ConditionKind::Negation, + Some(Operator::Eq), + ), + ( + 2, + r#"[tag | some tag in input.tags; tag == "public"]"#, + ConditionKind::Binding, + None, + ), + (3, "some tag in input.tags", ConditionKind::Iteration, None), + ( + 4, + r#"tag == "public""#, + ConditionKind::Comparison, + Some(Operator::Eq), + ), + ] { + report.checks.push(ConditionSite { + site_id, + text: String::from(text), + kind, + location: None, + operator, + }); + } + let json = serde_json::to_value(&report)?; + let proof = json + .pointer("/rules/0/results/0/proofs/0") + .context("proof")?; + assert_eq!( + proof.get("bindings"), + Some(&serde_json::json!([ + {"site_id":0,"collection":1,"key":0,"value":"bob"} + ])) + ); + assert_eq!( + proof.pointer("/conditions/1"), + Some(&serde_json::json!({ + "site_id":3,"owner":{"rule":"data.test.deny","call_instance":1,"attempt":1,"scope":2}, + "outcome":"success","binding":"tag", + "witness":{"iterations":1,"successes":1, + "sample_key":{"concrete_path":{"status":"not_captured"},"value":0}, + "sample_value":{"path":"input.tags","concrete_path":{"status":"not_captured"},"value":"public"}} + })) + ); + assert_eq!( + proof.pointer("/conditions/2/owner/scope"), + Some(&serde_json::json!(2)) + ); + assert_eq!( + proof.pointer("/conditions/3/owner/scope"), + Some(&serde_json::json!(1)) + ); + assert_eq!(proof.pointer("/conditions/0/owner/scope"), None); + assert_eq!( + json.pointer("/rules/0/scopes"), + Some(&serde_json::json!([ + {"scope":1,"kind":"negation","attempt":1,"site_id":1,"outcome":"success"}, + {"scope":2,"kind":"array_comprehension","parent":1,"attempt":1,"site_id":2,"outcome":"success"} + ])) + ); + Ok(()) +} + +#[test] +fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow::Result<()> { + // identity(x) := x; allow := [identity(input.a > 0), identity(input.b > 0)]. + let mut report = complete_rule_report(); + report.query.call_instance = Some(1); + report.query_result = Value::from(vec![Value::from(false), Value::from(false)]); + report.checks = vec![ConditionSite { + site_id: 0, + text: String::from("x"), + kind: ConditionKind::Binding, + location: Some(SourceLocation { + file: String::from("p.rego"), + line: 2, + column: 10, + }), + operator: None, + }]; + let rule = report.rules.first_mut().context("queried rule")?; + rule.call_instance = 1; + rule.result = ReportedValue::Known(report.query_result.clone()); + rule.definitions = vec![DefinitionExplanation { + index: 0, + body: 0, + outcome: Outcome::Success, + location: None, + conditions: Vec::new(), + }]; + rule.attempts = Some(vec![AttemptExplanation { + attempt: 1, + definition: 0, + body: 0, + outcome: Some(Outcome::Success), + conditions: Some(Vec::new()), + }]); + rule.scopes = Some(Vec::new()); + rule.calls = Some(vec![ + CallUse { + call_instance: 2, + attempt: Some(1), + scope: None, + }, + CallUse { + call_instance: 3, + attempt: Some(1), + scope: None, + }, + ]); + let template = rule.clone(); + let mut contributions = Vec::new(); + for (call_instance, key) in [(2, "a"), (3, "b")] { + let mut argument = known(Value::from(false), None); + argument.concrete_path = ConcretePath::NoPath; + argument.origins = Some(CausalOrigins { + paths: vec![ConcretePath::Captured { + root: PathRoot::Input, + segments: vec![PathSegment::Key(String::from(key))], + }], + complete: true, + }); + let binding = ConditionExplanation { + site_id: 0, + owner: ConditionOwner { + rule: String::from("data.test.identity"), + call_instance, + attempt: Some(call_instance), + scope: None, + }, + outcome: Outcome::Success, + left: Some(argument), + right: None, + witness: None, + binding: Some(String::from("x")), + }; + let mut helper = template.clone(); + helper.name = String::from("data.test.identity"); + helper.call_instance = call_instance; + helper.kind = RuleKind::Function; + helper.result = ReportedValue::Known(Value::from(false)); + helper.attempts = Some(vec![AttemptExplanation { + attempt: call_instance, + definition: 0, + body: 0, + outcome: Some(Outcome::Success), + conditions: Some(vec![binding.clone()]), + }]); + helper.calls = Some(Vec::new()); + contributions.push(binding); + report.rules.push(helper); + } + report.rules.first_mut().context("queried rule")?.results = Some(vec![ResultExplanation::new( + None, + ReportedValue::Known(report.query_result.clone()), + Count::Exact(1), + Vec::new(), + vec![Derivation { + definition: 0, + body: 0, + attempt: Some(1), + conditionality: Some(Conditionality::Concrete), + conditions: contributions, + bindings: Some(Vec::new()), + }], + ) + .context("valid proof count")?]); + let json = serde_json::to_value(&report)?; + for (index, call_instance, key) in [(1, 2, "a"), (2, 3, "b")] { + let helper = json.pointer(&format!("/rules/{index}")).context("helper")?; + assert_eq!(helper.get("result"), Some(&serde_json::json!(false))); + assert_eq!( + helper.pointer("/definitions/0/conditions"), + Some(&serde_json::json!([])) + ); + assert_eq!( + helper.pointer("/attempts/0/conditions"), + Some(&serde_json::json!([{ + "site_id":0, + "owner":{"rule":"data.test.identity","call_instance":call_instance,"attempt":call_instance}, + "outcome":"success","binding":"x", + "left":{"concrete_path":{"status":"no_path"},"value":false, + "origins":{"paths":[{"status":"captured","root":"input","segments":[{"key":key}]}],"complete":true}} + }])) + ); + assert_eq!( + json.pointer(&format!( + "/rules/0/results/0/proofs/0/conditions/{}", + index - 1 + )), + helper.pointer("/attempts/0/conditions/0"), + ); + } + assert_eq!( + json.pointer("/rules/0/calls"), + Some(&serde_json::json!([ + {"call_instance":2,"attempt":1},{"call_instance":3,"attempt":1} + ])) + ); + Ok(()) +} + +#[test] +fn uncaptured_bindings_are_not_an_empty_contributor_set() -> Result<(), serde_json::Error> { + let mut proof = Derivation { + definition: 0, + body: 0, + attempt: None, + conditionality: None, + conditions: Vec::new(), + bindings: None, + }; + assert_eq!( + serde_json::to_value(&proof)?, + serde_json::json!({"definition":0,"body":0,"conditions":[]}) + ); + proof.bindings = Some(Vec::new()); + assert_eq!( + serde_json::to_value(&proof)?, + serde_json::json!({"definition":0,"body":0,"conditions":[],"bindings":[]}) + ); + Ok(()) +} + +#[test] +fn computed_origins_preserve_identity_without_claiming_source_values( +) -> Result<(), serde_json::Error> { + let mut operand = known(Value::from(true), None); + operand.concrete_path = ConcretePath::NoPath; + operand.origins = Some(CausalOrigins { + paths: alloc::vec![ConcretePath::Captured { + root: PathRoot::Context, + segments: alloc::vec![ + PathSegment::Key(String::from("resourceGroup")), + PathSegment::Key(String::from("location")) + ], + }], + complete: true, + }); + assert_eq!( + serde_json::to_value(&operand)?, + serde_json::json!({ + "concrete_path":{"status":"no_path"},"value":true, + "origins":{"paths":[{"status":"captured","root":"context", + "segments":[{"key":"resourceGroup"},{"key":"location"}]}],"complete":true} + }) + ); + operand.origins = Some(CausalOrigins { + paths: alloc::vec![ConcretePath::Redacted], + complete: false, + }); + assert_eq!( + serde_json::to_value(&operand)?.get("origins"), + Some(&serde_json::json!({"paths":[{"status":"redacted"}],"complete":false})) + ); + operand.origins = Some(CausalOrigins { + paths: Vec::new(), + complete: false, + }); + let incomplete = serde_json::to_value(&operand)?; + operand.origins = Some(CausalOrigins { + paths: Vec::new(), + complete: true, + }); + let no_inputs = serde_json::to_value(&operand)?; + operand.origins = None; + let uncaptured = serde_json::to_value(&operand)?; + assert_ne!(incomplete, no_inputs); + assert_ne!(uncaptured, no_inputs); + assert!(uncaptured.get("origins").is_none()); + Ok(()) +} + +#[test] +fn partial_object_conflict_keys_keep_redaction_and_elision() -> Result<(), serde_json::Error> { + for (key, expected) in [ + (None, serde_json::json!({})), + ( + Some(ReportedValue::Known(Value::from("env"))), + serde_json::json!({"key":"env"}), + ), + ( + Some(ReportedValue::Redacted), + serde_json::json!({"key_redacted":true}), + ), + ( + Some(ReportedValue::Elided), + serde_json::json!({"key_elided":true}), + ), + ] { + let conflict = RuleOutcome::Conflict { + values: alloc::vec![ + ReportedValue::Known(Value::from("a")), + ReportedValue::Known(Value::from("b")) + ], + key, + }; + let mut wanted = + serde_json::json!({"status":"conflict","values":[{"value":"a"},{"value":"b"}]}); + if let (Some(wanted), Some(expected)) = (wanted.as_object_mut(), expected.as_object()) { + wanted.extend(expected.clone()); + } + assert_eq!(serde_json::to_value(&conflict)?, wanted); + } + Ok(()) +} From da8adbb67ae8facdad578af10ee169548482a422 Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:11:17 +0000 Subject: [PATCH 2/5] fix(explain): disambiguate query and cached-use ownership Represent query-owned checks and scopes without fabricated rule attempts. Give call uses unique ids and explicit dependency paths, distinguish completed constructs from enclosing scopes, and restrict conditionality and negation context to what the evidence establishes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/explain/fixtures.rs | 18 ++ src/explain/mod.rs | 17 +- src/explain/report.rs | 130 +++++++++-- src/explain/tests.rs | 478 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 616 insertions(+), 27 deletions(-) diff --git a/src/explain/fixtures.rs b/src/explain/fixtures.rs index 237684b25..b95b71aa7 100644 --- a/src/explain/fixtures.rs +++ b/src/explain/fixtures.rs @@ -19,6 +19,8 @@ use alloc::vec::Vec; /// redacted. pub fn complete_rule_report() -> ExplanationReport { let role = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 0, owner: owner("data.test.allow", 0), outcome: Outcome::Failure, @@ -28,6 +30,8 @@ pub fn complete_rule_report() -> ExplanationReport { binding: None, }; let token = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 1, owner: owner("data.test.allow", 0), outcome: Outcome::Success, @@ -37,6 +41,7 @@ pub fn complete_rule_report() -> ExplanationReport { binding: None, }; ExplanationReport { + query_conditions: None, query: query("data.test.allow"), query_result: Value::from(true), rules: vec![RuleExplanation { @@ -79,6 +84,8 @@ pub fn complete_rule_report() -> ExplanationReport { pub fn partial_set_report() -> ExplanationReport { let names: BTreeSet = [Value::from("bob")].into_iter().collect(); let in_users = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 0, owner: owner("data.test.deny", 0), outcome: Outcome::Success, @@ -93,6 +100,7 @@ pub fn partial_set_report() -> ExplanationReport { binding: Some(String::from("name")), }; ExplanationReport { + query_conditions: None, query: query("data.test.deny"), query_result: Value::from(names.clone()), rules: vec![RuleExplanation { @@ -126,6 +134,8 @@ pub fn partial_object_report() -> ExplanationReport { .collect(); let labels = Value::from(labels); let in_tags = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 0, owner: owner("data.test.labels", 0), outcome: Outcome::Success, @@ -140,6 +150,7 @@ pub fn partial_object_report() -> ExplanationReport { binding: None, }; ExplanationReport { + query_conditions: None, query: query("data.test.labels"), query_result: labels.clone(), rules: vec![RuleExplanation { @@ -194,11 +205,14 @@ pub fn attributed_report() -> ExplanationReport { count: Some(Count::Exact(count)), }; let proof = Derivation { + call_uses: None, definition: 0, body: 0, attempt: None, conditionality: None, conditions: vec![ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 2, owner: owner("data.test.deny", 0), outcome: Outcome::Success, @@ -242,6 +256,7 @@ pub fn attributed_report() -> ExplanationReport { operator: None, }; ExplanationReport { + query_conditions: None, query: query("data.test.deny"), query_result: Value::from(public.clone()), rules: vec![RuleExplanation { @@ -280,6 +295,7 @@ pub fn conflict_report() -> ExplanationReport { let mut target = query("data.test.allow"); target.with_overrides = true; ExplanationReport { + query_conditions: None, query: target, query_result: Value::Undefined, rules: vec![RuleExplanation { @@ -584,6 +600,8 @@ pub fn redacted(path: &str) -> Operand { /// A query naming `rule`, whose top-level evaluation is call instance 0. pub fn query(rule: &str) -> QueryTarget { QueryTarget { + calls: None, + scopes: None, entry_point: String::from(rule), rule: Some(String::from(rule)), call_instance: Some(0), diff --git a/src/explain/mod.rs b/src/explain/mod.rs index c9e997dc0..a88f8821a 100644 --- a/src/explain/mod.rs +++ b/src/explain/mod.rs @@ -65,9 +65,14 @@ //! captured absence of a direct path. //! [`AttemptExplanation`] and call-local [`ScopeExplanation`] distinguish //! producing attempts from failed alternatives. [`CallUse`] preserves caller -//! context for cached results used under different polarities. +//! syntactic context for cached results used under different negation scopes, +//! not logical influence through intervening operations. Query-owned uses and +//! scopes live in [`QueryTarget`]; conditions and proofs can identify their +//! contributing use edges without changing the callee's evaluation owner. //! Per-result and per-proof [`Conditionality`] is unknown when not captured; //! bounded proofs cannot establish that omitted evidence was concrete. +//! It describes producing contributions, not a guarantee that evaluation +//! succeeds: assumption-dependent conflicts or errors remain authoritative. //! Computed operands can name [`CausalOrigins`] without claiming that their //! input sources held the computed value. //! @@ -109,10 +114,10 @@ pub use report::{ AttemptExplanation, CallUse, CausalOrigins, ConcretePath, ConditionExplanation, ConditionKind, ConditionOwner, ConditionSite, Conditionality, Count, DefinitionExplanation, Derivation, DistinctElements, EmissionExplanation, ExplanationReport, IterationBinding, LoopWitness, - Operand, Operator, Outcome, PartialEvalResult, PathRoot, PathSegment, QueryTarget, - ReportedValue, ResidualAlternativeStatus, ResidualArgument, ResidualCall, ResidualCondition, - ResidualKind, ResidualQuery, ResidualStatus, ResidualUnresolved, ResidualUnresolvedReason, - ResultExplanation, RuleExplanation, RuleKind, RuleOutcome, ScopeExplanation, ScopeKind, - SourceLocation, + Operand, Operator, Outcome, PartialEvalResult, PathRoot, PathSegment, + QueryConditionExplanation, QueryScopeExplanation, QueryTarget, ReportedValue, + ResidualAlternativeStatus, ResidualArgument, ResidualCall, ResidualCondition, ResidualKind, + ResidualQuery, ResidualStatus, ResidualUnresolved, ResidualUnresolvedReason, ResultExplanation, + RuleExplanation, RuleKind, RuleOutcome, ScopeExplanation, ScopeKind, SourceLocation, }; pub use settings::{ConditionMode, ExplanationScope, ExplanationSettings, ValueMode}; diff --git a/src/explain/report.rs b/src/explain/report.rs index fb8f6c0ba..252de0199 100644 --- a/src/explain/report.rs +++ b/src/explain/report.rs @@ -118,6 +118,10 @@ impl Serialize for ReportedEntries<'_> { pub struct ExplanationReport { /// What was queried; see [`QueryTarget`]. pub query: QueryTarget, + /// Checks executed by the query itself, with no invented rule owner. + /// Callee checks retain their rule owners and are reached through use paths. + /// `None` means not captured; an empty list means no query check ran. + pub query_conditions: Option>, /// The value returned by the query. Omitted from JSON when undefined, /// and [`Value::Undefined`] when the evaluation failed and returned no /// value. @@ -143,10 +147,21 @@ impl ExplanationReport { impl Serialize for ExplanationReport { fn serialize(&self, serializer: S) -> Result { let defined = !is_undefined(&self.query_result); - let len = field_count(&[true, true, defined, true, true]); + let len = field_count(&[ + true, + true, + self.query_conditions.is_some(), + defined, + true, + true, + ]); let mut state = serializer.serialize_struct("ExplanationReport", len)?; state.serialize_field("schema_version", &Self::SCHEMA_VERSION)?; state.serialize_field("query", &self.query)?; + match self.query_conditions { + Some(ref conditions) => state.serialize_field("query_conditions", conditions)?, + None => state.skip_field("query_conditions")?, + } if defined { state.serialize_field("query_result", &self.query_result)?; } else { @@ -162,7 +177,8 @@ impl Serialize for ExplanationReport { /// /// Serializes as `{"entry_point": ..., "rule": ..., "call_instance": ..., /// "with_overrides": ...}`; `rule` and `call_instance` are omitted when -/// absent. +/// absent. Optional `calls` and `scopes` describe evaluation outside any +/// rule invocation, including arbitrary query expressions. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[non_exhaustive] pub struct QueryTarget { @@ -187,6 +203,57 @@ pub struct QueryTarget { /// the evaluation was given. `with` modifiers inside the policy are not /// counted here; they show up as separate rule evaluations. pub with_overrides: bool, + /// Callee uses made directly by the query, not by a rule invocation. + /// `None` means not captured; an empty list means no query-owned uses. + #[serde(skip_serializing_if = "Option::is_none")] + pub calls: Option>, + /// Scopes entered directly by the query. Parents resolve within this + /// list, and query-owned scopes have no body attempt. + #[serde(skip_serializing_if = "Option::is_none")] + pub scopes: Option>, +} + +/// One dynamic query-owned construct, separate from rule body attempts. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[non_exhaustive] +pub struct QueryScopeExplanation { + /// Evaluation-local scope identifier, using the same space as rule scopes. + pub scope: u64, + /// Construct entered by the query. + pub kind: ScopeKind, + /// Parent in [`QueryTarget::scopes`], absent at the query's local root. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// Static construct site in [`ExplanationReport::checks`]. + pub site_id: u32, + /// Construct outcome; absent if evaluation aborted before completion. + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, +} + +/// A query-owned check, without a rule invocation or body attempt. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[non_exhaustive] +pub struct QueryConditionExplanation { + /// Static check site in [`ExplanationReport::checks`]. + pub site_id: u32, + /// Enclosing query scope, absent at its root or when not captured. + #[serde(skip_serializing_if = "Option::is_none")] + pub scope: Option, + /// Dynamic construct completed by this check, not its enclosing scope. + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_scope: Option, + /// Outcome of this query check. + pub outcome: Outcome, + /// Left or unary operand. + #[serde(skip_serializing_if = "Option::is_none")] + pub left: Option, + /// Right operand. + #[serde(skip_serializing_if = "Option::is_none")] + pub right: Option, + /// Contributing use paths; see [`ConditionExplanation::call_uses`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub call_uses: Option>>, } /// Explanation of one evaluation of a rule. @@ -565,7 +632,8 @@ pub struct AttemptExplanation { #[serde(rename_all = "snake_case")] #[non_exhaustive] pub enum ScopeKind { - /// A `not` operand, entered before its evaluation. + /// A `not` operand, entered before its evaluation. The completed `not` + /// check belongs to the enclosing scope, not to its own operand scope. Negation, /// An `every` quantifier. Every, @@ -580,10 +648,11 @@ pub enum ScopeKind { /// One dynamic entry into a logical construct within a rule invocation. /// /// Scopes form call-local trees: a callee starts a new tree even when used -/// inside a caller's negation. Follow [`CallUse`] edges to recover polarity -/// for a particular use; do not assign one inherited polarity to a cached -/// callee used under several different scopes. -#[derive(Debug, Clone, PartialEq, Serialize)] +/// inside a caller's negation. Follow [`CallUse`] edges to recover syntactic +/// negation nesting for a particular use, not its logical influence through +/// operations such as `count` or comparisons. Do not assign one inherited +/// context to a cached callee used under several different scopes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[non_exhaustive] pub struct ScopeExplanation { /// Evaluation-local identifier, assigned sequentially by the VM. @@ -604,19 +673,23 @@ pub struct ScopeExplanation { pub outcome: Option, } -/// One use of a callee result by the enclosing rule invocation. +/// One use of a callee result by the enclosing rule invocation or query. /// -/// The callee's checks retain their own owners/scopes. Local polarity is -/// the parity of negation scopes enclosing a check; logical polarity for -/// one use also follows the caller scope on each edge from the query. +/// The callee's checks retain their own owners/scopes. Negation-scope parity +/// describes syntactic nesting only, including caller scopes along use edges; +/// it does not determine how an inner check logically influences the result. /// A fresh call and each cached reuse have separate edges to the same /// callee invocation. Equal returned values do not identify invocations. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[non_exhaustive] pub struct CallUse { + /// Report-local use identifier, unique across query and rule use lists. + /// Assigned sequentially below 2^53, independently of callee identity. + pub use_id: u64, /// Callee [`RuleExplanation::call_instance`]. pub call_instance: u64, - /// Caller attempt, absent outside a body or when not captured. + /// Caller attempt, absent for query-owned uses, outside a body or when + /// not captured. #[serde(skip_serializing_if = "Option::is_none")] pub attempt: Option, /// Innermost caller scope, absent at its local root or when not captured. @@ -634,6 +707,21 @@ pub struct ConditionExplanation { pub site_id: u32, /// Invocation that evaluated this check. pub owner: ConditionOwner, + /// Contributing callee-use paths, each ordered from the containing + /// proof/query's caller toward a dependency. Sibling calls use separate + /// paths, not one artificial chain. Each id resolves to [`CallUse::use_id`]. + /// For a copied callee check, a path identifies the use reaching its owner; + /// for a caller-owned check, paths identify its contributing callee uses. + /// Ownership is independent of the path endpoints. `None` means not + /// captured; an empty list means no callee use contributed. + #[serde(skip_serializing_if = "Option::is_none")] + pub call_uses: Option>>, + /// Dynamic scope of the construct this check completed. For example, + /// a completed `not` names its operand scope here but is owned by the + /// enclosing scope. Resolves in its owner's invocation; absent when not + /// captured or when this check completes no construct. + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_scope: Option, /// Outcome of this evaluation, not an aggregate over other iterations. pub outcome: Outcome, /// Left operand, or the checked value of a unary condition. @@ -884,6 +972,12 @@ pub struct Derivation { /// not established, including when a helper's evidence was not captured. #[serde(skip_serializing_if = "Option::is_none")] pub conditionality: Option, + /// Contributing callee-use ids, resolving to [`CallUse::use_id`] across + /// the report's query and rule lists. Includes nested uses, not failed + /// alternatives. `None` means not captured; `Some([])` means none + /// contributed. Individual checks retain their ordered use chains. + #[serde(skip_serializing_if = "Option::is_none")] + pub call_uses: Option>, /// Evaluated checks on this producing path, in evaluation order. /// Contributing parameter bindings may be copied from callee attempts, /// retaining their callee owners. An argument's presence alone does not @@ -897,8 +991,10 @@ pub struct Derivation { pub bindings: Option>, } -/// Whether unknown information is necessary for a particular derivation or -/// for the existence of a result. +/// Whether unknown information is necessary for a producing derivation or +/// contribution to a result. This does not certify evaluation success: +/// assumption-dependent conflicts or errors can still prevent a result. +/// The evaluation outcome/error remains authoritative. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] #[non_exhaustive] @@ -1071,9 +1167,11 @@ pub struct ResultExplanation { pub key: Option, /// Complete/function result or emitted partial-rule value. pub value: ReportedValue, - /// Whether this result's existence depends on assumptions. One concrete + /// Whether producing contributions depend on assumptions. One concrete /// derivation suffices for `Concrete`, but does not make an assumed - /// contributor concrete. `None` means unknown, never concrete by default. + /// contributor concrete or rule out assumption-dependent conflicts/errors. + /// This field never guarantees successful evaluation or result existence. + /// `None` means unknown, never concrete by default. /// Computed independently of retained proofs, so a cap cannot certify /// concreteness or hide a concrete derivation. pub conditionality: Option, diff --git a/src/explain/tests.rs b/src/explain/tests.rs index aa01aa520..0850ff06d 100644 --- a/src/explain/tests.rs +++ b/src/explain/tests.rs @@ -854,6 +854,7 @@ fn result_attribution() -> ResultExplanation { count: Some(Count::Exact(200)), }], proofs: alloc::vec![Derivation { + call_uses: None, definition: 0, body: 0, attempt: None, @@ -991,6 +992,7 @@ fn proofs_reference_shared_sites_but_keep_helper_call_ownership() -> anyhow::Res condition.witness = None; condition.binding = None; let proof = Derivation { + call_uses: None, definition: 0, body: 0, attempt: None, @@ -1311,6 +1313,8 @@ fn query_target_identifies_entry_point_and_with_overrides() -> Result<(), serde_ Some(&serde_json::json!(true)) ); let expression = QueryTarget { + calls: None, + scopes: None, entry_point: String::from("data.test.allow == data.test.deny"), rule: None, call_instance: None, @@ -1520,6 +1524,7 @@ fn redacted_binding_conflict_and_result_key_json() -> Result<(), serde_json::Err derivations_total: Count::Exact(1), distinct_elements: Vec::new(), proofs: alloc::vec![Derivation { + call_uses: None, definition: 0, body: 0, attempt: None, @@ -1601,11 +1606,13 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { ]); rule.calls = Some(alloc::vec![ CallUse { + use_id: 1, call_instance: 2, attempt: Some(2), scope: None }, CallUse { + use_id: 2, call_instance: 2, attempt: Some(2), scope: Some(1) @@ -1665,6 +1672,33 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { condition.owner.attempt = Some(2); } rule.definitions = alloc::vec![deciding_body]; + let retained_check = helper + .definitions + .first() + .and_then(|definition| definition.conditions.first()) + .context("retained callee check")? + .clone(); + let proof = |use_id| { + let mut condition = retained_check.clone(); + condition.call_uses = Some(vec![vec![use_id]]); + Derivation { + definition: 0, + body: 1, + attempt: Some(2), + conditionality: Some(Conditionality::Concrete), + call_uses: Some(vec![use_id]), + conditions: vec![condition], + bindings: Some(Vec::new()), + } + }; + rule.results = Some(vec![ResultExplanation::new( + None, + rule.result.clone(), + Count::Exact(2), + Vec::new(), + vec![proof(1), proof(2)], + ) + .context("two cached-use proofs")?]); report.query.call_instance = Some(1); for (site_id, kind) in [(2, ConditionKind::Negation), (3, ConditionKind::Binding)] { report.checks.push(ConditionSite { @@ -1719,8 +1753,8 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { assert_eq!( json.pointer("/rules/0/calls"), Some(&serde_json::json!([ - {"call_instance":2,"attempt":2}, - {"call_instance":2,"attempt":2,"scope":1} + {"use_id":1,"call_instance":2,"attempt":2}, + {"use_id":2,"call_instance":2,"attempt":2,"scope":1} ])) ); assert_eq!( @@ -1731,6 +1765,30 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { json.pointer("/rules/1/result"), Some(&serde_json::json!(false)) ); + for (index, use_id, scope) in [(0, 1, None), (1, 2, Some(1))] { + let proof_json = json + .pointer(&format!("/rules/0/results/0/proofs/{index}")) + .context("cached-use proof")?; + assert_eq!( + proof_json.get("call_uses"), + Some(&serde_json::json!([use_id])) + ); + assert_eq!( + proof_json.pointer("/conditions/0/call_uses"), + Some(&serde_json::json!([[use_id]])) + ); + assert_eq!( + proof_json.pointer("/conditions/0/owner"), + json.pointer("/rules/1/definitions/0/conditions/0/owner") + ); + let use_edge = report + .rules + .first() + .and_then(|caller| caller.calls.as_ref()) + .and_then(|calls| calls.iter().find(|call| call.use_id == use_id)) + .context("exact contributing use")?; + assert_eq!((use_edge.call_instance, use_edge.scope), (2, scope)); + } assert_eq!( json.pointer("/rules/1/scopes"), Some(&serde_json::json!([])) @@ -1746,9 +1804,127 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { Ok(()) } +#[test] +fn arbitrary_queries_own_cached_uses_and_negation_scopes() -> anyhow::Result<()> { + let mut report = complete_rule_report(); + let rule = report.rules.first_mut().context("queried rule")?; + rule.call_instance = 1; + for definition in &mut rule.definitions { + for condition in &mut definition.conditions { + condition.owner.call_instance = 1; + } + } + report.query.entry_point = String::from("data.test.allow; not data.test.allow == false"); + report.query.rule = None; + report.query.call_instance = None; + let truthiness_site = u32::try_from(report.checks.len())?; + report.checks.push(ConditionSite { + site_id: truthiness_site, + text: String::from("data.test.allow"), + kind: ConditionKind::Truthiness, + location: None, + operator: None, + }); + let site_id = u32::try_from(report.checks.len())?; + report.checks.push(ConditionSite { + site_id, + text: String::from("not data.test.allow == false"), + kind: ConditionKind::Negation, + location: None, + operator: Some(Operator::Eq), + }); + report.query.calls = Some(vec![ + CallUse { + use_id: 1, + call_instance: 1, + attempt: None, + scope: None, + }, + CallUse { + use_id: 2, + call_instance: 1, + attempt: None, + scope: Some(1), + }, + ]); + report.query.scopes = Some(vec![QueryScopeExplanation { + scope: 1, + kind: ScopeKind::Negation, + parent: None, + site_id, + outcome: Some(Outcome::Success), + }]); + report.query_conditions = Some(vec![ + QueryConditionExplanation { + site_id: truthiness_site, + scope: None, + completed_scope: None, + outcome: Outcome::Success, + left: Some(known(Value::from(true), None)), + right: None, + call_uses: Some(vec![vec![1]]), + }, + QueryConditionExplanation { + site_id, + scope: None, + completed_scope: Some(1), + outcome: Outcome::Success, + left: Some(known(Value::from(true), None)), + right: Some(known(Value::from(false), None)), + call_uses: Some(vec![vec![2]]), + }, + ]); + let json = serde_json::to_value(&report)?; + assert!(json.pointer("/query/rule").is_none()); + assert!(json.pointer("/query/call_instance").is_none()); + assert_eq!( + json.pointer("/query/calls"), + Some(&serde_json::json!([ + {"use_id":1,"call_instance":1}, + {"use_id":2,"call_instance":1,"scope":1} + ])) + ); + assert_eq!( + json.pointer("/query/scopes"), + Some(&serde_json::json!([ + {"scope":1,"kind":"negation","site_id":site_id,"outcome":"success"} + ])) + ); + assert_eq!( + json.pointer("/query_conditions/0/call_uses"), + Some(&serde_json::json!([[1]])) + ); + assert_eq!( + json.pointer("/query_conditions/1/call_uses"), + Some(&serde_json::json!([[2]])) + ); + assert_eq!( + json.pointer("/query_conditions/1/completed_scope"), + Some(&serde_json::json!(1)) + ); + assert!(json.pointer("/query_conditions/1/scope").is_none()); + assert!(json.pointer("/query_conditions/1/owner").is_none()); + report.query.calls = Some(Vec::new()); + report.query.scopes = Some(Vec::new()); + report.query_conditions = Some(Vec::new()); + let empty = serde_json::to_value(&report)?; + assert_eq!(empty.pointer("/query/calls"), Some(&serde_json::json!([]))); + assert_eq!(empty.pointer("/query/scopes"), Some(&serde_json::json!([]))); + assert_eq!(empty.get("query_conditions"), Some(&serde_json::json!([]))); + report.query.calls = None; + report.query.scopes = None; + report.query_conditions = None; + let uncaptured = serde_json::to_value(&report)?; + assert!(uncaptured.pointer("/query/calls").is_none()); + assert!(uncaptured.pointer("/query/scopes").is_none()); + assert!(uncaptured.get("query_conditions").is_none()); + Ok(()) +} + #[test] fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { let proof = |conditionality| Derivation { + call_uses: None, definition: 0, body: 0, attempt: Some(1), @@ -1806,6 +1982,283 @@ fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { Ok(()) } +#[test] +fn caller_checks_keep_separate_sibling_dependency_paths() -> anyhow::Result<()> { + let mut report = attributed_report(); + report.query.call_instance = Some(1); + let rule = report.rules.first_mut().context("queried rule")?; + rule.call_instance = 1; + let template = rule.clone(); + rule.calls = Some( + (1..=4) + .map(|use_id| CallUse { + use_id, + call_instance: use_id + 1, + attempt: Some(1), + scope: None, + }) + .collect(), + ); + let proof = rule + .results + .as_mut() + .and_then(|results| results.first_mut()) + .and_then(|result| result.proofs.first_mut()) + .context("retained proof")?; + let mut first = proof.conditions.first().context("caller check")?.clone(); + first.owner.call_instance = 1; + first.owner.attempt = Some(1); + first.call_uses = Some(vec![vec![1], vec![2]]); + let mut second = first.clone(); + second.call_uses = Some(vec![vec![3], vec![4]]); + proof.call_uses = Some(vec![1, 2, 3, 4]); + proof.conditions = vec![first, second]; + for call_instance in 2..=5 { + let mut helper = template.clone(); + helper.name = String::from("data.test.helper"); + helper.call_instance = call_instance; + helper.kind = RuleKind::Function; + helper.result = ReportedValue::Known(Value::from("public")); + helper.results = None; + helper.emissions.clear(); + helper.definitions.clear(); + report.rules.push(helper); + } + let json = serde_json::to_value(&report)?; + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/conditions/0/call_uses"), + Some(&serde_json::json!([[1], [2]])) + ); + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/conditions/1/call_uses"), + Some(&serde_json::json!([[3], [4]])) + ); + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/call_uses"), + Some(&serde_json::json!([1, 2, 3, 4])) + ); + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/conditions/0/owner/call_instance"), + Some(&serde_json::json!(1)) + ); + Ok(()) +} + +#[test] +fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { + let mut report = attributed_report(); + report.query.rule = None; + report.query.call_instance = None; + report.query.calls = Some(vec![CallUse { + use_id: 1, + call_instance: 2, + attempt: None, + scope: None, + }]); + let root = report.rules.first_mut().context("caller")?; + root.call_instance = 2; + root.calls = Some(vec![CallUse { + use_id: 2, + call_instance: 3, + attempt: Some(1), + scope: None, + }]); + let mut callee = root.clone(); + callee.name = String::from("data.test.helper"); + callee.call_instance = 3; + callee.calls = Some(Vec::new()); + callee.emissions.clear(); + let mut check = callee + .results + .as_ref() + .and_then(|results| results.first()) + .and_then(|result| result.proofs.first()) + .and_then(|proof| proof.conditions.first()) + .context("physical callee check")? + .clone(); + callee.results = None; + check.owner.rule = callee.name.clone(); + check.owner.call_instance = 3; + check.owner.attempt = Some(1); + check.call_uses = None; + callee.definitions = vec![DefinitionExplanation { + index: 0, + body: 0, + outcome: Outcome::Success, + location: None, + conditions: vec![check.clone()], + }]; + let retained = root + .results + .as_mut() + .and_then(|results| results.first_mut()) + .and_then(|result| result.proofs.first_mut()) + .context("contributing proof")?; + check.call_uses = Some(vec![vec![1, 2]]); + retained.conditions = vec![check]; + retained.call_uses = Some(vec![1, 2]); + report.rules.push(callee); + let json = serde_json::to_value(&report)?; + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/conditions/0/call_uses"), + Some(&serde_json::json!([[1, 2]])) + ); + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/conditions/0/owner"), + json.pointer("/rules/1/definitions/0/conditions/0/owner") + ); + let path = report + .rules + .first() + .and_then(|rule| rule.results.as_ref()) + .and_then(|results| results.first()) + .and_then(|result| result.proofs.first()) + .and_then(|proof| proof.conditions.first()) + .and_then(|condition| condition.call_uses.as_ref()) + .and_then(|paths| paths.first()) + .context("nested use path")?; + let mut calls = report.query.calls.as_ref().context("query uses")?; + let mut reached = None; + for use_id in path { + let edge = calls + .iter() + .find(|edge| edge.use_id == *use_id) + .context("contiguous use")?; + assert_eq!( + calls + .iter() + .filter(|candidate| candidate.use_id == *use_id) + .count(), + 1 + ); + let rule = report + .rules + .iter() + .find(|rule| rule.call_instance == edge.call_instance) + .context("physical callee")?; + reached = Some(rule.call_instance); + calls = rule.calls.as_ref().context("callee uses")?; + } + assert_eq!(reached, Some(3)); + Ok(()) +} + +#[test] +fn captured_empty_use_dependencies_are_not_uncaptured() -> anyhow::Result<()> { + let report = attributed_report(); + let mut proof = report + .rules + .first() + .and_then(|rule| rule.results.as_ref()) + .and_then(|results| results.first()) + .and_then(|result| result.proofs.first()) + .context("proof")? + .clone(); + let mut condition = proof.conditions.first().context("condition")?.clone(); + let mut query_condition = QueryConditionExplanation { + site_id: condition.site_id, + scope: None, + completed_scope: None, + outcome: condition.outcome, + left: condition.left.clone(), + right: condition.right.clone(), + call_uses: None, + }; + proof.call_uses = None; + condition.call_uses = None; + for value in [ + serde_json::to_value(&proof)?, + serde_json::to_value(&condition)?, + serde_json::to_value(&query_condition)?, + ] { + assert!(value.get("call_uses").is_none()); + } + proof.call_uses = Some(Vec::new()); + condition.call_uses = Some(Vec::new()); + query_condition.call_uses = Some(Vec::new()); + for value in [ + serde_json::to_value(&proof)?, + serde_json::to_value(&condition)?, + serde_json::to_value(&query_condition)?, + ] { + assert_eq!(value.get("call_uses"), Some(&serde_json::json!([]))); + } + Ok(()) +} + +#[test] +fn repeated_negation_completions_name_their_operand_scopes() -> anyhow::Result<()> { + let mut report = complete_rule_report(); + let rule = report.rules.first_mut().context("queried rule")?; + let mut condition = rule + .definitions + .get(1) + .and_then(|definition| definition.conditions.first()) + .context("check fixture")? + .clone(); + let construct_site = u32::try_from(report.checks.len())?; + let check_site = construct_site.checked_add(1).context("next site")?; + for (site_id, kind, text) in [ + (construct_site, ConditionKind::Binding, "[true | not x]"), + (check_site, ConditionKind::Negation, "not x"), + ] { + report.checks.push(ConditionSite { + site_id, + text: String::from(text), + kind, + location: None, + operator: None, + }); + } + condition.site_id = check_site; + condition.owner.attempt = Some(2); + condition.owner.scope = Some(1); + condition.completed_scope = Some(2); + let mut repeated = condition.clone(); + repeated.completed_scope = Some(3); + rule.attempts = Some(vec![AttemptExplanation { + attempt: 2, + definition: 0, + body: 1, + outcome: Some(Outcome::Success), + conditions: Some(vec![condition, repeated]), + }]); + rule.scopes = Some( + [1, 2, 3] + .into_iter() + .map(|scope| ScopeExplanation { + scope, + kind: if scope == 1 { + ScopeKind::ArrayComprehension + } else { + ScopeKind::Negation + }, + parent: (scope != 1).then_some(1), + attempt: 2, + site_id: if scope == 1 { + construct_site + } else { + check_site + }, + outcome: Some(Outcome::Success), + }) + .collect(), + ); + let json = serde_json::to_value(&report)?; + for (index, scope) in [(0, 2), (1, 3)] { + let check = json + .pointer(&format!("/rules/0/attempts/0/conditions/{index}")) + .context("completed check")?; + assert_eq!(check.get("site_id"), Some(&serde_json::json!(check_site))); + assert_eq!(check.pointer("/owner/scope"), Some(&serde_json::json!(1))); + assert_eq!( + check.get("completed_scope"), + Some(&serde_json::json!(scope)) + ); + } + Ok(()) +} + #[test] fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyhow::Result<()> { // deny contains name if { some name in input.users; not count([tag | @@ -1830,6 +2283,8 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho subject.owner = owner(None); subject.witness = None; let local = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 3, owner: owner(Some(2)), outcome: Outcome::Success, @@ -1844,6 +2299,8 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho binding: Some(String::from("tag")), }; let predicate = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 4, owner: owner(Some(2)), outcome: Outcome::Success, @@ -1853,8 +2310,10 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho binding: None, }; let negation = ConditionExplanation { + completed_scope: Some(1), + call_uses: None, site_id: 1, - owner: owner(Some(1)), + owner: owner(None), outcome: Outcome::Success, left: Some(known(Value::from(1), None)), right: Some(known(Value::from(0), None)), @@ -1906,6 +2365,7 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho count: Some(Count::Exact(1)), }], vec![Derivation { + call_uses: None, definition: 0, body: 0, attempt: Some(1), @@ -1973,8 +2433,9 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho proof.pointer("/conditions/2/owner/scope"), Some(&serde_json::json!(2)) ); + assert_eq!(proof.pointer("/conditions/3/owner/scope"), None); assert_eq!( - proof.pointer("/conditions/3/owner/scope"), + proof.pointer("/conditions/3/completed_scope"), Some(&serde_json::json!(1)) ); assert_eq!(proof.pointer("/conditions/0/owner/scope"), None); @@ -2025,11 +2486,13 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: rule.scopes = Some(Vec::new()); rule.calls = Some(vec![ CallUse { + use_id: 1, call_instance: 2, attempt: Some(1), scope: None, }, CallUse { + use_id: 2, call_instance: 3, attempt: Some(1), scope: None, @@ -2048,6 +2511,8 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: complete: true, }); let binding = ConditionExplanation { + completed_scope: None, + call_uses: None, site_id: 0, owner: ConditionOwner { rule: String::from("data.test.identity"), @@ -2083,6 +2548,7 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: Count::Exact(1), Vec::new(), vec![Derivation { + call_uses: None, definition: 0, body: 0, attempt: Some(1), @@ -2121,7 +2587,8 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: assert_eq!( json.pointer("/rules/0/calls"), Some(&serde_json::json!([ - {"call_instance":2,"attempt":1},{"call_instance":3,"attempt":1} + {"use_id":1,"call_instance":2,"attempt":1}, + {"use_id":2,"call_instance":3,"attempt":1} ])) ); Ok(()) @@ -2130,6 +2597,7 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: #[test] fn uncaptured_bindings_are_not_an_empty_contributor_set() -> Result<(), serde_json::Error> { let mut proof = Derivation { + call_uses: None, definition: 0, body: 0, attempt: None, From 4f49f81e1e7334a4662d571b351f49f6bc6b5826 Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:26:37 +0000 Subject: [PATCH 3/5] fix(explain): preserve query and operand evidence associations Retain query binding and witness metadata and identify standalone comprehension sites. Associate each operand with its contributing call uses and anchor shared invocation proof paths locally, keeping external query prefixes on query evidence. Cover equal-valued siblings and cached nested uses with source-consistent fixtures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/explain/fixtures.rs | 2 + src/explain/mod.rs | 8 ++ src/explain/report.rs | 28 +++- src/explain/tests.rs | 300 +++++++++++++++++++++++++++++++++++++--- 4 files changed, 317 insertions(+), 21 deletions(-) diff --git a/src/explain/fixtures.rs b/src/explain/fixtures.rs index b95b71aa7..066aff253 100644 --- a/src/explain/fixtures.rs +++ b/src/explain/fixtures.rs @@ -581,6 +581,7 @@ pub fn partial_eval_unsupported_result() -> PartialEvalResult { pub fn known(value: Value, path: Option<&str>) -> Operand { Operand { + call_uses: None, value: ReportedValue::Known(value), path: path.map(String::from), concrete_path: ConcretePath::NotCaptured, @@ -590,6 +591,7 @@ pub fn known(value: Value, path: Option<&str>) -> Operand { pub fn redacted(path: &str) -> Operand { Operand { + call_uses: None, value: ReportedValue::Redacted, path: Some(String::from(path)), concrete_path: ConcretePath::NotCaptured, diff --git a/src/explain/mod.rs b/src/explain/mod.rs index a88f8821a..6500cc5c1 100644 --- a/src/explain/mod.rs +++ b/src/explain/mod.rs @@ -69,6 +69,12 @@ //! not logical influence through intervening operations. Query-owned uses and //! scopes live in [`QueryTarget`]; conditions and proofs can identify their //! contributing use edges without changing the callee's evaluation owner. +//! Query checks can retain binding names and loop witnesses. Standalone +//! comprehension sites use [`ConditionKind::Comprehension`], not `Binding`. +//! Use paths in rule proofs start at that proof's owning invocation, never +//! with an external query/caller prefix; query-owned checks start at the query. +//! [`Operand::call_uses`] distinguishes which calls contributed to each +//! operand even when sibling calls return equal values. //! Per-result and per-proof [`Conditionality`] is unknown when not captured; //! bounded proofs cannot establish that omitted evidence was concrete. //! It describes producing contributions, not a guarantee that evaluation @@ -88,6 +94,8 @@ //! [`RuleOutcome::Conflict`] constructions now supply `key: None` when no //! object key was captured; exact variant patterns must account for `key`. //! These are source-breaking changes despite the outer `non_exhaustive`. +//! Direct constructors also initialize optional query witness/binding and +//! operand-use metadata, using `None` when uncaptured. //! JSON schema version 2 is retained: omitted bindings remain unknown, including //! older reports that omitted either empty or uncaptured bindings. Only an //! explicit empty array certifies that no contributing loop bindings exist. diff --git a/src/explain/report.rs b/src/explain/report.rs index 252de0199..8f8e9121b 100644 --- a/src/explain/report.rs +++ b/src/explain/report.rs @@ -254,6 +254,12 @@ pub struct QueryConditionExplanation { /// Contributing use paths; see [`ConditionExplanation::call_uses`]. #[serde(skip_serializing_if = "Option::is_none")] pub call_uses: Option>>, + /// Iteration summary of a query-owned loop-backed check. + #[serde(skip_serializing_if = "Option::is_none")] + pub witness: Option, + /// Variable bound by this query check. + #[serde(skip_serializing_if = "Option::is_none")] + pub binding: Option, } /// Explanation of one evaluation of a rule. @@ -708,7 +714,11 @@ pub struct ConditionExplanation { /// Invocation that evaluated this check. pub owner: ConditionOwner, /// Contributing callee-use paths, each ordered from the containing - /// proof/query's caller toward a dependency. Sibling calls use separate + /// proof's owning invocation toward a dependency, or from the query for + /// query-owned checks. Outside a proof, start at this check's owner. + /// The first edge resolves in that root's `calls`; subsequent edges + /// resolve in the preceding callee's `calls`. Never embed an external + /// caller prefix in an invocation-owned proof. Sibling calls use separate /// paths, not one artificial chain. Each id resolves to [`CallUse::use_id`]. /// For a copied callee check, a path identifies the use reaching its owner; /// for a caller-owned check, paths identify its contributing callee uses. @@ -760,6 +770,9 @@ pub enum ConditionKind { Negation, /// A variable binding, `x := ...`, or captured parameter-binding evidence. Binding, + /// A standalone array, set or object comprehension construct site. + /// Its enclosing scope's [`ScopeKind`] identifies the collection kind. + Comprehension, } /// Operator of a comparison or membership condition. @@ -848,6 +861,11 @@ pub struct Operand { /// concrete path capture and subject to its redaction rules. `None` /// means not captured, not no dependencies. pub origins: Option, + /// Callee-use paths contributing to this operand, with the same root + /// and continuity rules as [`ConditionExplanation::call_uses`]. + /// Distinguishes equal-valued sibling operands without parsing text. + /// `None` means uncaptured; `Some([])` means no callee use contributed. + pub call_uses: Option>>, } impl Serialize for Operand { @@ -857,6 +875,7 @@ impl Serialize for Operand { true, is_reported(Some(&self.value)), self.origins.is_some(), + self.call_uses.is_some(), ]); let mut state = serializer.serialize_struct("Operand", len)?; match self.path { @@ -869,6 +888,10 @@ impl Serialize for Operand { Some(ref origins) => state.serialize_field("origins", origins)?, None => state.skip_field("origins")?, } + match self.call_uses { + Some(ref paths) => state.serialize_field("call_uses", paths)?, + None => state.skip_field("call_uses")?, + } state.end() } } @@ -973,7 +996,8 @@ pub struct Derivation { #[serde(skip_serializing_if = "Option::is_none")] pub conditionality: Option, /// Contributing callee-use ids, resolving to [`CallUse::use_id`] across - /// the report's query and rule lists. Includes nested uses, not failed + /// the owning invocation's calls and their descendants, never its + /// external caller/query prefixes. Includes nested uses, not failed /// alternatives. `None` means not captured; `Some([])` means none /// contributed. Individual checks retain their ordered use chains. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/src/explain/tests.rs b/src/explain/tests.rs index 0850ff06d..4f8e86edd 100644 --- a/src/explain/tests.rs +++ b/src/explain/tests.rs @@ -487,6 +487,7 @@ fn every_reported_value_variant_has_a_json_form() -> Result<(), serde_json::Erro ReportedValue::Elided, ] { let operand = Operand { + call_uses: None, value: value.clone(), path: None, concrete_path: ConcretePath::NotCaptured, @@ -662,6 +663,7 @@ fn every_enum_variant_serializes_to_its_documented_name() -> Result<(), serde_js C::Existence, C::Negation, C::Binding, + C::Comprehension, ], |kind| match kind { C::Comparison => "comparison", @@ -671,6 +673,7 @@ fn every_enum_variant_serializes_to_its_documented_name() -> Result<(), serde_js C::Existence => "existence", C::Negation => "negation", C::Binding => "binding", + C::Comprehension => "comprehension", }, )?; check( @@ -1103,6 +1106,7 @@ fn concrete_path_states_and_typed_segments_are_distinct() -> Result<(), serde_js fn sensitive_concrete_path_can_be_withheld_independently_of_source_template( ) -> Result<(), serde_json::Error> { let operand = Operand { + call_uses: None, value: ReportedValue::Redacted, path: Some(String::from("data.tokens[input.user.token]")), concrete_path: ConcretePath::Redacted, @@ -1700,7 +1704,10 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { ) .context("two cached-use proofs")?]); report.query.call_instance = Some(1); - for (site_id, kind) in [(2, ConditionKind::Negation), (3, ConditionKind::Binding)] { + for (site_id, kind) in [ + (2, ConditionKind::Negation), + (3, ConditionKind::Comprehension), + ] { report.checks.push(ConditionSite { site_id, text: String::from("nested construct"), @@ -1856,6 +1863,8 @@ fn arbitrary_queries_own_cached_uses_and_negation_scopes() -> anyhow::Result<()> }]); report.query_conditions = Some(vec![ QueryConditionExplanation { + witness: None, + binding: None, site_id: truthiness_site, scope: None, completed_scope: None, @@ -1865,6 +1874,8 @@ fn arbitrary_queries_own_cached_uses_and_negation_scopes() -> anyhow::Result<()> call_uses: Some(vec![vec![1]]), }, QueryConditionExplanation { + witness: None, + binding: None, site_id, scope: None, completed_scope: Some(1), @@ -1921,6 +1932,102 @@ fn arbitrary_queries_own_cached_uses_and_negation_scopes() -> anyhow::Result<()> Ok(()) } +#[test] +fn query_iterations_and_bindings_keep_their_evidence() -> anyhow::Result<()> { + let mut report = complete_rule_report(); + report.query.rule = None; + report.query.call_instance = None; + report.query.entry_point = String::from("some x in input.xs; y := x"); + report.rules.clear(); + report.checks = vec![ + ConditionSite { + site_id: 0, + text: String::from("input.xs"), + kind: ConditionKind::Iteration, + location: None, + operator: None, + }, + ConditionSite { + site_id: 1, + text: String::from("y := x"), + kind: ConditionKind::Binding, + location: None, + operator: None, + }, + ]; + report.query_conditions = Some(vec![ + QueryConditionExplanation { + site_id: 0, + scope: None, + completed_scope: None, + outcome: Outcome::Success, + left: Some(known( + Value::from(vec![Value::from(false)]), + Some("input.xs"), + )), + right: None, + call_uses: Some(Vec::new()), + binding: Some(String::from("x")), + witness: Some(LoopWitness { + iterations: 1, + successes: 1, + sample_key: Some(known(Value::from(0), None)), + sample_value: Some(known(Value::from(false), Some("input.xs"))), + }), + }, + QueryConditionExplanation { + site_id: 1, + scope: None, + completed_scope: None, + outcome: Outcome::Success, + left: Some(known(Value::from(false), None)), + right: None, + call_uses: Some(Vec::new()), + binding: Some(String::from("y")), + witness: None, + }, + ]); + let json = serde_json::to_value(&report)?; + assert_eq!( + json.pointer("/query_conditions/0/binding"), + Some(&serde_json::json!("x")) + ); + assert_eq!( + json.pointer("/query_conditions/0/witness"), + Some(&serde_json::json!({ + "iterations":1,"successes":1, + "sample_key":{"concrete_path":{"status":"not_captured"},"value":0}, + "sample_value":{"path":"input.xs","concrete_path":{"status":"not_captured"},"value":false} + })) + ); + assert_eq!( + json.pointer("/query_conditions/1/binding"), + Some(&serde_json::json!("y")) + ); + assert_eq!( + json.pointer("/query_conditions/1/left/value"), + Some(&serde_json::json!(false)) + ); + assert!(json.pointer("/query_conditions/1/witness").is_none()); + for check in json + .get("query_conditions") + .and_then(serde_json::Value::as_array) + .context("query checks")? + { + assert!(check.get("owner").is_none()); + } + report + .query_conditions + .as_mut() + .and_then(|checks| checks.first_mut()) + .context("iteration check")? + .binding = None; + assert!(serde_json::to_value(&report)? + .pointer("/query_conditions/0/binding") + .is_none()); + Ok(()) +} + #[test] fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { let proof = |conditionality| Derivation { @@ -1985,6 +2092,19 @@ fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { #[test] fn caller_checks_keep_separate_sibling_dependency_paths() -> anyhow::Result<()> { let mut report = attributed_report(); + let first_site = u32::try_from(report.checks.len())?; + for (offset, text) in [ + (0, "f(input.a) == g(input.b)"), + (1, "h(input.a) == j(input.b)"), + ] { + report.checks.push(ConditionSite { + site_id: first_site + offset, + text: String::from(text), + kind: ConditionKind::Comparison, + location: None, + operator: Some(Operator::Eq), + }); + } report.query.call_instance = Some(1); let rule = report.rules.first_mut().context("queried rule")?; rule.call_instance = 1; @@ -2006,19 +2126,29 @@ fn caller_checks_keep_separate_sibling_dependency_paths() -> anyhow::Result<()> .and_then(|result| result.proofs.first_mut()) .context("retained proof")?; let mut first = proof.conditions.first().context("caller check")?.clone(); + first.site_id = first_site; first.owner.call_instance = 1; first.owner.attempt = Some(1); first.call_uses = Some(vec![vec![1], vec![2]]); + let mut left = known(Value::from(false), None); + left.call_uses = Some(vec![vec![1]]); + let mut right = left.clone(); + right.call_uses = Some(vec![vec![2]]); + first.left = Some(left); + first.right = Some(right); let mut second = first.clone(); + second.site_id = first_site + 1; second.call_uses = Some(vec![vec![3], vec![4]]); + second.left.as_mut().context("second left")?.call_uses = Some(vec![vec![3]]); + second.right.as_mut().context("second right")?.call_uses = Some(vec![vec![4]]); proof.call_uses = Some(vec![1, 2, 3, 4]); proof.conditions = vec![first, second]; - for call_instance in 2..=5 { + for (call_instance, name) in [(2, "f"), (3, "g"), (4, "h"), (5, "j")] { let mut helper = template.clone(); - helper.name = String::from("data.test.helper"); + helper.name = format!("data.test.{name}"); helper.call_instance = call_instance; helper.kind = RuleKind::Function; - helper.result = ReportedValue::Known(Value::from("public")); + helper.result = ReportedValue::Known(Value::from(false)); helper.results = None; helper.emissions.clear(); helper.definitions.clear(); @@ -2041,19 +2171,80 @@ fn caller_checks_keep_separate_sibling_dependency_paths() -> anyhow::Result<()> json.pointer("/rules/0/results/0/proofs/0/conditions/0/owner/call_instance"), Some(&serde_json::json!(1)) ); + for (index, uses, names) in [(0, [1, 2], ["f", "g"]), (1, [3, 4], ["h", "j"])] { + let check = json + .pointer(&format!("/rules/0/results/0/proofs/0/conditions/{index}")) + .context("sibling comparison")?; + assert_eq!( + check.get("site_id"), + Some(&serde_json::json!(first_site + index)) + ); + assert_eq!(check.pointer("/left/value"), check.pointer("/right/value")); + for ((side, use_id), name) in ["left", "right"].into_iter().zip(uses).zip(names) { + assert_eq!( + check.pointer(&format!("/{side}/call_uses")), + Some(&serde_json::json!([[use_id]])) + ); + let edge = report + .rules + .first() + .and_then(|root| root.calls.as_ref()) + .and_then(|calls| calls.iter().find(|call| call.use_id == use_id)) + .context("operand producer edge")?; + let producer = report + .rules + .iter() + .find(|helper| helper.call_instance == edge.call_instance) + .context("operand producer")?; + assert_eq!(producer.result, ReportedValue::Known(Value::from(false))); + assert_eq!(producer.name, format!("data.test.{name}")); + } + } Ok(()) } #[test] fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { let mut report = attributed_report(); + let query_site = u32::try_from(report.checks.len())?; + report.checks.push(ConditionSite { + site_id: query_site, + text: String::from("data.test.deny"), + kind: ConditionKind::Truthiness, + location: None, + operator: None, + }); + let negation_site = query_site + 1; + report.checks.push(ConditionSite { + site_id: negation_site, + text: String::from("not data.test.deny == set()"), + kind: ConditionKind::Negation, + location: None, + operator: Some(Operator::Eq), + }); report.query.rule = None; report.query.call_instance = None; - report.query.calls = Some(vec![CallUse { - use_id: 1, - call_instance: 2, - attempt: None, - scope: None, + report.query.entry_point = String::from("data.test.deny; not data.test.deny == set()"); + report.query.calls = Some(vec![ + CallUse { + use_id: 1, + call_instance: 2, + attempt: None, + scope: None, + }, + CallUse { + use_id: 4, + call_instance: 2, + attempt: None, + scope: Some(1), + }, + ]); + report.query.scopes = Some(vec![QueryScopeExplanation { + scope: 1, + kind: ScopeKind::Negation, + parent: None, + site_id: negation_site, + outcome: Some(Outcome::Success), }]); let root = report.rules.first_mut().context("caller")?; root.call_instance = 2; @@ -2064,8 +2255,20 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { scope: None, }]); let mut callee = root.clone(); + let mut middle = root.clone(); + middle.name = String::from("data.test.middle"); + middle.call_instance = 3; + middle.results = None; + middle.definitions.clear(); + middle.emissions.clear(); + middle.calls = Some(vec![CallUse { + use_id: 3, + call_instance: 4, + attempt: Some(1), + scope: None, + }]); callee.name = String::from("data.test.helper"); - callee.call_instance = 3; + callee.call_instance = 4; callee.calls = Some(Vec::new()); callee.emissions.clear(); let mut check = callee @@ -2078,7 +2281,7 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { .clone(); callee.results = None; check.owner.rule = callee.name.clone(); - check.owner.call_instance = 3; + check.owner.call_instance = 4; check.owner.attempt = Some(1); check.call_uses = None; callee.definitions = vec![DefinitionExplanation { @@ -2094,18 +2297,63 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { .and_then(|results| results.first_mut()) .and_then(|result| result.proofs.first_mut()) .context("contributing proof")?; - check.call_uses = Some(vec![vec![1, 2]]); + check.call_uses = Some(vec![vec![2, 3]]); retained.conditions = vec![check]; - retained.call_uses = Some(vec![1, 2]); + retained.call_uses = Some(vec![2, 3]); + report.rules.push(middle); report.rules.push(callee); + report.query_conditions = Some( + [(1, query_site, None), (4, negation_site, Some(1))] + .into_iter() + .map( + |(use_id, site_id, completed_scope)| QueryConditionExplanation { + site_id, + scope: None, + completed_scope, + outcome: Outcome::Success, + left: Some(known(report.query_result.clone(), None)), + right: completed_scope + .map(|_| known(Value::from(BTreeSet::::new()), None)), + witness: None, + binding: None, + call_uses: Some(vec![vec![use_id, 2, 3]]), + }, + ) + .collect(), + ); let json = serde_json::to_value(&report)?; assert_eq!( json.pointer("/rules/0/results/0/proofs/0/conditions/0/call_uses"), - Some(&serde_json::json!([[1, 2]])) + Some(&serde_json::json!([[2, 3]])) ); assert_eq!( json.pointer("/rules/0/results/0/proofs/0/conditions/0/owner"), - json.pointer("/rules/1/definitions/0/conditions/0/owner") + json.pointer("/rules/2/definitions/0/conditions/0/owner") + ); + assert_eq!( + json.pointer("/rules/0/results/0/proofs/0/call_uses"), + Some(&serde_json::json!([2, 3])) + ); + assert_eq!( + json.pointer("/query_conditions/0/call_uses"), + Some(&serde_json::json!([[1, 2, 3]])) + ); + assert_eq!( + json.pointer("/query_conditions/1/call_uses"), + Some(&serde_json::json!([[4, 2, 3]])) + ); + assert_eq!( + json.pointer("/query_conditions/0/site_id"), + Some(&serde_json::json!(query_site)) + ); + assert_eq!( + json.pointer("/query_conditions/1/site_id"), + Some(&serde_json::json!(negation_site)) + ); + assert!(json.pointer("/query_conditions/1/scope").is_none()); + assert_eq!( + json.pointer("/query_conditions/1/completed_scope"), + Some(&serde_json::json!(1)) ); let path = report .rules @@ -2117,7 +2365,11 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { .and_then(|condition| condition.call_uses.as_ref()) .and_then(|paths| paths.first()) .context("nested use path")?; - let mut calls = report.query.calls.as_ref().context("query uses")?; + let mut calls = report + .rules + .first() + .and_then(|rule| rule.calls.as_ref()) + .context("proof-owning invocation uses")?; let mut reached = None; for use_id in path { let edge = calls @@ -2139,7 +2391,7 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { reached = Some(rule.call_instance); calls = rule.calls.as_ref().context("callee uses")?; } - assert_eq!(reached, Some(3)); + assert_eq!(reached, Some(4)); Ok(()) } @@ -2156,6 +2408,8 @@ fn captured_empty_use_dependencies_are_not_uncaptured() -> anyhow::Result<()> { .clone(); let mut condition = proof.conditions.first().context("condition")?.clone(); let mut query_condition = QueryConditionExplanation { + witness: None, + binding: None, site_id: condition.site_id, scope: None, completed_scope: None, @@ -2166,20 +2420,24 @@ fn captured_empty_use_dependencies_are_not_uncaptured() -> anyhow::Result<()> { }; proof.call_uses = None; condition.call_uses = None; + let mut operand = known(Value::from(false), None); for value in [ serde_json::to_value(&proof)?, serde_json::to_value(&condition)?, serde_json::to_value(&query_condition)?, + serde_json::to_value(&operand)?, ] { assert!(value.get("call_uses").is_none()); } proof.call_uses = Some(Vec::new()); condition.call_uses = Some(Vec::new()); query_condition.call_uses = Some(Vec::new()); + operand.call_uses = Some(Vec::new()); for value in [ serde_json::to_value(&proof)?, serde_json::to_value(&condition)?, serde_json::to_value(&query_condition)?, + serde_json::to_value(&operand)?, ] { assert_eq!(value.get("call_uses"), Some(&serde_json::json!([]))); } @@ -2199,7 +2457,11 @@ fn repeated_negation_completions_name_their_operand_scopes() -> anyhow::Result<( let construct_site = u32::try_from(report.checks.len())?; let check_site = construct_site.checked_add(1).context("next site")?; for (site_id, kind, text) in [ - (construct_site, ConditionKind::Binding, "[true | not x]"), + ( + construct_site, + ConditionKind::Comprehension, + "[true | not x]", + ), (check_site, ConditionKind::Negation, "not x"), ] { report.checks.push(ConditionSite { @@ -2390,7 +2652,7 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho ( 2, r#"[tag | some tag in input.tags; tag == "public"]"#, - ConditionKind::Binding, + ConditionKind::Comprehension, None, ), (3, "some tag in input.tags", ConditionKind::Iteration, None), From 4891ee3f9c63b159b6a9aa557fa83fafaf80069d Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:46:09 +0000 Subject: [PATCH 4/5] fix(explain): retain incoming argument and iteration binding provenance Name key and value iteration roles and retain actual arguments on caller-owned uses. Link callee binding and body operands through typed parameter projections, preserving shared proof roots and cached-use identity. Resolve comprehension kinds through matching construct sites and preserve uncertainty for uncaptured or constructed-element provenance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/explain/fixtures.rs | 6 + src/explain/mod.rs | 9 +- src/explain/report.rs | 59 ++++- src/explain/tests.rs | 486 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 545 insertions(+), 15 deletions(-) diff --git a/src/explain/fixtures.rs b/src/explain/fixtures.rs index 066aff253..669689672 100644 --- a/src/explain/fixtures.rs +++ b/src/explain/fixtures.rs @@ -92,6 +92,8 @@ pub fn partial_set_report() -> ExplanationReport { left: None, right: None, witness: Some(LoopWitness { + key_binding: None, + value_binding: None, iterations: 2, successes: 1, sample_key: Some(known(Value::from(1_u64), None)), @@ -142,6 +144,8 @@ pub fn partial_object_report() -> ExplanationReport { left: None, right: None, witness: Some(LoopWitness { + key_binding: None, + value_binding: None, iterations: 1, successes: 1, sample_key: Some(known(Value::from("env"), None)), @@ -581,6 +585,7 @@ pub fn partial_eval_unsupported_result() -> PartialEvalResult { pub fn known(value: Value, path: Option<&str>) -> Operand { Operand { + parameter_origins: None, call_uses: None, value: ReportedValue::Known(value), path: path.map(String::from), @@ -591,6 +596,7 @@ pub fn known(value: Value, path: Option<&str>) -> Operand { pub fn redacted(path: &str) -> Operand { Operand { + parameter_origins: None, call_uses: None, value: ReportedValue::Redacted, path: Some(String::from(path)), diff --git a/src/explain/mod.rs b/src/explain/mod.rs index 6500cc5c1..188e81313 100644 --- a/src/explain/mod.rs +++ b/src/explain/mod.rs @@ -75,6 +75,10 @@ //! with an external query/caller prefix; query-owned checks start at the query. //! [`Operand::call_uses`] distinguishes which calls contributed to each //! operand even when sibling calls return equal values. +//! Caller-owned [`CallUse::arguments`] preserve incoming argument provenance; +//! callee binding/body operands identify parameter projections without importing +//! caller paths into callee proofs. Witness key/value binding names preserve +//! both roles of a two-variable iteration without parsing source text. //! Per-result and per-proof [`Conditionality`] is unknown when not captured; //! bounded proofs cannot establish that omitted evidence was concrete. //! It describes producing contributions, not a guarantee that evaluation @@ -96,6 +100,9 @@ //! These are source-breaking changes despite the outer `non_exhaustive`. //! Direct constructors also initialize optional query witness/binding and //! operand-use metadata, using `None` when uncaptured. +//! They also initialize optional witness binding roles, call arguments and +//! parameter origins. `QueryTarget` and `CallUse` retain `PartialEq`, not `Eq`, +//! because captured arguments contain operands. //! JSON schema version 2 is retained: omitted bindings remain unknown, including //! older reports that omitted either empty or uncaptured bindings. Only an //! explicit empty array certifies that no contributing loop bindings exist. @@ -122,7 +129,7 @@ pub use report::{ AttemptExplanation, CallUse, CausalOrigins, ConcretePath, ConditionExplanation, ConditionKind, ConditionOwner, ConditionSite, Conditionality, Count, DefinitionExplanation, Derivation, DistinctElements, EmissionExplanation, ExplanationReport, IterationBinding, LoopWitness, - Operand, Operator, Outcome, PartialEvalResult, PathRoot, PathSegment, + Operand, Operator, Outcome, ParameterOrigin, PartialEvalResult, PathRoot, PathSegment, QueryConditionExplanation, QueryScopeExplanation, QueryTarget, ReportedValue, ResidualAlternativeStatus, ResidualArgument, ResidualCall, ResidualCondition, ResidualKind, ResidualQuery, ResidualStatus, ResidualUnresolved, ResidualUnresolvedReason, ResultExplanation, diff --git a/src/explain/report.rs b/src/explain/report.rs index 8f8e9121b..bfccf4f01 100644 --- a/src/explain/report.rs +++ b/src/explain/report.rs @@ -179,7 +179,7 @@ impl Serialize for ExplanationReport { /// "with_overrides": ...}`; `rule` and `call_instance` are omitted when /// absent. Optional `calls` and `scopes` describe evaluation outside any /// rule invocation, including arbitrary query expressions. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] pub struct QueryTarget { /// The query or entry point as the caller gave it, for example @@ -625,8 +625,12 @@ pub struct AttemptExplanation { /// /// Captured parameter bindings can use [`ConditionKind::Binding`] at /// the parameter's source site: `binding` names the parameter and `left` - /// holds the actual argument, including its concrete path or causal - /// origins. The owner is the callee attempt. This records a real binding, + /// holds its matched value. [`Operand::parameter_origins`] links both + /// binding and body operands to incoming [`CallUse::arguments`]. + /// Caller-specific paths/origins belong on those incoming arguments, + /// never on shared callee evidence; parameter projections specialize + /// that evidence for each use, including cached equal-valued arguments. + /// The owner is the callee attempt. This records a real binding, /// not a fabricated body predicate: binding a defined `false` succeeds. /// It also works for a value-only function with no body checks. #[serde(skip_serializing_if = "Option::is_none")] @@ -686,7 +690,7 @@ pub struct ScopeExplanation { /// it does not determine how an inner check logically influences the result. /// A fresh call and each cached reuse have separate edges to the same /// callee invocation. Equal returned values do not identify invocations. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] pub struct CallUse { /// Report-local use identifier, unique across query and rule use lists. @@ -701,6 +705,14 @@ pub struct CallUse { /// Innermost caller scope, absent at its local root or when not captured. #[serde(skip_serializing_if = "Option::is_none")] pub scope: Option, + /// Actual arguments in parameter order, before callee pattern matching. + /// Operand use paths start in this use's caller (query or invocation), + /// not the callee, even for cached reuse. They describe supplied arguments, + /// not necessarily contributors to the returned value. `None` is uncaptured; + /// `Some([])` certifies no arguments. Callee binding checks name the index + /// with [`Operand::parameter_origins`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub arguments: Option>, } /// One evaluation of a condition, referencing text/semantics stored once @@ -771,7 +783,8 @@ pub enum ConditionKind { /// A variable binding, `x := ...`, or captured parameter-binding evidence. Binding, /// A standalone array, set or object comprehension construct site. - /// Its enclosing scope's [`ScopeKind`] identifies the collection kind. + /// The captured rule or query scope whose `site_id` matches this site + /// supplies its [`ScopeKind`], not the enclosing scope. Comprehension, } @@ -866,6 +879,17 @@ pub struct Operand { /// Distinguishes equal-valued sibling operands without parsing text. /// `None` means uncaptured; `Some([])` means no callee use contributed. pub call_uses: Option>>, + /// Contributing parameter projections in this operand's evaluating + /// invocation (the physical check owner, or caller for call arguments). + /// Resolve against the incoming use being explained, not outgoing calls. + /// Computed operands may list several; their values need not equal the + /// operand. `None` is uncaptured; `Some([])` means none contributed. + /// Aggregate contributor lists do not identify an element's contributors; + /// projecting a constructed argument cannot distribute that list among + /// elements. Keep element provenance unknown unless independently captured. + /// Capture/redaction follows concrete paths; omit a sensitive projection + /// path in its entirety, never replace its keys with fabricated strings. + pub parameter_origins: Option>, } impl Serialize for Operand { @@ -876,6 +900,7 @@ impl Serialize for Operand { is_reported(Some(&self.value)), self.origins.is_some(), self.call_uses.is_some(), + self.parameter_origins.is_some(), ]); let mut state = serializer.serialize_struct("Operand", len)?; match self.path { @@ -892,10 +917,27 @@ impl Serialize for Operand { Some(ref paths) => state.serialize_field("call_uses", paths)?, None => state.skip_field("call_uses")?, } + match self.parameter_origins { + Some(ref origins) => state.serialize_field("parameter_origins", origins)?, + None => state.skip_field("parameter_origins")?, + } state.end() } } +/// An input projection of a function parameter, resolved per incoming use. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[non_exhaustive] +pub struct ParameterOrigin { + /// Zero-based position in [`CallUse::arguments`]. + pub argument: usize, + /// Typed path within that argument; empty means the whole argument. + /// Same key/index semantics as concrete paths. `None` means the projection + /// is uncaptured, withheld or unrepresentable, not the whole argument. + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option>, +} + /// Bounded causal input identities for a computed operand, not direct reads /// of the operand's returned value. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] @@ -1297,6 +1339,13 @@ impl Serialize for ResultExplanation { #[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] pub struct LoopWitness { + /// Variable bound to the iteration key, absent if unnamed or uncaptured. + #[serde(skip_serializing_if = "Option::is_none")] + pub key_binding: Option, + /// Variable bound to the iteration value, absent if unnamed or uncaptured. + /// These roles apply to every iteration, not just the retained sample. + #[serde(skip_serializing_if = "Option::is_none")] + pub value_binding: Option, /// Number of iterations executed, saturating at `u32::MAX`. pub iterations: u32, /// Number of iterations whose body succeeded, saturating at `u32::MAX`. diff --git a/src/explain/tests.rs b/src/explain/tests.rs index 4f8e86edd..6d010b1b5 100644 --- a/src/explain/tests.rs +++ b/src/explain/tests.rs @@ -487,6 +487,7 @@ fn every_reported_value_variant_has_a_json_form() -> Result<(), serde_json::Erro ReportedValue::Elided, ] { let operand = Operand { + parameter_origins: None, call_uses: None, value: value.clone(), path: None, @@ -1106,6 +1107,7 @@ fn concrete_path_states_and_typed_segments_are_distinct() -> Result<(), serde_js fn sensitive_concrete_path_can_be_withheld_independently_of_source_template( ) -> Result<(), serde_json::Error> { let operand = Operand { + parameter_origins: None, call_uses: None, value: ReportedValue::Redacted, path: Some(String::from("data.tokens[input.user.token]")), @@ -1610,12 +1612,14 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { ]); rule.calls = Some(alloc::vec![ CallUse { + arguments: None, use_id: 1, call_instance: 2, attempt: Some(2), scope: None }, CallUse { + arguments: None, use_id: 2, call_instance: 2, attempt: Some(2), @@ -1842,12 +1846,14 @@ fn arbitrary_queries_own_cached_uses_and_negation_scopes() -> anyhow::Result<()> }); report.query.calls = Some(vec![ CallUse { + arguments: None, use_id: 1, call_instance: 1, attempt: None, scope: None, }, CallUse { + arguments: None, use_id: 2, call_instance: 1, attempt: None, @@ -1969,6 +1975,8 @@ fn query_iterations_and_bindings_keep_their_evidence() -> anyhow::Result<()> { call_uses: Some(Vec::new()), binding: Some(String::from("x")), witness: Some(LoopWitness { + key_binding: None, + value_binding: None, iterations: 1, successes: 1, sample_key: Some(known(Value::from(0), None)), @@ -2028,6 +2036,434 @@ fn query_iterations_and_bindings_keep_their_evidence() -> anyhow::Result<()> { Ok(()) } +#[test] +fn two_variable_query_witness_names_key_and_value_roles() -> anyhow::Result<()> { + let mut report = complete_rule_report(); + report.rules.clear(); + report.query.rule = None; + report.query.call_instance = None; + report.query.entry_point = String::from("some k, v in input.tags"); + report.query_result = Value::from(true); + report.checks = vec![ConditionSite { + site_id: 0, + text: report.query.entry_point.clone(), + kind: ConditionKind::Iteration, + location: None, + operator: None, + }]; + report.query_conditions = Some(vec![QueryConditionExplanation { + site_id: 0, + scope: None, + completed_scope: None, + outcome: Outcome::Success, + left: Some(known( + Value::from(vec![Value::from(false)]), + Some("input.tags"), + )), + right: None, + call_uses: Some(Vec::new()), + binding: None, + witness: Some(LoopWitness { + key_binding: Some(String::from("k")), + value_binding: Some(String::from("v")), + iterations: 1, + successes: 1, + sample_key: Some(known(Value::from(0), None)), + sample_value: Some(known(Value::from(false), Some("input.tags"))), + }), + }]); + let json = serde_json::to_value(&report)?; + assert_eq!( + json.pointer("/query_conditions/0/witness"), + Some(&serde_json::json!({ + "key_binding":"k","value_binding":"v","iterations":1,"successes":1, + "sample_key":{"concrete_path":{"status":"not_captured"},"value":0}, + "sample_value":{"path":"input.tags","concrete_path":{"status":"not_captured"},"value":false} + })) + ); + assert!(json.pointer("/query_conditions/0/binding").is_none()); + let witness = report + .query_conditions + .as_mut() + .and_then(|checks| checks.first_mut()) + .and_then(|check| check.witness.as_mut()) + .context("query witness")?; + witness.key_binding = None; + witness.value_binding = None; + let uncaptured = serde_json::to_value(&report)?; + assert!(uncaptured + .pointer("/query_conditions/0/witness/key_binding") + .is_none()); + assert!(uncaptured + .pointer("/query_conditions/0/witness/value_binding") + .is_none()); + Ok(()) +} + +#[test] +fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow::Result<()> { + for query_owned in [false, true] { + let mut report = complete_rule_report(); + let mut template = report.rules.first().context("rule template")?.clone(); + template.definitions.clear(); + template.emissions.clear(); + template.results = None; + template.attempts = None; + template.scopes = Some(Vec::new()); + template.calls = Some(Vec::new()); + report.rules.clear(); + report.checks = ["x", "y", "x == y"] + .into_iter() + .enumerate() + .map(|(index, text)| { + Ok(ConditionSite { + site_id: u32::try_from(index)?, + text: String::from(text), + kind: if index == 2 { + ConditionKind::Comparison + } else { + ConditionKind::Binding + }, + operator: (index == 2).then_some(Operator::Eq), + location: None, + }) + }) + .collect::>()?; + report.query_result = Value::from(true); + report.query.rule = None; + report.query.call_instance = None; + report.query.entry_point = + String::from("same(f(input.a), g(input.b)); same(g(input.b), f(input.a))"); + let argument = |use_id| { + let mut operand = known(Value::from(false), None); + operand.call_uses = Some(vec![vec![use_id]]); + operand + }; + let mut calls = vec![ + CallUse { + use_id: 1, + call_instance: 2, + attempt: None, + scope: None, + arguments: Some(vec![known(Value::from(false), Some("input.a"))]), + }, + CallUse { + use_id: 2, + call_instance: 3, + attempt: None, + scope: None, + arguments: Some(vec![known(Value::from(false), Some("input.b"))]), + }, + CallUse { + use_id: 3, + call_instance: 4, + attempt: None, + scope: None, + arguments: Some(vec![argument(1), argument(2)]), + }, + CallUse { + use_id: 4, + call_instance: 3, + attempt: None, + scope: None, + arguments: Some(vec![known(Value::from(false), Some("input.b"))]), + }, + CallUse { + use_id: 5, + call_instance: 2, + attempt: None, + scope: None, + arguments: Some(vec![known(Value::from(false), Some("input.a"))]), + }, + CallUse { + use_id: 6, + call_instance: 4, + attempt: None, + scope: None, + arguments: Some(vec![argument(4), argument(5)]), + }, + ]; + if query_owned { + report.query.calls = Some(calls); + } else { + report.query.entry_point = String::from("data.test.allow"); + report.query.rule = Some(String::from("data.test.allow")); + report.query.call_instance = Some(1); + for call in &mut calls { + call.attempt = Some(1); + } + let mut caller = template.clone(); + caller.name = String::from("data.test.allow"); + caller.call_instance = 1; + caller.result = ReportedValue::Known(Value::from(true)); + caller.definitions = vec![DefinitionExplanation { + index: 0, + body: 0, + outcome: Outcome::Success, + location: None, + conditions: Vec::new(), + }]; + caller.attempts = Some(vec![AttemptExplanation { + attempt: 1, + definition: 0, + body: 0, + outcome: Some(Outcome::Success), + conditions: Some(Vec::new()), + }]); + caller.calls = Some(calls); + report.rules.push(caller); + } + for (call_instance, helper_name) in [(2, "f"), (3, "g"), (4, "same")] { + let mut helper = template.clone(); + helper.name = format!("data.test.{helper_name}"); + helper.call_instance = call_instance; + helper.kind = RuleKind::Function; + helper.result = ReportedValue::Known(Value::from(call_instance == 4)); + if call_instance == 4 { + let parameter = |index| { + let mut operand = known(Value::from(false), None); + operand.parameter_origins = Some(vec![ParameterOrigin { + argument: index, + path: Some(Vec::new()), + }]); + operand + }; + let mut conditions = ["x", "y"] + .into_iter() + .enumerate() + .map(|(index, name)| { + Ok(ConditionExplanation { + site_id: u32::try_from(index)?, + owner: ConditionOwner { + rule: helper.name.clone(), + call_instance, + attempt: Some(4), + scope: None, + }, + call_uses: Some(Vec::new()), + completed_scope: None, + outcome: Outcome::Success, + left: Some(parameter(index)), + right: None, + witness: None, + binding: Some(String::from(name)), + }) + }) + .collect::>>()?; + let comparison = ConditionExplanation { + site_id: 2, + owner: ConditionOwner { + rule: helper.name.clone(), + call_instance, + attempt: Some(4), + scope: None, + }, + call_uses: Some(Vec::new()), + completed_scope: None, + outcome: Outcome::Success, + left: Some(parameter(0)), + right: Some(parameter(1)), + witness: None, + binding: None, + }; + conditions.push(comparison.clone()); + helper.definitions = vec![DefinitionExplanation { + index: 0, + body: 0, + outcome: Outcome::Success, + location: None, + conditions: vec![comparison], + }]; + helper.attempts = Some(vec![AttemptExplanation { + attempt: 4, + definition: 0, + body: 0, + outcome: Some(Outcome::Success), + conditions: Some(conditions.clone()), + }]); + helper.results = Some(vec![ResultExplanation::new( + None, + ReportedValue::Known(Value::from(true)), + Count::Exact(1), + Vec::new(), + vec![Derivation { + definition: 0, + body: 0, + attempt: Some(4), + conditionality: None, + call_uses: Some(Vec::new()), + conditions, + bindings: Some(Vec::new()), + }], + ) + .context("callee proof")?]); + } + report.rules.push(helper); + } + let json = serde_json::to_value(&report)?; + let caller_uses = if query_owned { + json.pointer("/query/calls") + } else { + json.pointer("/rules/0/calls") + } + .and_then(serde_json::Value::as_array) + .context("caller uses")?; + let helpers = json + .get("rules") + .and_then(serde_json::Value::as_array) + .context("rules")?; + let same = helpers.last().context("same")?; + for (use_index, expected) in [ + (2, ["data.test.f", "data.test.g"]), + (5, ["data.test.g", "data.test.f"]), + ] { + for (position, name) in expected.into_iter().enumerate() { + assert_eq!( + same.pointer(&format!( + "/attempts/0/conditions/{position}/left/parameter_origins/0/argument" + )), + Some(&serde_json::json!(position)) + ); + assert_eq!( + same.pointer(&format!( + "/attempts/0/conditions/2/{}/parameter_origins", + if position == 0 { "left" } else { "right" } + )), + Some(&serde_json::json!([{"argument":position,"path":[]}])) + ); + let actual = caller_uses + .get(use_index) + .and_then(|call| call.pointer(&format!("/arguments/{position}"))) + .context("argument")?; + assert_eq!(actual.get("value"), Some(&serde_json::json!(false))); + let use_id = actual.pointer("/call_uses/0/0").context("producer use")?; + assert_eq!( + use_id, + &serde_json::json!(if use_index == 2 { + position + 1 + } else { + position + 4 + }) + ); + let edge = caller_uses + .iter() + .find(|call| call.get("use_id") == Some(use_id)) + .context("caller-owned producer")?; + let producer = helpers + .iter() + .find(|rule| rule.get("call_instance") == edge.get("call_instance")) + .context("producer")?; + assert_eq!(producer.get("name"), Some(&serde_json::json!(name))); + } + } + assert_eq!(same.get("calls"), Some(&serde_json::json!([]))); + assert_eq!( + same.pointer("/results/0/proofs/0/call_uses"), + Some(&serde_json::json!([])) + ); + } + Ok(()) +} + +#[test] +fn destructured_parameter_origins_preserve_typed_projections() -> anyhow::Result<()> { + // same([x, {"y": y}]) := x == y with argument [false, {"y": false}]. + let mut call = CallUse { + use_id: 1, + call_instance: 2, + attempt: None, + scope: None, + arguments: Some(vec![known( + Value::from(vec![ + Value::from(false), + Value::from_json_str(r#"{"y":false}"#)?, + ]), + None, + )]), + }; + let incoming = serde_json::to_value(&call)?; + for (path, expected) in [ + ( + vec![PathSegment::Index(0)], + serde_json::json!([{"index":0}]), + ), + ( + vec![PathSegment::Index(1), PathSegment::Key(String::from("y"))], + serde_json::json!([{"index":1},{"key":"y"}]), + ), + ] { + let mut operand = known(Value::from(false), None); + operand.parameter_origins = Some(vec![ParameterOrigin { + argument: 0, + path: Some(path), + }]); + let json = serde_json::to_value(&operand)?; + assert_eq!( + json.get("parameter_origins"), + Some(&serde_json::json!([{"argument":0,"path":expected}])) + ); + let origin = json + .pointer("/parameter_origins/0") + .context("parameter origin")?; + let argument = usize::try_from( + origin + .get("argument") + .and_then(serde_json::Value::as_u64) + .context("argument index")?, + )?; + let mut value = incoming + .pointer(&format!("/arguments/{argument}/value")) + .context("incoming value")?; + for segment in origin + .get("path") + .and_then(serde_json::Value::as_array) + .context("typed projection")? + { + value = if let Some(index) = segment.get("index").and_then(serde_json::Value::as_u64) { + value + .get(usize::try_from(index)?) + .context("array element")? + } else { + value + .get( + segment + .get("key") + .and_then(serde_json::Value::as_str) + .context("object key")?, + ) + .context("object element")? + }; + } + assert_eq!(json.get("value"), Some(value)); + } + let mut operand = known(Value::from(false), None); + operand.parameter_origins = Some(Vec::new()); + assert_eq!( + serde_json::to_value(&operand)?.get("parameter_origins"), + Some(&serde_json::json!([])) + ); + operand.parameter_origins = None; + assert!(serde_json::to_value(&operand)? + .get("parameter_origins") + .is_none()); + call.arguments = Some(Vec::new()); + assert_eq!( + serde_json::to_value(&call)?.get("arguments"), + Some(&serde_json::json!([])) + ); + call.arguments = None; + assert!(serde_json::to_value(&call)?.get("arguments").is_none()); + let projection = ParameterOrigin { + argument: 0, + path: None, + }; + assert_eq!( + serde_json::to_value(projection)?, + serde_json::json!({"argument":0}) + ); + Ok(()) +} + #[test] fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { let proof = |conditionality| Derivation { @@ -2112,6 +2548,7 @@ fn caller_checks_keep_separate_sibling_dependency_paths() -> anyhow::Result<()> rule.calls = Some( (1..=4) .map(|use_id| CallUse { + arguments: None, use_id, call_instance: use_id + 1, attempt: Some(1), @@ -2227,12 +2664,14 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { report.query.entry_point = String::from("data.test.deny; not data.test.deny == set()"); report.query.calls = Some(vec![ CallUse { + arguments: None, use_id: 1, call_instance: 2, attempt: None, scope: None, }, CallUse { + arguments: None, use_id: 4, call_instance: 2, attempt: None, @@ -2249,6 +2688,7 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { let root = report.rules.first_mut().context("caller")?; root.call_instance = 2; root.calls = Some(vec![CallUse { + arguments: None, use_id: 2, call_instance: 3, attempt: Some(1), @@ -2262,6 +2702,7 @@ fn nested_use_paths_resolve_in_caller_to_callee_order() -> anyhow::Result<()> { middle.definitions.clear(); middle.emissions.clear(); middle.calls = Some(vec![CallUse { + arguments: None, use_id: 3, call_instance: 4, attempt: Some(1), @@ -2553,6 +2994,8 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho left: None, right: None, witness: Some(LoopWitness { + key_binding: None, + value_binding: None, iterations: 1, successes: 1, sample_key: Some(known(Value::from(0), None)), @@ -2748,12 +3191,14 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: rule.scopes = Some(Vec::new()); rule.calls = Some(vec![ CallUse { + arguments: None, use_id: 1, call_instance: 2, attempt: Some(1), scope: None, }, CallUse { + arguments: None, use_id: 2, call_instance: 3, attempt: Some(1), @@ -2772,6 +3217,23 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: }], complete: true, }); + report + .rules + .first_mut() + .and_then(|caller| caller.calls.as_mut()) + .and_then(|calls| { + calls + .iter_mut() + .find(|call| call.call_instance == call_instance) + }) + .context("incoming identity use")? + .arguments = Some(vec![argument]); + let mut parameter = known(Value::from(false), None); + parameter.concrete_path = ConcretePath::NoPath; + parameter.parameter_origins = Some(vec![ParameterOrigin { + argument: 0, + path: Some(Vec::new()), + }]); let binding = ConditionExplanation { completed_scope: None, call_uses: None, @@ -2783,7 +3245,7 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: scope: None, }, outcome: Outcome::Success, - left: Some(argument), + left: Some(parameter), right: None, witness: None, binding: Some(String::from("x")), @@ -2835,9 +3297,16 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: "owner":{"rule":"data.test.identity","call_instance":call_instance,"attempt":call_instance}, "outcome":"success","binding":"x", "left":{"concrete_path":{"status":"no_path"},"value":false, - "origins":{"paths":[{"status":"captured","root":"input","segments":[{"key":key}]}],"complete":true}} + "parameter_origins":[{"argument":0,"path":[]}]} }])) ); + assert_eq!( + json.pointer(&format!("/rules/0/calls/{}/arguments/0", index - 1)), + Some(&serde_json::json!({ + "concrete_path":{"status":"no_path"},"value":false, + "origins":{"paths":[{"status":"captured","root":"input","segments":[{"key":key}]}],"complete":true} + })) + ); assert_eq!( json.pointer(&format!( "/rules/0/results/0/proofs/0/conditions/{}", @@ -2846,13 +3315,12 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: helper.pointer("/attempts/0/conditions/0"), ); } - assert_eq!( - json.pointer("/rules/0/calls"), - Some(&serde_json::json!([ - {"use_id":1,"call_instance":2,"attempt":1}, - {"use_id":2,"call_instance":3,"attempt":1} - ])) - ); + for (index, call_instance) in [(0, 2), (1, 3)] { + assert_eq!( + json.pointer(&format!("/rules/0/calls/{index}/call_instance")), + Some(&serde_json::json!(call_instance)) + ); + } Ok(()) } From 2ca028347e35601ad5c2225291b791232140f5aa Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:18:39 +0000 Subject: [PATCH 5/5] fix(explain): retain fallback eligibility and proof-local ownership Restore query equality, distinguish producing paths from callee uses, preserve uncached function identities, and clarify loop binding capture. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/explain/fixtures.rs | 1 + src/explain/mod.rs | 8 +- src/explain/report.rs | 49 +++--- src/explain/tests.rs | 367 ++++++++++++++++++++++++++++++++++------ 4 files changed, 350 insertions(+), 75 deletions(-) diff --git a/src/explain/fixtures.rs b/src/explain/fixtures.rs index 669689672..d883fddec 100644 --- a/src/explain/fixtures.rs +++ b/src/explain/fixtures.rs @@ -209,6 +209,7 @@ pub fn attributed_report() -> ExplanationReport { count: Some(Count::Exact(count)), }; let proof = Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, diff --git a/src/explain/mod.rs b/src/explain/mod.rs index 188e81313..8f4844b25 100644 --- a/src/explain/mod.rs +++ b/src/explain/mod.rs @@ -100,12 +100,12 @@ //! These are source-breaking changes despite the outer `non_exhaustive`. //! Direct constructors also initialize optional query witness/binding and //! operand-use metadata, using `None` when uncaptured. -//! They also initialize optional witness binding roles, call arguments and -//! parameter origins. `QueryTarget` and `CallUse` retain `PartialEq`, not `Eq`, -//! because captured arguments contain operands. +//! They also initialize optional witness roles, call arguments, parameter +//! origins and proof eligibility checks. `QueryTarget` retains `Eq`. //! JSON schema version 2 is retained: omitted bindings remain unknown, including //! older reports that omitted either empty or uncaptured bindings. Only an -//! explicit empty array certifies that no contributing loop bindings exist. +//! explicit empty array certifies no result-producing iteration bindings; +//! nested-scope loop evidence can still contribute through conditions. mod error; mod provenance; diff --git a/src/explain/report.rs b/src/explain/report.rs index bfccf4f01..dec0d16ac 100644 --- a/src/explain/report.rs +++ b/src/explain/report.rs @@ -179,7 +179,7 @@ impl Serialize for ExplanationReport { /// "with_overrides": ...}`; `rule` and `call_instance` are omitted when /// absent. Optional `calls` and `scopes` describe evaluation outside any /// rule invocation, including arbitrary query expressions. -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[non_exhaustive] pub struct QueryTarget { /// The query or entry point as the caller gave it, for example @@ -688,9 +688,9 @@ pub struct ScopeExplanation { /// The callee's checks retain their own owners/scopes. Negation-scope parity /// describes syntactic nesting only, including caller scopes along use edges; /// it does not determine how an inner check logically influences the result. -/// A fresh call and each cached reuse have separate edges to the same -/// callee invocation. Equal returned values do not identify invocations. -#[derive(Debug, Clone, PartialEq, Serialize)] +/// Cached rule reuses have separate edges to one invocation; uncached +/// function calls have distinct invocations even for equal arguments/results. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[non_exhaustive] pub struct CallUse { /// Report-local use identifier, unique across query and rule use lists. @@ -830,7 +830,7 @@ impl fmt::Display for Operator { } /// A runtime value that may have been withheld. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum ReportedValue { /// The recorded value. @@ -856,7 +856,7 @@ pub enum ReportedValue { /// `concrete_path` is always present (see [`ConcretePath`]); `path` is /// omitted when absent. `value` is replaced by `"redacted": true` or /// `"elided": true` when withheld, and omitted when undefined. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct Operand { /// The runtime value. @@ -1016,12 +1016,13 @@ pub enum PathSegment { } /// A successful producing path, including helper checks, without copying -/// policy text. Definition/body indices refer to the queried rule; each -/// check's owner identifies the invocation that actually evaluated it. +/// policy text. Definition/body indices and attempt resolve in the invocation +/// containing this proof, not necessarily the query. Checks keep their owners. /// -/// Serializes as `{"definition": ..., "body": ..., "conditions": [...], -/// "bindings": [...]}`, with `bindings` omitted when not captured and an -/// empty array when capture established that no loops contributed. +/// JSON has definition/body, conditions, optional attempt/conditionality, +/// call_uses/eligibility and bindings; omitted capture lists mean unknown. +/// Empty bindings certify no result-producing iteration bindings, not no +/// nested-scope loop evidence on conditions. #[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] pub struct Derivation { @@ -1029,21 +1030,28 @@ pub struct Derivation { pub definition: usize, /// Producing body index (`0` is the primary body). pub body: usize, - /// Producing body attempt, resolving in the queried invocation's + /// Producing body attempt, resolving in the containing invocation's /// [`RuleExplanation::attempts`]. Absent when not captured. #[serde(skip_serializing_if = "Option::is_none")] pub attempt: Option, - /// Whether this derivation depends on unknown information. Absent when - /// not established, including when a helper's evidence was not captured. + /// Whether production, including eligibility, depends on unknown information. + /// Absent when not established, including uncaptured helper evidence. #[serde(skip_serializing_if = "Option::is_none")] pub conditionality: Option, /// Contributing callee-use ids, resolving to [`CallUse::use_id`] across /// the owning invocation's calls and their descendants, never its - /// external caller/query prefixes. Includes nested uses, not failed - /// alternatives. `None` means not captured; `Some([])` means none + /// external caller/query prefixes. Includes nested/eligibility uses, not + /// unrelated failed alternatives. `None` is uncaptured; `Some([])` means none /// contributed. Individual checks retain their ordered use chains. #[serde(skip_serializing_if = "Option::is_none")] pub call_uses: Option>, + /// Checks establishing eligibility, such as earlier body failures needed + /// to select an `else`, separate from successful producing-body conditions. + /// Owners and use paths follow the same rules as `conditions`. Outcomes + /// retain failure/undefined rather than being rewritten to success. + /// `None` is uncaptured; `Some([])` certifies no eligibility checks. + #[serde(skip_serializing_if = "Option::is_none")] + pub eligibility: Option>, /// Evaluated checks on this producing path, in evaluation order. /// Contributing parameter bindings may be copied from callee attempts, /// retaining their callee owners. An argument's presence alone does not @@ -1051,8 +1059,8 @@ pub struct Derivation { pub conditions: Vec, /// The loop iteration that produced this proof at each loop on its /// path, outermost first, unlike a condition's loop-wide - /// [`witness`](ConditionExplanation::witness). `Some([])` means no loop - /// contributed; `None` means iteration bindings were not captured. + /// [`witness`](ConditionExplanation::witness). `Some([])` means no producing + /// iteration bindings, not no nested loops; `None` is uncaptured. #[serde(skip_serializing_if = "Option::is_none")] pub bindings: Option>, } @@ -1342,8 +1350,9 @@ pub struct LoopWitness { /// Variable bound to the iteration key, absent if unnamed or uncaptured. #[serde(skip_serializing_if = "Option::is_none")] pub key_binding: Option, - /// Variable bound to the iteration value, absent if unnamed or uncaptured. - /// These roles apply to every iteration, not just the retained sample. + /// Value variable for a two-variable loop; single-variable loops use the + /// condition's `binding` instead. Absent if unnamed or uncaptured. + /// Roles apply to every iteration, not just the retained sample. #[serde(skip_serializing_if = "Option::is_none")] pub value_binding: Option, /// Number of iterations executed, saturating at `u32::MAX`. diff --git a/src/explain/tests.rs b/src/explain/tests.rs index 6d010b1b5..30224308b 100644 --- a/src/explain/tests.rs +++ b/src/explain/tests.rs @@ -858,6 +858,7 @@ fn result_attribution() -> ResultExplanation { count: Some(Count::Exact(200)), }], proofs: alloc::vec![Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, @@ -996,6 +997,7 @@ fn proofs_reference_shared_sites_but_keep_helper_call_ownership() -> anyhow::Res condition.witness = None; condition.binding = None; let proof = Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, @@ -1309,6 +1311,8 @@ fn schema_version_is_serialized_first_in_every_report() -> Result<(), serde_json #[test] fn query_target_identifies_entry_point_and_with_overrides() -> Result<(), serde_json::Error> { let mut target = fixtures::query("data.test.allow"); + fn requires_eq(_: &T) {} + requires_eq(&target); assert_eq!( serde_json::to_string(&target)?, r#"{"entry_point":"data.test.allow","rule":"data.test.allow","call_instance":0,"with_overrides":false}"# @@ -1530,6 +1534,7 @@ fn redacted_binding_conflict_and_result_key_json() -> Result<(), serde_json::Err derivations_total: Count::Exact(1), distinct_elements: Vec::new(), proofs: alloc::vec![Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, @@ -1686,27 +1691,32 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { .and_then(|definition| definition.conditions.first()) .context("retained callee check")? .clone(); - let proof = |use_id| { - let mut condition = retained_check.clone(); - condition.call_uses = Some(vec![vec![use_id]]); - Derivation { - definition: 0, - body: 1, - attempt: Some(2), - conditionality: Some(Conditionality::Concrete), - call_uses: Some(vec![use_id]), - conditions: vec![condition], - bindings: Some(Vec::new()), - } + let conditions = [1, 2] + .into_iter() + .map(|use_id| { + let mut condition = retained_check.clone(); + condition.call_uses = Some(vec![vec![use_id]]); + condition + }) + .collect(); + let proof = Derivation { + definition: 0, + body: 1, + attempt: Some(2), + conditionality: None, + call_uses: Some(vec![1, 2]), + eligibility: None, + conditions, + bindings: Some(Vec::new()), }; rule.results = Some(vec![ResultExplanation::new( None, rule.result.clone(), - Count::Exact(2), + Count::Exact(1), Vec::new(), - vec![proof(1), proof(2)], + vec![proof], ) - .context("two cached-use proofs")?]); + .context("one producing path with two cached uses")?]); report.query.call_instance = Some(1); for (site_id, kind) in [ (2, ConditionKind::Negation), @@ -1776,20 +1786,29 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { json.pointer("/rules/1/result"), Some(&serde_json::json!(false)) ); + let result_json = json.pointer("/rules/0/results/0").context("result")?; + assert_eq!( + result_json.get("derivations_total"), + Some(&serde_json::json!({"exact":1})) + ); + assert_eq!( + result_json.get("derivations_shown"), + Some(&serde_json::json!(1)) + ); for (index, use_id, scope) in [(0, 1, None), (1, 2, Some(1))] { - let proof_json = json - .pointer(&format!("/rules/0/results/0/proofs/{index}")) + let proof_json = result_json + .pointer("/proofs/0") .context("cached-use proof")?; assert_eq!( proof_json.get("call_uses"), - Some(&serde_json::json!([use_id])) + Some(&serde_json::json!([1, 2])) ); assert_eq!( - proof_json.pointer("/conditions/0/call_uses"), + proof_json.pointer(&format!("/conditions/{index}/call_uses")), Some(&serde_json::json!([[use_id]])) ); assert_eq!( - proof_json.pointer("/conditions/0/owner"), + proof_json.pointer(&format!("/conditions/{index}/owner")), json.pointer("/rules/1/definitions/0/conditions/0/owner") ); let use_edge = report @@ -1815,6 +1834,206 @@ fn attempts_scopes_and_cached_uses_keep_ownership() -> anyhow::Result<()> { Ok(()) } +#[test] +fn fallback_eligibility_retains_failed_helper_dependencies() -> anyhow::Result<()> { + // p := 1 if data.test.gate else := 2; p := 2 if data.test.other + // Both helpers are false; only gate's failure makes the else eligible. + for conditionality in [Conditionality::Concrete, Conditionality::Assumed] { + let mut report = complete_rule_report(); + report.query = fixtures::query("data.test.p"); + report.query.call_instance = Some(1); + report.query_result = Value::from(2); + report.checks = ["data.test.gate", "data.test.other"] + .into_iter() + .enumerate() + .map(|(index, text)| { + Ok(ConditionSite { + site_id: u32::try_from(index)?, + text: String::from(text), + kind: ConditionKind::Truthiness, + location: None, + operator: None, + }) + }) + .collect::>()?; + let mut caller = report.rules.first().context("template")?.clone(); + caller.name = String::from("data.test.p"); + caller.call_instance = 1; + caller.result = ReportedValue::Known(Value::from(2)); + caller.scopes = Some(Vec::new()); + let check = |site_id, attempt, use_id| ConditionExplanation { + site_id, + owner: ConditionOwner { + rule: String::from("data.test.p"), + call_instance: 1, + attempt: Some(attempt), + scope: None, + }, + call_uses: Some(vec![vec![use_id]]), + completed_scope: None, + outcome: Outcome::Failure, + left: Some(known(Value::from(false), None)), + right: None, + witness: None, + binding: None, + }; + let guard = check(0, 1, 1); + let unrelated = check(1, 3, 2); + caller.attempts = Some(vec![ + AttemptExplanation { + attempt: 1, + definition: 0, + body: 0, + outcome: Some(Outcome::Failure), + conditions: Some(vec![guard.clone()]), + }, + AttemptExplanation { + attempt: 2, + definition: 0, + body: 1, + outcome: Some(Outcome::Success), + conditions: Some(Vec::new()), + }, + AttemptExplanation { + attempt: 3, + definition: 1, + body: 0, + outcome: Some(Outcome::Failure), + conditions: Some(vec![unrelated.clone()]), + }, + ]); + caller.definitions = vec![ + DefinitionExplanation { + index: 0, + body: 1, + outcome: Outcome::Success, + location: None, + conditions: Vec::new(), + }, + DefinitionExplanation { + index: 1, + body: 0, + outcome: Outcome::Failure, + location: None, + conditions: vec![unrelated], + }, + ]; + caller.calls = Some(vec![ + CallUse { + use_id: 1, + call_instance: 2, + attempt: Some(1), + scope: None, + arguments: Some(Vec::new()), + }, + CallUse { + use_id: 2, + call_instance: 3, + attempt: Some(3), + scope: None, + arguments: Some(Vec::new()), + }, + ]); + let proof = Derivation { + definition: 0, + body: 1, + attempt: Some(2), + conditionality: Some(conditionality), + call_uses: Some(vec![1]), + eligibility: Some(vec![guard]), + conditions: Vec::new(), + bindings: Some(Vec::new()), + }; + let mut result = ResultExplanation::new( + None, + caller.result.clone(), + Count::Exact(1), + Vec::new(), + vec![proof], + ) + .context("fallback result")?; + result.conditionality = Some(conditionality); + caller.results = Some(vec![result]); + let helpers = ["gate", "other"] + .into_iter() + .enumerate() + .map(|(index, name)| { + let mut helper = caller.clone(); + helper.name = format!("data.test.{name}"); + helper.call_instance = if index == 0 { 2 } else { 3 }; + helper.result = ReportedValue::Known(Value::from(false)); + helper.definitions.clear(); + helper.attempts = None; + helper.calls = Some(Vec::new()); + helper.results = None; + helper + }) + .collect::>(); + report.rules = vec![caller]; + report.rules.extend(helpers); + let json = serde_json::to_value(&report)?; + let result_json = json.pointer("/rules/0/results/0").context("result")?; + let proof_json = result_json.pointer("/proofs/0").context("proof")?; + assert_eq!(proof_json.get("conditions"), Some(&serde_json::json!([]))); + assert_eq!(proof_json.get("call_uses"), Some(&serde_json::json!([1]))); + assert_eq!( + proof_json.get("conditionality"), + Some(&serde_json::to_value(conditionality)?) + ); + assert_eq!( + proof_json.get("conditionality"), + result_json.get("conditionality") + ); + let eligibility = proof_json + .get("eligibility") + .and_then(serde_json::Value::as_array) + .context("captured eligibility")?; + assert_eq!(eligibility.len(), 1); + let guard_json = eligibility.first().context("guard")?; + assert_eq!( + guard_json.get("outcome"), + Some(&serde_json::json!("failure")) + ); + assert_eq!( + guard_json.get("owner"), + Some(&serde_json::json!({ + "rule":"data.test.p", "call_instance":1, "attempt":1 + })) + ); + assert_eq!(guard_json.get("call_uses"), Some(&serde_json::json!([[1]]))); + assert_eq!( + guard_json, + json.pointer("/rules/0/attempts/0/conditions/0") + .context("failed primary")? + ); + assert_eq!( + json.pointer("/rules/0/calls/0/call_instance"), + json.pointer("/rules/1/call_instance") + ); + assert_eq!( + json.pointer("/rules/0/attempts/2/conditions/0/call_uses"), + Some(&serde_json::json!([[2]])) + ); + let mutable_proof = report + .rules + .first_mut() + .and_then(|rule| rule.results.as_mut()) + .and_then(|results| results.first_mut()) + .and_then(|attribution| attribution.proofs.first_mut()) + .context("mutable proof")?; + mutable_proof.eligibility = None; + assert!(serde_json::to_value(&mutable_proof)? + .get("eligibility") + .is_none()); + mutable_proof.eligibility = Some(Vec::new()); + assert_eq!( + serde_json::to_value(&mutable_proof)?.get("eligibility"), + Some(&serde_json::json!([])) + ); + } + Ok(()) +} + #[test] fn arbitrary_queries_own_cached_uses_and_negation_scopes() -> anyhow::Result<()> { let mut report = complete_rule_report(); @@ -2101,7 +2320,7 @@ fn two_variable_query_witness_names_key_and_value_roles() -> anyhow::Result<()> } #[test] -fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow::Result<()> { +fn incoming_arguments_keep_caller_paths_out_of_uncached_function_proofs() -> anyhow::Result<()> { for query_owned in [false, true] { let mut report = complete_rule_report(); let mut template = report.rules.first().context("rule template")?.clone(); @@ -2163,21 +2382,21 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: }, CallUse { use_id: 4, - call_instance: 3, + call_instance: 5, attempt: None, scope: None, arguments: Some(vec![known(Value::from(false), Some("input.b"))]), }, CallUse { use_id: 5, - call_instance: 2, + call_instance: 6, attempt: None, scope: None, arguments: Some(vec![known(Value::from(false), Some("input.a"))]), }, CallUse { use_id: 6, - call_instance: 4, + call_instance: 7, attempt: None, scope: None, arguments: Some(vec![argument(4), argument(5)]), @@ -2213,13 +2432,20 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: caller.calls = Some(calls); report.rules.push(caller); } - for (call_instance, helper_name) in [(2, "f"), (3, "g"), (4, "same")] { + for (call_instance, helper_name) in [ + (2, "f"), + (3, "g"), + (4, "same"), + (5, "g"), + (6, "f"), + (7, "same"), + ] { let mut helper = template.clone(); helper.name = format!("data.test.{helper_name}"); helper.call_instance = call_instance; helper.kind = RuleKind::Function; - helper.result = ReportedValue::Known(Value::from(call_instance == 4)); - if call_instance == 4 { + helper.result = ReportedValue::Known(Value::from(helper_name == "same")); + if helper_name == "same" { let parameter = |index| { let mut operand = known(Value::from(false), None); operand.parameter_origins = Some(vec![ParameterOrigin { @@ -2237,7 +2463,7 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: owner: ConditionOwner { rule: helper.name.clone(), call_instance, - attempt: Some(4), + attempt: Some(call_instance), scope: None, }, call_uses: Some(Vec::new()), @@ -2255,7 +2481,7 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: owner: ConditionOwner { rule: helper.name.clone(), call_instance, - attempt: Some(4), + attempt: Some(call_instance), scope: None, }, call_uses: Some(Vec::new()), @@ -2267,29 +2493,40 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: binding: None, }; conditions.push(comparison.clone()); + // This helper succeeds in the else body of its second definition. helper.definitions = vec![DefinitionExplanation { - index: 0, - body: 0, + index: 1, + body: 1, outcome: Outcome::Success, location: None, conditions: vec![comparison], }]; - helper.attempts = Some(vec![AttemptExplanation { - attempt: 4, - definition: 0, - body: 0, - outcome: Some(Outcome::Success), - conditions: Some(conditions.clone()), - }]); + helper.attempts = Some(vec![ + AttemptExplanation { + attempt: call_instance.saturating_sub(1), + definition: 1, + body: 0, + outcome: Some(Outcome::Failure), + conditions: None, + }, + AttemptExplanation { + attempt: call_instance, + definition: 1, + body: 1, + outcome: Some(Outcome::Success), + conditions: Some(conditions.clone()), + }, + ]); helper.results = Some(vec![ResultExplanation::new( None, ReportedValue::Known(Value::from(true)), Count::Exact(1), Vec::new(), vec![Derivation { - definition: 0, - body: 0, - attempt: Some(4), + eligibility: None, + definition: 1, + body: 1, + attempt: Some(call_instance), conditionality: None, call_uses: Some(Vec::new()), conditions, @@ -2312,21 +2549,40 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: .get("rules") .and_then(serde_json::Value::as_array) .context("rules")?; - let same = helpers.last().context("same")?; for (use_index, expected) in [ (2, ["data.test.f", "data.test.g"]), (5, ["data.test.g", "data.test.f"]), ] { + let incoming = caller_uses.get(use_index).context("incoming same call")?; + let same = helpers + .iter() + .find(|rule| rule.get("call_instance") == incoming.get("call_instance")) + .context("owning same invocation")?; + let proof = same.pointer("/results/0/proofs/0").context("same proof")?; + let attempt = same + .get("attempts") + .and_then(serde_json::Value::as_array) + .and_then(|attempts| { + attempts + .iter() + .find(|attempt| attempt.get("attempt") == proof.get("attempt")) + }) + .context("proof attempt resolves in its containing invocation")?; + assert_eq!(attempt.get("definition"), proof.get("definition")); + assert_eq!(attempt.get("body"), proof.get("body")); + assert_eq!(proof.get("definition"), Some(&serde_json::json!(1))); + assert_eq!(proof.get("body"), Some(&serde_json::json!(1))); + assert_ne!(proof.get("attempt"), Some(&serde_json::json!(1))); for (position, name) in expected.into_iter().enumerate() { assert_eq!( - same.pointer(&format!( - "/attempts/0/conditions/{position}/left/parameter_origins/0/argument" + attempt.pointer(&format!( + "/conditions/{position}/left/parameter_origins/0/argument" )), Some(&serde_json::json!(position)) ); assert_eq!( - same.pointer(&format!( - "/attempts/0/conditions/2/{}/parameter_origins", + attempt.pointer(&format!( + "/conditions/2/{}/parameter_origins", if position == 0 { "left" } else { "right" } )), Some(&serde_json::json!([{"argument":position,"path":[]}])) @@ -2355,12 +2611,17 @@ fn incoming_arguments_keep_caller_paths_out_of_shared_callee_proofs() -> anyhow: .context("producer")?; assert_eq!(producer.get("name"), Some(&serde_json::json!(name))); } + assert_eq!(same.get("calls"), Some(&serde_json::json!([]))); + assert_eq!(proof.get("call_uses"), Some(&serde_json::json!([]))); } - assert_eq!(same.get("calls"), Some(&serde_json::json!([]))); - assert_eq!( - same.pointer("/results/0/proofs/0/call_uses"), - Some(&serde_json::json!([])) - ); + let invocations = caller_uses + .iter() + .filter_map(|edge| { + edge.get("call_instance") + .and_then(serde_json::Value::as_u64) + }) + .collect::>(); + assert_eq!(invocations.len(), 6, "user function calls are not cached",); } Ok(()) } @@ -2467,6 +2728,7 @@ fn destructured_parameter_origins_preserve_typed_projections() -> anyhow::Result #[test] fn conditionality_is_independent_of_bounded_proofs() -> anyhow::Result<()> { let proof = |conditionality| Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, @@ -3070,6 +3332,7 @@ fn nested_comprehension_conditions_do_not_replace_the_finding_subject() -> anyho count: Some(Count::Exact(1)), }], vec![Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, @@ -3272,6 +3535,7 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: Count::Exact(1), Vec::new(), vec![Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0, @@ -3327,6 +3591,7 @@ fn value_only_helpers_keep_argument_origins_without_body_predicates() -> anyhow: #[test] fn uncaptured_bindings_are_not_an_empty_contributor_set() -> Result<(), serde_json::Error> { let mut proof = Derivation { + eligibility: None, call_uses: None, definition: 0, body: 0,