Skip to main content

lemma/evaluation/
response.rs

1use crate::computation::{OperationResult, VetoType};
2use crate::evaluation::explanations::Explanation;
3
4use crate::error::Error;
5use crate::evaluation::evaluate_data::EvaluateDataValue;
6use crate::evaluation::rows::row_result;
7use crate::evaluation::tree::{ensure_row_rule, materialize_row};
8use crate::evaluation::EvaluationContext;
9use crate::parsing::ast::DateTimeValue;
10use crate::planning::execution_plan::ExecutionPlan;
11use crate::planning::semantics::{
12    DataDefinition, DataPath, InstanceKey, LemmaType, LiteralValue, ReferenceEnd, RulePath, Source,
13    SpecValue, ValueKind,
14};
15use crate::planning::unit_family::FamilyUnitCatalog;
16use crate::result_value::{
17    rule_result_value_failure_message, rule_result_value_from_literal, RowReference, RowResult,
18    RuleResultValue, RuleResultValueFailure, SpecResult, SpecRuleResult,
19};
20use indexmap::IndexMap;
21use std::collections::HashMap;
22use std::sync::Arc;
23
24/// Rule info with resolved expressions for use in evaluation response.
25/// Evaluation uses only semantics types; no parsing types.
26#[derive(Debug, Clone)]
27pub struct EvaluatedRule {
28    pub name: String,
29    pub path: RulePath,
30    pub source_location: Source,
31    pub rule_type: Arc<LemmaType>,
32}
33
34/// Response from evaluating a Lemma spec
35#[derive(Debug, Clone)]
36pub struct Response {
37    pub spec_name: String,
38    pub effective: String,
39    /// Declared temporal window `[spec_effective_from, spec_effective_to)` of the
40    /// resolved spec version. Set by [`crate::Engine::evaluate`] after evaluation;
41    /// `None` here (evaluation-internal construction) until that assignment.
42    pub spec_effective_from: Option<DateTimeValue>,
43    pub spec_effective_to: Option<DateTimeValue>,
44    pub results: IndexMap<String, RuleResult>,
45    /// Rows reached by `results`, indexed by [`RowReference::index`].
46    pub rows: Vec<RowResult>,
47}
48
49/// Result of evaluating a single rule. Struct fields match the API JSON shape.
50#[derive(Debug, Clone)]
51pub struct RuleResult {
52    pub rule: EvaluatedRule,
53    pub veto_detail: Option<VetoType>,
54
55    pub vetoed: bool,
56    pub veto_reason: Option<String>,
57    pub rule_type: String,
58
59    /// Flattened value fields, including `result` when the rule is not vetoed.
60    pub result: Option<RuleResultValue>,
61    pub explanation: Option<Explanation>,
62    /// Unbound caller data paths still live for this rule under the current run data
63    /// (`DataPath::input_key` strings; subset of `Show.data` keys with non-empty
64    /// `needed_by_rules`). Ordered by evaluation / decision-tree preorder (first key =
65    /// next fact the live tree needs); `Show.data` stays declaration order.
66    missing_data: Vec<String>,
67    /// Closed options for keys in [`Self::missing_data`]. A key with no entry is not
68    /// constrained by a set. An empty list is a closed set with nothing valid.
69    /// Each value is what the next evaluate accepts.
70    missing_data_options: IndexMap<String, Vec<EvaluateDataValue>>,
71}
72
73impl RuleResult {
74    /// Engine-rendered one-liner from the flattened [`RuleResultValue`].
75    #[must_use]
76    pub fn result(&self) -> Option<&str> {
77        self.result
78            .as_ref()
79            .and_then(|value| value.result.as_deref())
80    }
81
82    /// True when this result is a [`VetoType::MissingData`] or [`VetoType::MissingRowData`] veto.
83    ///
84    /// Value and other vetoes are settled answers; leftover live keys in
85    /// [`Self::missing_data`] must not drive prompts or human "Missing data" display.
86    #[must_use]
87    pub fn is_missing_data(&self) -> bool {
88        matches!(
89            self.veto_detail.as_ref(),
90            Some(VetoType::MissingData { .. } | VetoType::MissingRowData { .. })
91        )
92    }
93
94    /// Unbound caller data paths still live for this rule (`DataPath::input_key`),
95    /// in evaluation / decision-tree order (contrast `Show.data` declaration order).
96    #[must_use]
97    pub fn missing_data(&self) -> &[String] {
98        &self.missing_data
99    }
100
101    /// Closed sets for this rule's missing inputs. Keys are a subset of [`Self::missing_data`].
102    #[must_use]
103    pub fn missing_data_options(&self) -> &IndexMap<String, Vec<EvaluateDataValue>> {
104        &self.missing_data_options
105    }
106
107    pub(crate) fn with_missing_data_options(
108        mut self,
109        missing_data_options: IndexMap<String, Vec<EvaluateDataValue>>,
110    ) -> Self {
111        for key in missing_data_options.keys() {
112            if !self.missing_data.iter().any(|listed| listed == key) {
113                panic!(
114                    "BUG: missing_data_options key '{key}' is not in missing_data {:?}",
115                    self.missing_data
116                );
117            }
118        }
119        self.missing_data_options = missing_data_options;
120        self
121    }
122
123    /// Build a [`RuleResult`] for API output from a rule evaluation result.
124    ///
125    /// Measure and ratio payloads expand into every unit in the result type's family.
126    pub(crate) fn from_operation_result(
127        rule: EvaluatedRule,
128        operation_result: &OperationResult,
129        rule_type: &LemmaType,
130        family_units: &FamilyUnitCatalog,
131        explanation: Option<Explanation>,
132        missing_data: Vec<String>,
133    ) -> Self {
134        Self::from_evaluated(
135            rule,
136            operation_result,
137            rule_type,
138            family_units,
139            explanation,
140            missing_data,
141            None,
142        )
143    }
144
145    pub(crate) fn from_evaluated(
146        rule: EvaluatedRule,
147        operation_result: &OperationResult,
148        rule_type: &LemmaType,
149        family_units: &FamilyUnitCatalog,
150        explanation: Option<Explanation>,
151        missing_data: Vec<String>,
152        runtime_scales: Option<
153            &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
154        >,
155    ) -> Self {
156        match operation_result {
157            OperationResult::Veto(VetoType::MissingData { data, .. }) => {
158                let key = data.input_key();
159                if !missing_data.iter().any(|listed| listed == &key) {
160                    panic!("BUG: MissingData path {key} not in missing_data {missing_data:?}");
161                }
162            }
163            OperationResult::Veto(VetoType::MissingRowData { key }) => {
164                if !missing_data.contains(key) {
165                    panic!("BUG: missing row field {key} not in missing_data {missing_data:?}");
166                }
167            }
168            _ => {
169                if !missing_data.is_empty() {
170                    panic!(
171                        "BUG: missing_data must be empty when result is not MissingData: {missing_data:?}"
172                    );
173                }
174            }
175        }
176        let rule_type_name = rule_type.name().to_string();
177        match operation_result {
178            OperationResult::Veto(veto) => Self::vetoed_with(
179                rule,
180                veto.clone(),
181                rule_type_name,
182                explanation,
183                missing_data,
184                IndexMap::new(),
185            ),
186            OperationResult::Value(bound) => {
187                if (rule_type.is_measure() || rule_type.is_measure_range())
188                    && !crate::planning::semantics::measure_family_has_expressible_unit(
189                        rule_type,
190                        runtime_scales,
191                    )
192                {
193                    return Self::vetoed_with(
194                        rule,
195                        VetoType::computation(format!(
196                            "no conversion factor is known for any unit of {}",
197                            rule_type.name()
198                        )),
199                        rule_type_name,
200                        explanation,
201                        missing_data,
202                        IndexMap::new(),
203                    );
204                }
205                match rule_result_value_from_literal(
206                    &bound.to_literal(),
207                    rule_type,
208                    family_units,
209                    runtime_scales,
210                ) {
211                    Ok(value) => Self {
212                        rule,
213                        veto_detail: None,
214                        vetoed: false,
215                        veto_reason: None,
216                        rule_type: rule_type_name,
217                        result: Some(value),
218                        explanation,
219                        missing_data,
220                        missing_data_options: IndexMap::new(),
221                    },
222                    Err(failure) => vetoed_rule_result_for_rule_result_value_failure(
223                        rule,
224                        rule_type,
225                        explanation,
226                        failure,
227                        missing_data,
228                    ),
229                }
230            }
231        }
232    }
233
234    fn vetoed_with(
235        rule: EvaluatedRule,
236        veto: VetoType,
237        rule_type: String,
238        explanation: Option<Explanation>,
239        missing_data: Vec<String>,
240        missing_data_options: IndexMap<String, Vec<EvaluateDataValue>>,
241    ) -> Self {
242        Self {
243            rule,
244            veto_reason: match &veto {
245                VetoType::UserDefined { message: None } => None,
246                _ => Some(veto.to_string()),
247            },
248            veto_detail: Some(veto),
249            vetoed: true,
250            rule_type,
251            result: None,
252            explanation,
253            missing_data,
254            missing_data_options,
255        }
256    }
257
258    /// Reconstruct the evaluated [`LiteralValue`] from committed [`RuleResultValue`] fields.
259    ///
260    /// Panics if the rule is vetoed or fields cannot be reconstructed.
261    pub fn to_literal(&self) -> LiteralValue {
262        assert!(
263            !self.vetoed,
264            "BUG: to_literal called on vetoed rule '{}'",
265            self.rule.name
266        );
267        let value = self
268            .result
269            .as_ref()
270            .unwrap_or_else(|| panic!("BUG: non-vetoed rule '{}' missing result", self.rule.name));
271        value.to_literal(&self.rule.rule_type)
272    }
273}
274
275fn vetoed_rule_result_for_rule_result_value_failure(
276    rule: EvaluatedRule,
277    rule_type: &LemmaType,
278    explanation: Option<Explanation>,
279    failure: RuleResultValueFailure,
280    missing_data: Vec<String>,
281) -> RuleResult {
282    RuleResult::vetoed_with(
283        rule,
284        VetoType::computation(rule_result_value_failure_message(failure).to_string()),
285        rule_type.name().to_string(),
286        explanation,
287        missing_data,
288        IndexMap::new(),
289    )
290}
291
292impl Response {
293    /// Looks up a rule result by name.
294    ///
295    /// Returns an error if the rule is not found.
296    pub fn get(&self, rule_name: &str) -> Result<&RuleResult, Error> {
297        self.results
298            .get(rule_name)
299            .ok_or_else(|| crate::error::Error::rule_not_found(rule_name, None::<String>))
300    }
301
302    pub fn add_result(&mut self, result: RuleResult) {
303        self.results.insert(result.rule.name.clone(), result);
304    }
305}
306
307/// Distinct rows reached by one response, in first-reached order. Each row is filled
308/// once and referenced by index everywhere else, so output grows with the number of
309/// rows, not with the number of paths that reach them.
310#[derive(Default)]
311pub(crate) struct RowTable {
312    index: HashMap<InstanceKey, usize>,
313    rows: Vec<Option<RowResult>>,
314}
315
316impl RowTable {
317    pub(crate) fn into_rows(self) -> Vec<RowResult> {
318        self.rows
319            .into_iter()
320            .enumerate()
321            .map(|(index, row)| row.unwrap_or_else(|| panic!("BUG: row {index} never filled")))
322            .collect()
323    }
324}
325
326/// Fill every spec value inside `literal`'s API `value`: a planned instance (a `uses`
327/// import or a row written in a spec, at any depth) gets its data and rules inline,
328/// any other row a reference into `table`.
329pub(crate) fn fill_spec_values(
330    literal: &ValueKind,
331    value: &mut RuleResultValue,
332    plan: &ExecutionPlan,
333    ctx: &mut EvaluationContext,
334    table: &mut RowTable,
335) {
336    if matches!(
337        literal,
338        ValueKind::Number(_)
339            | ValueKind::Measure(_)
340            | ValueKind::Ratio(_)
341            | ValueKind::Text(_)
342            | ValueKind::Date(_)
343            | ValueKind::Time(_)
344            | ValueKind::Boolean(_)
345            | ValueKind::Range(_, _)
346    ) {
347        return;
348    }
349    let mut walk = Walk {
350        root: plan,
351        base: ctx,
352        table,
353        ancestors: Vec::new(),
354    };
355    let root = Frame::fill(literal.clone(), std::mem::take(value));
356    *value = walk.run(root).into_value();
357}
358
359/// Shared state of one fill walk. `root` is the plan being evaluated and `base` its
360/// context: every instance is evaluated from there, by its key.
361struct Walk<'a, 'b> {
362    root: &'a ExecutionPlan,
363    base: &'b mut EvaluationContext,
364    table: &'b mut RowTable,
365    ancestors: Vec<InstanceKey>,
366}
367
368impl<'a> Walk<'a, '_> {
369    /// Reads `row`'s context, built when the walk entered the row.
370    fn in_row<T>(&self, row: &InstanceKey, read: impl FnOnce(&EvaluationContext) -> T) -> T {
371        let contexts = self.base.caches.row_contexts.borrow();
372        read(
373            contexts
374                .get(row)
375                .unwrap_or_else(|| panic!("BUG: row '{row}' is walked without its context")),
376        )
377    }
378
379    /// Value of rule `path` of `row` over its template `plan`.
380    fn row_rule(
381        &mut self,
382        row: &InstanceKey,
383        plan: &'a ExecutionPlan,
384        path: &RulePath,
385    ) -> OperationResult {
386        ensure_row_rule(row, plan, plan.rule_index(path), self.root, self.base);
387        self.in_row(row, |ctx| ctx.rule_value(plan, path).clone())
388    }
389
390    fn run(&mut self, root: Frame<'a>) -> Output {
391        let mut frames = vec![root];
392        let mut input = None;
393        loop {
394            let frame = frames.last_mut().expect("BUG: fill walk frame stack empty");
395            match frame.resume(self, input.take()) {
396                Step::Call(child) => frames.push(child),
397                Step::Return(output) => {
398                    frames.pop();
399                    if frames.is_empty() {
400                        return output;
401                    }
402                    input = Some(output);
403                }
404            }
405        }
406    }
407}
408
409enum Frame<'a> {
410    Fill(Box<FillFrame>),
411    Instance(InstanceFrame),
412    Members(Box<MembersFrame<'a>>),
413}
414
415impl<'a> Frame<'a> {
416    fn fill(literal: ValueKind, value: RuleResultValue) -> Self {
417        Frame::Fill(Box::new(FillFrame::new(literal, value)))
418    }
419
420    fn resume(&mut self, walk: &mut Walk<'a, '_>, input: Option<Output>) -> Step<'a> {
421        match self {
422            Frame::Fill(frame) => frame.resume(walk, input),
423            Frame::Instance(frame) => frame.resume(walk, input),
424            Frame::Members(frame) => frame.resume(walk, input),
425        }
426    }
427}
428
429enum Step<'a> {
430    Call(Frame<'a>),
431    Return(Output),
432}
433
434enum Output {
435    Value(Box<RuleResultValue>),
436    Spec(Box<SpecResult>),
437    Row(RowReference),
438    Members(FilledMembers),
439}
440
441impl Output {
442    fn into_value(self) -> RuleResultValue {
443        match self {
444            Output::Value(value) => *value,
445            _ => panic!("BUG: fill walk expected a value output"),
446        }
447    }
448
449    fn into_spec(self) -> SpecResult {
450        match self {
451            Output::Spec(spec) => *spec,
452            _ => panic!("BUG: fill walk expected a spec output"),
453        }
454    }
455
456    fn into_row(self) -> RowReference {
457        match self {
458            Output::Row(row) => row,
459            _ => panic!("BUG: fill walk expected a row output"),
460        }
461    }
462
463    fn into_members(self) -> FilledMembers {
464        match self {
465            Output::Members(members) => members,
466            _ => panic!("BUG: fill walk expected a members output"),
467        }
468    }
469}
470
471fn child_output(input: Option<Output>) -> Output {
472    input.expect("BUG: fill walk frame resumed without child output")
473}
474
475enum FillState {
476    Start(ValueKind),
477    AwaitSpec,
478    /// The table row a value publishes under, labelled with the value's instance.
479    AwaitRow(Option<String>),
480    Items(
481        std::vec::IntoIter<(ValueKind, RuleResultValue)>,
482        Vec<RuleResultValue>,
483    ),
484}
485
486/// Fills one value: a planned instance gets its data and rules inline, any other row a
487/// reference into the table, a list fills each entry in order.
488struct FillFrame {
489    value: RuleResultValue,
490    state: Option<FillState>,
491}
492
493impl FillFrame {
494    fn new(literal: ValueKind, value: RuleResultValue) -> Self {
495        Self {
496            value,
497            state: Some(FillState::Start(literal)),
498        }
499    }
500
501    fn resume<'a>(&mut self, walk: &mut Walk<'a, '_>, input: Option<Output>) -> Step<'a> {
502        match self
503            .state
504            .take()
505            .expect("BUG: fill frame resumed after completion")
506        {
507            FillState::Start(literal) => {
508                assert!(
509                    input.is_none(),
510                    "BUG: fill frame started with a child output"
511                );
512                self.start(walk, literal)
513            }
514            FillState::AwaitSpec => {
515                self.value.spec = Some(Box::new(child_output(input).into_spec()));
516                self.finish()
517            }
518            FillState::AwaitRow(instance) => {
519                let mut reference = child_output(input).into_row();
520                reference.instance = instance;
521                self.value.row = Some(reference);
522                self.finish()
523            }
524            FillState::Items(items, mut filled) => {
525                filled.push(child_output(input).into_value());
526                self.next_item(items, filled)
527            }
528        }
529    }
530
531    fn start<'a>(&mut self, walk: &mut Walk<'a, '_>, literal: ValueKind) -> Step<'a> {
532        match literal {
533            ValueKind::Spec(SpecValue::Row(key)) => {
534                if key.is_planned() {
535                    assert!(
536                        self.value.spec.is_some(),
537                        "BUG: planned instance '{key}' without spec arm"
538                    );
539                    if walk.ancestors.contains(&key) {
540                        panic!("BUG: spec result walked instance '{key}' twice");
541                    }
542                    self.state = Some(FillState::AwaitSpec);
543                    return Step::Call(Frame::Instance(InstanceFrame::new(key, Publication::Spec)));
544                }
545                assert!(self.value.row.is_none(), "BUG: row '{key}' filled twice");
546                let (table, instance) = key.table_row();
547                let table = table.clone();
548                self.state = Some(FillState::AwaitRow(instance));
549                Step::Call(Frame::Instance(InstanceFrame::new(
550                    table,
551                    Publication::Table,
552                )))
553            }
554            ValueKind::List(rows) => {
555                let entries = self
556                    .value
557                    .list
558                    .take()
559                    .expect("BUG: list value without list arm");
560                assert_eq!(
561                    entries.len(),
562                    rows.len(),
563                    "BUG: list arm row count differs from the list value"
564                );
565                let filled = Vec::with_capacity(entries.len());
566                let items: Vec<(ValueKind, RuleResultValue)> = rows
567                    .iter()
568                    .map(|row| row.value.clone())
569                    .zip(entries)
570                    .collect();
571                self.next_item(items.into_iter(), filled)
572            }
573            ValueKind::Number(_)
574            | ValueKind::Measure(_)
575            | ValueKind::UnscaledMeasure { .. }
576            | ValueKind::Ratio(_)
577            | ValueKind::Text(_)
578            | ValueKind::Date(_)
579            | ValueKind::Time(_)
580            | ValueKind::Boolean(_)
581            | ValueKind::Range(_, _) => self.finish(),
582            ValueKind::Spec(SpecValue::Fixed(_)) => {
583                unreachable!("BUG: evaluation produces only row spec values")
584            }
585        }
586    }
587
588    fn next_item<'a>(
589        &mut self,
590        mut items: std::vec::IntoIter<(ValueKind, RuleResultValue)>,
591        filled: Vec<RuleResultValue>,
592    ) -> Step<'a> {
593        match items.next() {
594            Some((literal, entry)) => {
595                self.state = Some(FillState::Items(items, filled));
596                Step::Call(Frame::fill(literal, entry))
597            }
598            None => {
599                self.value.list = Some(filled);
600                self.finish()
601            }
602        }
603    }
604
605    fn finish<'a>(&mut self) -> Step<'a> {
606        Step::Return(Output::Value(Box::new(std::mem::take(&mut self.value))))
607    }
608}
609
610/// Where a reached instance publishes.
611#[derive(Clone, Copy)]
612enum Publication {
613    /// A reference into the response rows table: rows supplied by evaluation data or
614    /// appended by a rule, and anything under them.
615    Table,
616    /// Inline as the `spec` arm: `uses` imports and rows written in a spec, at any depth.
617    Spec,
618    /// Only its rules, handed to the walk of the instance that holds it as `uses` slot.
619    Rules,
620}
621
622/// Members of instance `key`, filled in its own context over its template plan. A
623/// table row is filled once and referenced by index everywhere else.
624struct InstanceFrame {
625    key: InstanceKey,
626    publication: Publication,
627    index: usize,
628}
629
630impl InstanceFrame {
631    fn new(key: InstanceKey, publication: Publication) -> Self {
632        Self {
633            key,
634            publication,
635            index: 0,
636        }
637    }
638
639    fn reference(&self, index: usize) -> RowReference {
640        RowReference {
641            repository: self.key.row.identity.repository.clone(),
642            spec: self.key.row.identity.spec.clone(),
643            effective: self.key.row.identity.effective.to_string(),
644            instance: self.key.path(),
645            index,
646        }
647    }
648
649    fn resume<'a>(&mut self, walk: &mut Walk<'a, '_>, input: Option<Output>) -> Step<'a> {
650        match input {
651            None => {
652                match self.publication {
653                    Publication::Table => {
654                        if let Some(index) = walk.table.index.get(&self.key).copied() {
655                            return Step::Return(Output::Row(self.reference(index)));
656                        }
657                        let index = walk.table.rows.len();
658                        walk.table.index.insert(self.key.clone(), index);
659                        walk.table.rows.push(None);
660                        self.index = index;
661                    }
662                    Publication::Spec => walk.ancestors.push(self.key.clone()),
663                    Publication::Rules => {}
664                }
665                let template = walk.root.row_template(&self.key.row.identity);
666                materialize_row(&self.key, template, walk.root, walk.base);
667                Step::Call(Frame::Members(Box::new(MembersFrame::new(
668                    template,
669                    self.key.clone(),
670                    matches!(self.publication, Publication::Rules),
671                ))))
672            }
673            Some(output) => {
674                let (data, rules) = output.into_members();
675                match self.publication {
676                    Publication::Table => {
677                        walk.table.rows[self.index] = Some(RowResult {
678                            repository: self.key.row.identity.repository.clone(),
679                            spec: self.key.row.identity.spec.clone(),
680                            effective: self.key.row.identity.effective.to_string(),
681                            data,
682                            rules,
683                        });
684                        Step::Return(Output::Row(self.reference(self.index)))
685                    }
686                    Publication::Spec => {
687                        let popped = walk.ancestors.pop();
688                        assert!(
689                            popped.as_ref() == Some(&self.key),
690                            "BUG: spec result of '{}' ended on another instance",
691                            self.key
692                        );
693                        let path = self.key.segments().unwrap_or_else(|| {
694                            panic!("BUG: planned instance '{}' has no hops", self.key)
695                        });
696                        Step::Return(Output::Spec(Box::new(SpecResult {
697                            repository: self.key.row.identity.repository.clone(),
698                            spec: self.key.row.identity.spec.clone(),
699                            effective: self.key.row.identity.effective.to_string(),
700                            instance: self.key.to_string(),
701                            path: path.iter().map(crate::api::PathSegment::from).collect(),
702                            data,
703                            rules,
704                        })))
705                    }
706                    Publication::Rules => Step::Return(Output::Members((data, rules))),
707                }
708            }
709        }
710    }
711}
712
713/// An entry whose value is being filled, with the key it is inserted under once filled,
714/// or the `uses` slot whose rules are being filled.
715enum Awaiting {
716    Data(String, SpecRuleResult),
717    Rule(String, SpecRuleResult),
718    Import(String),
719}
720
721/// Data then rules of instance `row` over its template `plan`, then the rules of every
722/// `uses` instance under it, keyed by their alias hops (`sub.total`). Missing data is
723/// reported under the instance's path.
724struct MembersFrame<'a> {
725    plan: &'a ExecutionPlan,
726    row: InstanceKey,
727    data_keys: std::vec::IntoIter<(&'a DataPath, &'a DataDefinition)>,
728    rule_paths: std::vec::IntoIter<&'a RulePath>,
729    imports: std::vec::IntoIter<&'a DataPath>,
730    data: IndexMap<String, SpecRuleResult>,
731    rules: IndexMap<String, SpecRuleResult>,
732    awaiting: Option<Awaiting>,
733}
734
735impl<'a> MembersFrame<'a> {
736    fn new(plan: &'a ExecutionPlan, row: InstanceKey, rules_only: bool) -> Self {
737        let data_keys: Vec<(&'a DataPath, &'a DataDefinition)> = if rules_only {
738            Vec::new()
739        } else {
740            plan.input_slots().collect()
741        };
742        let imports: Vec<&'a DataPath> = plan
743            .data
744            .iter()
745            .filter(|(_, definition)| matches!(definition, DataDefinition::Import { .. }))
746            .map(|(path, _)| path)
747            .collect();
748        Self {
749            plan,
750            row,
751            data_keys: data_keys.into_iter(),
752            rule_paths: plan.rules.keys().collect::<Vec<_>>().into_iter(),
753            imports: imports.into_iter(),
754            data: IndexMap::new(),
755            rules: IndexMap::new(),
756            awaiting: None,
757        }
758    }
759
760    fn resume(&mut self, walk: &mut Walk<'a, '_>, input: Option<Output>) -> Step<'a> {
761        match (self.awaiting.take(), input) {
762            (None, None) => {}
763            (Some(Awaiting::Data(key, mut entry)), Some(output)) => {
764                entry.result = Some(output.into_value());
765                self.data.insert(key, entry);
766            }
767            (Some(Awaiting::Rule(key, mut entry)), Some(output)) => {
768                entry.result = Some(output.into_value());
769                self.rules.insert(key, entry);
770            }
771            (Some(Awaiting::Import(alias)), Some(output)) => {
772                let (data, rules) = output.into_members();
773                assert!(
774                    data.is_empty(),
775                    "BUG: rules of `uses {alias}` were filled with data"
776                );
777                for (key, entry) in rules {
778                    self.rules.insert(format!("{alias}.{key}"), entry);
779                }
780            }
781            _ => panic!("BUG: members frame resumed with an unexpected child output"),
782        }
783        while let Some((path, definition)) = self.data_keys.next() {
784            if let Some(step) = self.data_item(walk, path, definition) {
785                return step;
786            }
787        }
788        while let Some(path) = self.rule_paths.next() {
789            if let Some(step) = self.rule_item(walk, path) {
790                return step;
791            }
792        }
793        for slot in self.imports.by_ref() {
794            let caches = std::rc::Rc::clone(&walk.base.caches);
795            let Some(nested) =
796                crate::evaluation::read_import_key(self.plan, Some(&self.row), slot, &caches)
797            else {
798                // A `-> effective` body this request never selected here: nothing read.
799                continue;
800            };
801            self.awaiting = Some(Awaiting::Import(slot.input_key()));
802            return Step::Call(Frame::Instance(InstanceFrame::new(
803                nested,
804                Publication::Rules,
805            )));
806        }
807        Step::Return(Output::Members((
808            std::mem::take(&mut self.data),
809            std::mem::take(&mut self.rules),
810        )))
811    }
812
813    fn data_item(
814        &mut self,
815        walk: &mut Walk<'a, '_>,
816        path: &'a DataPath,
817        definition: &'a DataDefinition,
818    ) -> Option<Step<'a>> {
819        let plan = self.plan;
820        definition.schema_type()?;
821        let key = path.input_key();
822        let slot = match walk.in_row(&self.row, |ctx| ctx.data_slot(plan, path).cloned()) {
823            Some(slot) => slot,
824            None => match plan.reference_ends.get(path) {
825                Some(ReferenceEnd::Rule(rule)) => walk.row_rule(&self.row, plan, rule),
826                Some(ReferenceEnd::Promptable(_)) | None => return None,
827            },
828        };
829        // Unbound data is not a member value: a field left unset, or one wired to data
830        // its owner leaves unset (`-> with x: base`, `base` unbound).
831        if matches!(
832            slot,
833            OperationResult::Veto(VetoType::MissingData { .. } | VetoType::MissingRowData { .. })
834        ) {
835            return None;
836        }
837        let display_type =
838            crate::evaluation::EvaluationContext::data_display_type(plan, path, &slot);
839        let mut entry = spec_entry(
840            &slot,
841            key.clone(),
842            RulePath {
843                segments: path.segments.clone(),
844                rule: path.data.clone(),
845            },
846            definition.source().clone(),
847            display_type.as_ref(),
848            &plan.family_units,
849            Vec::new(),
850        );
851        let OperationResult::Value(bound) = slot else {
852            self.data.insert(key, entry);
853            return None;
854        };
855        let Some(value) = entry.result.take() else {
856            self.data.insert(key, entry);
857            return None;
858        };
859        self.awaiting = Some(Awaiting::Data(key, entry));
860        Some(Step::Call(Frame::fill(bound.value, value)))
861    }
862
863    fn rule_item(&mut self, walk: &mut Walk<'a, '_>, path: &'a RulePath) -> Option<Step<'a>> {
864        let plan = self.plan;
865        let exec = plan
866            .rules
867            .get(path)
868            .expect("BUG: rule path missing from plan");
869        let local = walk.row_rule(&self.row, plan, path);
870        let missing_data = if local.is_missing_data() {
871            walk.base.settled_missing_data_for_instance(
872                walk.root,
873                plan,
874                exec.normal_form,
875                &self.row,
876            )
877        } else {
878            Vec::new()
879        };
880        let operation = row_result(local, &self.row, plan, &walk.base.caches);
881        let key = path.input_key();
882        let mut entry = spec_entry(
883            &operation,
884            key.clone(),
885            path.clone(),
886            exec.source.clone(),
887            exec.rule_type.as_ref(),
888            &plan.family_units,
889            missing_data,
890        );
891        match operation {
892            OperationResult::Value(bound) => match entry.result.take() {
893                Some(value) => {
894                    self.awaiting = Some(Awaiting::Rule(key, entry));
895                    Some(Step::Call(Frame::fill(bound.value, value)))
896                }
897                None => {
898                    self.rules.insert(key, entry);
899                    None
900                }
901            },
902            OperationResult::Veto(_) => {
903                self.rules.insert(key, entry);
904                None
905            }
906        }
907    }
908}
909
910type FilledMembers = (
911    IndexMap<String, SpecRuleResult>,
912    IndexMap<String, SpecRuleResult>,
913);
914
915fn spec_entry(
916    operation: &OperationResult,
917    name: String,
918    path: RulePath,
919    source: Source,
920    display_type: &LemmaType,
921    family_units: &FamilyUnitCatalog,
922    missing_data: Vec<String>,
923) -> SpecRuleResult {
924    let built = RuleResult::from_operation_result(
925        EvaluatedRule {
926            name,
927            path,
928            source_location: source,
929            rule_type: Arc::new(display_type.clone()),
930        },
931        operation,
932        display_type,
933        family_units,
934        None,
935        missing_data,
936    );
937    SpecRuleResult {
938        vetoed: built.vetoed,
939        veto_reason: built.veto_reason.clone(),
940        rule_type: built.rule_type.clone(),
941        result: built.result.clone(),
942    }
943}
944
945#[cfg(test)]
946mod tests {
947    use super::*;
948    use crate::literals::DateGranularity;
949    use crate::parsing::ast::Span;
950    use crate::planning::semantics::{
951        primitive_number_arc, BaseMeasureVector, DataPath, LemmaType, LiteralValue, MeasureUnit,
952        MeasureUnits, RatioUnit, RatioUnits, RulePath, TypeExtends, TypeSpecification, ValueKind,
953    };
954    use crate::planning::unit_family::FamilyUnitCatalog;
955    use crate::planning::unit_index::{UnitIndex, UnitOwner};
956    use rust_decimal::Decimal;
957    use std::str::FromStr;
958    use std::sync::Arc;
959
960    fn dec(s: &str) -> Decimal {
961        Decimal::from_str(s).expect("BUG: test decimal literal")
962    }
963
964    fn empty_family_catalog() -> FamilyUnitCatalog {
965        FamilyUnitCatalog::default()
966    }
967
968    fn family_catalog_for_index(index: &UnitIndex) -> FamilyUnitCatalog {
969        FamilyUnitCatalog::build(index)
970    }
971
972    fn family_catalog_for_money(money: &LemmaType) -> FamilyUnitCatalog {
973        family_catalog_for_index(&unit_index_for_money(money))
974    }
975
976    fn family_catalog_for_ratio(ratio_type: &LemmaType) -> FamilyUnitCatalog {
977        family_catalog_for_index(&unit_index_for_ratio(ratio_type))
978    }
979
980    fn unit_index_for_money(money: &LemmaType) -> UnitIndex {
981        let mut index = UnitIndex::new();
982        let arc = Arc::new(money.clone());
983        for unit_name in money.measure_unit_names().into_iter().flatten() {
984            index.insert_owner(
985                unit_name.to_string(),
986                UnitOwner::Named {
987                    import_path: Vec::new(),
988                    type_name: "money".into(),
989                    lemma_type: Arc::clone(&arc),
990                },
991            );
992        }
993        index
994    }
995
996    fn unit_index_for_ratio(ratio_type: &LemmaType) -> UnitIndex {
997        let mut index = UnitIndex::new();
998        let arc = Arc::new(ratio_type.clone());
999        let type_name = ratio_type.name();
1000        for unit_name in ratio_type.ratio_unit_names().into_iter().flatten() {
1001            index.insert_owner(
1002                unit_name.to_string(),
1003                UnitOwner::Named {
1004                    import_path: Vec::new(),
1005                    type_name: type_name.clone(),
1006                    lemma_type: Arc::clone(&arc),
1007                },
1008            );
1009        }
1010        index
1011    }
1012
1013    fn dummy_source() -> Source {
1014        Source::new(
1015            crate::parsing::source::SourceType::Volatile,
1016            Span {
1017                start: 0,
1018                end: 0,
1019                line: 1,
1020                col: 1,
1021            },
1022        )
1023    }
1024
1025    fn dummy_evaluated_rule(name: &str, rule_type: &LemmaType) -> EvaluatedRule {
1026        EvaluatedRule {
1027            name: name.to_string(),
1028            path: RulePath::new(vec![], name.to_string()),
1029            source_location: dummy_source(),
1030            rule_type: Arc::new(rule_type.clone()),
1031        }
1032    }
1033
1034    #[test]
1035    fn test_response_serialization() {
1036        let mut results = IndexMap::new();
1037        results.insert(
1038            "test_rule".to_string(),
1039            RuleResult::from_operation_result(
1040                dummy_evaluated_rule("test_rule", primitive_number_arc().as_ref()),
1041                &OperationResult::from_literal(LiteralValue::number_from_decimal(Decimal::from(
1042                    42,
1043                ))),
1044                primitive_number_arc().as_ref(),
1045                &empty_family_catalog(),
1046                None,
1047                Vec::new(),
1048            ),
1049        );
1050        let response = Response {
1051            spec_name: "test_spec".to_string(),
1052            effective: "2026-01-01".to_string(),
1053            spec_effective_from: None,
1054            spec_effective_to: None,
1055            results,
1056            rows: Vec::new(),
1057        };
1058
1059        let json = serde_json::to_string(&crate::api::Response::from(&response)).unwrap();
1060        assert!(json.contains("test_spec"));
1061        assert!(json.contains("test_rule"));
1062        assert!(json.contains("\"number\":\"42\""));
1063        assert!(!json.contains("lemma_type"));
1064    }
1065
1066    #[test]
1067    fn response_number_json_never_uses_fraction_notation() {
1068        use crate::computation::rational::decimal_to_rational;
1069
1070        let rational = decimal_to_rational(Decimal::new(1, 1) / Decimal::new(3, 1)).unwrap();
1071        let decimal_string = rational.try_to_decimal().unwrap().to_string();
1072        let mut results = IndexMap::new();
1073        results.insert(
1074            "third".to_string(),
1075            RuleResult::from_operation_result(
1076                dummy_evaluated_rule("third", primitive_number_arc().as_ref()),
1077                &OperationResult::from_literal(LiteralValue::number_from_decimal(
1078                    rational.try_to_decimal().unwrap(),
1079                )),
1080                primitive_number_arc().as_ref(),
1081                &empty_family_catalog(),
1082                None,
1083                Vec::new(),
1084            ),
1085        );
1086        // Override committed decimal number field to match serialization path under test
1087        if let Some(rule) = results.get_mut("third") {
1088            let decimal = rational.try_to_decimal().unwrap();
1089            rule.result = Some(crate::result_value::RuleResultValue {
1090                result: Some(decimal_string.clone()),
1091                number: Some(decimal),
1092                ..Default::default()
1093            });
1094        }
1095
1096        let response = Response {
1097            spec_name: "test".to_string(),
1098            effective: "test".to_string(),
1099            spec_effective_from: None,
1100            spec_effective_to: None,
1101            results,
1102            rows: Vec::new(),
1103        };
1104
1105        let json: serde_json::Value = serde_json::from_str(
1106            &serde_json::to_string(&crate::api::Response::from(&response)).unwrap(),
1107        )
1108        .unwrap();
1109        let number = json["results"]["third"]["number"]
1110            .as_str()
1111            .expect("number must be a JSON string");
1112        assert!(
1113            !number.contains('/'),
1114            "API decimal string must not use fraction notation, got {number}"
1115        );
1116    }
1117
1118    #[test]
1119    fn test_rule_result_veto() {
1120        let missing = RuleResult::from_operation_result(
1121            dummy_evaluated_rule("rule3", &LemmaType::veto_type()),
1122            &OperationResult::Veto(VetoType::missing_data(
1123                DataPath::new(vec![], "data1".to_string()),
1124                None,
1125            )),
1126            &LemmaType::veto_type(),
1127            &empty_family_catalog(),
1128            None,
1129            vec!["data1".to_string()],
1130        );
1131        assert!(missing.vetoed);
1132        assert!(missing.veto_reason.as_ref().unwrap().contains("data1"));
1133
1134        let veto = RuleResult::from_operation_result(
1135            dummy_evaluated_rule("rule4", &LemmaType::veto_type()),
1136            &OperationResult::Veto(VetoType::UserDefined {
1137                message: Some("Vetoed".to_string()),
1138            }),
1139            &LemmaType::veto_type(),
1140            &empty_family_catalog(),
1141            None,
1142            Vec::new(),
1143        );
1144        assert_eq!(veto.veto_reason.as_deref(), Some("Vetoed"));
1145    }
1146
1147    /// Attach hole: MissingData + empty missing_data is a BUG, not a silent stall.
1148    #[test]
1149    #[should_panic(expected = "BUG: MissingData")]
1150    fn missing_data_veto_must_not_attach_empty_missing_data_list() {
1151        RuleResult::from_operation_result(
1152            dummy_evaluated_rule("rule3", &LemmaType::veto_type()),
1153            &OperationResult::Veto(VetoType::missing_data(
1154                DataPath::new(vec![], "data1".to_string()),
1155                None,
1156            )),
1157            &LemmaType::veto_type(),
1158            &empty_family_catalog(),
1159            None,
1160            Vec::new(),
1161        );
1162    }
1163
1164    #[test]
1165    #[should_panic(expected = "BUG: MissingData")]
1166    fn missing_data_veto_must_include_veto_path_in_list() {
1167        RuleResult::from_operation_result(
1168            dummy_evaluated_rule("rule3", &LemmaType::veto_type()),
1169            &OperationResult::Veto(VetoType::missing_data(
1170                DataPath::new(vec![], "data1".to_string()),
1171                None,
1172            )),
1173            &LemmaType::veto_type(),
1174            &empty_family_catalog(),
1175            None,
1176            vec!["other".to_string()],
1177        );
1178    }
1179
1180    #[test]
1181    #[should_panic(expected = "BUG: missing_data must be empty")]
1182    fn non_missing_data_result_must_not_attach_leftover_missing_data() {
1183        RuleResult::from_operation_result(
1184            dummy_evaluated_rule("rule4", &LemmaType::veto_type()),
1185            &OperationResult::Veto(VetoType::UserDefined {
1186                message: Some("Vetoed".to_string()),
1187            }),
1188            &LemmaType::veto_type(),
1189            &empty_family_catalog(),
1190            None,
1191            vec!["leftover".to_string()],
1192        );
1193    }
1194
1195    #[test]
1196    fn rule_result_value_out_of_memory_is_not_decimal_limit_veto() {
1197        let result = vetoed_rule_result_for_rule_result_value_failure(
1198            dummy_evaluated_rule("rule", primitive_number_arc().as_ref()),
1199            primitive_number_arc().as_ref(),
1200            None,
1201            RuleResultValueFailure::OutOfMemory,
1202            Vec::new(),
1203        );
1204        assert_eq!(
1205            result.veto_reason.as_deref(),
1206            Some("The calculation ran out of memory.")
1207        );
1208        assert_ne!(
1209            result.veto_reason.as_deref(),
1210            Some("The calculated result exceeds the decimal value limit.")
1211        );
1212    }
1213
1214    #[test]
1215    fn rule_result_value_decimal_limit_uses_commit_message() {
1216        let result = vetoed_rule_result_for_rule_result_value_failure(
1217            dummy_evaluated_rule("rule", primitive_number_arc().as_ref()),
1218            primitive_number_arc().as_ref(),
1219            None,
1220            RuleResultValueFailure::DecimalLimit,
1221            Vec::new(),
1222        );
1223        assert_eq!(
1224            result.veto_reason.as_deref(),
1225            Some("The calculated result exceeds the decimal value limit.")
1226        );
1227    }
1228
1229    fn test_money_type() -> LemmaType {
1230        LemmaType::new(
1231            "money".to_string(),
1232            TypeSpecification::Measure {
1233                minimum: None,
1234                maximum: None,
1235                units: MeasureUnits::from(vec![
1236                    MeasureUnit {
1237                        name: "eur".to_string(),
1238                        scale: crate::literals::UnitScale::Literal(
1239                            crate::computation::rational::rational_one(),
1240                        ),
1241                        derived_measure_factors: Vec::new(),
1242                        decomposition: BaseMeasureVector::new(),
1243                        minimum: None,
1244                        maximum: None,
1245                        suggestion_magnitude: None,
1246                    },
1247                    MeasureUnit {
1248                        name: "usd".to_string(),
1249                        scale: crate::literals::UnitScale::Literal(
1250                            crate::computation::rational::decimal_to_rational(Decimal::new(91, 2))
1251                                .expect("factor"),
1252                        ),
1253                        derived_measure_factors: Vec::new(),
1254                        decomposition: BaseMeasureVector::new(),
1255                        minimum: None,
1256                        maximum: None,
1257                        suggestion_magnitude: None,
1258                    },
1259                ]),
1260                traits: Vec::new(),
1261                decomposition: Some(BaseMeasureVector::new()),
1262                unit: None,
1263                help: String::new(),
1264            },
1265            TypeExtends::Primitive,
1266        )
1267    }
1268
1269    #[test]
1270    fn measure_rule_result_value_uses_rule_type_when_expression_index_empty() {
1271        let money = test_money_type();
1272        let family_units = family_catalog_for_money(&money);
1273        let ten_usd = LiteralValue {
1274            value: ValueKind::Measure(
1275                crate::computation::rational::checked_mul(
1276                    &crate::computation::rational::decimal_to_rational(Decimal::from(10))
1277                        .expect("ten"),
1278                    &crate::computation::rational::decimal_to_rational(Decimal::new(91, 2))
1279                        .expect("usd factor"),
1280                )
1281                .expect("canonical usd"),
1282            ),
1283        };
1284        let result = RuleResult::from_operation_result(
1285            dummy_evaluated_rule("total", &money),
1286            &OperationResult::from_literal(ten_usd),
1287            &money,
1288            &family_units,
1289            None,
1290            Vec::new(),
1291        );
1292        let measure = result
1293            .result
1294            .as_ref()
1295            .expect("value")
1296            .measure
1297            .clone()
1298            .expect("measure map");
1299        assert_eq!(measure.get("usd"), Some(&dec("10.00")));
1300        assert!(measure.contains_key("eur"));
1301    }
1302
1303    #[test]
1304    fn test_measure_rule_result_value_multi_unit() {
1305        let money = test_money_type();
1306        let family_units = family_catalog_for_money(&money);
1307        let ten_eur = LiteralValue {
1308            value: ValueKind::Measure(
1309                crate::computation::rational::decimal_to_rational(Decimal::from(10)).expect("ten"),
1310            ),
1311        };
1312        let result = RuleResult::from_operation_result(
1313            dummy_evaluated_rule("total", &money),
1314            &OperationResult::from_literal(ten_eur),
1315            &money,
1316            &family_units,
1317            None,
1318            Vec::new(),
1319        );
1320        let measure = result
1321            .result
1322            .as_ref()
1323            .expect("value")
1324            .measure
1325            .clone()
1326            .expect("measure map");
1327        assert_eq!(measure.get("eur"), Some(&dec("10.00")));
1328        assert_eq!(
1329            measure.get("usd"),
1330            Some(&dec("10.98901098901098901098901098"))
1331        );
1332    }
1333
1334    #[test]
1335    fn measure_rule_result_value_keeps_unit_conversion_unrounded() {
1336        let money = LemmaType::new(
1337            "money".to_string(),
1338            TypeSpecification::Measure {
1339                minimum: None,
1340                maximum: None,
1341                units: MeasureUnits::from(vec![
1342                    MeasureUnit {
1343                        name: "eur".to_string(),
1344                        scale: crate::literals::UnitScale::Literal(
1345                            crate::computation::rational::rational_one(),
1346                        ),
1347                        derived_measure_factors: Vec::new(),
1348                        decomposition: BaseMeasureVector::new(),
1349                        minimum: None,
1350                        maximum: None,
1351                        suggestion_magnitude: None,
1352                    },
1353                    MeasureUnit {
1354                        name: "usd".to_string(),
1355                        scale: crate::literals::UnitScale::Literal(
1356                            crate::computation::rational::decimal_to_rational(Decimal::new(84, 2))
1357                                .expect("usd factor"),
1358                        ),
1359                        derived_measure_factors: Vec::new(),
1360                        decomposition: BaseMeasureVector::new(),
1361                        minimum: None,
1362                        maximum: None,
1363                        suggestion_magnitude: None,
1364                    },
1365                ]),
1366                traits: Vec::new(),
1367                decomposition: Some(BaseMeasureVector::new()),
1368                unit: None,
1369                help: String::new(),
1370            },
1371            TypeExtends::Primitive,
1372        );
1373        let family_units = family_catalog_for_money(&money);
1374        let three_twelve_eur = LiteralValue {
1375            value: ValueKind::Measure(
1376                crate::computation::rational::decimal_to_rational(Decimal::new(312, 2))
1377                    .expect("3.12 eur canonical"),
1378            ),
1379        };
1380        let result = RuleResult::from_operation_result(
1381            dummy_evaluated_rule("delivery_cost", &money),
1382            &OperationResult::from_literal(three_twelve_eur),
1383            &money,
1384            &family_units,
1385            None,
1386            Vec::new(),
1387        );
1388        let measure = result
1389            .result
1390            .as_ref()
1391            .expect("value")
1392            .measure
1393            .clone()
1394            .expect("measure map");
1395        assert_eq!(measure.get("eur"), Some(&dec("3.12")));
1396        assert_eq!(
1397            measure.get("usd"),
1398            Some(&dec("3.714285714285714285714285714"))
1399        );
1400    }
1401
1402    #[test]
1403    fn test_ratio_rule_result_value_multi_unit() {
1404        let ratio_type = LemmaType::new(
1405            "rate".to_string(),
1406            TypeSpecification::Ratio {
1407                minimum: None,
1408                maximum: None,
1409                units: RatioUnits::from(vec![
1410                    RatioUnit {
1411                        name: "percent".to_string(),
1412                        value: crate::computation::rational::decimal_to_rational(Decimal::from(
1413                            100,
1414                        ))
1415                        .expect("percent"),
1416                        minimum: None,
1417                        maximum: None,
1418                        suggestion_magnitude: None,
1419                    },
1420                    RatioUnit {
1421                        name: "basis_points".to_string(),
1422                        value: crate::computation::rational::decimal_to_rational(Decimal::from(
1423                            10_000,
1424                        ))
1425                        .expect("bp"),
1426                        minimum: None,
1427                        maximum: None,
1428                        suggestion_magnitude: None,
1429                    },
1430                ]),
1431                unit: None,
1432                help: String::new(),
1433            },
1434            TypeExtends::Primitive,
1435        );
1436        let family_units = family_catalog_for_ratio(&ratio_type);
1437        let half = crate::computation::rational::rational_new(1, 2);
1438        let lit = LiteralValue {
1439            value: ValueKind::Ratio(half),
1440        };
1441        let result = RuleResult::from_operation_result(
1442            dummy_evaluated_rule("rate_out", &ratio_type),
1443            &OperationResult::from_literal(lit),
1444            &ratio_type,
1445            &family_units,
1446            None,
1447            Vec::new(),
1448        );
1449        let ratio = result
1450            .result
1451            .as_ref()
1452            .expect("value")
1453            .ratio
1454            .clone()
1455            .expect("ratio map");
1456        assert_eq!(ratio.get("percent"), Some(&dec("50")));
1457        assert_eq!(ratio.get("basis_points"), Some(&dec("5000")));
1458    }
1459
1460    #[test]
1461    fn test_measure_rule_result_value_cross_spec_import() {
1462        use crate::parsing::source::SourceType;
1463        use crate::Engine;
1464
1465        let mut engine = Engine::new();
1466        engine
1467            .load([(
1468                SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("t.lemma"))),
1469                r#"
1470spec consumer 2025-01-01
1471uses d: dep 2025-10-01
1472rule out: d.doubled
1473
1474spec dep 2025-01-01
1475uses c: child 2025-06-01
1476data money: c.money
1477data p: 5 usd
1478rule doubled: p * 2
1479
1480spec child 2025-01-01
1481data money: measure
1482 -> unit eur: 1.00
1483
1484spec child 2025-06-01
1485data money: measure
1486 -> unit eur: 1.00
1487 -> unit usd: 0.91
1488"#
1489                .to_string(),
1490            )])
1491            .expect("load");
1492        let effective = crate::literals::DateTimeValue {
1493            year: 2025,
1494            month: 3,
1495            day: 1,
1496            hour: 0,
1497            minute: 0,
1498            second: 0,
1499            microsecond: 0,
1500            timezone: None,
1501
1502            granularity: DateGranularity::Full,
1503        };
1504        let response = engine
1505            .evaluate(
1506                None,
1507                "consumer",
1508                Some(&effective),
1509                IndexMap::new(),
1510                None,
1511                false,
1512            )
1513            .expect("evaluate");
1514        let out = response.results.get("out").expect("out rule");
1515        assert!(!out.vetoed);
1516        let measure = out
1517            .result
1518            .as_ref()
1519            .expect("value")
1520            .measure
1521            .as_ref()
1522            .expect("measure map");
1523        assert!(measure.contains_key("usd"));
1524        assert!(measure.contains_key("eur"));
1525    }
1526
1527    #[test]
1528    fn to_literal_roundtrips_number() {
1529        let literal = LiteralValue::number_from_decimal(Decimal::from(42));
1530        let rule_result = RuleResult::from_operation_result(
1531            dummy_evaluated_rule("answer", primitive_number_arc().as_ref()),
1532            &OperationResult::from_literal(literal.clone()),
1533            primitive_number_arc().as_ref(),
1534            &empty_family_catalog(),
1535            None,
1536            Vec::new(),
1537        );
1538        assert_eq!(rule_result.to_literal(), literal);
1539    }
1540
1541    #[test]
1542    fn to_literal_roundtrips_measure() {
1543        let money = test_money_type();
1544        let family_units = family_catalog_for_money(&money);
1545        let literal = LiteralValue::measure(crate::computation::rational::rational_new(60, 1));
1546        let rule_result = RuleResult::from_operation_result(
1547            dummy_evaluated_rule("pay", &money),
1548            &OperationResult::from_literal(literal.clone()),
1549            &money,
1550            &family_units,
1551            None,
1552            Vec::new(),
1553        );
1554        assert_eq!(rule_result.to_literal(), literal);
1555    }
1556}