zen-engine 2.0.1

Business rules engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::sync::Arc;

use serde_json::{json, Value};
use zen_engine::loader::MemoryLoader;
use zen_engine::model::DecisionContent;
use zen_engine::policy::{BlockExecution, BlockTrace, GraphTraceMap, Trace, Workspace};
use zen_engine::{DecisionEngine, EvaluationOptions};

fn document(value: Value) -> DecisionContent {
    serde_json::from_value(value).expect("valid decision content")
}

fn node(id: &str, kind: &str, content: Value) -> Value {
    json!({ "id": id, "name": id, "type": kind, "content": content })
}

fn edge(id: &str, source: &str, target: &str) -> Value {
    json!({ "id": id, "sourceId": source, "targetId": target, "sourceHandle": null })
}

fn expression_node(id: &str, rows: &[(&str, &str)], attributes: Value) -> Value {
    let expressions: Vec<Value> = rows
        .iter()
        .enumerate()
        .map(|(i, (key, value))| json!({ "id": format!("{id}-e{i}"), "key": key, "value": value }))
        .collect();
    let mut content = json!({ "expressions": expressions });
    merge(&mut content, attributes);
    node(id, "expressionNode", content)
}

fn merge(target: &mut Value, extra: Value) {
    let (Some(target), Some(extra)) = (target.as_object_mut(), extra.as_object()) else {
        return;
    };
    for (key, value) in extra {
        target.insert(key.clone(), value.clone());
    }
}

fn linear_graph(middle: Vec<Value>) -> Value {
    let mut nodes = vec![node("in", "inputNode", json!({}))];
    let mut edges = Vec::new();
    let mut prev = "in".to_string();
    for n in middle {
        let id = n["id"].as_str().unwrap().to_string();
        edges.push(edge(&format!("edge-{prev}-{id}"), &prev, &id));
        nodes.push(n);
        prev = id;
    }
    nodes.push(node("out", "outputNode", json!({})));
    edges.push(edge(&format!("edge-{prev}-out"), &prev, "out"));
    json!({ "nodes": nodes, "edges": edges })
}

async fn graph_trace(documents: &[(&str, Value)], entry: &str, input: Value) -> GraphTraceMap {
    let loader = Arc::new(MemoryLoader::default());
    for (key, value) in documents {
        loader.add(*key, document(value.clone()));
    }
    let engine = DecisionEngine::default().with_loader(loader);
    let response = engine
        .evaluate_with_opts(
            entry,
            input.into(),
            EvaluationOptions {
                trace: true,
                max_depth: 10,
            },
        )
        .await
        .expect("evaluation succeeds");
    response
        .trace
        .expect("trace present")
        .into_graph()
        .expect("graph trace")
}

async fn enhance(documents: &[(&str, Value)], entry: &str, input: Value) -> Trace {
    let trace = graph_trace(documents, entry, input.clone()).await;
    let mut ws = Workspace::new();
    for (key, value) in documents {
        ws.set_document(*key, document(value.clone()));
    }
    ws.enhance_graph_trace(&Arc::from(entry), &trace)
        .expect("enhance succeeds")
}

fn execution<'a>(trace: &'a Trace, block_id: &str) -> &'a BlockExecution {
    trace
        .executions
        .iter()
        .find(|ex| ex.block_id.as_ref() == block_id)
        .unwrap_or_else(|| panic!("execution {block_id} missing"))
}

fn sorted_reads(execution: &BlockExecution) -> Vec<String> {
    let mut reads: Vec<String> = execution.reads.iter().map(|r| r.to_string()).collect();
    reads.sort();
    reads
}

#[tokio::test]
async fn expression_rows_get_ast_reads_including_dollar_refs() {
    let docs = [(
        "g",
        linear_graph(vec![expression_node(
            "calc",
            &[
                ("priorFee", "ledger.prior"),
                (
                    "feeEntry",
                    "inject ? { fee: merge([$.priorFee, { roundedTotal: round(($.priorFee.sum ?? 0) + surcharge, 2) }]) } : {}",
                ),
            ],
            json!({}),
        )]),
    )];
    let trace = enhance(
        &docs,
        "g",
        json!({ "ledger": { "prior": { "sum": 1 } }, "surcharge": 2, "inject": true }),
    )
    .await;

    let first = execution(&trace, "calc:calc-e0");
    assert!(
        matches!(&first.trace, BlockTrace::Expression { property, .. } if property.as_ref() == "priorFee")
    );
    assert_eq!(sorted_reads(first), vec!["ledger.prior"]);

    let second = execution(&trace, "calc:calc-e1");
    assert_eq!(
        sorted_reads(second),
        vec!["inject", "priorFee", "priorFee.sum", "surcharge"]
    );
    assert_eq!(
        second.operand_values.get("surcharge"),
        Some(&json!(2).into())
    );
    assert_eq!(
        second.operand_values.get("$.priorFee.sum"),
        Some(&json!(1).into())
    );
    assert!(trace.properties.contains_key("feeEntry"));
}

#[tokio::test]
async fn dotted_expression_keys_resolve_trace_values() {
    // Expression trace maps are keyed by the LITERAL row key; a key containing
    // dots ("quote.annualPremium") must not be resolved as a nested path.
    let docs = [(
        "g",
        linear_graph(vec![expression_node(
            "calc",
            &[
                ("base", "100"),
                ("quote.annualPremium", "round($.base * 2.5, 2)"),
                ("doubled", "$.quote.annualPremium * 2"),
                ("quote.factors.driver", "$.base / 100"),
            ],
            json!({}),
        )]),
    )];
    let trace = enhance(&docs, "g", json!({})).await;

    let premium = execution(&trace, "calc:calc-e1");
    match &premium.trace {
        BlockTrace::Expression { property, value } => {
            assert_eq!(property.as_ref(), "quote.annualPremium");
            assert_eq!(value, &json!(250).into());
        }
        other => panic!("unexpected trace: {other:?}"),
    }

    // The dotted key must also reach the $ scope of subsequent rows.
    let doubled = execution(&trace, "calc:calc-e2");
    assert_eq!(
        doubled.operand_values.get("$.quote.annualPremium"),
        Some(&json!(250).into())
    );

    // Depth is irrelevant: two-level keys resolve the same way.
    let driver = execution(&trace, "calc:calc-e3");
    assert!(matches!(
        &driver.trace,
        BlockTrace::Expression { property, value }
            if property.as_ref() == "quote.factors.driver" && *value == json!(1).into()
    ));
}

#[tokio::test]
async fn decision_table_maps_rows_reads_and_evaluations() {
    let table = node(
        "pricing",
        "decisionTableNode",
        json!({
            "hitPolicy": "first",
            "inputs": [{ "id": "c1", "name": "Total", "field": "cart.total" }],
            "outputs": [{ "id": "o1", "name": "Discount", "field": "discount" }],
            "rules": [
                { "c1": "> 500", "o1": "0.2" },
                { "c1": "", "o1": "0.1" }
            ]
        }),
    );
    let docs = [("g", linear_graph(vec![table]))];
    let trace = enhance(&docs, "g", json!({ "cart": { "total": 100 } })).await;

    let table = execution(&trace, "pricing");
    let BlockTrace::DecisionTable {
        matched_rows,
        evaluations,
        extras,
    } = &table.trace
    else {
        panic!("expected decision table trace");
    };
    assert_eq!(matched_rows, &vec![1]);
    assert_eq!(evaluations.len(), 1);
    assert_eq!(evaluations[0].get("discount"), Some(&json!(0.1).into()));
    assert!(sorted_reads(table).contains(&"cart.total".to_string()));
    assert_eq!(trace.properties.get("discount"), Some(&json!(0.1).into()));
    assert_eq!(input_pass_bits(extras), vec![0b0, 0b1]);
}

fn input_pass_bits(extras: &Option<zen_engine::policy::DecisionTableExtras>) -> Vec<u8> {
    use base64::Engine as _;
    let extras = extras.as_ref().expect("extras present");
    base64::engine::general_purpose::STANDARD
        .decode(&extras.input_pass)
        .expect("valid base64")
}

#[tokio::test]
async fn switch_records_arms_and_condition_reads() {
    let switch = node(
        "route",
        "switchNode",
        json!({ "statements": [
            { "id": "s1", "condition": "fee > 5" },
            { "id": "s2", "condition": "" }
        ]}),
    );
    let branch_a = expression_node("high", &[("tier", "'high'")], json!({}));
    let branch_b = expression_node("low", &[("tier", "'low'")], json!({}));
    let graph = json!({
        "nodes": [
            node("in", "inputNode", json!({})),
            switch,
            branch_a,
            branch_b,
            node("out", "outputNode", json!({}))
        ],
        "edges": [
            edge("e1", "in", "route"),
            { "id": "e2", "sourceId": "route", "targetId": "high", "sourceHandle": "s1" },
            { "id": "e3", "sourceId": "route", "targetId": "low", "sourceHandle": "s2" },
            edge("e4", "high", "out"),
            edge("e5", "low", "out")
        ]
    });
    let docs = [("g", graph)];
    let trace = enhance(&docs, "g", json!({ "fee": 10 })).await;

    let switch = execution(&trace, "route");
    let BlockTrace::Match {
        matched_arm, arms, ..
    } = &switch.trace
    else {
        panic!("expected match trace");
    };
    assert_eq!(matched_arm.as_deref(), Some("s1"));
    assert_eq!(
        arms.iter().map(|arm| arm.result).collect::<Vec<_>>(),
        vec![true, false]
    );
    assert_eq!(sorted_reads(switch), vec!["fee"]);
    assert_eq!(switch.operand_values.get("fee"), Some(&json!(10).into()));
}

#[tokio::test]
async fn sub_decision_recurses_with_prefixed_ids_and_free_reads() {
    let sub = linear_graph(vec![expression_node(
        "risk",
        &[("risk", "total > 500 ? 'high' : 'low'")],
        json!({}),
    )]);
    let main = linear_graph(vec![node("call", "decisionNode", json!({ "key": "sub" }))]);
    let docs = [("g", main), ("sub", sub)];
    let trace = enhance(&docs, "g", json!({ "total": 600 })).await;

    let group = execution(&trace, "call");
    assert_eq!(sorted_reads(group), vec!["total"]);
    assert!(group
        .writes
        .iter()
        .any(|write| write.path.as_ref() == "risk"));

    let nested = execution(&trace, "call/risk:risk-e0");
    assert!(
        matches!(&nested.trace, BlockTrace::Expression { property, .. } if property.as_ref() == "risk")
    );
    assert_eq!(sorted_reads(nested), vec!["total"]);
    assert_eq!(trace.properties.get("risk"), Some(&json!("high").into()));
}

#[tokio::test]
async fn looped_sub_decision_gets_instance_paths_and_mapped_reads() {
    let sub = linear_graph(vec![expression_node(
        "risk",
        &[("risk", "total > 500 ? 'high' : 'low'")],
        json!({}),
    )]);
    let main = linear_graph(vec![node(
        "call",
        "decisionNode",
        json!({
            "key": "sub",
            "inputField": "items",
            "outputPath": "results",
            "executionMode": "loop"
        }),
    )]);
    let docs = [("g", main), ("sub", sub)];
    let trace = enhance(
        &docs,
        "g",
        json!({ "items": [{ "total": 600 }, { "total": 100 }] }),
    )
    .await;

    let group = execution(&trace, "call");
    assert_eq!(sorted_reads(group), vec!["items.total"]);
    assert!(group
        .writes
        .iter()
        .any(|write| write.path.as_ref() == "results"));

    let first = execution(&trace, "call[0]/risk:risk-e0");
    assert_eq!(first.instance_path.as_deref(), Some("items.0"));
    assert!(
        matches!(&first.trace, BlockTrace::Expression { value, .. } if *value == json!("high").into())
    );
    let second = execution(&trace, "call[1]/risk:risk-e0");
    assert_eq!(second.instance_path.as_deref(), Some("items.1"));
    assert!(
        matches!(&second.trace, BlockTrace::Expression { value, .. } if *value == json!("low").into())
    );
}

#[tokio::test]
async fn looped_table_extracts_per_iteration_evaluations_under_output_path() {
    let table = node(
        "pricing",
        "decisionTableNode",
        json!({
            "hitPolicy": "first",
            "inputField": "carts",
            "outputPath": "discounts",
            "executionMode": "loop",
            "inputs": [{ "id": "c1", "name": "Total", "field": "total" }],
            "outputs": [{ "id": "o1", "name": "Discount", "field": "discount" }],
            "rules": [
                { "c1": "> 500", "o1": "0.2" },
                { "c1": "", "o1": "0.1" }
            ]
        }),
    );
    let docs = [("g", linear_graph(vec![table]))];
    let trace = enhance(
        &docs,
        "g",
        json!({ "carts": [{ "total": 600 }, { "total": 100 }] }),
    )
    .await;

    let iterations: Vec<&BlockExecution> = trace
        .executions
        .iter()
        .filter(|ex| ex.block_id.as_ref() == "pricing")
        .collect();
    assert_eq!(iterations.len(), 2);
    assert_eq!(iterations[0].instance_path.as_deref(), Some("carts.0"));
    assert_eq!(iterations[1].instance_path.as_deref(), Some("carts.1"));

    let BlockTrace::DecisionTable {
        matched_rows,
        evaluations,
        extras,
    } = &iterations[0].trace
    else {
        panic!("expected decision table trace");
    };
    assert_eq!(matched_rows, &vec![0]);
    assert_eq!(
        evaluations[0].get("discounts.discount"),
        Some(&json!(0.2).into())
    );
    assert_eq!(input_pass_bits(extras), vec![0b1, 0b1]);
    let BlockTrace::DecisionTable { extras, .. } = &iterations[1].trace else {
        panic!("expected decision table trace");
    };
    assert_eq!(input_pass_bits(extras), vec![0b0, 0b1]);
    assert!(sorted_reads(iterations[0]).contains(&"carts.total".to_string()));
    assert_eq!(
        iterations[0].operand_values.get("total"),
        Some(&json!(600).into())
    );
    assert_eq!(
        iterations[1].operand_values.get("total"),
        Some(&json!(100).into())
    );
}