1use crate::application::{
11 evaluate_precondition, AccessMode, ApplicationContractDocument, ApplicationPolicyContext,
12 EvaluationResult as AppResult, FieldType, ScalarType, TypedValue,
13};
14use crate::graph::Graph;
15use crate::policy::Policy;
16use crate::primitives::Instance;
17use indexmap::IndexMap;
18use serde::Deserialize;
19use serde_json::{json, Map, Value};
20use std::collections::{BTreeSet, HashSet};
21
22pub const FACTS_SCHEMA: &str = "domainforge.evaluate-facts.v1";
23pub const OUTPUT_SCHEMA: &str = "domainforge.evaluate-output.v1";
24
25#[derive(Debug, Clone, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct Facts {
29 pub schema: String,
30 #[serde(default)]
31 pub instances: Vec<FactInstance>,
32 #[serde(default)]
33 pub operation_inputs: Vec<OperationInput>,
34}
35
36#[derive(Debug, Clone, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct FactInstance {
39 pub namespace: String,
40 pub entity: String,
41 pub name: String,
42 #[serde(default)]
43 pub fields: Map<String, Value>,
44}
45
46#[derive(Debug, Clone, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct OperationInput {
49 pub id: String,
50 pub operation: String,
51 #[serde(default)]
54 pub input: IndexMap<String, TypedValue>,
55}
56
57impl Facts {
58 pub fn from_json(text: &str) -> Result<Self, String> {
59 let facts: Facts =
60 serde_json::from_str(text).map_err(|e| format!("invalid facts file: {e}"))?;
61 if facts.schema != FACTS_SCHEMA {
62 return Err(format!(
63 "unsupported facts schema '{}': expected '{FACTS_SCHEMA}'",
64 facts.schema
65 ));
66 }
67 Ok(facts)
68 }
69}
70
71fn kind_matches(declared: &FieldType, value: &TypedValue) -> bool {
72 match (declared, value) {
73 (FieldType::Scalar { scalar }, v) => matches!(
74 (scalar, v),
75 (ScalarType::String, TypedValue::String(_))
76 | (ScalarType::Int, TypedValue::Int(_))
77 | (ScalarType::Decimal, TypedValue::Decimal(_))
78 | (ScalarType::Bool, TypedValue::Bool(_))
79 | (ScalarType::Timestamp, TypedValue::Timestamp(_))
80 | (ScalarType::Uuid, TypedValue::Uuid(_))
81 ),
82 (FieldType::Quantity { unit }, TypedValue::Quantity { unit: supplied, .. }) => {
83 unit == supplied
84 }
85 (
86 FieldType::EntityRef { entity },
87 TypedValue::EntityRef {
88 entity: supplied, ..
89 },
90 ) => entity == supplied,
91 (
92 FieldType::Enum { symbol },
93 TypedValue::Enum {
94 symbol: supplied, ..
95 },
96 ) => symbol == supplied,
97 (FieldType::List { element }, TypedValue::List(items)) => {
98 items.iter().all(|i| kind_matches(element, i))
99 }
100 _ => false,
101 }
102}
103
104fn tri(value: Option<bool>) -> &'static str {
105 match value {
106 Some(true) => "true",
107 Some(false) => "false",
108 None => "unknown",
109 }
110}
111
112pub fn load_instances(graph: &mut Graph, facts: &Facts) -> Result<(), String> {
115 let instances = facts
118 .instances
119 .iter()
120 .map(|fact| {
121 let mut instance =
122 Instance::new_with_namespace(&fact.name, &fact.entity, &fact.namespace);
123 for (key, value) in &fact.fields {
124 instance.set_field(key.clone(), value.clone());
125 }
126 instance
127 })
128 .collect();
129 graph
130 .add_entity_instances(instances)
131 .map_err(|e| format!("facts instances: {e}"))
132}
133
134fn policy_head(policy: &Policy) -> Map<String, Value> {
135 let mut row = Map::new();
136 row.insert("policy_id".into(), json!(policy.id.to_string()));
137 row.insert("policy".into(), json!(policy.name));
138 row.insert("namespace".into(), json!(policy.namespace));
139 row.insert(
140 "kind".into(),
141 json!(format!("{:?}", policy.kind()).to_lowercase()),
142 );
143 row.insert(
144 "modality".into(),
145 json!(format!("{:?}", policy.modality).to_lowercase()),
146 );
147 row
148}
149
150pub fn evaluate_model(
154 graph: &Graph,
155 contract: &ApplicationContractDocument,
156 facts: &Facts,
157) -> Result<Vec<Value>, String> {
158 if !graph.use_three_valued_logic() {
159 return Err(
160 "evaluate requires three-valued logic; the graph is in boolean mode".to_string(),
161 );
162 }
163 let operations = &contract.contract.operations;
164 let records = &contract.contract.records;
165
166 let mut seen_ids = BTreeSet::new();
167 for supplied in &facts.operation_inputs {
168 if !seen_ids.insert(supplied.id.as_str()) {
169 return Err(format!("duplicate operation input id '{}'", supplied.id));
170 }
171 let mut matching = operations.iter().filter(|op| op.name == supplied.operation);
172 let operation = matching.next().ok_or_else(|| {
173 format!(
174 "operation input '{}': unknown operation '{}'",
175 supplied.id, supplied.operation
176 )
177 })?;
178 if matching.next().is_some() {
179 return Err(format!(
180 "operation input '{}': ambiguous operation '{}'",
181 supplied.id, supplied.operation
182 ));
183 }
184 let governed = matches!(&operation.access,
185 AccessMode::PolicyGoverned { bindings } if !bindings.is_empty());
186 if !governed {
187 return Err(format!(
188 "operation input '{}': operation '{}' is not policy-governed, so no policy would evaluate it",
189 supplied.id, supplied.operation
190 ));
191 }
192 let record = records.iter().find(|r| r.id == operation.input);
193 for (field, value) in &supplied.input {
194 let declared = record.and_then(|r| r.fields.iter().find(|f| &f.name == field));
195 let Some(declared) = declared else {
196 return Err(format!(
197 "operation input '{}': unknown input field '{}' for operation '{}'",
198 supplied.id, field, supplied.operation
199 ));
200 };
201 if !kind_matches(&declared.field_type, value) {
202 return Err(format!(
203 "operation input '{}': field '{}' has the wrong value kind, unit, entity or enum symbol for its declared type {:?}",
204 supplied.id, field, declared.field_type
205 ));
206 }
207 }
208 }
209
210 let fact_names: HashSet<&str> = facts.instances.iter().map(|i| i.name.as_str()).collect();
211 let mut bound_ids = HashSet::new();
212 let mut rows: Vec<(String, String, Value)> = Vec::new();
213
214 for operation in operations {
215 let AccessMode::PolicyGoverned { bindings } = &operation.access else {
216 continue;
217 };
218 for binding in bindings {
219 bound_ids.insert(binding.policy.clone());
220 let Some(policy) = graph.get_policy(&binding.policy) else {
221 return Err(format!(
222 "operation '{}' binds a policy that is not in the graph",
223 operation.name
224 ));
225 };
226 let mut supplied: Vec<&OperationInput> = facts
227 .operation_inputs
228 .iter()
229 .filter(|s| s.operation == operation.name)
230 .collect();
231 supplied.sort_by(|a, b| a.id.cmp(&b.id));
232 if supplied.is_empty() {
233 let mut row = policy_head(policy);
234 row.insert("operation_bound".into(), json!(true));
235 row.insert("operation".into(), json!(operation.name));
236 row.insert("result".into(), json!("unknown"));
237 row.insert("reason".into(), json!("no_operation_input"));
238 rows.push((
239 policy.id.to_string(),
240 format!("{}\u{0}", operation.name),
241 Value::Object(row),
242 ));
243 }
244 for input in &supplied {
245 let context = ApplicationPolicyContext {
246 operation: operation.id.clone(),
247 actor: operation.actor.clone(),
248 input: input.input.clone(),
249 pre_state: None,
250 };
251 let mut row = policy_head(policy);
252 row.insert("operation_bound".into(), json!(true));
253 row.insert("operation".into(), json!(operation.name));
254 row.insert("input_set_id".into(), json!(input.id));
255 let result = match evaluate_precondition(policy.expression(), &context) {
256 AppResult::True => Some(true),
257 AppResult::False => Some(false),
258 AppResult::Unknown => {
259 row.insert("reason".into(), json!("unknown_input"));
260 None
261 }
262 AppResult::Error(message) => {
263 row.insert("reason".into(), json!("evaluation_error"));
264 row.insert("error".into(), json!(message));
265 None
266 }
267 };
268 row.insert("result".into(), json!(tri(result)));
269 rows.push((
270 policy.id.to_string(),
271 format!("{}\u{0}{}", operation.name, input.id),
272 Value::Object(row),
273 ));
274 }
275 }
276 }
277
278 for policy in graph.all_policies() {
279 if bound_ids.contains(&policy.id) || graph.is_operation_bound_policy(&policy.id) {
280 continue;
281 }
282 let mut row = policy_head(policy);
283 row.insert("operation_bound".into(), json!(false));
284 match policy.evaluate_bindings(graph) {
285 Ok(report) => {
286 row.insert("result".into(), json!(tri(report.result)));
287 row.insert("support".into(), json!(report.support));
288 if report.support.is_some() {
289 row.insert("binding_depth".into(), json!("outermost"));
290 }
291 let bindings: Vec<Value> = report
292 .bindings
293 .iter()
294 .map(|b| {
295 let from_facts = fact_names.contains(b.instance.as_str());
296 json!({
297 "source": if from_facts { "facts" } else { "model" },
298 "entity": b.entity,
299 "namespace": b.namespace,
300 "instance": b.instance,
301 "instance_id": b.instance_id,
302 "result": tri(b.result),
303 })
304 })
305 .collect();
306 row.insert("bindings".into(), Value::Array(bindings));
307 }
308 Err(message) => {
309 row.insert("result".into(), json!("unknown"));
310 row.insert("support".into(), Value::Null);
311 row.insert("reason".into(), json!("evaluation_error"));
312 row.insert("error".into(), json!(message));
313 row.insert("bindings".into(), json!([]));
314 }
315 }
316 rows.push((policy.id.to_string(), String::new(), Value::Object(row)));
317 }
318
319 rows.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
320 Ok(rows.into_iter().map(|(_, _, row)| row).collect())
321}