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 fn add_lemma_code_blocking(
425 engine: &mut Engine,
426 code: &str,
427 source: &str,
428 ) -> Result<(), crate::Errors> {
429 engine.load(code, crate::SourceType::Labeled(source))
430 }
431
432 #[test]
433 fn test_format_target_eq() {
434 let target = Target::value(LiteralValue::number(Decimal::from(42)));
435 let formatted = target.format();
436 assert_eq!(formatted, "= 42");
437 }
438
439 #[test]
440 fn test_format_target_any() {
441 let target = Target::any_value();
442 let formatted = target.format();
443 assert_eq!(formatted, "= any");
444 }
445
446 #[test]
447 fn test_compute_undetermined_facts_empty() {
448 let domains: Vec<HashMap<FactPath, Domain>> = vec![];
449 let undetermined = compute_undetermined_facts(&domains);
450 assert!(undetermined.is_empty());
451 }
452
453 #[test]
454 fn test_compute_undetermined_facts_single_value() {
455 let mut domain_map = HashMap::new();
456 domain_map.insert(
457 FactPath::new(vec![], "age".to_string()),
458 Domain::Enumeration(Arc::new(vec![LiteralValue::number(Decimal::from(25))])),
459 );
460 let domains = vec![domain_map];
461 let undetermined = compute_undetermined_facts(&domains);
462 assert!(undetermined.is_empty());
463 }
464
465 #[test]
466 fn test_compute_undetermined_facts_range() {
467 let mut domain_map = HashMap::new();
468 domain_map.insert(
469 FactPath::new(vec![], "age".to_string()),
470 Domain::Range {
471 min: Bound::Exclusive(Arc::new(LiteralValue::number(Decimal::from(18)))),
472 max: Bound::Unbounded,
473 },
474 );
475 let domains = vec![domain_map];
476 let undetermined = compute_undetermined_facts(&domains);
477 assert_eq!(undetermined.len(), 1);
478 }
479
480 #[test]
481 fn test_compute_is_determined_empty() {
482 let domains: Vec<HashMap<FactPath, Domain>> = vec![];
483 assert!(compute_is_determined(&domains));
484 }
485
486 #[test]
487 fn test_compute_is_determined_true() {
488 let mut domain_map = HashMap::new();
489 domain_map.insert(
490 FactPath::new(vec![], "age".to_string()),
491 Domain::Enumeration(Arc::new(vec![LiteralValue::number(Decimal::from(25))])),
492 );
493 let domains = vec![domain_map];
494 assert!(compute_is_determined(&domains));
495 }
496
497 #[test]
498 fn test_compute_is_determined_false() {
499 let mut domain_map = HashMap::new();
500 domain_map.insert(
501 FactPath::new(vec![], "age".to_string()),
502 Domain::Range {
503 min: Bound::Exclusive(Arc::new(LiteralValue::number(Decimal::from(18)))),
504 max: Bound::Unbounded,
505 },
506 );
507 let domains = vec![domain_map];
508 assert!(!compute_is_determined(&domains));
509 }
510
511 #[test]
512 fn test_invert_strict_rule_reference_expands_constraints() {
513 let code = r#"
516spec example
517fact x: [number]
518rule base: x
519 unless x > 3 then veto "too much"
520 unless x < 0 then veto "too little"
521
522rule another: base
523 unless x > 5 then veto "way too much"
524"#;
525
526 let mut engine = Engine::new();
527 add_lemma_code_blocking(&mut engine, code, "test.lemma").unwrap();
528 let now = DateTimeValue::now();
529
530 let inv = engine
531 .invert(
532 "example",
533 &now,
534 "another",
535 Target::value(LiteralValue::number(3.into())),
536 HashMap::new(),
537 )
538 .expect("inversion should succeed");
539
540 assert!(!inv.is_empty(), "expected at least one solution");
541
542 let x = FactPath::new(vec![], "x".to_string());
543 let three = LiteralValue::number(3.into());
544
545 for (_solution, domains) in inv.iter() {
547 let d = domains.get(&x).expect("domain for x should exist");
548 assert!(
549 d.contains(&three),
550 "x domain should contain 3. Domain: {}",
551 d
552 );
553 }
554 }
555
556 #[test]
557 fn test_invert_strict_no_solution_when_value_is_blocked_by_veto() {
558 let code = r#"
559spec example
560fact x: [number]
561rule base: x
562 unless x > 3 then veto "too much"
563 unless x < 0 then veto "too little"
564
565rule another: base
566 unless x > 5 then veto "way too much"
567"#;
568
569 let mut engine = Engine::new();
570 add_lemma_code_blocking(&mut engine, code, "test.lemma").unwrap();
571 let now = DateTimeValue::now();
572
573 let inv = engine
574 .invert(
575 "example",
576 &now,
577 "another",
578 Target::value(LiteralValue::number(7.into())),
579 HashMap::new(),
580 )
581 .expect("inversion should succeed");
582
583 assert!(
584 inv.is_empty(),
585 "Should have no solutions because another can never equal 7"
586 );
587 }
588
589 #[test]
590 fn test_invert_strict_veto_target_constrains_domain() {
591 let code = r#"
592spec example
593fact x: [number]
594rule base: x
595 unless x > 3 then veto "too much"
596 unless x < 0 then veto "too little"
597
598rule another: base
599 unless x > 5 then veto "way too much"
600"#;
601
602 let mut engine = Engine::new();
603 add_lemma_code_blocking(&mut engine, code, "test.lemma").unwrap();
604 let now = DateTimeValue::now();
605
606 let inv = engine
607 .invert(
608 "example",
609 &now,
610 "another",
611 Target::veto(Some("way too much".to_string())),
612 HashMap::new(),
613 )
614 .expect("inversion should succeed");
615
616 assert!(!inv.is_empty(), "expected solutions for veto query");
617
618 let x = FactPath::new(vec![], "x".to_string());
619 let five = LiteralValue::number(5.into());
620 let six = LiteralValue::number(6.into());
621
622 for (solution, domains) in inv.iter() {
623 assert_eq!(
624 solution.outcome,
625 OperationResult::Veto(Some("way too much".to_string())),
626 "Expected solution outcome to be veto('way too much'), got: {:?}",
627 solution.outcome
628 );
629
630 let d = domains.get(&x).expect("domain for x should exist");
631 match d {
632 Domain::Range { min, max } => {
633 assert!(
634 matches!(min, Bound::Exclusive(v) if v.as_ref() == &five),
635 "Expected min bound to be (5), got: {}",
636 d
637 );
638 assert!(
639 matches!(max, Bound::Unbounded),
640 "Expected max bound to be +inf, got: {}",
641 d
642 );
643 }
644 other => panic!("Expected range domain for x, got: {}", other),
645 }
646 assert!(
647 !d.contains(&five),
648 "x=5 should not be in veto('way too much') domain. Domain: {}",
649 d
650 );
651 assert!(
652 d.contains(&six),
653 "x=6 should be in veto('way too much') domain. Domain: {}",
654 d
655 );
656 }
657 }
658
659 #[test]
660 fn test_invert_strict_any_veto_target_matches_all_veto_ranges() {
661 let code = r#"
662spec example
663fact x: [number]
664rule base: x
665 unless x > 3 then veto "too much"
666 unless x < 0 then veto "too little"
667
668rule another: base
669 unless x > 5 then veto "way too much"
670"#;
671
672 let mut engine = Engine::new();
673 add_lemma_code_blocking(&mut engine, code, "test.lemma").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}