lemma-engine 0.11.4

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
//! Missing-data propagation when rules reference other rules (normalized expression).
//!
//! These tests encode **intended** behavior for normalized expression evaluation and
//! needs_data derived from live Piecewise arms.

use indexmap::IndexMap;
use lemma::DateGranularity;
use lemma::DateTimeValue;
use lemma::Engine;
use std::path::PathBuf;
use std::sync::Arc;

fn coffee_example_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/coffee_order.lemma")
}

fn net_salary_example_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/nl/tax/net_salary.lemma")
}

fn effective_2026() -> DateTimeValue {
    DateTimeValue {
        year: 2026,
        month: 6,
        day: 1,
        hour: 12,
        minute: 0,
        second: 0,
        microsecond: 0,
        timezone: None,
        granularity: DateGranularity::DateTime,
    }
}

fn load_volatile(engine: &mut Engine, code: &str) {
    engine
        .load([(lemma::SourceType::Volatile, code.to_string())])
        .expect("spec must plan");
}

fn rule_by_name<'a>(response: &'a lemma::Response, name: &str) -> &'a lemma::RuleResult {
    response
        .results
        .get(name)
        .or_else(|| response.results.values().find(|r| r.rule.name == name))
        .unwrap_or_else(|| panic!("rule '{name}' not in results"))
}

fn assert_veto_reason_contains(rr: &lemma::RuleResult, needle: &str) {
    assert!(rr.vetoed, "rule '{}' must veto", rr.rule.name);
    let reason = rr
        .veto_reason
        .as_deref()
        .unwrap_or_else(|| panic!("rule '{}' vetoed without reason", rr.rule.name));
    assert!(
        reason.contains(needle),
        "rule '{}': expected veto reason containing {needle:?}, got {reason:?}",
        rr.rule.name
    );
}

#[test]
fn missing_data_empty_when_all_datas_provided() {
    let mut engine = Engine::new();
    let code = std::fs::read_to_string(coffee_example_path()).expect("read example");
    engine
        .load([(
            lemma::SourceType::Path(Arc::new(PathBuf::from("01_coffee_order.lemma"))),
            &code.to_string(),
        )])
        .expect("load");

    let now = DateTimeValue::now();

    let mut data = IndexMap::new();
    data.insert("sku".to_string(), "latte".into());
    data.insert("size".to_string(), "medium".into());
    data.insert("number_of_cups".to_string(), "1".into());
    data.insert("has_loyalty_card".to_string(), "false".into());
    data.insert("age".to_string(), "30".into());

    let response = engine
        .evaluate(None, "coffee_order", Some(&now), data, None, false)
        .expect("evaluate");
    for result in response.results.values() {
        assert!(
            result.missing_data().is_empty(),
            "all data provided: {} {:?}",
            result.rule.name,
            result.missing_data()
        );
    }
}

#[test]
fn missing_data_includes_product_when_no_inputs() {
    let mut engine = Engine::new();
    let code = std::fs::read_to_string(coffee_example_path()).expect("read example");
    engine
        .load([(
            lemma::SourceType::Path(Arc::new(PathBuf::from("01_coffee_order.lemma"))),
            &code.to_string(),
        )])
        .expect("load");

    let now = DateTimeValue::now();
    let response = engine
        .evaluate(
            None,
            "coffee_order",
            Some(&now),
            IndexMap::new(),
            None,
            false,
        )
        .expect("evaluate");

    let base_price = rule_by_name(&response, "base_price");
    assert!(
        base_price.is_missing_data(),
        "base_price must be MissingData when sku is unbound: {:?}",
        base_price.veto_reason
    );
    assert_eq!(
        base_price.missing_data(),
        ["sku".to_string()].as_slice(),
        "base_price missing_data must list sku, got {:?}",
        base_price.missing_data()
    );
    assert_eq!(
        base_price.veto_reason.as_deref(),
        Some("Required data 'sku' was not provided."),
        "got {:?}",
        base_price.veto_reason
    );
}

// --- F2 (minimal): dependent rule must propagate Missing data, not default veto arm ---

#[test]
fn rule_ref_dependent_propagates_missing_data_not_default_veto_message() {
    let code = r#"
spec pricing
data sku: text
  -> option "latte"
rule base_price: veto "Unknown product"
  unless sku is "latte" then 3
rule total: base_price * 2
"#;
    let mut engine = Engine::new();
    load_volatile(&mut engine, code);

    let now = DateTimeValue::now();
    let response = engine
        .evaluate(None, "pricing", Some(&now), IndexMap::new(), None, false)
        .expect("evaluate");

    assert_veto_reason_contains(rule_by_name(&response, "base_price"), "Required data");
    assert_veto_reason_contains(rule_by_name(&response, "total"), "Required data");
}

#[test]
fn coffee_order_dependent_rules_propagate_missing_product_not_default_veto() {
    let mut engine = Engine::new();
    let code = std::fs::read_to_string(coffee_example_path()).expect("read example");
    engine
        .load([(
            lemma::SourceType::Path(Arc::new(PathBuf::from("01_coffee_order.lemma"))),
            &code.to_string(),
        )])
        .expect("load");

    let now = DateTimeValue::now();
    let response = engine
        .evaluate(
            None,
            "coffee_order",
            Some(&now),
            IndexMap::new(),
            None,
            false,
        )
        .expect("evaluate");

    assert_veto_reason_contains(rule_by_name(&response, "base_price"), "sku");
    for name in ["price_per_cup", "subtotal", "discount_amount", "total"] {
        let rr = rule_by_name(&response, name);
        assert_veto_reason_contains(rr, "Required data");
        assert!(
            !rr.veto_reason
                .as_deref()
                .is_some_and(|r| r.contains("Unknown type of coffee")),
            "rule '{name}' must not surface default veto arm when dependency lacks data"
        );
    }
}

// --- F1 (minimal): arithmetic on rule ref must not use default unless literal when dependency vetoes ---

#[test]
fn rule_ref_in_product_vetoes_when_periods_rule_missing_data_not_default_twelve() {
    let code = r#"
spec payroll
data gross: number
data pay_period: text
  -> option "month"
  -> option "week"
rule periods_per_year: 12
  unless pay_period is "week" then 52
rule gross_annual: gross * periods_per_year
"#;
    let mut engine = Engine::new();
    load_volatile(&mut engine, code);

    let now = DateTimeValue::now();
    let mut data = IndexMap::new();
    data.insert("gross".to_string(), "5000".into());
    let response = engine
        .evaluate(None, "payroll", Some(&now), data, None, false)
        .expect("evaluate");

    assert_veto_reason_contains(rule_by_name(&response, "periods_per_year"), "pay_period");
    let gross_annual = rule_by_name(&response, "gross_annual");
    assert!(
        gross_annual.vetoed,
        "gross_annual must veto when periods_per_year lacks pay_period (must not assume 12)"
    );
    assert!(
        gross_annual.result().is_none(),
        "gross_annual must not produce a numeric value, got {:?}",
        gross_annual.result()
    );
}

#[test]
fn net_salary_per_period_outputs_veto_when_pay_period_missing() {
    let mut engine = Engine::new();
    let code = std::fs::read_to_string(net_salary_example_path()).expect("read example");
    engine
        .load([(
            lemma::SourceType::Path(Arc::new(PathBuf::from("nl/tax/net_salary.lemma"))),
            &code.to_string(),
        )])
        .expect("load");

    let effective = effective_2026();
    let mut data = IndexMap::new();
    data.insert("gross_salary".to_string(), "5000 eur".into());
    let response = engine
        .evaluate(None, "net_salary", Some(&effective), data, None, false)
        .expect("evaluate");

    assert_veto_reason_contains(rule_by_name(&response, "periods_per_year"), "pay_period");

    for name in ["net_salary", "payroll_tax_per_period"] {
        let rr = rule_by_name(&response, name);
        assert!(
            rr.vetoed,
            "rule '{name}' must veto when periods_per_year is missing pay_period"
        );
        assert!(
            rr.result().is_none(),
            "rule '{name}' must not emit a per-period amount without pay_period, got {:?}",
            rr.result()
        );
    }
}

// --- missing_data of a rule depends only on that rule, not on the other requested rules ---

#[test]
fn missing_data_does_not_depend_on_other_requested_rules() {
    let code = r#"
spec shipping
data weight: number
data distance: number
data express: boolean
rule fee:
  0
  unless weight > 5 or distance > 5 then 10
  unless express then 20
rule heavy: weight > 5
"#;
    let mut engine = Engine::new();
    load_volatile(&mut engine, code);

    let now = DateTimeValue::now();
    let data = || {
        let mut data = IndexMap::new();
        data.insert("weight".to_string(), "10".into());
        data
    };
    let fee_alone = engine
        .evaluate(
            None,
            "shipping",
            Some(&now),
            data(),
            Some(&["fee".to_string()]),
            false,
        )
        .expect("evaluate");
    let fee_with_heavy = engine
        .evaluate(
            None,
            "shipping",
            Some(&now),
            data(),
            Some(&["fee".to_string(), "heavy".to_string()]),
            false,
        )
        .expect("evaluate");
    let heavy_first = engine
        .evaluate(
            None,
            "shipping",
            Some(&now),
            data(),
            Some(&["heavy".to_string(), "fee".to_string()]),
            false,
        )
        .expect("evaluate");

    let fee_explained = engine
        .evaluate(
            None,
            "shipping",
            Some(&now),
            data(),
            Some(&["fee".to_string()]),
            true,
        )
        .expect("evaluate");

    let alone = rule_by_name(&fee_alone, "fee").missing_data().to_vec();
    assert_eq!(
        alone,
        vec!["express".to_string()],
        "a true `or` operand decides it, so distance is not missing"
    );
    assert_eq!(
        rule_by_name(&fee_explained, "fee").missing_data(),
        alone.as_slice(),
        "fee missing_data changed when explained"
    );
    assert_eq!(
        rule_by_name(&fee_with_heavy, "fee").missing_data(),
        alone.as_slice(),
        "fee missing_data changed when heavy was also requested"
    );
    assert_eq!(
        rule_by_name(&heavy_first, "fee").missing_data(),
        alone.as_slice(),
        "fee missing_data changed when heavy was requested first"
    );
}

#[test]
fn explanation_does_not_depend_on_other_requested_rules() {
    let code = r#"
spec shipping
data weight: number
data distance: number
data express: boolean
rule fee:
  0
  unless weight > 5 or distance > 5 then 10
  unless express then 20
rule heavy: weight > 5
"#;
    let mut engine = Engine::new();
    load_volatile(&mut engine, code);

    let now = DateTimeValue::now();
    let explain = |rules: &[&str]| {
        let mut data = IndexMap::new();
        data.insert("weight".to_string(), "10".into());
        let rules: Vec<String> = rules.iter().map(|rule| rule.to_string()).collect();
        let response = engine
            .evaluate(None, "shipping", Some(&now), data, Some(&rules), true)
            .expect("evaluate");
        serde_json::to_string(&rule_by_name(&response, "fee").explanation)
            .expect("explanation serializes")
    };
    let alone = explain(&["fee"]);
    assert_eq!(
        explain(&["fee", "heavy"]),
        alone,
        "fee explanation changed when heavy was also requested"
    );
    assert_eq!(
        explain(&["heavy", "fee"]),
        alone,
        "fee explanation changed when heavy was requested first"
    );
}

#[test]
fn missing_data_through_uses_does_not_depend_on_other_requested_rules() {
    let code = r#"
spec parcel
data weight: number
data distance: number
data express: boolean
rule fee:
  0
  unless weight > 5 or distance > 5 then 10
  unless express then 20
rule heavy: weight > 5

spec order
uses parcel: parcel
  -> with weight: 10
rule fee: parcel.fee
rule heavy: parcel.heavy
"#;
    let mut engine = Engine::new();
    load_volatile(&mut engine, code);

    let now = DateTimeValue::now();
    let missing = |rules: &[&str]| {
        let rules: Vec<String> = rules.iter().map(|rule| rule.to_string()).collect();
        let response = engine
            .evaluate(
                None,
                "order",
                Some(&now),
                IndexMap::new(),
                Some(&rules),
                false,
            )
            .expect("evaluate");
        rule_by_name(&response, "fee").missing_data().to_vec()
    };
    let alone = missing(&["fee"]);
    assert_eq!(
        alone,
        vec!["parcel.express".to_string()],
        "a true `or` operand decides it, so distance is not missing"
    );
    assert_eq!(missing(&["fee", "heavy"]), alone);
    assert_eq!(missing(&["heavy", "fee"]), alone);
}