lemma-engine 0.8.10

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
use lemma::parsing::ast::DateTimeValue;
use lemma::Engine;
use rust_decimal::Decimal;
use std::collections::HashMap;
use std::str::FromStr;

/// Rule references work through one level of spec reference.
#[test]
fn test_single_level_spec_ref_with_rule_reference() {
    let mut engine = Engine::new();

    let base_spec = r#"
spec pricing
fact base_price: 100
fact tax_rate: 21%
rule final_price: base_price * (1 + tax_rate)
"#;

    let line_item_spec = r#"
spec line_item
fact pricing: spec pricing
fact quantity: 10
rule line_total: pricing.final_price * quantity
"#;

    engine
        .load(base_spec, lemma::SourceType::Labeled("pricing.lemma"))
        .unwrap();
    engine
        .load(
            line_item_spec,
            lemma::SourceType::Labeled("line_item.lemma"),
        )
        .unwrap();

    let now = DateTimeValue::now();
    let response = engine
        .run("line_item", Some(&now), HashMap::new(), false)
        .unwrap();
    let line_total = response
        .results
        .values()
        .find(|r| r.rule.name == "line_total")
        .unwrap();

    // Should be: (100 * 1.21) * 10 = 1210
    match &line_total.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("1210").unwrap()),
            other => panic!("Expected Number for line_total, got {:?}", other),
        },
        other => panic!("Expected Value for line_total, got {:?}", other),
    }
}

/// Multi-level spec rule references should work correctly.
/// When spec A references spec B which references spec C,
/// rule references through the chain should resolve properly.
#[test]
fn test_multi_level_spec_rule_reference() {
    let mut engine = Engine::new();

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

    let middle_spec = r#"
spec middle
fact base_ref: spec base
rule middle_calc: base_ref.doubled + 50
"#;

    let top_spec = r#"
spec top
fact middle_ref: spec middle
rule top_calc: middle_ref.middle_calc
"#;

    engine
        .load(base_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(middle_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(top_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

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

    let top_calc = response
        .results
        .values()
        .find(|r| r.rule.name == "top_calc")
        .expect("top_calc rule not found in results");

    match &top_calc.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("250").unwrap()),
            other => panic!("Expected Number for top_calc, got {:?}", other),
        },
        other => panic!("Expected Value for top_calc, got {:?}", other),
    }
}

/// Overriding nested spec references should propagate through rule evaluations.
/// When we bind a nested spec reference and reference rules through that chain,
/// the overridden spec should be used in the evaluation.
#[test]
fn test_nested_spec_binding_with_rule_reference() {
    let mut engine = Engine::new();

    let pricing_spec = r#"
spec pricing
fact base_price: 100
rule final_price: base_price * 1.1
"#;

    let wholesale_spec = r#"
spec wholesale_pricing
fact base_price: 75
rule final_price: base_price * 1.1
"#;

    let line_item_spec = r#"
spec line_item
fact pricing: spec pricing
fact quantity: 10
rule line_total: pricing.final_price * quantity
"#;

    let order_spec = r#"
spec order
fact line: spec line_item
fact line.pricing: spec wholesale_pricing
fact line.quantity: 100
rule order_total: line.line_total
"#;

    engine
        .load(pricing_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(wholesale_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(line_item_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(order_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

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

    let order_total = response
        .results
        .values()
        .find(|r| r.rule.name == "order_total")
        .expect("order_total rule not found in results");

    match &order_total.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("8250").unwrap()),
            other => panic!("Expected Number for order_total, got {:?}", other),
        },
        other => panic!("Expected Value for order_total, got {:?}", other),
    }
}

/// Accessing facts through multi-level spec references with nested bindings works correctly.
#[test]
fn test_multi_level_fact_access_through_spec_refs() {
    let mut engine = Engine::new();

    let base_spec = r#"
spec base
fact value: 50
"#;

    let middle_spec = r#"
spec middle
fact config: spec base
fact config.value: 100
"#;

    let top_spec = r#"
spec top
fact settings: spec middle
rule final_value: settings.config.value * 2
"#;

    engine
        .load(base_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(middle_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(top_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

    let now = DateTimeValue::now();
    let response = engine
        .run("top", Some(&now), HashMap::new(), false)
        .unwrap();
    let final_value = response
        .results
        .values()
        .find(|r| r.rule.name == "final_value")
        .unwrap();

    // Should be: 100 * 2 = 200 (using the overridden value from middle)
    match &final_value.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("200").unwrap()),
            other => panic!("Expected Number for final_value, got {:?}", other),
        },
        other => panic!("Expected Value for final_value, got {:?}", other),
    }
}

/// Deep nested fact bindings through multiple spec layers should work.
/// Overriding facts like order.line.pricing.tax_rate through multiple levels.
#[test]
fn test_deep_nested_fact_binding() {
    let mut engine = Engine::new();

    let pricing_spec = r#"
spec pricing
fact base_price: 100
fact tax_rate: 21%
rule final_price: base_price * (1 + tax_rate)
"#;

    let line_item_spec = r#"
spec line_item
fact pricing: spec pricing
fact quantity: 10
rule line_total: pricing.final_price * quantity
"#;

    let order_spec = r#"
spec order
fact line: spec line_item
fact line.pricing.tax_rate: 10%
fact line.quantity: 5
rule order_total: line.line_total
"#;

    engine
        .load(pricing_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(line_item_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(order_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

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

    let order_total = response
        .results
        .values()
        .find(|r| r.rule.name == "order_total")
        .expect("order_total rule not found");

    // base_price=100, tax_rate=10% (overridden), quantity=5
    // (100 * 1.10) * 5 = 550
    match &order_total.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("550").unwrap()),
            other => panic!("Expected Number for order_total, got {:?}", other),
        },
        other => panic!("Expected Value for order_total, got {:?}", other),
    }
}

/// Different fact paths to the same base spec should produce different results
/// when bindings are applied. This tests that rule evaluation respects the specific
/// path through spec references.
#[test]
fn test_different_paths_different_results() {
    let mut engine = Engine::new();

    let base_spec = r#"
spec base
fact price: 100
rule total: price * 1.21
"#;

    let wrapper_spec = r#"
spec wrapper
fact base: spec base
"#;

    let comparison_spec = r#"
spec comparison
fact path1: spec wrapper
fact path2: spec wrapper
fact path2.base.price: 75
rule total1: path1.base.total
rule total2: path2.base.total
rule difference: total2 - total1
"#;

    engine
        .load(base_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(wrapper_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(comparison_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

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

    let total1 = response
        .results
        .values()
        .find(|r| r.rule.name == "total1")
        .unwrap();
    let total2 = response
        .results
        .values()
        .find(|r| r.rule.name == "total2")
        .unwrap();
    let difference = response
        .results
        .values()
        .find(|r| r.rule.name == "difference")
        .unwrap();

    // path1: 100 * 1.21 = 121
    match &total1.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("121").unwrap()),
            other => panic!("Expected Number for total1, got {:?}", other),
        },
        other => panic!("Expected Value for total1, got {:?}", other),
    }
    // path2: 75 * 1.21 = 90.75
    match &total2.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("90.75").unwrap()),
            other => panic!("Expected Number for total2, got {:?}", other),
        },
        other => panic!("Expected Value for total2, got {:?}", other),
    }
    // difference: 90.75 - 121 = -30.25
    match &difference.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("-30.25").unwrap()),
            other => panic!("Expected Number for difference, got {:?}", other),
        },
        other => panic!("Expected Value for difference, got {:?}", other),
    }
}

/// Multiple independent spec references in a single spec should all work.
/// Each reference should be independently resolvable.
#[test]
fn test_multiple_independent_spec_refs() {
    let mut engine = Engine::new();

    let config1_spec = r#"
spec config1
fact value: 100
rule doubled: value * 2
"#;

    let config2_spec = r#"
spec config2
fact value: 50
rule tripled: value * 3
"#;

    let combined_spec = r#"
spec combined
fact c1: spec config1
fact c2: spec config2
rule sum: c1.doubled + c2.tripled
rule product: c1.value * c2.value
"#;

    engine
        .load(config1_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(config2_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(combined_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

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

    let sum = response
        .results
        .values()
        .find(|r| r.rule.name == "sum")
        .unwrap();
    let product = response
        .results
        .values()
        .find(|r| r.rule.name == "product")
        .unwrap();

    // sum: (100 * 2) + (50 * 3) = 200 + 150 = 350
    match &sum.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("350").unwrap()),
            other => panic!("Expected Number for sum, got {:?}", other),
        },
        other => panic!("Expected Value for sum, got {:?}", other),
    }
    // product: 100 * 50 = 5000
    match &product.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("5000").unwrap()),
            other => panic!("Expected Number for product, got {:?}", other),
        },
        other => panic!("Expected Value for product, got {:?}", other),
    }
}

/// Referencing rules from a spec that itself has spec references.
/// This tests transitive rule dependencies across spec boundaries.
#[test]
fn test_transitive_rule_dependencies() {
    let mut engine = Engine::new();

    let base_spec = r#"
spec base
fact x: 10
rule x_squared: x * x
"#;

    let middle_spec = r#"
spec middle
fact base_config: spec base
fact base_config.x: 20
rule x_squared_plus_ten: base_config.x_squared + 10
"#;

    let top_spec = r#"
spec top
fact middle_config: spec middle
rule final_result: middle_config.x_squared_plus_ten * 2
"#;

    engine
        .load(base_spec, lemma::SourceType::Labeled("base.lemma"))
        .unwrap();
    engine
        .load(middle_spec, lemma::SourceType::Labeled("middle.lemma"))
        .unwrap();
    engine
        .load(top_spec, lemma::SourceType::Labeled("top.lemma"))
        .unwrap();

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

    let final_result = response
        .results
        .values()
        .find(|r| r.rule.name == "final_result")
        .unwrap();

    // x=20 (overridden), x_squared=400, x_squared_plus_ten=410, final=820
    match &final_result.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("820").unwrap()),
            other => panic!("Expected Number for final_result, got {:?}", other),
        },
        other => panic!("Expected Value for final_result, got {:?}", other),
    }
}

/// Overriding the same spec reference in different ways should produce
/// different results based on the specific binding path.
#[test]
fn test_same_spec_different_bindings() {
    let mut engine = Engine::new();

    let pricing_spec = r#"
spec pricing
fact price: 100
fact discount: 0%
rule final_price: price * (1 - discount)
"#;

    let scenario_spec = r#"
spec scenarios
fact retail: spec pricing
fact retail.discount: 5%

fact wholesale: spec pricing
fact wholesale.discount: 15%
fact wholesale.price: 80

rule retail_final: retail.final_price
rule wholesale_final: wholesale.final_price
rule price_difference: retail_final - wholesale_final
"#;

    engine
        .load(pricing_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(scenario_spec, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();

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

    let retail_final = response
        .results
        .values()
        .find(|r| r.rule.name == "retail_final")
        .unwrap();
    let wholesale_final = response
        .results
        .values()
        .find(|r| r.rule.name == "wholesale_final")
        .unwrap();
    let price_difference = response
        .results
        .values()
        .find(|r| r.rule.name == "price_difference")
        .unwrap();

    // retail: 100 * (1 - 0.05) = 95
    match &retail_final.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("95").unwrap()),
            other => panic!("Expected Number for retail_final, got {:?}", other),
        },
        other => panic!("Expected Value for retail_final, got {:?}", other),
    }
    // wholesale: 80 * (1 - 0.15) = 68
    match &wholesale_final.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("68").unwrap()),
            other => panic!("Expected Number for wholesale_final, got {:?}", other),
        },
        other => panic!("Expected Value for wholesale_final, got {:?}", other),
    }
    // difference: 95 - 68 = 27
    match &price_difference.result {
        lemma::OperationResult::Value(lit) => match &lit.value {
            lemma::ValueKind::Number(n) => assert_eq!(*n, Decimal::from_str("27").unwrap()),
            other => panic!("Expected Number for price_difference, got {:?}", other),
        },
        other => panic!("Expected Value for price_difference, got {:?}", other),
    }
}

/// Binding interface validation: binding a spec ref to a spec with the same rule name
/// but incompatible result type is rejected at the binding site.
#[test]
fn test_spec_ref_binding_interface_rule_type_rejected() {
    let mut engine = Engine::new();

    let spec_a = r#"
spec a
rule x: 5
"#;

    let spec_b = r#"
spec b
rule x: true
"#;

    let spec_c = r#"
spec c
fact aa: spec a
rule y: aa.x > 1
"#;

    let spec_d = r#"
spec d
fact cc: spec c
fact cc.aa: spec b
rule yy: cc.y
"#;

    engine
        .load(spec_a, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(spec_b, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    engine
        .load(spec_c, lemma::SourceType::Labeled("test.lemma"))
        .unwrap();
    let errs = engine
        .load(spec_d, lemma::SourceType::Labeled("test.lemma"))
        .unwrap_err();
    let err_str = errs
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");
    // We must reject the bad binding. Either we report at the binding site (preferred)
    // or the expression type checker reports the comparison error.
    let binding_site_error =
        err_str.contains("Fact binding 'cc.aa'") && err_str.contains("sets spec reference to 'b'");
    let comparison_error = err_str.contains("Cannot compare") && err_str.contains("Boolean");
    assert!(
        binding_site_error || comparison_error,
        "expected binding-site or comparison type error for bad spec binding, got: {}",
        err_str
    );
}