lemma-engine 0.9.8

A pure, declarative language for business rules.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use lemma::{Engine, SourceType};
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;

fn explanation_json(response: &lemma::Response, rule: &str) -> Value {
    serde_json::to_value(response).unwrap()["results"][rule]["explanation"].clone()
}

fn compose_nodes_matching<'a>(value: &'a Value, needle: &str) -> Vec<&'a Value> {
    let mut found = Vec::new();
    fn walk<'a>(value: &'a Value, needle: &str, found: &mut Vec<&'a Value>) {
        match value {
            Value::Object(obj) => {
                if obj.get("type").and_then(|t| t.as_str()) == Some("compose")
                    && obj
                        .get("expression")
                        .and_then(|e| e.as_str())
                        .is_some_and(|expr| expr.contains(needle))
                {
                    found.push(value);
                }
                for child in obj.values() {
                    walk(child, needle, found);
                }
            }
            Value::Array(arr) => {
                for child in arr {
                    walk(child, needle, found);
                }
            }
            _ => {}
        }
    }
    walk(value, needle, &mut found);
    found
}

fn assert_rule_binary_right_veto_children(explanation: &Value, body_needle: &str) {
    assert!(
        explanation["body"]
            .as_str()
            .is_some_and(|body| body.contains(body_needle)),
        "rule body must retain binary expression, got: {explanation}"
    );
    let children = explanation["children"]
        .as_array()
        .expect("rule explanation must have children");
    assert_eq!(
        children.len(),
        2,
        "binary right veto must expose both operands under rule, got: {explanation}"
    );
    assert_eq!(
        children[0]["type"], "compose",
        "left settled operand must be compose child: {explanation}"
    );
    assert_eq!(
        children[1]["type"], "rule",
        "right veto embed must remain second operand: {explanation}"
    );
    assert_eq!(children[1]["name"], "base");
}

fn run_settled_left_right_veto_explanation(
    engine: &mut Engine,
    spec: &str,
    rule_body: &str,
) -> Value {
    engine
        .load([(
            SourceType::Volatile,
            format!(
                r#"
spec demo
data age: number
rule base: veto "no rate"
  unless age < 70 then 10
rule main: {rule_body}
"#
            ),
        )])
        .expect("load");
    let mut data = HashMap::new();
    data.insert("age".to_string(), "80".to_string());
    let response = engine
        .run(None, spec, None, data, Some(&["main".to_string()]), true)
        .expect("evaluation must succeed");
    explanation_json(&response, "main")
}

#[test]
fn explanation_comparison_right_veto_compose() {
    let mut engine = Engine::new();
    let explanation = run_settled_left_right_veto_explanation(&mut engine, "demo", "100 > base");
    assert_rule_binary_right_veto_children(&explanation, ">");
    assert_eq!(explanation["body"], "100 > base");
    assert_eq!(explanation["children"][0]["expression"], "100");
}

#[test]
fn explanation_range_literal_right_veto_compose() {
    let mut engine = Engine::new();
    let explanation = run_settled_left_right_veto_explanation(&mut engine, "demo", "0...base");
    assert_rule_binary_right_veto_children(&explanation, "base");
    assert!(
        explanation["body"]
            .as_str()
            .is_some_and(|body| body.contains("0") && body.contains("base")),
        "range literal body must name both endpoints: {}",
        explanation["body"]
    );
    assert_eq!(explanation["children"][0]["expression"], "0");
}

#[test]
fn explanation_range_containment_right_veto_compose() {
    let mut engine = Engine::new();
    let explanation =
        run_settled_left_right_veto_explanation(&mut engine, "demo", "50 in 0...base");
    assert!(
        explanation["body"]
            .as_str()
            .is_some_and(|body| body.contains("50") && body.contains("in")),
        "range containment body must name value and range: {}",
        explanation["body"]
    );
    let children = explanation["children"]
        .as_array()
        .expect("rule explanation must have children");
    assert_eq!(
        children.len(),
        2,
        "range containment right veto must expose value and range operands: {explanation}"
    );
    assert_eq!(children[0]["type"], "compose");
    assert_eq!(children[0]["expression"], "50");
    assert_eq!(children[1]["type"], "compose");
    let range = compose_nodes_matching(&children[1], "to");
    assert!(
        !range.is_empty(),
        "range operand must remain a compose subtree: {explanation}"
    );
    fn has_rule_named_base(value: &Value) -> bool {
        match value {
            Value::Object(obj) => {
                if obj.get("type").and_then(|t| t.as_str()) == Some("rule")
                    && obj.get("name").and_then(|n| n.as_str()) == Some("base")
                {
                    return true;
                }
                obj.values().any(has_rule_named_base)
            }
            Value::Array(arr) => arr.iter().any(has_rule_named_base),
            _ => false,
        }
    }
    assert!(
        has_rule_named_base(&children[1]),
        "range compose must still embed vetoing base rule: {explanation}"
    );
}

#[test]
fn explanation_unless_default_matched() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data x: text -> option "a" -> option "b"
rule out: 1 unless x is "b" then 2
"#
            .to_string(),
        )])
        .unwrap();
    let mut data = HashMap::new();
    data.insert("x".into(), "a".into());
    let response = engine
        .run(None, "t", None, data, Some(&["out".to_string()]), true)
        .unwrap();
    let explanation = explanation_json(&response, "out");

    assert_eq!(explanation["type"], "rule");
    assert_eq!(explanation["name"], "out");
    assert_eq!(explanation["result"], "1");
    assert_eq!(explanation["body"], "1");
    let causes = explanation["causes"].as_array().unwrap();
    assert_eq!(causes.len(), 1);
    assert_eq!(causes[0]["condition"], "x is not b");
    assert_eq!(causes[0]["value"], "true");
    let cause_children = causes[0]["children"].as_array().unwrap();
    assert_eq!(cause_children[0]["name"], "x");
    assert_eq!(cause_children[0]["display"], "a");
}

#[test]
fn explanation_compose_with_data_operands() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data money: measure -> unit eur: 1 -> decimals 2
data price: 100 eur
data quantity: number
data q: 3
rule total: price * q
"#
            .to_string(),
        )])
        .unwrap();
    let response = engine
        .run(
            None,
            "t",
            None,
            HashMap::new(),
            Some(&["total".to_string()]),
            true,
        )
        .unwrap();
    let explanation = explanation_json(&response, "total");

    assert_eq!(explanation["body"], "price * q");
    let children = explanation["children"].as_array().unwrap();
    assert_eq!(children.len(), 2);
    assert_eq!(children[0]["type"], "data");
    assert_eq!(children[0]["name"], "price");
    assert_eq!(children[0]["display"], "100.00 eur");
    assert_eq!(children[1]["name"], "q");
    assert_eq!(children[1]["display"], "3");
}

#[test]
fn explanation_rule_addition_expands_both_rules() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data n: number
data x: 5
rule base: x * 2
rule a: base + 1
rule b: a + base
"#
            .to_string(),
        )])
        .unwrap();
    let response = engine
        .run(
            None,
            "t",
            None,
            HashMap::new(),
            Some(&["b".to_string()]),
            true,
        )
        .unwrap();
    let explanation = explanation_json(&response, "b");

    assert_eq!(explanation["body"], "a + base");
    let children = explanation["children"].as_array().unwrap();
    assert_eq!(children.len(), 2);
    assert_eq!(children[0]["type"], "rule");
    assert_eq!(children[0]["name"], "a");
    assert_eq!(children[1]["type"], "rule");
    assert_eq!(children[1]["name"], "base");
}

#[test]
fn explanation_veto_missing_data() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data n: number
rule out: n * 2
"#
            .to_string(),
        )])
        .unwrap();
    let response = engine
        .run(
            None,
            "t",
            None,
            HashMap::new(),
            Some(&["out".to_string()]),
            true,
        )
        .unwrap();
    let explanation = explanation_json(&response, "out");

    assert_eq!(explanation["result"], "Missing data: n");
    // Walk-faithful: missing data leaf is data; veto text is on result (and display).
    let children = explanation["children"].as_array().unwrap();
    assert_eq!(children[0]["type"], "data");
    assert_eq!(children[0]["name"], "n");
    assert!(children[0]["display"]
        .as_str()
        .unwrap()
        .contains("Missing data: n"));
}

#[test]
fn explanation_always_built_by_engine() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data n: number
data x: 5
rule out: x + 1
"#
            .to_string(),
        )])
        .unwrap();
    let response = engine
        .run(
            None,
            "t",
            None,
            HashMap::new(),
            Some(&["out".to_string()]),
            true,
        )
        .unwrap();
    let json: Value = serde_json::to_value(&response).unwrap();
    assert!(json["results"]["out"]["explanation"].is_object());
}

#[test]
fn explanation_json_compact_for_net_salary() {
    let source = std::fs::read_to_string(
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/nl/tax/net_salary.lemma"),
    )
    .expect("read net_salary fixture");
    let mut engine = Engine::new();
    engine
        .load([(SourceType::Volatile, &source.to_string())])
        .unwrap();
    let mut data = HashMap::new();
    data.insert("gross_salary".into(), "5000 eur".into());
    data.insert("pay_period".into(), "month".into());
    let response = engine
        .run(
            None,
            "net_salary",
            None,
            data,
            Some(&["net_salary".to_string()]),
            true,
        )
        .unwrap();
    let explanation = response
        .get("net_salary")
        .expect("net_salary evaluated")
        .explanation
        .as_ref()
        .expect("explanation");
    let json_string = serde_json::to_string_pretty(explanation).unwrap();
    let line_count = json_string.lines().count();
    // Rule references embed their full explanation tree wherever they appear
    // (no dedup/collapse heuristics), so the JSON grows with the dependency
    // tree. This bound guards against accidental unbounded regressions.
    assert!(
        line_count < 6000,
        "Single-rule explanation JSON should stay bounded with full embedded rule subtrees, got {line_count} lines"
    );
}

#[test]
fn explanation_logical_and_in_body() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data contract_start: 2020-01-01
data contract_end: 2030-01-01
data current_date: 2025-01-01
rule active: current_date >= contract_start and current_date <= contract_end
"#
            .to_string(),
        )])
        .unwrap();
    let response = engine
        .run(
            None,
            "t",
            None,
            HashMap::new(),
            Some(&["active".to_string()]),
            true,
        )
        .unwrap();
    let explanation = explanation_json(&response, "active");

    assert!(
        explanation["body"].as_str().unwrap().contains(" and "),
        "expected and in body, got: {}",
        explanation["body"]
    );
    assert_eq!(explanation["result"], "true");
}

#[test]
fn explanation_unit_conversion() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data weight: measure -> unit kg: 1 -> unit gram: 0.001
data w: 2 kg
rule in_grams: w as gram
"#
            .to_string(),
        )])
        .unwrap();
    let response = engine
        .run(
            None,
            "t",
            None,
            HashMap::new(),
            Some(&["in_grams".to_string()]),
            true,
        )
        .unwrap();
    let explanation = explanation_json(&response, "in_grams");

    let children = explanation["children"].as_array().unwrap();
    assert_eq!(children[0]["type"], "conversion");
    let steps = children[0]["steps"].as_array().unwrap();
    assert!(steps.iter().any(|s| s["role"] == "outcome"));
    assert!(steps.iter().any(|s| s["role"] == "source"));
    assert!(steps
        .iter()
        .any(|s| s["role"] == "rule" && s["text"].as_str().unwrap().contains("1000")));
}

#[test]
fn explain_parameter_gates_explanation_build() {
    let mut engine = Engine::new();
    engine
        .load([(
            SourceType::Volatile,
            r#"
spec t
data x: text -> option "a" -> option "b"
rule out: 1 unless x is "b" then 2
"#
            .to_string(),
        )])
        .unwrap();
    let mut data = HashMap::new();
    data.insert("x".into(), "a".into());
    let without = engine
        .run(None, "t", None, data.clone(), None, false)
        .unwrap();
    assert!(without.results["out"].explanation.is_none());
    let with = engine
        .run(None, "t", None, data, Some(&["out".to_string()]), true)
        .unwrap();
    assert!(with.results["out"].explanation.is_some());
}