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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! A rule's `missing_data` names exactly what a concrete request still needs: a key that
//! no completion of the missing data reads is not on it, and every key that some
//! completion reads is.

use indexmap::IndexMap;
use lemma::{DateTimeValue, Engine, EvaluateDataValue, RuleResult, SourceType};
use std::collections::BTreeSet;

fn load(code: &str) -> Engine {
    let mut engine = Engine::new();
    engine
        .load([(SourceType::Volatile, code.to_string())])
        .unwrap_or_else(|e| panic!("specs must load: {e:?}\n{code}"));
    engine
}

type Inputs<'a> = &'a [(&'a str, &'a str)];

fn data(inputs: Inputs) -> IndexMap<String, EvaluateDataValue> {
    inputs
        .iter()
        .map(|(name, value)| (name.to_string(), EvaluateDataValue::string(*value)))
        .collect()
}

fn evaluate(
    engine: &Engine,
    spec: &str,
    data: IndexMap<String, EvaluateDataValue>,
    rules: Option<&[&str]>,
    explain: bool,
) -> lemma::Response {
    let rules: Option<Vec<String>> =
        rules.map(|rules| rules.iter().map(|rule| rule.to_string()).collect());
    let now = DateTimeValue::now();
    engine
        .evaluate(None, spec, Some(&now), data, rules.as_deref(), explain)
        .expect("evaluation must succeed")
}

fn rule<'a>(response: &'a lemma::Response, name: &str) -> &'a RuleResult {
    response
        .results
        .get(name)
        .unwrap_or_else(|| panic!("rule '{name}' missing from results"))
}

/// Rule `r` of `main`, asked alone, with every rule, and explained, misses `expected`.
fn assert_missing(code: &str, inputs: Inputs, expected: &[&str]) {
    let engine = load(code);
    for (rules, explain) in [
        (Some(&["r"][..]), false),
        (None, false),
        (Some(&["r"][..]), true),
    ] {
        let response = evaluate(&engine, "main", data(inputs), rules, explain);
        let result = rule(&response, "r");
        assert_eq!(
            result.missing_data(),
            expected,
            "rules {rules:?}, explain {explain}, given {inputs:?}, result {:?}",
            result.result()
        );
        for key in result.missing_data_options().keys() {
            assert!(
                expected.contains(&key.as_str()),
                "options of '{key}', which is not missing"
            );
        }
    }
}

fn assert_result(code: &str, inputs: Inputs, expected: &str) {
    let engine = load(code);
    let response = evaluate(&engine, "main", data(inputs), Some(&["r"]), false);
    let result = rule(&response, "r");
    assert_eq!(
        result.result(),
        Some(expected),
        "given {inputs:?}: missing {:?}, veto {:?}",
        result.missing_data(),
        result.veto_reason
    );
}

/// Spec `main` with numbers `x`, `y`, `z`, booleans `a`, `b`, `c` and `rules`.
fn main_spec(rules: &str) -> String {
    format!(
        "spec main\ndata x: number\ndata y: number\ndata z: number\ndata a: boolean\ndata b: boolean\ndata c: boolean\nrule stop: veto \"stop\"\n{rules}\n"
    )
}

// =============================================================================
// A condition below an undecided one that is already decided
// =============================================================================

#[test]
fn a_true_condition_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless c then 5\n  unless b then 7"),
        &[("c", "true")],
        &["b"],
    );
}

#[test]
fn a_false_condition_below_keeps_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless c then 5\n  unless b then 7"),
        &[("c", "false")],
        &["b", "x"],
    );
}

#[test]
fn a_negated_condition_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless not(c) then 5\n  unless b then 7"),
        &[("c", "false")],
        &["b"],
    );
}

#[test]
fn a_comparison_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless y > 1 then 5\n  unless b then 7"),
        &[("y", "3")],
        &["b"],
    );
}

#[test]
fn a_conjunction_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless c and a then 5\n  unless b then 7"),
        &[("c", "true"), ("a", "true")],
        &["b"],
    );
}

#[test]
fn a_disjunction_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless c or a then 5\n  unless b then 7"),
        &[("c", "true")],
        &["b"],
    );
}

#[test]
fn a_rule_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule g: c\nrule r: x\n  unless g then 5\n  unless b then 7"),
        &[("c", "true")],
        &["b"],
    );
}

#[test]
fn a_constant_rule_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule g: 2 > 1\nrule r: x\n  unless g then 5\n  unless b then 7"),
        &[],
        &["b"],
    );
}

#[test]
fn a_branch_below_that_wins_keeps_its_own_data() {
    assert_missing(
        &main_spec("rule r: x\n  unless c then z\n  unless b then 7"),
        &[("c", "true")],
        &["b", "z"],
    );
}

#[test]
fn a_branch_below_that_wins_rules_out_the_arms_under_it() {
    assert_missing(
        &main_spec("rule r: x\n  unless a then y\n  unless c then 5\n  unless b then 7"),
        &[("c", "true")],
        &["b"],
    );
}

#[test]
fn an_open_condition_between_stays_needed() {
    assert_missing(
        &main_spec("rule r: x\n  unless c then 5\n  unless a then 6\n  unless b then 7"),
        &[("c", "true")],
        &["b", "a"],
    );
}

#[test]
fn a_branch_below_that_wins_with_a_veto_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless c then veto \"closed\"\n  unless b then 7"),
        &[("c", "true")],
        &["b"],
    );
}

#[test]
fn a_vetoed_condition_below_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless stop > 1 then 5\n  unless b then 7"),
        &[],
        &["b"],
    );
}

#[test]
fn a_vetoed_condition_below_rules_out_its_own_branch() {
    assert_missing(
        &main_spec("rule r: x\n  unless stop > 1 then z\n  unless b then 7"),
        &[],
        &["b"],
    );
}

#[test]
fn a_condition_that_fails_its_type_below_rules_out_the_default() {
    assert_missing(
        &main_spec(
            "data n: number\n  -> maximum 9\nrule r: x\n  unless n > 1 then 5\n  unless b then 7",
        ),
        &[("n", "99")],
        &["b"],
    );
}

/// A branch that is a veto whatever the missing data is needs none of it.
#[test]
fn an_open_branch_that_is_a_veto_anyway_rules_out_its_data() {
    for body in [
        "x + stop",
        "stop + x",
        "x * stop",
        "x - stop",
        "stop / x",
        "(x + y) * stop",
    ] {
        assert_missing(
            &main_spec(&format!("rule r: 1\n  unless b then {body}")),
            &[],
            &["b"],
        );
    }
}

#[test]
fn an_open_branch_that_has_its_value_rules_out_the_rest() {
    assert_missing(
        &main_spec("rule q: a and c\nrule r: 1\n  unless b then 2\n  unless y > 1 and q then 3"),
        &[("a", "false")],
        &["b"],
    );
    assert_missing(
        &main_spec("rule q: x\n  unless c then 5\nrule r: q\n  unless b then q + 1"),
        &[("c", "true")],
        &["b"],
    );
}

#[test]
fn a_branch_below_that_is_a_veto_anyway_rules_out_its_data() {
    assert_missing(
        &main_spec("rule q: 1\n  unless c then x\n  unless stop > 1 then x\nrule p: 2\n  unless y > 1 then 3\nrule r: p + q\n  unless b then 1"),
        &[],
        &["b"],
    );
}

// =============================================================================
// The same through what reads the rule
// =============================================================================

const DECIDED: &str = "rule q: x\n  unless c then 5\n  unless b then 7\n";

#[test]
fn a_reference_to_the_rule_misses_the_same() {
    let code = main_spec(&format!("{DECIDED}rule r: q"));
    assert_missing(&code, &[("c", "true")], &["b"]);
}

#[test]
fn arithmetic_on_the_rule_misses_the_same() {
    let code = main_spec(&format!("{DECIDED}rule r: q + z"));
    assert_missing(&code, &[("c", "true"), ("z", "1")], &["b"]);
}

#[test]
fn a_condition_on_the_rule_misses_the_same() {
    let code = main_spec(&format!("{DECIDED}rule r: 1\n  unless q is z then 2"));
    assert_missing(&code, &[("c", "true"), ("z", "1")], &["b"]);
}

#[test]
fn a_branch_that_is_the_rule_misses_the_same() {
    let code = main_spec(&format!("{DECIDED}rule r: z\n  unless a then q"));
    assert_missing(&code, &[("c", "true"), ("a", "true")], &["b"]);
}

#[test]
fn folded_arithmetic_on_the_rule_misses_the_same() {
    let code = main_spec(&format!("{DECIDED}rule r: q + 0"));
    assert_missing(&code, &[("c", "true")], &["b"]);
}

#[test]
fn a_used_spec_misses_the_same() {
    assert_missing(
        "spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n  unless c then 5\n  unless b then 7\n\nspec main\nuses inner\nrule r: inner.q\n",
        &[("inner.c", "true")],
        &["inner.b"],
    );
}

#[test]
fn a_spec_two_uses_deep_misses_the_same() {
    assert_missing(
        "spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n  unless c then 5\n  unless b then 7\n\nspec middle\nuses inner\nrule q: inner.q\n\nspec main\nuses middle\nrule r: middle.q\n",
        &[("middle.inner.c", "true")],
        &["middle.inner.b"],
    );
}

#[test]
fn a_global_misses_the_same() {
    assert_missing(
        "spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n  unless c then 5\n  unless b then 7\n\nspec main\nuses global inner\nrule r: inner.q\n",
        &[("global.inner.c", "true")],
        &["global.inner.b"],
    );
}

const WIRED: &str = "spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n  unless c then 5\n  unless b then 7\n\nspec main\nuses inner\n  -> with x: worth\n  -> with c: known\ndata n: number\ndata known: boolean\nrule worth: n + 1\nrule r: inner.q\n";

/// `inner.x` is bound to a rule that misses `n`; nothing can read it.
#[test]
fn a_slot_bound_to_a_rule_misses_the_same() {
    assert_missing(WIRED, &[("known", "true")], &["inner.b"]);
}

#[test]
fn a_slot_bound_to_a_rule_that_is_read_names_its_data() {
    assert_missing(WIRED, &[("known", "false")], &["inner.b", "n"]);
}

#[test]
fn a_slot_bound_to_a_condition_that_misses_data_names_that_data() {
    assert_missing(
        "spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n  unless c then 5\n  unless b then 7\n\nspec main\nuses inner\n  -> with b: open\ndata n: number\nrule open: n > 1\nrule r: inner.q\n",
        &[("inner.c", "true")],
        &["n"],
    );
}

const ROW: &str = "spec row\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n  unless c then 5\n  unless b then 7\n\n";

fn one_row(pairs: Inputs) -> IndexMap<String, EvaluateDataValue> {
    let row = pairs
        .iter()
        .map(|(name, value)| (name.to_string(), EvaluateDataValue::string(*value)))
        .collect();
    IndexMap::from([(
        "rows".to_string(),
        EvaluateDataValue::List(vec![EvaluateDataValue::Map(row)]),
    )])
}

#[test]
fn a_request_row_misses_the_same() {
    let engine = load(&format!(
        "{ROW}spec main\nuses row\ndata rows: row list\nrule r: rows -> sum rows.q\n"
    ));
    let response = evaluate(&engine, "main", one_row(&[("c", "true")]), None, false);
    assert_eq!(rule(&response, "r").missing_data(), ["rows.1.b"]);
}

#[test]
fn a_member_read_of_a_request_row_misses_the_same() {
    let engine = load(&format!(
        "{ROW}spec main\nuses row\ndata rows: row list\nrule r: (rows -> first).q\n"
    ));
    let response = evaluate(&engine, "main", one_row(&[("c", "true")]), None, false);
    assert_eq!(rule(&response, "r").missing_data(), ["rows.1.b"]);
}

#[test]
fn a_spec_written_row_misses_the_same() {
    assert_missing(
        &format!("{ROW}spec main\nuses row\ndata n: number\ndata open: boolean\ndata rows: row list\n  -> with x: n, b: open, c: true\nrule r: rows -> sum rows.q\n"),
        &[],
        &["open"],
    );
}

/// A rule that makes rows reads every field it writes: it vetoes when one misses data.
#[test]
fn rows_a_rule_makes_miss_every_field_it_writes() {
    let code = format!("{ROW}spec main\nuses row\ndata n: number\ndata open: boolean\nrule rows: row list\n  -> with x: n, b: open, c: true\nrule r: rows -> sum q\n");
    assert_missing(&code, &[], &["n", "open"]);
    assert_missing(&code, &[("open", "true")], &["n"]);
    assert_missing(&code, &[("n", "1")], &["open"]);
}

// =============================================================================
// Conditions on one value
// =============================================================================

/// `y is 1 and c` is false when `c` is, whatever `y` is.
const KEYED: &str = "rule r: x\n  unless y is 1 and c then 5\n  unless y is 2 and c then 6";

#[test]
fn a_false_operand_decides_conditions_on_one_value() {
    assert_result(&main_spec(KEYED), &[("c", "false"), ("x", "1")], "1");
}

#[test]
fn a_false_operand_decides_conditions_on_one_value_in_either_order() {
    assert_result(
        &main_spec("rule r: x\n  unless c and y is 1 then 5\n  unless c and y is 2 then 6"),
        &[("c", "false"), ("x", "1")],
        "1",
    );
}

#[test]
fn a_false_operand_decides_conditions_on_one_vetoed_value() {
    assert_result(
        &main_spec("rule r: x\n  unless stop is 1 and c then 5\n  unless stop is 2 and c then 6"),
        &[("c", "false"), ("x", "1")],
        "1",
    );
}

#[test]
fn different_false_operands_decide_conditions_on_one_value() {
    assert_result(
        &main_spec("rule r: x\n  unless y is 1 and c then 5\n  unless y is 2 and b then 6"),
        &[("c", "false"), ("b", "false"), ("x", "1")],
        "1",
    );
}

#[test]
fn decided_conditions_on_one_value_miss_only_the_default() {
    assert_missing(&main_spec(KEYED), &[("c", "false")], &["x"]);
}

#[test]
fn a_decided_branch_on_one_value_rules_out_its_data() {
    assert_missing(
        &main_spec("rule r: x\n  unless y is 1 and c then z\n  unless y is 2 and b then 6"),
        &[("c", "false"), ("x", "1"), ("b", "true")],
        &["y"],
    );
}

#[test]
fn a_decided_condition_under_conditions_on_one_value_rules_out_the_default() {
    assert_missing(
        &main_spec("rule r: x\n  unless c then 5\n  unless y is 1 and b then 6\n  unless y is 2 and b then 7"),
        &[("c", "true"), ("b", "true")],
        &["y"],
    );
}

// =============================================================================
// Every subset of the data, against evaluation itself
// =============================================================================

const DOMAINS: &[(&str, &[&str])] = &[
    ("x", &["3"]),
    ("y", &["0", "2"]),
    ("z", &["4"]),
    ("a", &["true", "false"]),
    ("b", &["true", "false"]),
    ("c", &["true", "false"]),
];

/// Every choice of one value per domain.
fn choices<'a>(domains: &[(&'a str, &'a [&'a str])]) -> Vec<Vec<(&'a str, &'a str)>> {
    domains
        .iter()
        .fold(vec![Vec::new()], |chosen, (name, values)| {
            chosen
                .iter()
                .flat_map(|prefix| {
                    values.iter().map(move |value| {
                        let mut next = prefix.clone();
                        next.push((*name, *value));
                        next
                    })
                })
                .collect()
        })
}

/// For every subset of the data of `rules` and every value of it: a rule that misses data
/// misses exactly the keys `k` that some values of the other missing data leave it
/// missing. Each input is in one condition only, so conditions do not exclude each other.
fn assert_exact(rules: &str) {
    let engine = load(&main_spec(rules));
    let used: Vec<(&str, &[&str])> = DOMAINS
        .iter()
        .copied()
        .filter(|(name, _)| {
            rules
                .split(|c: char| !c.is_alphanumeric() && c != '_')
                .any(|word| word == *name)
        })
        .collect();
    let mut wrong = Vec::new();
    for subset in 0..(1usize << used.len()) {
        let given: Vec<_> = used
            .iter()
            .copied()
            .enumerate()
            .filter(|(index, _)| subset & (1 << index) != 0)
            .map(|(_, domain)| domain)
            .collect();
        let open: Vec<_> = used
            .iter()
            .copied()
            .filter(|(name, _)| !given.iter().any(|(other, _)| other == name))
            .collect();
        for inputs in choices(&given) {
            let response = evaluate(&engine, "main", data(&inputs), None, false);
            let mut needed: IndexMap<String, BTreeSet<String>> = IndexMap::new();
            for (key, _) in &open {
                let others: Vec<_> = open.iter().copied().filter(|(o, _)| o != key).collect();
                for rest in choices(&others) {
                    let all: Vec<_> = inputs.iter().chain(&rest).copied().collect();
                    let completed = evaluate(&engine, "main", data(&all), None, false);
                    for (name, result) in &completed.results {
                        if !result.missing_data().is_empty() {
                            needed
                                .entry(name.clone())
                                .or_default()
                                .insert(key.to_string());
                        }
                    }
                }
            }
            for (name, result) in &response.results {
                if result.missing_data().is_empty() {
                    continue;
                }
                let listed: BTreeSet<String> = result.missing_data().iter().cloned().collect();
                let needed = needed.get(name).cloned().unwrap_or_default();
                if listed != needed {
                    wrong.push(format!(
                        "{name} given {inputs:?}: lists {listed:?}, needs {needed:?}"
                    ));
                }
            }
        }
    }
    assert!(
        wrong.is_empty(),
        "{} of the requests are wrong, the first: {}",
        wrong.len(),
        wrong[0]
    );
}

#[test]
fn exact_for_one_unless() {
    assert_exact("rule r: x\n  unless b then z");
}

#[test]
fn exact_for_two_unless() {
    assert_exact("rule r: x\n  unless c then z\n  unless b then 7");
}

#[test]
fn exact_for_four_unless() {
    assert_exact(
        "rule r: x\n  unless y > 1 then 1\n  unless a then z\n  unless c then 3\n  unless b then x",
    );
}

#[test]
fn exact_for_nested_rules() {
    assert_exact(
        "rule q: x\n  unless c then z\nrule r: q\n  unless b then 7\nrule s: z\n  unless a then r",
    );
}

#[test]
fn exact_for_vetoes_in_branches() {
    assert_exact("rule r: x\n  unless c then veto \"closed\"\n  unless b then z\n  unless a then veto \"full\"");
}

#[test]
fn exact_for_connectives() {
    assert_exact("rule r: x\n  unless a and c then z\n  unless b then 7");
}

#[test]
fn exact_for_a_disjunction() {
    assert_exact("rule r: x\n  unless a or y > 1 then 5\n  unless b or c then z");
}

#[test]
fn exact_for_arithmetic_on_branches() {
    assert_exact("rule q: x\n  unless c then 5\n  unless b then z\nrule r: q + x");
}