1mod constraint;
10mod derived;
11mod domain;
12mod solve;
13mod target;
14mod world;
15
16pub use derived::{DerivedExpression, DerivedExpressionKind};
17pub use domain::{extract_domains_from_constraint, Bound, Domain};
18pub use target::{Target, TargetOp};
19pub use world::World;
20
21use crate::planning::semantics::{Expression, FactPath, LiteralValue, ValueKind};
22use crate::planning::ExecutionPlan;
23use crate::{Error, OperationResult};
24use serde::ser::{Serialize, SerializeStruct, Serializer};
25use std::collections::{HashMap, HashSet};
26
27use world::{WorldEnumerator, WorldSolution};
28
29#[derive(Debug, Clone, serde::Serialize)]
38pub struct Solution {
39 pub outcome: OperationResult,
41 pub world: World,
43 #[serde(skip_serializing_if = "Option::is_none")]
46 pub shape: Option<Expression>,
47}
48
49#[derive(Debug, Clone)]
51pub struct InversionResponse {
52 pub solutions: Vec<Solution>,
54 pub domains: Vec<HashMap<FactPath, Domain>>,
56 pub undetermined_facts: Vec<FactPath>,
58 pub is_determined: bool,
60}
61
62impl InversionResponse {
63 pub fn new(solutions: Vec<Solution>, domains: Vec<HashMap<FactPath, Domain>>) -> Self {
65 let undetermined_facts = compute_undetermined_facts(&domains);
66 let is_determined = compute_is_determined(&domains);
67 Self {
68 solutions,
69 domains,
70 undetermined_facts,
71 is_determined,
72 }
73 }
74
75 pub fn is_empty(&self) -> bool {
77 self.solutions.is_empty()
78 }
79
80 pub fn len(&self) -> usize {
82 self.solutions.len()
83 }
84
85 pub fn iter(&self) -> impl Iterator<Item = (&Solution, &HashMap<FactPath, Domain>)> {
87 self.solutions.iter().zip(self.domains.iter())
88 }
89}
90
91impl Serialize for InversionResponse {
92 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
93 where
94 S: Serializer,
95 {
96 let mut state = serializer.serialize_struct("InversionResponse", 4)?;
97 state.serialize_field("solutions", &self.solutions)?;
98
99 let domains_serializable: Vec<HashMap<String, String>> = self
100 .domains
101 .iter()
102 .map(|d| {
103 d.iter()
104 .map(|(k, v)| (k.to_string(), v.to_string()))
105 .collect()
106 })
107 .collect();
108 state.serialize_field("domains", &domains_serializable)?;
109
110 let undetermined_serializable: Vec<String> = self
111 .undetermined_facts
112 .iter()
113 .map(|fp| fp.to_string())
114 .collect();
115 state.serialize_field("undetermined_facts", &undetermined_serializable)?;
116 state.serialize_field("is_determined", &self.is_determined)?;
117 state.end()
118 }
119}
120
121pub fn invert(
136 rule_name: &str,
137 target: Target,
138 plan: &ExecutionPlan,
139 provided_facts: &HashSet<FactPath>,
140) -> Result<InversionResponse, Error> {
141 let executable_rule = plan.get_rule(rule_name).ok_or_else(|| {
142 Error::request(
143 format!("Rule not found: {}.{}", plan.spec_name, rule_name),
144 None::<String>,
145 )
146 })?;
147
148 let rule_path = executable_rule.path.clone();
149
150 let mut enumerator = WorldEnumerator::new(plan, &rule_path)?;
152 let enumeration_result = enumerator.enumerate(provided_facts)?;
153
154 let mut solutions = Vec::new();
156 let mut all_domains = Vec::new();
157
158 let filtered_literal_solutions =
160 filter_literal_solutions_by_target(enumeration_result.literal_solutions, &target);
161
162 for world_solution in filtered_literal_solutions {
163 let constraint_domains = extract_domains_from_constraint(&world_solution.constraint)?;
164
165 let solution = Solution {
166 outcome: world_solution.outcome,
167 world: world_solution.world,
168 shape: None,
169 };
170
171 solutions.push(solution);
172 all_domains.push(constraint_domains);
173 }
174
175 if let Some(OperationResult::Value(target_value)) = &target.outcome {
177 let solved_indices: std::collections::HashSet<usize> = if target.op == TargetOp::Eq {
179 let algebraic_solutions = solve::solve_arithmetic_batch(
180 enumeration_result.arithmetic_solutions.clone(),
181 target_value,
182 provided_facts,
183 );
184
185 let indices: std::collections::HashSet<usize> = algebraic_solutions
187 .iter()
188 .filter_map(|(ws, _, _)| {
189 enumeration_result
190 .arithmetic_solutions
191 .iter()
192 .position(|orig| orig.world == ws.world)
193 })
194 .collect();
195
196 for (world_solution, solved_outcome, solved_domains) in algebraic_solutions {
198 let constraint_domains =
199 extract_domains_from_constraint(&world_solution.constraint)?;
200
201 let mut is_valid = true;
203 for (fact_path, solved_domain) in &solved_domains {
204 if let Some(constraint_domain) = constraint_domains.get(fact_path) {
205 if let Domain::Enumeration(values) = solved_domain {
207 for value in values.iter() {
208 if !constraint_domain.contains(value) {
209 is_valid = false;
210 break;
211 }
212 }
213 }
214 }
215 if !is_valid {
216 break;
217 }
218 }
219
220 if !is_valid {
221 continue; }
223
224 let solved_outcome_result = OperationResult::Value(Box::new(solved_outcome));
225
226 let mut combined_domains = constraint_domains;
227 for (fact_path, domain) in solved_domains {
228 combined_domains.insert(fact_path, domain);
229 }
230
231 let solution = Solution {
232 outcome: solved_outcome_result,
233 world: world_solution.world,
234 shape: None,
235 };
236
237 solutions.push(solution);
238 all_domains.push(combined_domains);
239 }
240
241 indices
242 } else {
243 std::collections::HashSet::new()
244 };
245
246 for (idx, arith_solution) in enumeration_result.arithmetic_solutions.iter().enumerate() {
249 if solved_indices.contains(&idx) {
250 continue; }
252
253 let mut combined_domains = extract_domains_from_constraint(&arith_solution.constraint)?;
255
256 let unknown_facts =
258 extract_fact_paths_from_expression(&arith_solution.outcome_expression);
259 for fact_path in unknown_facts {
260 if !combined_domains.contains_key(&fact_path)
262 && !provided_facts.contains(&fact_path)
263 {
264 combined_domains.insert(fact_path, Domain::Unconstrained);
265 }
266 }
267
268 let solution = Solution {
269 outcome: OperationResult::Value(Box::new(target_value.as_ref().clone())),
270 world: arith_solution.world.clone(),
271 shape: Some(arith_solution.outcome_expression.clone()),
272 };
273
274 solutions.push(solution);
275 all_domains.push(combined_domains);
276 }
277 }
278
279 Ok(InversionResponse::new(solutions, all_domains))
280}
281
282fn filter_literal_solutions_by_target(
288 solutions: Vec<WorldSolution>,
289 target: &Target,
290) -> Vec<WorldSolution> {
291 let mut filtered = Vec::new();
292
293 for solution in solutions {
294 let matches = match (&target.outcome, &solution.outcome) {
295 (None, _) => {
296 true
298 }
299 (Some(OperationResult::Value(target_value)), OperationResult::Value(outcome_value)) => {
300 match target.op {
305 TargetOp::Eq => outcome_value.value == target_value.value,
306 TargetOp::Neq => outcome_value.value != target_value.value,
307 TargetOp::Lt => {
308 compare_values(outcome_value, target_value)
309 == Some(std::cmp::Ordering::Less)
310 }
311 TargetOp::Lte => {
312 let cmp = compare_values(outcome_value, target_value);
313 cmp == Some(std::cmp::Ordering::Less)
314 || cmp == Some(std::cmp::Ordering::Equal)
315 }
316 TargetOp::Gt => {
317 compare_values(outcome_value, target_value)
318 == Some(std::cmp::Ordering::Greater)
319 }
320 TargetOp::Gte => {
321 let cmp = compare_values(outcome_value, target_value);
322 cmp == Some(std::cmp::Ordering::Greater)
323 || cmp == Some(std::cmp::Ordering::Equal)
324 }
325 }
326 }
327 (Some(OperationResult::Veto(target_msg)), OperationResult::Veto(outcome_msg)) => {
328 match target_msg {
330 None => true, Some(t_msg) => outcome_msg.as_ref().map(|m| m == t_msg).unwrap_or(false),
332 }
333 }
334 _ => false, };
336
337 if matches {
338 filtered.push(solution);
339 }
340 }
341
342 filtered
343}
344
345fn compare_values(a: &LiteralValue, b: &LiteralValue) -> Option<std::cmp::Ordering> {
347 match (&a.value, &b.value) {
348 (ValueKind::Number(a_val), ValueKind::Number(b_val)) => Some(a_val.cmp(b_val)),
349 (ValueKind::Ratio(a_val, _), ValueKind::Ratio(b_val, _)) => Some(a_val.cmp(b_val)),
350 (ValueKind::Scale(a_val, _), ValueKind::Scale(b_val, _)) => Some(a_val.cmp(b_val)),
351 (ValueKind::Duration(a_val, unit_a), ValueKind::Duration(b_val, unit_b)) => {
352 if unit_a == unit_b {
353 Some(a_val.cmp(b_val))
354 } else {
355 None
356 }
357 }
358 _ => None,
359 }
360}
361
362fn extract_fact_paths_from_expression(expr: &Expression) -> Vec<FactPath> {
364 let mut set = std::collections::HashSet::new();
365 expr.collect_fact_paths(&mut set);
366 set.into_iter().collect()
367}
368
369fn compute_undetermined_facts(all_domains: &[HashMap<FactPath, Domain>]) -> Vec<FactPath> {
371 let mut undetermined: HashSet<FactPath> = HashSet::new();
372
373 for solution_domains in all_domains {
374 for (fact_path, domain) in solution_domains {
375 let is_determined = matches!(
376 domain,
377 Domain::Enumeration(values) if values.len() == 1
378 );
379 if !is_determined {
380 undetermined.insert(fact_path.clone());
381 }
382 }
383 }
384
385 let mut result: Vec<FactPath> = undetermined.into_iter().collect();
386 result.sort_by_key(|a| a.to_string());
387 result
388}
389
390fn compute_is_determined(all_domains: &[HashMap<FactPath, Domain>]) -> bool {
392 if all_domains.is_empty() {
393 return true;
394 }
395
396 for solution_domains in all_domains {
397 for domain in solution_domains.values() {
398 let is_single_value = matches!(
399 domain,
400 Domain::Enumeration(values) if values.len() == 1
401 );
402 if !is_single_value {
403 return false;
404 }
405 }
406 }
407
408 true
409}
410
411#[cfg(test)]
416mod tests {
417 use super::*;
418 use crate::parsing::ast::DateTimeValue;
419 use crate::Engine;
420 use rust_decimal::Decimal;
421 use std::collections::HashMap;
422 use std::sync::Arc;
423
424 #[test]
425 fn test_format_target_eq() {
426 let target = Target::value(LiteralValue::number(Decimal::from(42)));
427 let formatted = target.format();
428 assert_eq!(formatted, "= 42");
429 }
430
431 #[test]
432 fn test_format_target_any() {
433 let target = Target::any_value();
434 let formatted = target.format();
435 assert_eq!(formatted, "= any");
436 }
437
438 #[test]
439 fn test_compute_undetermined_facts_empty() {
440 let domains: Vec<HashMap<FactPath, Domain>> = vec![];
441 let undetermined = compute_undetermined_facts(&domains);
442 assert!(undetermined.is_empty());
443 }
444
445 #[test]
446 fn test_compute_undetermined_facts_single_value() {
447 let mut domain_map = HashMap::new();
448 domain_map.insert(
449 FactPath::new(vec![], "age".to_string()),
450 Domain::Enumeration(Arc::new(vec![LiteralValue::number(Decimal::from(25))])),
451 );
452 let domains = vec![domain_map];
453 let undetermined = compute_undetermined_facts(&domains);
454 assert!(undetermined.is_empty());
455 }
456
457 #[test]
458 fn test_compute_undetermined_facts_range() {
459 let mut domain_map = HashMap::new();
460 domain_map.insert(
461 FactPath::new(vec![], "age".to_string()),
462 Domain::Range {
463 min: Bound::Exclusive(Arc::new(LiteralValue::number(Decimal::from(18)))),
464 max: Bound::Unbounded,
465 },
466 );
467 let domains = vec![domain_map];
468 let undetermined = compute_undetermined_facts(&domains);
469 assert_eq!(undetermined.len(), 1);
470 }
471
472 #[test]
473 fn test_compute_is_determined_empty() {
474 let domains: Vec<HashMap<FactPath, Domain>> = vec![];
475 assert!(compute_is_determined(&domains));
476 }
477
478 #[test]
479 fn test_compute_is_determined_true() {
480 let mut domain_map = HashMap::new();
481 domain_map.insert(
482 FactPath::new(vec![], "age".to_string()),
483 Domain::Enumeration(Arc::new(vec![LiteralValue::number(Decimal::from(25))])),
484 );
485 let domains = vec![domain_map];
486 assert!(compute_is_determined(&domains));
487 }
488
489 #[test]
490 fn test_compute_is_determined_false() {
491 let mut domain_map = HashMap::new();
492 domain_map.insert(
493 FactPath::new(vec![], "age".to_string()),
494 Domain::Range {
495 min: Bound::Exclusive(Arc::new(LiteralValue::number(Decimal::from(18)))),
496 max: Bound::Unbounded,
497 },
498 );
499 let domains = vec![domain_map];
500 assert!(!compute_is_determined(&domains));
501 }
502
503 #[test]
504 fn test_invert_strict_rule_reference_expands_constraints() {
505 let code = r#"
508spec example
509fact x: [number]
510rule base: x
511 unless x > 3 then veto "too much"
512 unless x < 0 then veto "too little"
513
514rule another: base
515 unless x > 5 then veto "way too much"
516"#;
517
518 let mut engine = Engine::new();
519 engine
520 .load(code, crate::SourceType::Labeled("test.lemma"))
521 .unwrap();
522 let now = DateTimeValue::now();
523
524 let inv = engine
525 .invert(
526 "example",
527 &now,
528 "another",
529 Target::value(LiteralValue::number(3.into())),
530 HashMap::new(),
531 )
532 .expect("inversion should succeed");
533
534 assert!(!inv.is_empty(), "expected at least one solution");
535
536 let x = FactPath::new(vec![], "x".to_string());
537 let three = LiteralValue::number(3.into());
538
539 for (_solution, domains) in inv.iter() {
541 let d = domains.get(&x).expect("domain for x should exist");
542 assert!(
543 d.contains(&three),
544 "x domain should contain 3. Domain: {}",
545 d
546 );
547 }
548 }
549
550 #[test]
551 fn test_invert_strict_no_solution_when_value_is_blocked_by_veto() {
552 let code = r#"
553spec example
554fact x: [number]
555rule base: x
556 unless x > 3 then veto "too much"
557 unless x < 0 then veto "too little"
558
559rule another: base
560 unless x > 5 then veto "way too much"
561"#;
562
563 let mut engine = Engine::new();
564 engine
565 .load(code, crate::SourceType::Labeled("test.lemma"))
566 .unwrap();
567 let now = DateTimeValue::now();
568
569 let inv = engine
570 .invert(
571 "example",
572 &now,
573 "another",
574 Target::value(LiteralValue::number(7.into())),
575 HashMap::new(),
576 )
577 .expect("inversion should succeed");
578
579 assert!(
580 inv.is_empty(),
581 "Should have no solutions because another can never equal 7"
582 );
583 }
584
585 #[test]
586 fn test_invert_strict_veto_target_constrains_domain() {
587 let code = r#"
588spec example
589fact x: [number]
590rule base: x
591 unless x > 3 then veto "too much"
592 unless x < 0 then veto "too little"
593
594rule another: base
595 unless x > 5 then veto "way too much"
596"#;
597
598 let mut engine = Engine::new();
599 engine
600 .load(code, crate::SourceType::Labeled("test.lemma"))
601 .unwrap();
602 let now = DateTimeValue::now();
603
604 let inv = engine
605 .invert(
606 "example",
607 &now,
608 "another",
609 Target::veto(Some("way too much".to_string())),
610 HashMap::new(),
611 )
612 .expect("inversion should succeed");
613
614 assert!(!inv.is_empty(), "expected solutions for veto query");
615
616 let x = FactPath::new(vec![], "x".to_string());
617 let five = LiteralValue::number(5.into());
618 let six = LiteralValue::number(6.into());
619
620 for (solution, domains) in inv.iter() {
621 assert_eq!(
622 solution.outcome,
623 OperationResult::Veto(Some("way too much".to_string())),
624 "Expected solution outcome to be veto('way too much'), got: {:?}",
625 solution.outcome
626 );
627
628 let d = domains.get(&x).expect("domain for x should exist");
629 match d {
630 Domain::Range { min, max } => {
631 assert!(
632 matches!(min, Bound::Exclusive(v) if v.as_ref() == &five),
633 "Expected min bound to be (5), got: {}",
634 d
635 );
636 assert!(
637 matches!(max, Bound::Unbounded),
638 "Expected max bound to be +inf, got: {}",
639 d
640 );
641 }
642 other => panic!("Expected range domain for x, got: {}", other),
643 }
644 assert!(
645 !d.contains(&five),
646 "x=5 should not be in veto('way too much') domain. Domain: {}",
647 d
648 );
649 assert!(
650 d.contains(&six),
651 "x=6 should be in veto('way too much') domain. Domain: {}",
652 d
653 );
654 }
655 }
656
657 #[test]
658 fn test_invert_strict_any_veto_target_matches_all_veto_ranges() {
659 let code = r#"
660spec example
661fact x: [number]
662rule base: x
663 unless x > 3 then veto "too much"
664 unless x < 0 then veto "too little"
665
666rule another: base
667 unless x > 5 then veto "way too much"
668"#;
669
670 let mut engine = Engine::new();
671 engine
672 .load(code, crate::SourceType::Labeled("test.lemma"))
673 .unwrap();
674
675 let now = DateTimeValue::now();
676 let inv = engine
677 .invert(
678 "example",
679 &now,
680 "another",
681 Target::any_veto(),
682 HashMap::new(),
683 )
684 .expect("inversion should succeed");
685
686 assert!(!inv.is_empty(), "expected solutions for any-veto query");
687
688 let x = FactPath::new(vec![], "x".to_string());
689 let minus_one = LiteralValue::number((-1).into());
690 let zero = LiteralValue::number(0.into());
691 let two = LiteralValue::number(2.into());
692 let three = LiteralValue::number(3.into());
693 let four = LiteralValue::number(4.into());
694 let five = LiteralValue::number(5.into());
695 let six = LiteralValue::number(6.into());
696
697 let mut saw_too_little = false;
698 let mut saw_too_much = false;
699 let mut saw_way_too_much = false;
700
701 for (solution, domains) in inv.iter() {
702 let d = domains.get(&x).expect("domain for x should exist");
703 assert!(
704 !d.contains(&two),
705 "x=2 should not be in any-veto domain. Domain: {}",
706 d
707 );
708
709 match &solution.outcome {
710 OperationResult::Veto(Some(msg)) if msg == "too little" => {
711 saw_too_little = true;
712
713 match d {
714 Domain::Range { min, max } => {
715 assert!(
716 matches!(min, Bound::Unbounded),
717 "Expected min bound to be -inf for 'too little', got: {}",
718 d
719 );
720 assert!(
721 matches!(max, Bound::Exclusive(v) if v.as_ref() == &zero),
722 "Expected max bound to be (0) for 'too little', got: {}",
723 d
724 );
725 }
726 other => panic!("Expected range domain for x, got: {}", other),
727 }
728
729 assert!(
730 d.contains(&minus_one),
731 "x=-1 should be in veto('too little') domain. Domain: {}",
732 d
733 );
734 assert!(
735 !d.contains(&zero),
736 "x=0 should not be in veto('too little') domain. Domain: {}",
737 d
738 );
739 }
740 OperationResult::Veto(Some(msg)) if msg == "too much" => {
741 saw_too_much = true;
742
743 match d {
744 Domain::Range { min, max } => {
745 assert!(
746 matches!(min, Bound::Exclusive(v) if v.as_ref() == &three),
747 "Expected min bound to be (3) for 'too much', got: {}",
748 d
749 );
750 assert!(
751 matches!(max, Bound::Inclusive(v) if v.as_ref() == &five),
752 "Expected max bound to be [5] for 'too much', got: {}",
753 d
754 );
755 }
756 other => panic!("Expected range domain for x, got: {}", other),
757 }
758
759 assert!(
760 d.contains(&four),
761 "x=4 should be in veto('too much') domain. Domain: {}",
762 d
763 );
764 assert!(
765 d.contains(&five),
766 "x=5 should be in veto('too much') domain. Domain: {}",
767 d
768 );
769 assert!(
770 !d.contains(&three),
771 "x=3 should not be in veto('too much') domain. Domain: {}",
772 d
773 );
774 assert!(
775 !d.contains(&six),
776 "x=6 should not be in veto('too much') domain. Domain: {}",
777 d
778 );
779 }
780 OperationResult::Veto(Some(msg)) if msg == "way too much" => {
781 saw_way_too_much = true;
782
783 match d {
784 Domain::Range { min, max } => {
785 assert!(
786 matches!(min, Bound::Exclusive(v) if v.as_ref() == &five),
787 "Expected min bound to be (5) for 'way too much', got: {}",
788 d
789 );
790 assert!(
791 matches!(max, Bound::Unbounded),
792 "Expected max bound to be +inf for 'way too much', got: {}",
793 d
794 );
795 }
796 other => panic!("Expected range domain for x, got: {}", other),
797 }
798
799 assert!(
800 d.contains(&six),
801 "x=6 should be in veto('way too much') domain. Domain: {}",
802 d
803 );
804 assert!(
805 !d.contains(&five),
806 "x=5 should not be in veto('way too much') domain. Domain: {}",
807 d
808 );
809 }
810 OperationResult::Veto(Some(other)) => {
811 panic!("Unexpected veto message in any-veto results: {:?}", other)
812 }
813 OperationResult::Veto(None) => {
814 panic!("Unexpected veto(None) in any-veto results (expected a message)")
815 }
816 OperationResult::Value(v) => {
817 panic!("Unexpected value result in any-veto results: {:?}", v)
818 }
819 }
820 }
821
822 assert!(
823 saw_too_little,
824 "Expected at least one veto('too little') solution"
825 );
826 assert!(
827 saw_too_much,
828 "Expected at least one veto('too much') solution"
829 );
830 assert!(
831 saw_way_too_much,
832 "Expected at least one veto('way too much') solution"
833 );
834 }
835}