lemma-engine 0.8.13

A language that means business.
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use lemma::parsing::ast::DateTimeValue;
use lemma::{Engine, LiteralValue, OperationResult, VetoType};
use rust_decimal::Decimal;
use std::collections::HashMap;

#[test]
fn test_explanation_generated_during_evaluation() {
    let mut engine = Engine::new();

    let spec = r#"
spec test_explanation

data base_value: 100

rule doubled: base_value * 2
"#;

    engine
        .load(
            spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("test.lemma"))),
        )
        .unwrap();
    let now = DateTimeValue::now();
    let response = engine
        .run(None, "test_explanation", Some(&now), HashMap::new(), false)
        .unwrap();

    let doubled_result = response
        .results
        .values()
        .find(|r| r.rule.name == "doubled")
        .expect("doubled rule should exist");

    // Verify result (literal carries resolved LemmaType; compare rendered value)
    assert_eq!(
        doubled_result.result.value().unwrap().to_string(),
        LiteralValue::number(200.into()).to_string(),
    );

    // Verify explanation was built
    let explanation = doubled_result
        .explanation
        .as_ref()
        .expect("Explanation should be generated during evaluation");

    assert_eq!(explanation.rule_path.rule, "doubled");
    assert_eq!(
        explanation.result.value().unwrap().to_string(),
        LiteralValue::number(200.into()).to_string(),
    );

    // Verify explanation tree structure exists
    match explanation.tree.as_ref() {
        lemma::explanation::ExplanationNode::Computation { .. } => {
            // Expected: multiplication computation
        }
        other => panic!("Expected Computation node, got {:?}", other),
    }
}

#[test]
fn test_explanation_with_rule_reference() {
    let mut engine = Engine::new();

    let spec = r#"
spec test_explanation_ref

data base_value: 50

rule doubled: base_value * 2
rule quadruple: doubled * 2
"#;

    engine
        .load(
            spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("test.lemma"))),
        )
        .unwrap();
    let now = DateTimeValue::now();
    let response = engine
        .run(
            None,
            "test_explanation_ref",
            Some(&now),
            HashMap::new(),
            false,
        )
        .unwrap();

    let quadruple_result = response
        .results
        .values()
        .find(|r| r.rule.name == "quadruple")
        .expect("quadruple rule should exist");

    assert_eq!(
        quadruple_result.result.value().unwrap().to_string(),
        LiteralValue::number(200.into()).to_string(),
    );

    // Verify explanation exists
    let explanation = quadruple_result
        .explanation
        .as_ref()
        .expect("Explanation should be generated");

    // Verify explanation tree contains rule reference
    match explanation.tree.as_ref() {
        lemma::explanation::ExplanationNode::Computation {
            operands, result, ..
        } => {
            assert_eq!(
                result.to_string(),
                LiteralValue::number(200.into()).to_string()
            );

            // First operand should be a rule reference to doubled
            match &operands[0] {
                lemma::explanation::ExplanationNode::RuleReference {
                    rule_path,
                    expansion,
                    ..
                } => {
                    assert_eq!(rule_path.rule, "doubled");

                    // Expansion should contain the explanation for doubled
                    match expansion.as_ref() {
                        lemma::explanation::ExplanationNode::Computation { result, .. } => {
                            assert_eq!(
                                result.to_string(),
                                LiteralValue::number(100.into()).to_string()
                            );
                        }
                        other => panic!("Expected Computation in expansion, got {:?}", other),
                    }
                }
                other => panic!("Expected RuleReference for doubled?, got {:?}", other),
            }
        }
        other => panic!("Expected Computation at root, got {:?}", other),
    }
}

#[test]
fn test_explanation_with_unless_clauses() {
    let mut engine = Engine::new();

    let spec = r#"
spec test_unless

data quantity: 5
data is_premium: false

rule discount_percentage: 0%
  unless quantity >= 10 then 10%
  unless quantity >= 20 then 20%
  unless is_premium then 15%
"#;

    engine
        .load(
            spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("test.lemma"))),
        )
        .unwrap();
    let now = DateTimeValue::now();
    let response = engine
        .run(None, "test_unless", Some(&now), HashMap::new(), false)
        .unwrap();

    let discount_result = response
        .results
        .values()
        .find(|r| r.rule.name == "discount_percentage")
        .expect("discount_percentage rule should exist");

    // Verify result - default should match since no unless clauses match
    // 0% is stored as Ratio(0, Some("percent")) to indicate it's a percentage
    assert_eq!(
        discount_result.result,
        OperationResult::Value(Box::new(LiteralValue::ratio(
            Decimal::from(0),
            Some("percent".to_string())
        )))
    );

    // Verify explanation exists
    let explanation = discount_result
        .explanation
        .as_ref()
        .expect("Explanation should be generated");

    // Verify explanation tree shows branches
    match explanation.tree.as_ref() {
        lemma::explanation::ExplanationNode::Branches {
            matched,
            non_matched,
            ..
        } => {
            // Matched branch should be the default (no condition)
            assert!(
                matched.condition.is_none(),
                "Default branch should have no condition"
            );

            // Should have 3 non-matched unless clauses
            assert_eq!(
                non_matched.len(),
                3,
                "Should have 3 non-matched unless clauses"
            );
        }
        other => panic!(
            "Expected Branches node for rule with unless clauses, got {:?}",
            other
        ),
    }
}

#[test]
fn test_explanation_with_veto_result() {
    let mut engine = Engine::new();

    let spec = r#"
spec test_veto

data age: 17

rule age_validation: accept
  unless age < 18 then veto "Must be 18 or older"
"#;

    engine
        .load(
            spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("test.lemma"))),
        )
        .unwrap();
    let now = DateTimeValue::now();
    let response = engine
        .run(None, "test_veto", Some(&now), HashMap::new(), false)
        .unwrap();

    let validation_result = response
        .results
        .values()
        .find(|r| r.rule.name == "age_validation")
        .expect("age_validation rule should exist");

    // Verify veto result
    assert_eq!(
        validation_result.result,
        OperationResult::Veto(VetoType::UserDefined {
            message: Some("Must be 18 or older".to_string()),
        })
    );

    // Verify explanation exists even for veto
    let explanation = validation_result
        .explanation
        .as_ref()
        .expect("Explanation should be generated even for veto results");

    assert_eq!(explanation.rule_path.rule, "age_validation");
    assert_eq!(
        explanation.result,
        OperationResult::Veto(VetoType::UserDefined {
            message: Some("Must be 18 or older".to_string()),
        })
    );
}

#[test]
fn test_explanation_with_cross_spec_rule_reference() {
    let mut engine = Engine::new();

    let base_spec = r#"
spec base
data value: 100
rule doubled: value * 2
"#;

    let main_spec = r#"
spec main
uses base_ref: base
rule result: base_ref.doubled + 50
"#;

    engine
        .load(
            base_spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("base.lemma"))),
        )
        .unwrap();
    engine
        .load(
            main_spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("main.lemma"))),
        )
        .unwrap();

    let now = DateTimeValue::now();
    let response = engine
        .run(None, "main", Some(&now), HashMap::new(), false)
        .unwrap();

    let result = response
        .results
        .values()
        .find(|r| r.rule.name == "result")
        .expect("result rule should exist");

    assert_eq!(
        result.result.value().unwrap().to_string(),
        LiteralValue::number(250.into()).to_string(),
    );

    // Verify explanation exists
    let explanation = result
        .explanation
        .as_ref()
        .expect("Explanation should be generated");

    // Verify explanation tree contains cross-spec rule reference
    match explanation.tree.as_ref() {
        lemma::explanation::ExplanationNode::Computation { operands, .. } => {
            // First operand should be a rule reference to base_ref.doubled
            match &operands[0] {
                lemma::explanation::ExplanationNode::RuleReference {
                    rule_path,
                    expansion,
                    ..
                } => {
                    assert_eq!(rule_path.rule, "doubled");
                    assert_eq!(rule_path.segments.len(), 1);
                    assert_eq!(rule_path.segments[0].data, "base_ref");

                    // Expansion should exist
                    match expansion.as_ref() {
                        lemma::explanation::ExplanationNode::Computation { .. } => {
                            // Good - cross-spec rule explanation is included
                        }
                        other => panic!(
                            "Expected Computation in cross-spec expansion, got {:?}",
                            other
                        ),
                    }
                }
                other => panic!(
                    "Expected RuleReference for base_ref.doubled?, got {:?}",
                    other
                ),
            }
        }
        other => panic!("Expected Computation at root, got {:?}", other),
    }
}

#[test]
fn test_cross_spec_explanation_has_correct_path() {
    // This test specifically validates that explanations stored in context
    // have the correct rule_path including segments
    let mut engine = Engine::new();

    let base_spec = r#"
spec base
data value: 100
rule doubled: value * 2
"#;

    let main_spec = r#"
spec main
uses base_ref: base
rule use_cross_spec: base_ref.doubled + 1
"#;

    engine
        .load(
            base_spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("base.lemma"))),
        )
        .unwrap();
    engine
        .load(
            main_spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("main.lemma"))),
        )
        .unwrap();

    let now = DateTimeValue::now();
    let response = engine
        .run(None, "main", Some(&now), HashMap::new(), false)
        .unwrap();

    let main_rule = response
        .results
        .values()
        .find(|r| r.rule.name == "use_cross_spec")
        .expect("use_cross_spec rule should exist");

    let explanation = main_rule
        .explanation
        .as_ref()
        .expect("Explanation should exist");

    // The main rule's explanation should have empty segments (it's local)
    assert_eq!(explanation.rule_path.rule, "use_cross_spec");
    assert_eq!(
        explanation.rule_path.segments.len(),
        0,
        "Main spec rule should have no segments"
    );

    // Now check the referenced rule's explanation inside the tree
    match explanation.tree.as_ref() {
        lemma::explanation::ExplanationNode::Computation { operands, .. } => {
            match &operands[0] {
                lemma::explanation::ExplanationNode::RuleReference {
                    rule_path: ref_path,
                    ..
                } => {
                    // CRITICAL: The rule_path in the RuleReference node should have segments
                    assert_eq!(ref_path.rule, "doubled");
                    assert_eq!(
                        ref_path.segments.len(),
                        1,
                        "Cross-spec rule reference MUST have segments showing the path"
                    );
                    assert_eq!(ref_path.segments[0].data, "base_ref");
                    assert_eq!(ref_path.segments[0].spec, "base");
                }
                other => panic!("Expected RuleReference, got {:?}", other),
            }
        }
        other => panic!("Expected Computation, got {:?}", other),
    }
}

#[test]
fn test_explanation_serialization_preserves_cross_spec_paths() {
    // CRITICAL TEST: This catches the bug where Explanation.rule_path had empty segments
    // even for cross-spec rules. The buggy code would pass all other tests
    // because they only checked the tree structure, not the top-level Explanation metadata.
    let mut engine = Engine::new();

    let base_spec = r#"
spec base
data value: 50
rule doubled: value * 2
"#;

    let main_spec = r#"
spec main
uses base_ref: base
rule use_doubled: base_ref.doubled + 10
"#;

    engine
        .load(
            base_spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("base.lemma"))),
        )
        .unwrap();
    engine
        .load(
            main_spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("main.lemma"))),
        )
        .unwrap();

    let now = DateTimeValue::now();
    let response = engine
        .run(None, "main", Some(&now), HashMap::new(), false)
        .unwrap();

    let main_rule = response
        .results
        .values()
        .find(|r| r.rule.name == "use_doubled")
        .expect("use_doubled rule should exist");

    let explanation = main_rule
        .explanation
        .as_ref()
        .expect("Explanation should exist");

    // Check that the main rule's explanation has correct structure
    assert_eq!(explanation.rule_path.rule, "use_doubled");
    assert_eq!(explanation.rule_path.segments.len(), 0);

    // Now serialize and check the RuleReference path in the JSON
    let json_value = serde_json::to_value(&response).expect("Should serialize");

    // Serialize to JSON for validation
    let json_str = serde_json::to_string_pretty(&response).unwrap();

    // Navigate to the explanation for use_doubled -> tree -> operands[0] (the RuleReference)
    // results is now an IndexMap (object), so we need to find the use_doubled rule by key
    let results_obj = json_value["results"].as_object().unwrap();
    let use_doubled_result = results_obj
        .get("use_doubled")
        .expect("use_doubled result not found");
    let explanation_tree = &use_doubled_result["explanation"]["tree"];

    // The tree should be a `computation` node with operands
    let computation = explanation_tree["computation"]
        .as_object()
        .unwrap_or_else(|| {
            panic!(
                "Expected computation node in explanation tree. JSON:\n{}",
                json_str
            )
        });

    let operands = computation["operands"].as_array().unwrap_or_else(|| {
        panic!(
            "Expected operands array in Computation. JSON:\n{}",
            json_str
        )
    });

    assert!(
        !operands.is_empty(),
        "Should have at least one operand (the rule reference)"
    );

    let rule_ref_node = &operands[0];

    // The ExplanationNode is serialized as a tagged enum, so it's {"rule_reference": {...}}
    let rule_ref = rule_ref_node["rule_reference"]
        .as_object()
        .unwrap_or_else(|| {
            panic!(
                "Expected rule_reference variant. Got:\n{}",
                serde_json::to_string_pretty(rule_ref_node).unwrap()
            )
        });

    // This should be the RuleReference to base_ref.doubled
    let rule_ref_path = &rule_ref["rule_path"];
    assert_eq!(
        rule_ref_path["rule"].as_str().unwrap(),
        "doubled",
        "Rule reference should point to 'doubled'"
    );

    // THIS IS THE CRITICAL ASSERTION that would have caught the bug:
    // The segments array should NOT be empty for a cross-spec reference
    let segments = rule_ref_path["segments"].as_array().unwrap_or_else(|| {
        panic!(
            "Expected segments array. Rule ref path JSON:\n{}",
            serde_json::to_string_pretty(rule_ref_path).unwrap()
        )
    });

    assert_eq!(
        segments.len(),
        1,
        "BUG: Cross-spec rule reference MUST have segments! \
         Empty segments means we lost the path information during explanation construction."
    );

    assert_eq!(
        segments[0]["data"].as_str().unwrap(),
        "base_ref",
        "Segment should reference base_ref data"
    );
    assert_eq!(
        segments[0]["spec"].as_str().unwrap(),
        "base",
        "Segment should reference base spec"
    );
}

#[test]
fn test_comparison_false_normalized_to_positive_in_explanation() {
    let mut engine = Engine::new();

    let spec = r#"
spec test
rule out: true
 unless 5 < 3 then false
"#;

    engine
        .load(
            spec,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("test.lemma"))),
        )
        .unwrap();
    let now = DateTimeValue::now();
    let response = engine
        .run(None, "test", Some(&now), HashMap::new(), false)
        .unwrap();

    let result = response
        .results
        .values()
        .find(|r| r.rule.name == "out")
        .expect("out rule should exist");

    assert_eq!(
        result.result,
        OperationResult::Value(Box::new(LiteralValue::from_bool(true))),
        "default branch is taken"
    );

    let explanation = result
        .explanation
        .as_ref()
        .expect("explanation should exist");
    let lemma::explanation::ExplanationNode::Branches { non_matched, .. } =
        explanation.tree.as_ref()
    else {
        panic!("expected Branches at root, got {:?}", explanation.tree);
    };
    assert_eq!(non_matched.len(), 1, "one unless branch did not match");

    let condition_node = &non_matched[0].condition;
    let lemma::explanation::ExplanationNode::Computation {
        original_expression,
        result: cond_result,
        ..
    } = condition_node.as_ref()
    else {
        panic!(
            "expected Computation for condition, got {:?}",
            condition_node
        );
    };

    assert!(
        original_expression.contains(">="),
        "negated comparison should show >= not <; got original_expression: {}",
        original_expression
    );
    assert_eq!(
        cond_result,
        &LiteralValue::from_bool(true),
        "normalized condition should have result true"
    );
}