Skip to main content

neco_expr/
product.rs

1use alloc::vec::Vec;
2
3use neco_bigint::Sign;
4
5use crate::error::{map_eval_failure, map_resolve_failure, map_storage_failure};
6use crate::evaluate::{evaluate_reachable, EvaluationRunError};
7use crate::float::FloatError;
8use crate::storage::{reserve_entries, StorageResource};
9use crate::value::{decide_equality, decide_sign, decide_zero};
10use crate::{
11    AbsoluteBits, AtomStore, CertifiedF64, ConsumerId, EvaluationCache, ExactValue, ExprGraph,
12    ExprId, FailureLocation, FailureOperation, IsolationCache, NecoFailure, ResolveError,
13    UnsupportedFailurePayload,
14};
15
16pub const IMPLEMENTATION_REVISION: &str = "64f179e915c48a32c9652c1be0a91748045dfd4d";
17pub const PUBLIC_API_IDENTITY: &str = "neco-expr-exact-computation-v1";
18
19#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
20pub enum ExactDecisionKind {
21    Zero,
22    Equality,
23    Sign,
24    Degeneracy,
25}
26
27#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
28pub enum ExactDecisionValue {
29    Zero,
30    NonZero,
31    Equal,
32    NotEqual,
33    Negative,
34    Positive,
35    Degenerate,
36    NonDegenerate,
37}
38
39#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
40pub enum ExactDecisionRequest {
41    Zero(ExprId),
42    Equality(ExprId, ExprId),
43    Sign(ExprId),
44    Degeneracy(ExprId),
45}
46
47impl ExactDecisionRequest {
48    pub const fn kind(self) -> ExactDecisionKind {
49        match self {
50            Self::Zero(_) => ExactDecisionKind::Zero,
51            Self::Equality(_, _) => ExactDecisionKind::Equality,
52            Self::Sign(_) => ExactDecisionKind::Sign,
53            Self::Degeneracy(_) => ExactDecisionKind::Degeneracy,
54        }
55    }
56}
57
58#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
59pub enum NumericalOwner {
60    ModalFieldProjection,
61    Wavesim,
62}
63
64#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
65pub enum ExactInput {
66    GeometryIdentity,
67    GeometryDimension,
68    SourceNode,
69    ReceiverNode,
70    FrequencyBandEndpoints,
71    ModeLimit,
72    SamplingCount,
73    SamplingRate,
74    ModeIndexOrdering,
75    ModeRowCardinality,
76    ModeRowWidth,
77    DampingDefinition,
78    SystemIdentity,
79    SubsystemIdentity,
80    StateShape,
81    StateExtents,
82    InitialStateIndex,
83    TimeDomainEndpoints,
84    CalibrationInterval,
85    HeldOutInterval,
86    ConditionIdentity,
87    CouplingTopology,
88    CouplingSelector,
89    ComparatorDirection,
90    AcceptanceDomainBound,
91}
92
93#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
94pub enum ExactDecisionAssignment {
95    ProvenanceNonempty,
96    SourceReceiverIdentityValidity,
97    ModeSetNonempty,
98    ModeIdentityEqualityOrdering,
99    ModeShapeCardinalityAxisEquality,
100    SamplingDomainValidity,
101    ZeroDivisionGuard,
102    Rt60RoundTripEquality,
103    MfpBranchIdentity,
104    StateShapeEquality,
105    CalibrationHeldOutDisjointness,
106    ConditionSetCompleteness,
107    SubsystemIdentityEquality,
108    FiniteNonNegative,
109    EnergyBalance,
110    SingularityZeroDenominator,
111    PredictionIndependenceEquality,
112    R2LowerBound,
113    AssemblyFailureSetEmptiness,
114}
115
116#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
117pub enum NumericalOperation {
118    ModeFrequencyEvaluation,
119    ModeShapeEvaluation,
120    DampingRateCalculation,
121    ModeContributionCalculation,
122    ModeSum,
123    ReceivedSeriesSamplingAccumulation,
124    TranscendentalEvaluationFem,
125    ModalRhsEvaluation,
126    InitialStateNumericalConstruction,
127    OdeIntegration,
128    EnergyObservation,
129    DddRegressionEstimation,
130    SeaRegressionEstimation,
131    HeldOutPredictionComparison,
132}
133
134#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
135pub enum ExactOperation {
136    NormalizeMonomial,
137    NormalizeFormSum,
138    NormalizeAlgebraic,
139    DecideZero,
140    DecideEquality,
141    DecideSign,
142    DecideDegeneracy,
143    ResolveCertifiedF64,
144}
145
146#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
147pub enum NumericalBudgetComponent {
148    ModeTruncation,
149    ModeShapeEvaluation,
150    DampingRt60Conversion,
151    ModeSumAccumulation,
152    ReceivedSeriesSamplingAccumulation,
153    SolverTolerance,
154    MaximumStepDiscretization,
155    OdeIntegration,
156    EnergyBalanceTolerance,
157    SmoothingRequirement,
158    DddRegressionEstimation,
159    SeaRegressionEstimation,
160    HeldOutComparatorTolerance,
161    R2AcceptanceMargin,
162}
163
164#[derive(Debug, Eq, PartialEq)]
165pub struct NumericalErrorBudget {
166    owner: NumericalOwner,
167    consumer_id: ConsumerId,
168    component: NumericalBudgetComponent,
169    requirement_or_bound: AbsoluteBits,
170}
171
172impl NumericalErrorBudget {
173    pub const fn new(
174        owner: NumericalOwner,
175        consumer_id: ConsumerId,
176        component: NumericalBudgetComponent,
177        requirement_or_bound: AbsoluteBits,
178    ) -> Self {
179        Self {
180            owner,
181            consumer_id,
182            component,
183            requirement_or_bound,
184        }
185    }
186
187    pub const fn owner(&self) -> NumericalOwner {
188        self.owner
189    }
190
191    pub const fn consumer_id(&self) -> ConsumerId {
192        self.consumer_id
193    }
194
195    pub const fn component(&self) -> NumericalBudgetComponent {
196        self.component
197    }
198
199    pub const fn requirement_or_bound(&self) -> AbsoluteBits {
200        self.requirement_or_bound
201    }
202}
203
204#[derive(Debug, Eq, PartialEq)]
205pub struct ExactExpressionRequirement {
206    consumer_id: ConsumerId,
207    expressions: Vec<ExprId>,
208    decision: ExactDecisionRequest,
209    precision: AbsoluteBits,
210}
211
212impl ExactExpressionRequirement {
213    pub fn new(
214        consumer_id: ConsumerId,
215        expressions: &[ExprId],
216        decision: ExactDecisionRequest,
217        precision: AbsoluteBits,
218    ) -> Result<Self, NecoFailure> {
219        let location =
220            FailureLocation::operation(FailureOperation::Allocate).with_consumer(consumer_id);
221        if expressions.is_empty() {
222            return Err(NecoFailure::MissingAssignment { location });
223        }
224        let (decision_operands, decision_operand_count) = decision_operands(decision);
225        if !decision_operands[..decision_operand_count]
226            .iter()
227            .all(|operand| expressions.contains(operand))
228        {
229            return Err(NecoFailure::MissingAssignment { location });
230        }
231        let mut owned = Vec::new();
232        reserve_entries(
233            &mut owned,
234            expressions.len(),
235            StorageResource::ProductEntries,
236        )
237        .map_err(|error| map_storage_failure(location, error))?;
238        for expression in expressions {
239            if owned.binary_search(expression).is_ok() {
240                continue;
241            }
242            let index = owned
243                .binary_search(expression)
244                .unwrap_or_else(|index| index);
245            owned.insert(index, *expression);
246        }
247        Ok(Self {
248            consumer_id,
249            expressions: owned,
250            decision,
251            precision,
252        })
253    }
254
255    pub const fn consumer_id(&self) -> ConsumerId {
256        self.consumer_id
257    }
258
259    pub fn expressions(&self) -> &[ExprId] {
260        &self.expressions
261    }
262
263    pub const fn decision(&self) -> ExactDecisionRequest {
264        self.decision
265    }
266
267    pub const fn precision(&self) -> AbsoluteBits {
268        self.precision
269    }
270}
271
272#[derive(Debug, Eq, PartialEq)]
273pub struct MfpCoreProduct {
274    graph: ExprGraph,
275    atoms: AtomStore,
276    requirements: Vec<ExactExpressionRequirement>,
277    numerical_error_budgets: Vec<NumericalErrorBudget>,
278}
279
280#[derive(Debug, Eq, PartialEq)]
281pub struct WavesimDddCoreProduct {
282    graph: ExprGraph,
283    atoms: AtomStore,
284    requirements: Vec<ExactExpressionRequirement>,
285    numerical_error_budgets: Vec<NumericalErrorBudget>,
286}
287
288impl MfpCoreProduct {
289    pub fn new(
290        graph: ExprGraph,
291        atoms: AtomStore,
292        requirements: Vec<ExactExpressionRequirement>,
293        numerical_error_budgets: Vec<NumericalErrorBudget>,
294    ) -> Result<Self, NecoFailure> {
295        validate_core(
296            NumericalOwner::ModalFieldProjection,
297            &graph,
298            &requirements,
299            &numerical_error_budgets,
300        )?;
301        Ok(Self {
302            graph,
303            atoms,
304            requirements,
305            numerical_error_budgets,
306        })
307    }
308
309    pub fn requirements(&self) -> &[ExactExpressionRequirement] {
310        &self.requirements
311    }
312
313    pub fn numerical_error_budgets(&self) -> &[NumericalErrorBudget] {
314        &self.numerical_error_budgets
315    }
316}
317
318impl WavesimDddCoreProduct {
319    pub fn new(
320        graph: ExprGraph,
321        atoms: AtomStore,
322        requirements: Vec<ExactExpressionRequirement>,
323        numerical_error_budgets: Vec<NumericalErrorBudget>,
324    ) -> Result<Self, NecoFailure> {
325        validate_core(
326            NumericalOwner::Wavesim,
327            &graph,
328            &requirements,
329            &numerical_error_budgets,
330        )?;
331        Ok(Self {
332            graph,
333            atoms,
334            requirements,
335            numerical_error_budgets,
336        })
337    }
338
339    pub fn requirements(&self) -> &[ExactExpressionRequirement] {
340        &self.requirements
341    }
342
343    pub fn numerical_error_budgets(&self) -> &[NumericalErrorBudget] {
344        &self.numerical_error_budgets
345    }
346}
347
348fn validate_core(
349    owner: NumericalOwner,
350    graph: &ExprGraph,
351    requirements: &[ExactExpressionRequirement],
352    budgets: &[NumericalErrorBudget],
353) -> Result<(), NecoFailure> {
354    for requirement in requirements {
355        for expression in requirement.expressions() {
356            if graph.get(*expression).is_none() {
357                return Err(NecoFailure::UnknownExpression {
358                    location: FailureLocation::operation(FailureOperation::Read)
359                        .with_consumer(requirement.consumer_id())
360                        .with_expr(*expression),
361                });
362            }
363        }
364    }
365    for budget in budgets {
366        if budget.owner() != owner
367            || !requirements
368                .iter()
369                .any(|requirement| requirement.consumer_id() == budget.consumer_id())
370        {
371            return Err(NecoFailure::MissingAssignment {
372                location: FailureLocation::operation(FailureOperation::Allocate)
373                    .with_consumer(budget.consumer_id()),
374            });
375        }
376    }
377    Ok(())
378}
379
380#[derive(Debug, Eq, PartialEq)]
381pub struct NecoObservedCapability {
382    source_identity: &'static str,
383    supported_operations: Vec<ExactOperation>,
384}
385
386impl NecoObservedCapability {
387    pub fn current(supported_operations: &[ExactOperation]) -> Result<Self, NecoFailure> {
388        Self::new(IMPLEMENTATION_REVISION, supported_operations)
389    }
390
391    pub fn new(
392        source_identity: &'static str,
393        supported_operations: &[ExactOperation],
394    ) -> Result<Self, NecoFailure> {
395        let location = FailureLocation::operation(FailureOperation::Read);
396        let mut supported = Vec::new();
397        reserve_entries(
398            &mut supported,
399            supported_operations.len(),
400            StorageResource::ProductEntries,
401        )
402        .map_err(|error| map_storage_failure(location, error))?;
403        supported.extend_from_slice(supported_operations);
404        supported.sort_unstable();
405        supported.dedup();
406        Ok(Self {
407            source_identity,
408            supported_operations: supported,
409        })
410    }
411
412    pub const fn source_identity(&self) -> &'static str {
413        self.source_identity
414    }
415
416    pub fn supported_operations(&self) -> &[ExactOperation] {
417        &self.supported_operations
418    }
419}
420
421#[derive(Debug, Eq, PartialEq)]
422pub struct NecoImplementationSource {
423    revision_identity: &'static str,
424    public_api_identity: &'static str,
425}
426
427impl NecoImplementationSource {
428    pub const fn new(revision_identity: &'static str, public_api_identity: &'static str) -> Self {
429        Self {
430            revision_identity,
431            public_api_identity,
432        }
433    }
434
435    pub const fn current() -> Self {
436        Self::new(IMPLEMENTATION_REVISION, PUBLIC_API_IDENTITY)
437    }
438
439    pub const fn revision_identity(&self) -> &'static str {
440        self.revision_identity
441    }
442
443    pub const fn public_api_identity(&self) -> &'static str {
444        self.public_api_identity
445    }
446}
447
448#[derive(Debug, Eq, PartialEq)]
449pub struct ExactAllocationInput {
450    mfp_core: MfpCoreProduct,
451    wavesim_ddd_core: WavesimDddCoreProduct,
452    observed_capability: NecoObservedCapability,
453    implementation_source: NecoImplementationSource,
454}
455
456impl ExactAllocationInput {
457    pub const fn new(
458        mfp_core: MfpCoreProduct,
459        wavesim_ddd_core: WavesimDddCoreProduct,
460        observed_capability: NecoObservedCapability,
461        implementation_source: NecoImplementationSource,
462    ) -> Self {
463        Self {
464            mfp_core,
465            wavesim_ddd_core,
466            observed_capability,
467            implementation_source,
468        }
469    }
470
471    pub fn mfp_core(&self) -> &MfpCoreProduct {
472        &self.mfp_core
473    }
474
475    pub fn wavesim_ddd_core(&self) -> &WavesimDddCoreProduct {
476        &self.wavesim_ddd_core
477    }
478
479    pub fn observed_capability(&self) -> &NecoObservedCapability {
480        &self.observed_capability
481    }
482
483    pub fn implementation_source(&self) -> &NecoImplementationSource {
484        &self.implementation_source
485    }
486}
487
488#[derive(Debug, Eq, PartialEq)]
489pub struct ExactNumericAllocation {
490    exact_inputs: Vec<ExactInput>,
491    exact_decisions: Vec<ExactDecisionAssignment>,
492    numerical_operations: Vec<NumericalOperation>,
493    descent_consumers: Vec<ConsumerId>,
494    numerical_error_budgets: Vec<NumericalErrorBudget>,
495}
496
497impl ExactNumericAllocation {
498    pub fn exact_inputs(&self) -> &[ExactInput] {
499        &self.exact_inputs
500    }
501
502    pub fn exact_decisions(&self) -> &[ExactDecisionAssignment] {
503        &self.exact_decisions
504    }
505
506    pub fn numerical_operations(&self) -> &[NumericalOperation] {
507        &self.numerical_operations
508    }
509
510    pub fn descent_consumers(&self) -> &[ConsumerId] {
511        &self.descent_consumers
512    }
513
514    pub fn numerical_error_budgets(&self) -> &[NumericalErrorBudget] {
515        &self.numerical_error_budgets
516    }
517}
518
519#[derive(Debug, Eq, PartialEq)]
520pub struct AllocatedExactNumericContext {
521    input: ExactAllocationInput,
522    allocation: ExactNumericAllocation,
523}
524
525impl AllocatedExactNumericContext {
526    pub fn allocation(&self) -> &ExactNumericAllocation {
527        &self.allocation
528    }
529}
530
531#[derive(Debug, Eq, PartialEq)]
532struct NormalFormEntry {
533    owner: NumericalOwner,
534    consumer: ConsumerId,
535    expr: ExprId,
536    value: ExactValue,
537}
538
539#[derive(Debug, Eq, PartialEq)]
540pub struct NormalizedExactNumericContext {
541    allocated: AllocatedExactNumericContext,
542    normal_forms: Vec<NormalFormEntry>,
543    evaluation_count: usize,
544}
545
546impl NormalizedExactNumericContext {
547    pub fn normal_form(&self, consumer: ConsumerId, expr: ExprId) -> Option<&ExactValue> {
548        self.normal_forms
549            .iter()
550            .find(|entry| entry.consumer == consumer && entry.expr == expr)
551            .map(|entry| &entry.value)
552    }
553
554    pub const fn evaluation_count(&self) -> usize {
555        self.evaluation_count
556    }
557}
558
559#[derive(Debug, Eq, PartialEq)]
560pub struct ExactDecisionWitness {
561    kind: ExactDecisionKind,
562    operands: Vec<ExprId>,
563    value: ExactDecisionValue,
564    normal_form_witness: ExactValue,
565}
566
567impl ExactDecisionWitness {
568    pub const fn kind(&self) -> ExactDecisionKind {
569        self.kind
570    }
571
572    pub fn operands(&self) -> &[ExprId] {
573        &self.operands
574    }
575
576    pub const fn value(&self) -> ExactDecisionValue {
577        self.value
578    }
579
580    pub fn normal_form_witness(&self) -> &ExactValue {
581        &self.normal_form_witness
582    }
583}
584
585#[derive(Debug, Eq, PartialEq)]
586struct DecisionEntry {
587    consumer: ConsumerId,
588    witness: ExactDecisionWitness,
589}
590
591#[derive(Debug, Eq, PartialEq)]
592pub struct DecidedExactNumericContext {
593    normalized: NormalizedExactNumericContext,
594    decisions: Vec<DecisionEntry>,
595}
596
597impl DecidedExactNumericContext {
598    pub fn decision(&self, consumer: ConsumerId) -> Option<&ExactDecisionWitness> {
599        self.decisions
600            .iter()
601            .find(|entry| entry.consumer == consumer)
602            .map(|entry| &entry.witness)
603    }
604}
605
606#[derive(Debug, Eq, PartialEq)]
607pub struct CertifiedF64Expression {
608    expr: ExprId,
609    certified: CertifiedF64,
610}
611
612impl CertifiedF64Expression {
613    pub const fn expr(&self) -> ExprId {
614        self.expr
615    }
616
617    pub fn certified(&self) -> &CertifiedF64 {
618        &self.certified
619    }
620}
621
622#[derive(Debug, Eq, PartialEq)]
623pub struct CertifiedF64Bundle {
624    consumer_id: ConsumerId,
625    values: Vec<CertifiedF64Expression>,
626}
627
628struct CachedResolution {
629    owner: NumericalOwner,
630    expr: ExprId,
631    bits: AbsoluteBits,
632    value: CertifiedF64,
633}
634
635impl CertifiedF64Bundle {
636    pub const fn consumer_id(&self) -> ConsumerId {
637        self.consumer_id
638    }
639
640    pub fn values(&self) -> &[CertifiedF64Expression] {
641        &self.values
642    }
643}
644
645#[derive(Debug, Eq, PartialEq)]
646pub struct ResolvedExactNumericContext {
647    decided: DecidedExactNumericContext,
648    certified_descents: Vec<CertifiedF64Bundle>,
649    shared_resolution_count: usize,
650}
651
652impl ResolvedExactNumericContext {
653    pub fn certified_descent(&self, consumer: ConsumerId) -> Option<&CertifiedF64Bundle> {
654        self.certified_descents
655            .iter()
656            .find(|bundle| bundle.consumer_id == consumer)
657    }
658
659    pub const fn shared_resolution_count(&self) -> usize {
660        self.shared_resolution_count
661    }
662}
663
664pub struct DirectInspection<'a> {
665    allocation: &'a ExactNumericAllocation,
666    requirements: Vec<&'a ExactExpressionRequirement>,
667    decisions: &'a [DecisionEntry],
668    certified_descents: &'a [CertifiedF64Bundle],
669    shared_resolution_count: usize,
670}
671
672impl DirectInspection<'_> {
673    pub fn allocation(&self) -> &ExactNumericAllocation {
674        self.allocation
675    }
676
677    pub fn requirements(&self) -> &[&ExactExpressionRequirement] {
678        &self.requirements
679    }
680
681    pub fn certified_descents(&self) -> &[CertifiedF64Bundle] {
682        self.certified_descents
683    }
684
685    pub const fn shared_resolution_count(&self) -> usize {
686        self.shared_resolution_count
687    }
688
689    pub fn decision(&self, consumer: ConsumerId) -> Option<&ExactDecisionWitness> {
690        self.decisions
691            .iter()
692            .find(|entry| entry.consumer == consumer)
693            .map(|entry| &entry.witness)
694    }
695}
696
697#[derive(Debug, Eq, PartialEq)]
698pub struct ExactComputationProduct {
699    resolved: ResolvedExactNumericContext,
700}
701
702impl ExactComputationProduct {
703    pub fn allocation(&self) -> &ExactNumericAllocation {
704        &self.resolved.decided.normalized.allocated.allocation
705    }
706
707    pub fn normal_form(&self, consumer: ConsumerId, expr: ExprId) -> Option<&ExactValue> {
708        self.resolved.decided.normalized.normal_form(consumer, expr)
709    }
710
711    pub fn decision(&self, consumer: ConsumerId) -> Option<&ExactDecisionWitness> {
712        self.resolved.decided.decision(consumer)
713    }
714
715    pub fn certified_descent(&self, consumer: ConsumerId) -> Option<&CertifiedF64Bundle> {
716        self.resolved.certified_descent(consumer)
717    }
718
719    pub fn direct_inspection(&self) -> Result<DirectInspection<'_>, NecoFailure> {
720        let mfp = &self.resolved.decided.normalized.allocated.input.mfp_core;
721        let wavesim = &self
722            .resolved
723            .decided
724            .normalized
725            .allocated
726            .input
727            .wavesim_ddd_core;
728        let total = mfp
729            .requirements
730            .len()
731            .checked_add(wavesim.requirements.len())
732            .ok_or_else(|| {
733                map_storage_failure(
734                    FailureLocation::operation(FailureOperation::Assemble),
735                    crate::StorageError::CapacityOverflow {
736                        resource: StorageResource::ProductEntries,
737                    },
738                )
739            })?;
740        let mut requirements = Vec::new();
741        reserve_entries(&mut requirements, total, StorageResource::ProductEntries).map_err(
742            |error| {
743                map_storage_failure(
744                    FailureLocation::operation(FailureOperation::Assemble),
745                    error,
746                )
747            },
748        )?;
749        requirements.extend(mfp.requirements.iter());
750        requirements.extend(wavesim.requirements.iter());
751        Ok(DirectInspection {
752            allocation: self.allocation(),
753            requirements,
754            decisions: &self.resolved.decided.decisions,
755            certified_descents: &self.resolved.certified_descents,
756            shared_resolution_count: self.resolved.shared_resolution_count,
757        })
758    }
759
760    pub const fn as_exact_computation(&self) -> &Self {
761        self
762    }
763}
764
765pub fn read_exact_numeric_inputs(
766    input: ExactAllocationInput,
767) -> Result<ExactAllocationInput, NecoFailure> {
768    if input.implementation_source.revision_identity != IMPLEMENTATION_REVISION
769        || input.implementation_source.public_api_identity != PUBLIC_API_IDENTITY
770        || input.observed_capability.source_identity != IMPLEMENTATION_REVISION
771    {
772        return Err(NecoFailure::UnsupportedRequiredOperation {
773            location: FailureLocation::operation(FailureOperation::Read),
774            payload: UnsupportedFailurePayload::SourceIdentity,
775        });
776    }
777    Ok(input)
778}
779
780pub fn allocate_exact_numeric(
781    mut input: ExactAllocationInput,
782) -> Result<AllocatedExactNumericContext, NecoFailure> {
783    let required_operations = [
784        ExactOperation::NormalizeMonomial,
785        ExactOperation::NormalizeFormSum,
786        ExactOperation::NormalizeAlgebraic,
787        ExactOperation::DecideZero,
788        ExactOperation::DecideEquality,
789        ExactOperation::DecideSign,
790        ExactOperation::DecideDegeneracy,
791        ExactOperation::ResolveCertifiedF64,
792    ];
793    for operation in required_operations {
794        if input
795            .observed_capability
796            .supported_operations
797            .binary_search(&operation)
798            .is_err()
799        {
800            return Err(NecoFailure::UnsupportedRequiredOperation {
801                location: FailureLocation::operation(FailureOperation::Allocate),
802                payload: UnsupportedFailurePayload::RequiredOperation(operation_name(operation)),
803            });
804        }
805    }
806    let mut consumers = Vec::new();
807    let mut budgets = Vec::new();
808    for requirement in input
809        .mfp_core
810        .requirements
811        .iter()
812        .chain(input.wavesim_ddd_core.requirements.iter())
813    {
814        if consumers.binary_search(&requirement.consumer_id).is_ok() {
815            return Err(NecoFailure::StorageFailure {
816                location: FailureLocation::operation(FailureOperation::Allocate)
817                    .with_consumer(requirement.consumer_id),
818                payload: crate::StorageFailurePayload::DuplicateId {
819                    resource: StorageResource::ProductEntries,
820                    id: requirement.consumer_id.get(),
821                },
822            });
823        }
824        let required = consumers.len().checked_add(1).ok_or_else(|| {
825            map_storage_failure(
826                FailureLocation::operation(FailureOperation::Allocate),
827                crate::StorageError::CapacityOverflow {
828                    resource: StorageResource::ProductEntries,
829                },
830            )
831        })?;
832        reserve_entries(&mut consumers, required, StorageResource::ProductEntries).map_err(
833            |error| {
834                map_storage_failure(
835                    FailureLocation::operation(FailureOperation::Allocate),
836                    error,
837                )
838            },
839        )?;
840        let index = consumers
841            .binary_search(&requirement.consumer_id)
842            .unwrap_or_else(|index| index);
843        consumers.insert(index, requirement.consumer_id);
844    }
845    move_budgets(&mut budgets, &mut input.mfp_core.numerical_error_budgets)?;
846    move_budgets(
847        &mut budgets,
848        &mut input.wavesim_ddd_core.numerical_error_budgets,
849    )?;
850    let allocation = ExactNumericAllocation {
851        exact_inputs: all_exact_inputs(),
852        exact_decisions: all_exact_decisions(),
853        numerical_operations: all_numerical_operations(),
854        descent_consumers: consumers,
855        numerical_error_budgets: budgets,
856    };
857    Ok(AllocatedExactNumericContext { input, allocation })
858}
859
860pub fn normalize_exact_expressions(
861    allocated: AllocatedExactNumericContext,
862) -> Result<NormalizedExactNumericContext, NecoFailure> {
863    #[cfg(test)]
864    if let Some(error) = injected_operation_failure(FailureOperation::Normalize) {
865        return Err(error);
866    }
867    let mut normal_forms = Vec::new();
868    let mut evaluation_count = 0_usize;
869    normalize_core(
870        NumericalOwner::ModalFieldProjection,
871        &allocated.input.mfp_core,
872        &mut normal_forms,
873        &mut evaluation_count,
874    )?;
875    normalize_core(
876        NumericalOwner::Wavesim,
877        &allocated.input.wavesim_ddd_core,
878        &mut normal_forms,
879        &mut evaluation_count,
880    )?;
881    Ok(NormalizedExactNumericContext {
882        allocated,
883        normal_forms,
884        evaluation_count,
885    })
886}
887
888pub fn decide_exact_properties(
889    normalized: NormalizedExactNumericContext,
890) -> Result<DecidedExactNumericContext, NecoFailure> {
891    #[cfg(test)]
892    if let Some(error) = injected_operation_failure(FailureOperation::Decide) {
893        return Err(error);
894    }
895    let mut decisions = Vec::new();
896    decide_core(
897        &normalized,
898        &normalized.allocated.input.mfp_core.requirements,
899        &mut decisions,
900    )?;
901    decide_core(
902        &normalized,
903        &normalized.allocated.input.wavesim_ddd_core.requirements,
904        &mut decisions,
905    )?;
906    Ok(DecidedExactNumericContext {
907        normalized,
908        decisions,
909    })
910}
911
912fn decide_core(
913    normalized: &NormalizedExactNumericContext,
914    requirements: &[ExactExpressionRequirement],
915    decisions: &mut Vec<DecisionEntry>,
916) -> Result<(), NecoFailure> {
917    for requirement in requirements {
918        let location = FailureLocation::operation(FailureOperation::Decide)
919            .with_consumer(requirement.consumer_id)
920            .with_decision(requirement.consumer_id.get());
921        let (operands, operand_count) = decision_operands(requirement.decision);
922        let operands = &operands[..operand_count];
923        let first = normalized
924            .normal_form(requirement.consumer_id, operands[0])
925            .ok_or(NecoFailure::UnknownExpression {
926                location: location.with_expr(operands[0]),
927            })?;
928        let (value, witness) = match requirement.decision {
929            ExactDecisionRequest::Zero(_) => (
930                if decide_zero(first) {
931                    ExactDecisionValue::Zero
932                } else {
933                    ExactDecisionValue::NonZero
934                },
935                first
936                    .try_clone()
937                    .map_err(|error| map_eval_failure(location, error))?,
938            ),
939            ExactDecisionRequest::Equality(_, right) => {
940                let right_value = normalized
941                    .normal_form(requirement.consumer_id, right)
942                    .ok_or(NecoFailure::UnknownExpression {
943                        location: location.with_expr(right),
944                    })?;
945                let equal = decide_equality(first, right_value)
946                    .map_err(|error| map_eval_failure(location, error))?;
947                let difference = crate::value::sub_exact(first, right_value)
948                    .map_err(|error| map_eval_failure(location, error))?;
949                (
950                    if equal {
951                        ExactDecisionValue::Equal
952                    } else {
953                        ExactDecisionValue::NotEqual
954                    },
955                    difference,
956                )
957            }
958            ExactDecisionRequest::Sign(_) => (
959                match decide_sign(first).map_err(|error| map_eval_failure(location, error))? {
960                    Sign::Negative => ExactDecisionValue::Negative,
961                    Sign::Zero => ExactDecisionValue::Zero,
962                    Sign::Positive => ExactDecisionValue::Positive,
963                },
964                first
965                    .try_clone()
966                    .map_err(|error| map_eval_failure(location, error))?,
967            ),
968            ExactDecisionRequest::Degeneracy(_) => (
969                if decide_zero(first) {
970                    ExactDecisionValue::Degenerate
971                } else {
972                    ExactDecisionValue::NonDegenerate
973                },
974                first
975                    .try_clone()
976                    .map_err(|error| map_eval_failure(location, error))?,
977            ),
978        };
979        let mut operand_values = Vec::new();
980        reserve_entries(
981            &mut operand_values,
982            operands.len(),
983            StorageResource::ProductEntries,
984        )
985        .map_err(|error| map_storage_failure(location, error))?;
986        operand_values.extend_from_slice(operands);
987        let required = decisions.len().checked_add(1).ok_or_else(|| {
988            map_storage_failure(
989                location,
990                crate::StorageError::CapacityOverflow {
991                    resource: StorageResource::ProductEntries,
992                },
993            )
994        })?;
995        reserve_entries(decisions, required, StorageResource::ProductEntries)
996            .map_err(|error| map_storage_failure(location, error))?;
997        decisions.push(DecisionEntry {
998            consumer: requirement.consumer_id,
999            witness: ExactDecisionWitness {
1000                kind: requirement.decision.kind(),
1001                operands: operand_values,
1002                value,
1003                normal_form_witness: witness,
1004            },
1005        });
1006    }
1007    Ok(())
1008}
1009
1010pub fn resolve_certified_f64(
1011    decided: DecidedExactNumericContext,
1012) -> Result<ResolvedExactNumericContext, NecoFailure> {
1013    #[cfg(test)]
1014    if let Some(error) = injected_operation_failure(FailureOperation::Resolve) {
1015        return Err(error);
1016    }
1017    let mut cache: Vec<CachedResolution> = Vec::new();
1018    let mut mfp_isolation = IsolationCache::new();
1019    let mut wavesim_isolation = IsolationCache::new();
1020    let mut bundles = Vec::new();
1021    resolve_core(
1022        NumericalOwner::ModalFieldProjection,
1023        &decided,
1024        &decided.normalized.allocated.input.mfp_core.requirements,
1025        &mut mfp_isolation,
1026        &mut cache,
1027        &mut bundles,
1028    )?;
1029    resolve_core(
1030        NumericalOwner::Wavesim,
1031        &decided,
1032        &decided
1033            .normalized
1034            .allocated
1035            .input
1036            .wavesim_ddd_core
1037            .requirements,
1038        &mut wavesim_isolation,
1039        &mut cache,
1040        &mut bundles,
1041    )?;
1042    Ok(ResolvedExactNumericContext {
1043        decided,
1044        certified_descents: bundles,
1045        shared_resolution_count: cache.len(),
1046    })
1047}
1048
1049fn resolve_core(
1050    owner: NumericalOwner,
1051    decided: &DecidedExactNumericContext,
1052    requirements: &[ExactExpressionRequirement],
1053    isolation: &mut IsolationCache,
1054    cache: &mut Vec<CachedResolution>,
1055    bundles: &mut Vec<CertifiedF64Bundle>,
1056) -> Result<(), NecoFailure> {
1057    for requirement in requirements {
1058        let location = FailureLocation::operation(FailureOperation::Resolve)
1059            .with_consumer(requirement.consumer_id);
1060        let mut values = Vec::new();
1061        reserve_entries(
1062            &mut values,
1063            requirement.expressions.len(),
1064            StorageResource::ProductResolutionEntries,
1065        )
1066        .map_err(|error| map_storage_failure(location, error))?;
1067        for expression in &requirement.expressions {
1068            let certified = match cache.iter().find(|entry| {
1069                entry.owner == owner
1070                    && entry.expr == *expression
1071                    && entry.bits == requirement.precision
1072            }) {
1073                Some(entry) => entry.value.try_clone().map_err(|error| {
1074                    map_resolve_failure(
1075                        location.with_expr(*expression),
1076                        ResolveError::Bigint(error),
1077                    )
1078                })?,
1079                None => {
1080                    let exact = decided
1081                        .normalized
1082                        .normal_form(requirement.consumer_id, *expression)
1083                        .ok_or(NecoFailure::UnknownExpression {
1084                            location: location.with_expr(*expression),
1085                        })?;
1086                    let resolved =
1087                        CertifiedF64::resolve(exact, *expression, requirement.precision, isolation)
1088                            .map_err(|error| {
1089                                map_float_failure(location.with_expr(*expression), error)
1090                            })?;
1091                    let cached = resolved.try_clone().map_err(|error| {
1092                        map_resolve_failure(
1093                            location.with_expr(*expression),
1094                            ResolveError::Bigint(error),
1095                        )
1096                    })?;
1097                    let required = cache.len().checked_add(1).ok_or_else(|| {
1098                        map_storage_failure(
1099                            location,
1100                            crate::StorageError::CapacityOverflow {
1101                                resource: StorageResource::ProductResolutionEntries,
1102                            },
1103                        )
1104                    })?;
1105                    reserve_entries(cache, required, StorageResource::ProductResolutionEntries)
1106                        .map_err(|error| map_storage_failure(location, error))?;
1107                    cache.push(CachedResolution {
1108                        owner,
1109                        expr: *expression,
1110                        bits: requirement.precision,
1111                        value: cached,
1112                    });
1113                    resolved
1114                }
1115            };
1116            values.push(CertifiedF64Expression {
1117                expr: *expression,
1118                certified,
1119            });
1120        }
1121        let required = bundles.len().checked_add(1).ok_or_else(|| {
1122            map_storage_failure(
1123                location,
1124                crate::StorageError::CapacityOverflow {
1125                    resource: StorageResource::ProductEntries,
1126                },
1127            )
1128        })?;
1129        reserve_entries(bundles, required, StorageResource::ProductEntries)
1130            .map_err(|error| map_storage_failure(location, error))?;
1131        bundles.push(CertifiedF64Bundle {
1132            consumer_id: requirement.consumer_id,
1133            values,
1134        });
1135    }
1136    Ok(())
1137}
1138
1139pub fn assemble_exact_computation_product(
1140    resolved: ResolvedExactNumericContext,
1141) -> Result<ExactComputationProduct, NecoFailure> {
1142    let expected = resolved
1143        .decided
1144        .normalized
1145        .allocated
1146        .allocation
1147        .descent_consumers
1148        .len();
1149    if resolved.certified_descents.len() != expected || resolved.decided.decisions.len() != expected
1150    {
1151        return Err(NecoFailure::MissingAssignment {
1152            location: FailureLocation::operation(FailureOperation::Assemble),
1153        });
1154    }
1155    Ok(ExactComputationProduct { resolved })
1156}
1157
1158fn normalize_core(
1159    owner: NumericalOwner,
1160    core: &impl CoreProduct,
1161    output: &mut Vec<NormalFormEntry>,
1162    evaluation_count: &mut usize,
1163) -> Result<(), NecoFailure> {
1164    let mut cache = EvaluationCache::new();
1165    for requirement in core.requirements() {
1166        for expression in requirement.expressions() {
1167            let location = FailureLocation::operation(FailureOperation::Normalize)
1168                .with_consumer(requirement.consumer_id())
1169                .with_expr(*expression);
1170            let before = cache.len();
1171            let value = evaluate_reachable(*expression, core.graph(), core.atoms(), &mut cache)
1172                .map_err(|error| map_evaluation_run_failure(location, error))?;
1173            *evaluation_count = evaluation_count
1174                .checked_add(cache.len() - before)
1175                .ok_or_else(|| {
1176                    map_storage_failure(
1177                        location,
1178                        crate::StorageError::CapacityOverflow {
1179                            resource: StorageResource::ProductEntries,
1180                        },
1181                    )
1182                })?;
1183            let required = output.len().checked_add(1).ok_or_else(|| {
1184                map_storage_failure(
1185                    location,
1186                    crate::StorageError::CapacityOverflow {
1187                        resource: StorageResource::ProductEntries,
1188                    },
1189                )
1190            })?;
1191            reserve_entries(output, required, StorageResource::ProductEntries)
1192                .map_err(|error| map_storage_failure(location, error))?;
1193            output.push(NormalFormEntry {
1194                owner,
1195                consumer: requirement.consumer_id(),
1196                expr: *expression,
1197                value,
1198            });
1199        }
1200    }
1201    Ok(())
1202}
1203
1204trait CoreProduct {
1205    fn graph(&self) -> &ExprGraph;
1206    fn atoms(&self) -> &AtomStore;
1207    fn requirements(&self) -> &[ExactExpressionRequirement];
1208}
1209
1210impl CoreProduct for MfpCoreProduct {
1211    fn graph(&self) -> &ExprGraph {
1212        &self.graph
1213    }
1214    fn atoms(&self) -> &AtomStore {
1215        &self.atoms
1216    }
1217    fn requirements(&self) -> &[ExactExpressionRequirement] {
1218        &self.requirements
1219    }
1220}
1221
1222impl CoreProduct for WavesimDddCoreProduct {
1223    fn graph(&self) -> &ExprGraph {
1224        &self.graph
1225    }
1226    fn atoms(&self) -> &AtomStore {
1227        &self.atoms
1228    }
1229    fn requirements(&self) -> &[ExactExpressionRequirement] {
1230        &self.requirements
1231    }
1232}
1233
1234fn move_budgets(
1235    target: &mut Vec<NumericalErrorBudget>,
1236    source: &mut Vec<NumericalErrorBudget>,
1237) -> Result<(), NecoFailure> {
1238    let required = target.len().checked_add(source.len()).ok_or_else(|| {
1239        map_storage_failure(
1240            FailureLocation::operation(FailureOperation::Allocate),
1241            crate::StorageError::CapacityOverflow {
1242                resource: StorageResource::ProductEntries,
1243            },
1244        )
1245    })?;
1246    reserve_entries(target, required, StorageResource::ProductEntries).map_err(|error| {
1247        map_storage_failure(
1248            FailureLocation::operation(FailureOperation::Allocate),
1249            error,
1250        )
1251    })?;
1252    target.append(source);
1253    Ok(())
1254}
1255
1256fn map_evaluation_run_failure(location: FailureLocation, error: EvaluationRunError) -> NecoFailure {
1257    match error {
1258        EvaluationRunError::UnknownExpr(expr) => NecoFailure::UnknownExpression {
1259            location: location.with_expr(expr),
1260        },
1261        EvaluationRunError::UnknownAtom { expr, atom } => NecoFailure::UnknownAtom {
1262            location: location.with_expr(expr).with_atom(atom),
1263        },
1264        EvaluationRunError::Evaluation(error) => map_eval_failure(location, error),
1265        EvaluationRunError::Storage(error) => map_storage_failure(location, error),
1266    }
1267}
1268
1269fn map_float_failure(location: FailureLocation, error: FloatError) -> NecoFailure {
1270    match error {
1271        FloatError::OutOfRange => NecoFailure::FloatOutOfRange { location },
1272        FloatError::Bigint(error) => map_resolve_failure(location, ResolveError::Bigint(error)),
1273        FloatError::Algnum(error) => map_resolve_failure(location, ResolveError::Algnum(error)),
1274        FloatError::Storage(error) => map_storage_failure(location, error),
1275    }
1276}
1277
1278fn decision_operands(decision: ExactDecisionRequest) -> ([ExprId; 2], usize) {
1279    match decision {
1280        ExactDecisionRequest::Zero(expr)
1281        | ExactDecisionRequest::Sign(expr)
1282        | ExactDecisionRequest::Degeneracy(expr) => ([expr, expr], 1),
1283        ExactDecisionRequest::Equality(left, right) => ([left, right], 2),
1284    }
1285}
1286
1287fn operation_name(operation: ExactOperation) -> &'static str {
1288    match operation {
1289        ExactOperation::NormalizeMonomial => "normalize-monomial",
1290        ExactOperation::NormalizeFormSum => "normalize-form-sum",
1291        ExactOperation::NormalizeAlgebraic => "normalize-algebraic",
1292        ExactOperation::DecideZero => "decide-zero",
1293        ExactOperation::DecideEquality => "decide-equality",
1294        ExactOperation::DecideSign => "decide-sign",
1295        ExactOperation::DecideDegeneracy => "decide-degeneracy",
1296        ExactOperation::ResolveCertifiedF64 => "resolve-certified-f64",
1297    }
1298}
1299
1300fn all_exact_inputs() -> Vec<ExactInput> {
1301    alloc::vec![
1302        ExactInput::GeometryIdentity,
1303        ExactInput::GeometryDimension,
1304        ExactInput::SourceNode,
1305        ExactInput::ReceiverNode,
1306        ExactInput::FrequencyBandEndpoints,
1307        ExactInput::ModeLimit,
1308        ExactInput::SamplingCount,
1309        ExactInput::SamplingRate,
1310        ExactInput::ModeIndexOrdering,
1311        ExactInput::ModeRowCardinality,
1312        ExactInput::ModeRowWidth,
1313        ExactInput::DampingDefinition,
1314        ExactInput::SystemIdentity,
1315        ExactInput::SubsystemIdentity,
1316        ExactInput::StateShape,
1317        ExactInput::StateExtents,
1318        ExactInput::InitialStateIndex,
1319        ExactInput::TimeDomainEndpoints,
1320        ExactInput::CalibrationInterval,
1321        ExactInput::HeldOutInterval,
1322        ExactInput::ConditionIdentity,
1323        ExactInput::CouplingTopology,
1324        ExactInput::CouplingSelector,
1325        ExactInput::ComparatorDirection,
1326        ExactInput::AcceptanceDomainBound,
1327    ]
1328}
1329
1330fn all_exact_decisions() -> Vec<ExactDecisionAssignment> {
1331    alloc::vec![
1332        ExactDecisionAssignment::ProvenanceNonempty,
1333        ExactDecisionAssignment::SourceReceiverIdentityValidity,
1334        ExactDecisionAssignment::ModeSetNonempty,
1335        ExactDecisionAssignment::ModeIdentityEqualityOrdering,
1336        ExactDecisionAssignment::ModeShapeCardinalityAxisEquality,
1337        ExactDecisionAssignment::SamplingDomainValidity,
1338        ExactDecisionAssignment::ZeroDivisionGuard,
1339        ExactDecisionAssignment::Rt60RoundTripEquality,
1340        ExactDecisionAssignment::MfpBranchIdentity,
1341        ExactDecisionAssignment::StateShapeEquality,
1342        ExactDecisionAssignment::CalibrationHeldOutDisjointness,
1343        ExactDecisionAssignment::ConditionSetCompleteness,
1344        ExactDecisionAssignment::SubsystemIdentityEquality,
1345        ExactDecisionAssignment::FiniteNonNegative,
1346        ExactDecisionAssignment::EnergyBalance,
1347        ExactDecisionAssignment::SingularityZeroDenominator,
1348        ExactDecisionAssignment::PredictionIndependenceEquality,
1349        ExactDecisionAssignment::R2LowerBound,
1350        ExactDecisionAssignment::AssemblyFailureSetEmptiness,
1351    ]
1352}
1353
1354fn all_numerical_operations() -> Vec<NumericalOperation> {
1355    alloc::vec![
1356        NumericalOperation::ModeFrequencyEvaluation,
1357        NumericalOperation::ModeShapeEvaluation,
1358        NumericalOperation::DampingRateCalculation,
1359        NumericalOperation::ModeContributionCalculation,
1360        NumericalOperation::ModeSum,
1361        NumericalOperation::ReceivedSeriesSamplingAccumulation,
1362        NumericalOperation::TranscendentalEvaluationFem,
1363        NumericalOperation::ModalRhsEvaluation,
1364        NumericalOperation::InitialStateNumericalConstruction,
1365        NumericalOperation::OdeIntegration,
1366        NumericalOperation::EnergyObservation,
1367        NumericalOperation::DddRegressionEstimation,
1368        NumericalOperation::SeaRegressionEstimation,
1369        NumericalOperation::HeldOutPredictionComparison,
1370    ]
1371}
1372
1373#[cfg(test)]
1374#[derive(Clone, Copy)]
1375enum InjectedOperationFailure {
1376    InvalidIsolation,
1377    MultipleTargetRoots,
1378    MissingAssignment(ConsumerId),
1379    FloatOutOfRange(ConsumerId, ExprId),
1380}
1381
1382#[cfg(test)]
1383std::thread_local! {
1384    static INJECTED_OPERATION_FAILURE: core::cell::Cell<Option<InjectedOperationFailure>> = const { core::cell::Cell::new(None) };
1385}
1386
1387#[cfg(test)]
1388fn injected_operation_failure(operation: FailureOperation) -> Option<NecoFailure> {
1389    INJECTED_OPERATION_FAILURE.with(|configured| {
1390        let failure = configured.take()?;
1391        let location = FailureLocation::operation(operation);
1392        Some(match failure {
1393            InjectedOperationFailure::InvalidIsolation => map_eval_failure(
1394                location,
1395                crate::EvalError::Algnum(neco_algnum::AlgnumError::InvalidIsolation),
1396            ),
1397            InjectedOperationFailure::MultipleTargetRoots => map_eval_failure(
1398                location,
1399                crate::EvalError::Algnum(neco_algnum::AlgnumError::MultipleTargetRoots),
1400            ),
1401            InjectedOperationFailure::MissingAssignment(consumer) => {
1402                map_resolve_failure(location, ResolveError::MissingAssignment { consumer })
1403            }
1404            InjectedOperationFailure::FloatOutOfRange(consumer, expr) => {
1405                map_resolve_failure(location, ResolveError::FloatOutOfRange { consumer, expr })
1406            }
1407        })
1408    })
1409}
1410
1411#[cfg(test)]
1412fn with_injected_operation_failure<R>(
1413    failure: InjectedOperationFailure,
1414    operation: impl FnOnce() -> R,
1415) -> R {
1416    INJECTED_OPERATION_FAILURE.with(|configured| configured.set(Some(failure)));
1417    let result = operation();
1418    INJECTED_OPERATION_FAILURE.with(|configured| configured.set(None));
1419    result
1420}
1421
1422#[cfg(test)]
1423mod proof_vectors {
1424    use alloc::vec;
1425
1426    use neco_monomial::Monomial;
1427
1428    use super::*;
1429    use crate::storage::{with_injected_failure, InjectedFailure};
1430    use crate::{AtomId, ExactValue, ExprNode, StorageError, StorageFailurePayload};
1431
1432    const OPERATIONS: [ExactOperation; 8] = [
1433        ExactOperation::NormalizeMonomial,
1434        ExactOperation::NormalizeFormSum,
1435        ExactOperation::NormalizeAlgebraic,
1436        ExactOperation::DecideZero,
1437        ExactOperation::DecideEquality,
1438        ExactOperation::DecideSign,
1439        ExactOperation::DecideDegeneracy,
1440        ExactOperation::ResolveCertifiedF64,
1441    ];
1442
1443    fn domain(atom: Option<ExactValue>) -> (ExprGraph, AtomStore, ExprId) {
1444        let mut graph = ExprGraph::new();
1445        let expr = graph.push(ExprNode::Atom(AtomId::new(0))).unwrap();
1446        let mut atoms = AtomStore::new();
1447        if let Some(value) = atom {
1448            atoms.insert(AtomId::new(0), value).unwrap();
1449        }
1450        (graph, atoms, expr)
1451    }
1452
1453    fn requirement(consumer: u32, expr: ExprId) -> ExactExpressionRequirement {
1454        ExactExpressionRequirement::new(
1455            ConsumerId::new(consumer),
1456            &[expr],
1457            ExactDecisionRequest::Zero(expr),
1458            AbsoluteBits::new(20),
1459        )
1460        .unwrap()
1461    }
1462
1463    fn input_with_domain(graph: ExprGraph, atoms: AtomStore, expr: ExprId) -> ExactAllocationInput {
1464        let mfp = MfpCoreProduct::new(graph, atoms, vec![requirement(0, expr)], vec![]).unwrap();
1465        let (wavesim_graph, wavesim_atoms, _) = domain(Some(ExactValue::Monomial(Monomial::one())));
1466        let wavesim =
1467            WavesimDddCoreProduct::new(wavesim_graph, wavesim_atoms, vec![], vec![]).unwrap();
1468        ExactAllocationInput::new(
1469            mfp,
1470            wavesim,
1471            NecoObservedCapability::current(&OPERATIONS).unwrap(),
1472            NecoImplementationSource::current(),
1473        )
1474    }
1475
1476    fn allocated_with_value(value: Option<ExactValue>) -> AllocatedExactNumericContext {
1477        let (graph, atoms, expr) = domain(value);
1478        allocate_exact_numeric(
1479            read_exact_numeric_inputs(input_with_domain(graph, atoms, expr)).unwrap(),
1480        )
1481        .unwrap()
1482    }
1483
1484    fn normalized() -> NormalizedExactNumericContext {
1485        normalize_exact_expressions(allocated_with_value(Some(ExactValue::Monomial(
1486            Monomial::one(),
1487        ))))
1488        .unwrap()
1489    }
1490
1491    fn decided() -> DecidedExactNumericContext {
1492        decide_exact_properties(normalized()).unwrap()
1493    }
1494
1495    #[test]
1496    fn allocation_storage_failure_preserves_operation_location_and_payload() {
1497        let (graph, atoms, expr) = domain(Some(ExactValue::Monomial(Monomial::one())));
1498        let input = read_exact_numeric_inputs(input_with_domain(graph, atoms, expr)).unwrap();
1499        let result = with_injected_failure(
1500            StorageResource::ProductEntries,
1501            InjectedFailure::Allocation,
1502            || allocate_exact_numeric(input),
1503        );
1504        assert_eq!(
1505            result,
1506            Err(NecoFailure::StorageFailure {
1507                location: FailureLocation::operation(FailureOperation::Allocate),
1508                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1509                    resource: StorageResource::ProductEntries,
1510                    requested_elements: 1,
1511                }),
1512            })
1513        );
1514    }
1515
1516    #[test]
1517    fn normalize_operation_failure_vectors_are_executable() {
1518        let (graph, atoms, expr) = domain(None);
1519        let unknown_atom = normalize_exact_expressions(
1520            allocate_exact_numeric(
1521                read_exact_numeric_inputs(input_with_domain(graph, atoms, expr)).unwrap(),
1522            )
1523            .unwrap(),
1524        );
1525        assert!(matches!(
1526            unknown_atom,
1527            Err(NecoFailure::UnknownAtom { location })
1528                if location.operation_kind() == FailureOperation::Normalize
1529                    && location.expr() == Some(expr)
1530                    && location.atom() == Some(AtomId::new(0))
1531        ));
1532
1533        let mut malformed = allocated_with_value(Some(ExactValue::Monomial(Monomial::one())));
1534        malformed.input.mfp_core.requirements[0].expressions[0] = ExprId::new(99);
1535        assert!(matches!(
1536            normalize_exact_expressions(malformed),
1537            Err(NecoFailure::UnknownExpression { location })
1538                if location.operation_kind() == FailureOperation::Normalize
1539                    && location.expr() == Some(ExprId::new(99))
1540        ));
1541
1542        let mut graph = ExprGraph::new();
1543        let zero = graph.push(ExprNode::Atom(AtomId::new(0))).unwrap();
1544        let division = graph.push(ExprNode::Div(zero, zero)).unwrap();
1545        let mut atoms = AtomStore::new();
1546        atoms
1547            .insert(AtomId::new(0), ExactValue::Monomial(Monomial::zero()))
1548            .unwrap();
1549        assert!(matches!(
1550            normalize_exact_expressions(
1551                allocate_exact_numeric(
1552                    read_exact_numeric_inputs(input_with_domain(graph, atoms, division)).unwrap(),
1553                )
1554                .unwrap(),
1555            ),
1556            Err(NecoFailure::DivisionByZero { location })
1557                if location.operation_kind() == FailureOperation::Normalize
1558        ));
1559
1560        let mut graph = ExprGraph::new();
1561        let zero = graph.push(ExprNode::Atom(AtomId::new(0))).unwrap();
1562        let power = graph
1563            .push(ExprNode::Pow {
1564                base: zero,
1565                exponent: neco_bigint::ReducedRational::from_bigint(neco_bigint::BigInt::zero())
1566                    .unwrap(),
1567            })
1568            .unwrap();
1569        let mut atoms = AtomStore::new();
1570        atoms
1571            .insert(AtomId::new(0), ExactValue::Monomial(Monomial::zero()))
1572            .unwrap();
1573        assert!(matches!(
1574            normalize_exact_expressions(
1575                allocate_exact_numeric(
1576                    read_exact_numeric_inputs(input_with_domain(graph, atoms, power)).unwrap(),
1577                )
1578                .unwrap(),
1579            ),
1580            Err(NecoFailure::UndefinedPower { location })
1581                if location.operation_kind() == FailureOperation::Normalize
1582        ));
1583
1584        let invalid_isolation =
1585            with_injected_operation_failure(InjectedOperationFailure::InvalidIsolation, || {
1586                normalize_exact_expressions(allocated_with_value(Some(ExactValue::Monomial(
1587                    Monomial::one(),
1588                ))))
1589            });
1590        assert!(matches!(
1591            invalid_isolation,
1592            Err(NecoFailure::InvalidIsolation { location })
1593                if location.operation_kind() == FailureOperation::Normalize
1594        ));
1595
1596        let storage = with_injected_failure(
1597            StorageResource::EvaluationEntries,
1598            InjectedFailure::Allocation,
1599            || {
1600                normalize_exact_expressions(allocated_with_value(Some(ExactValue::Monomial(
1601                    Monomial::one(),
1602                ))))
1603            },
1604        );
1605        assert!(matches!(
1606            storage,
1607            Err(NecoFailure::StorageFailure {
1608                location,
1609                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1610                    resource: StorageResource::EvaluationEntries,
1611                    ..
1612                }),
1613            }) if location.operation_kind() == FailureOperation::Normalize
1614        ));
1615    }
1616
1617    #[test]
1618    fn decide_operation_failure_vectors_are_executable() {
1619        let invalid_input = normalized();
1620        let invalid =
1621            with_injected_operation_failure(InjectedOperationFailure::InvalidIsolation, || {
1622                decide_exact_properties(invalid_input)
1623            });
1624        assert!(matches!(
1625            invalid,
1626            Err(NecoFailure::InvalidIsolation { location })
1627                if location.operation_kind() == FailureOperation::Decide
1628        ));
1629        let multiple_input = normalized();
1630        let multiple =
1631            with_injected_operation_failure(InjectedOperationFailure::MultipleTargetRoots, || {
1632                decide_exact_properties(multiple_input)
1633            });
1634        assert!(matches!(
1635            multiple,
1636            Err(NecoFailure::MultipleTargetRoots { location })
1637                if location.operation_kind() == FailureOperation::Decide
1638        ));
1639        let storage_input = normalized();
1640        let storage = with_injected_failure(
1641            StorageResource::ProductEntries,
1642            InjectedFailure::Allocation,
1643            || decide_exact_properties(storage_input),
1644        );
1645        assert!(matches!(
1646            storage,
1647            Err(NecoFailure::StorageFailure {
1648                location,
1649                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1650                    resource: StorageResource::ProductEntries,
1651                    ..
1652                }),
1653            }) if location.operation_kind() == FailureOperation::Decide
1654        ));
1655    }
1656
1657    #[test]
1658    fn resolve_operation_failure_vectors_are_executable() {
1659        let consumer = ConsumerId::new(7);
1660        let missing_input = decided();
1661        let missing = with_injected_operation_failure(
1662            InjectedOperationFailure::MissingAssignment(consumer),
1663            || resolve_certified_f64(missing_input),
1664        );
1665        assert!(matches!(
1666            missing,
1667            Err(NecoFailure::MissingAssignment { location })
1668                if location.operation_kind() == FailureOperation::Resolve
1669                    && location.consumer() == Some(consumer)
1670        ));
1671        let expr = ExprId::new(3);
1672        let out_of_range_input = decided();
1673        let out_of_range = with_injected_operation_failure(
1674            InjectedOperationFailure::FloatOutOfRange(consumer, expr),
1675            || resolve_certified_f64(out_of_range_input),
1676        );
1677        assert!(matches!(
1678            out_of_range,
1679            Err(NecoFailure::FloatOutOfRange { location })
1680                if location.operation_kind() == FailureOperation::Resolve
1681                    && location.consumer() == Some(consumer)
1682                    && location.expr() == Some(expr)
1683        ));
1684        let storage = with_injected_failure(
1685            StorageResource::ProductResolutionEntries,
1686            InjectedFailure::Allocation,
1687            || resolve_certified_f64(decided()),
1688        );
1689        assert!(matches!(
1690            storage,
1691            Err(NecoFailure::StorageFailure {
1692                location,
1693                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1694                    resource: StorageResource::ProductResolutionEntries,
1695                    ..
1696                }),
1697            }) if location.operation_kind() == FailureOperation::Resolve
1698        ));
1699    }
1700
1701    #[test]
1702    fn missing_domain_assembly_returns_failure_without_partial_product() {
1703        let mut resolved = resolve_certified_f64(decided()).unwrap();
1704        resolved.certified_descents.clear();
1705        let result = assemble_exact_computation_product(resolved);
1706        assert!(matches!(
1707            result,
1708            Err(NecoFailure::MissingAssignment { location })
1709                if location.operation_kind() == FailureOperation::Assemble
1710        ));
1711    }
1712}