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
628impl CertifiedF64Bundle {
629    pub const fn consumer_id(&self) -> ConsumerId {
630        self.consumer_id
631    }
632
633    pub fn values(&self) -> &[CertifiedF64Expression] {
634        &self.values
635    }
636}
637
638#[derive(Debug, Eq, PartialEq)]
639pub struct ResolvedExactNumericContext {
640    decided: DecidedExactNumericContext,
641    certified_descents: Vec<CertifiedF64Bundle>,
642    shared_resolution_count: usize,
643}
644
645impl ResolvedExactNumericContext {
646    pub fn certified_descent(&self, consumer: ConsumerId) -> Option<&CertifiedF64Bundle> {
647        self.certified_descents
648            .iter()
649            .find(|bundle| bundle.consumer_id == consumer)
650    }
651
652    pub const fn shared_resolution_count(&self) -> usize {
653        self.shared_resolution_count
654    }
655}
656
657pub struct DirectInspection<'a> {
658    allocation: &'a ExactNumericAllocation,
659    requirements: Vec<&'a ExactExpressionRequirement>,
660    decisions: &'a [DecisionEntry],
661    certified_descents: &'a [CertifiedF64Bundle],
662    shared_resolution_count: usize,
663}
664
665impl DirectInspection<'_> {
666    pub fn allocation(&self) -> &ExactNumericAllocation {
667        self.allocation
668    }
669
670    pub fn requirements(&self) -> &[&ExactExpressionRequirement] {
671        &self.requirements
672    }
673
674    pub fn certified_descents(&self) -> &[CertifiedF64Bundle] {
675        self.certified_descents
676    }
677
678    pub const fn shared_resolution_count(&self) -> usize {
679        self.shared_resolution_count
680    }
681
682    pub fn decision(&self, consumer: ConsumerId) -> Option<&ExactDecisionWitness> {
683        self.decisions
684            .iter()
685            .find(|entry| entry.consumer == consumer)
686            .map(|entry| &entry.witness)
687    }
688}
689
690#[derive(Debug, Eq, PartialEq)]
691pub struct ExactComputationProduct {
692    resolved: ResolvedExactNumericContext,
693}
694
695impl ExactComputationProduct {
696    pub fn allocation(&self) -> &ExactNumericAllocation {
697        &self.resolved.decided.normalized.allocated.allocation
698    }
699
700    pub fn normal_form(&self, consumer: ConsumerId, expr: ExprId) -> Option<&ExactValue> {
701        self.resolved.decided.normalized.normal_form(consumer, expr)
702    }
703
704    pub fn decision(&self, consumer: ConsumerId) -> Option<&ExactDecisionWitness> {
705        self.resolved.decided.decision(consumer)
706    }
707
708    pub fn certified_descent(&self, consumer: ConsumerId) -> Option<&CertifiedF64Bundle> {
709        self.resolved.certified_descent(consumer)
710    }
711
712    pub fn direct_inspection(&self) -> Result<DirectInspection<'_>, NecoFailure> {
713        let mfp = &self.resolved.decided.normalized.allocated.input.mfp_core;
714        let wavesim = &self
715            .resolved
716            .decided
717            .normalized
718            .allocated
719            .input
720            .wavesim_ddd_core;
721        let total = mfp
722            .requirements
723            .len()
724            .checked_add(wavesim.requirements.len())
725            .ok_or_else(|| {
726                map_storage_failure(
727                    FailureLocation::operation(FailureOperation::Assemble),
728                    crate::StorageError::CapacityOverflow {
729                        resource: StorageResource::ProductEntries,
730                    },
731                )
732            })?;
733        let mut requirements = Vec::new();
734        reserve_entries(&mut requirements, total, StorageResource::ProductEntries).map_err(
735            |error| {
736                map_storage_failure(
737                    FailureLocation::operation(FailureOperation::Assemble),
738                    error,
739                )
740            },
741        )?;
742        requirements.extend(mfp.requirements.iter());
743        requirements.extend(wavesim.requirements.iter());
744        Ok(DirectInspection {
745            allocation: self.allocation(),
746            requirements,
747            decisions: &self.resolved.decided.decisions,
748            certified_descents: &self.resolved.certified_descents,
749            shared_resolution_count: self.resolved.shared_resolution_count,
750        })
751    }
752
753    pub const fn as_exact_computation(&self) -> &Self {
754        self
755    }
756
757    pub const fn as_br_core_005_input(&self) -> &Self {
758        self
759    }
760}
761
762pub fn read_exact_numeric_inputs(
763    input: ExactAllocationInput,
764) -> Result<ExactAllocationInput, NecoFailure> {
765    if input.implementation_source.revision_identity != IMPLEMENTATION_REVISION
766        || input.implementation_source.public_api_identity != PUBLIC_API_IDENTITY
767        || input.observed_capability.source_identity != IMPLEMENTATION_REVISION
768    {
769        return Err(NecoFailure::UnsupportedRequiredOperation {
770            location: FailureLocation::operation(FailureOperation::Read),
771            payload: UnsupportedFailurePayload::SourceIdentity,
772        });
773    }
774    Ok(input)
775}
776
777pub fn allocate_exact_numeric(
778    mut input: ExactAllocationInput,
779) -> Result<AllocatedExactNumericContext, NecoFailure> {
780    let required_operations = [
781        ExactOperation::NormalizeMonomial,
782        ExactOperation::NormalizeFormSum,
783        ExactOperation::NormalizeAlgebraic,
784        ExactOperation::DecideZero,
785        ExactOperation::DecideEquality,
786        ExactOperation::DecideSign,
787        ExactOperation::DecideDegeneracy,
788        ExactOperation::ResolveCertifiedF64,
789    ];
790    for operation in required_operations {
791        if input
792            .observed_capability
793            .supported_operations
794            .binary_search(&operation)
795            .is_err()
796        {
797            return Err(NecoFailure::UnsupportedRequiredOperation {
798                location: FailureLocation::operation(FailureOperation::Allocate),
799                payload: UnsupportedFailurePayload::RequiredOperation(operation_name(operation)),
800            });
801        }
802    }
803    let mut consumers = Vec::new();
804    let mut budgets = Vec::new();
805    for requirement in input
806        .mfp_core
807        .requirements
808        .iter()
809        .chain(input.wavesim_ddd_core.requirements.iter())
810    {
811        if consumers.binary_search(&requirement.consumer_id).is_ok() {
812            return Err(NecoFailure::StorageFailure {
813                location: FailureLocation::operation(FailureOperation::Allocate)
814                    .with_consumer(requirement.consumer_id),
815                payload: crate::StorageFailurePayload::DuplicateId {
816                    resource: StorageResource::ProductEntries,
817                    id: requirement.consumer_id.get(),
818                },
819            });
820        }
821        let required = consumers.len().checked_add(1).ok_or_else(|| {
822            map_storage_failure(
823                FailureLocation::operation(FailureOperation::Allocate),
824                crate::StorageError::CapacityOverflow {
825                    resource: StorageResource::ProductEntries,
826                },
827            )
828        })?;
829        reserve_entries(&mut consumers, required, StorageResource::ProductEntries).map_err(
830            |error| {
831                map_storage_failure(
832                    FailureLocation::operation(FailureOperation::Allocate),
833                    error,
834                )
835            },
836        )?;
837        let index = consumers
838            .binary_search(&requirement.consumer_id)
839            .unwrap_or_else(|index| index);
840        consumers.insert(index, requirement.consumer_id);
841    }
842    move_budgets(&mut budgets, &mut input.mfp_core.numerical_error_budgets)?;
843    move_budgets(
844        &mut budgets,
845        &mut input.wavesim_ddd_core.numerical_error_budgets,
846    )?;
847    let allocation = ExactNumericAllocation {
848        exact_inputs: all_exact_inputs(),
849        exact_decisions: all_exact_decisions(),
850        numerical_operations: all_numerical_operations(),
851        descent_consumers: consumers,
852        numerical_error_budgets: budgets,
853    };
854    Ok(AllocatedExactNumericContext { input, allocation })
855}
856
857pub fn normalize_exact_expressions(
858    allocated: AllocatedExactNumericContext,
859) -> Result<NormalizedExactNumericContext, NecoFailure> {
860    #[cfg(test)]
861    if let Some(error) = injected_operation_failure(FailureOperation::Normalize) {
862        return Err(error);
863    }
864    let mut normal_forms = Vec::new();
865    let mut evaluation_count = 0_usize;
866    normalize_core(
867        NumericalOwner::ModalFieldProjection,
868        &allocated.input.mfp_core,
869        &mut normal_forms,
870        &mut evaluation_count,
871    )?;
872    normalize_core(
873        NumericalOwner::Wavesim,
874        &allocated.input.wavesim_ddd_core,
875        &mut normal_forms,
876        &mut evaluation_count,
877    )?;
878    Ok(NormalizedExactNumericContext {
879        allocated,
880        normal_forms,
881        evaluation_count,
882    })
883}
884
885pub fn decide_exact_properties(
886    normalized: NormalizedExactNumericContext,
887) -> Result<DecidedExactNumericContext, NecoFailure> {
888    #[cfg(test)]
889    if let Some(error) = injected_operation_failure(FailureOperation::Decide) {
890        return Err(error);
891    }
892    let mut decisions = Vec::new();
893    for requirement in all_requirements(&normalized.allocated.input) {
894        let location = FailureLocation::operation(FailureOperation::Decide)
895            .with_consumer(requirement.consumer_id)
896            .with_decision(requirement.consumer_id.get());
897        let (operands, operand_count) = decision_operands(requirement.decision);
898        let operands = &operands[..operand_count];
899        let first = normalized
900            .normal_form(requirement.consumer_id, operands[0])
901            .ok_or(NecoFailure::UnknownExpression {
902                location: location.with_expr(operands[0]),
903            })?;
904        let (value, witness) = match requirement.decision {
905            ExactDecisionRequest::Zero(_) => (
906                if decide_zero(first) {
907                    ExactDecisionValue::Zero
908                } else {
909                    ExactDecisionValue::NonZero
910                },
911                first
912                    .try_clone()
913                    .map_err(|error| map_eval_failure(location, error))?,
914            ),
915            ExactDecisionRequest::Equality(_, right) => {
916                let right_value = normalized
917                    .normal_form(requirement.consumer_id, right)
918                    .ok_or(NecoFailure::UnknownExpression {
919                        location: location.with_expr(right),
920                    })?;
921                let equal = decide_equality(first, right_value)
922                    .map_err(|error| map_eval_failure(location, error))?;
923                let difference = crate::value::sub_exact(first, right_value)
924                    .map_err(|error| map_eval_failure(location, error))?;
925                (
926                    if equal {
927                        ExactDecisionValue::Equal
928                    } else {
929                        ExactDecisionValue::NotEqual
930                    },
931                    difference,
932                )
933            }
934            ExactDecisionRequest::Sign(_) => (
935                match decide_sign(first).map_err(|error| map_eval_failure(location, error))? {
936                    Sign::Negative => ExactDecisionValue::Negative,
937                    Sign::Zero => ExactDecisionValue::Zero,
938                    Sign::Positive => ExactDecisionValue::Positive,
939                },
940                first
941                    .try_clone()
942                    .map_err(|error| map_eval_failure(location, error))?,
943            ),
944            ExactDecisionRequest::Degeneracy(_) => (
945                if decide_zero(first) {
946                    ExactDecisionValue::Degenerate
947                } else {
948                    ExactDecisionValue::NonDegenerate
949                },
950                first
951                    .try_clone()
952                    .map_err(|error| map_eval_failure(location, error))?,
953            ),
954        };
955        let mut operand_values = Vec::new();
956        reserve_entries(
957            &mut operand_values,
958            operands.len(),
959            StorageResource::ProductEntries,
960        )
961        .map_err(|error| map_storage_failure(location, error))?;
962        operand_values.extend_from_slice(operands);
963        let required = decisions.len().checked_add(1).ok_or_else(|| {
964            map_storage_failure(
965                location,
966                crate::StorageError::CapacityOverflow {
967                    resource: StorageResource::ProductEntries,
968                },
969            )
970        })?;
971        reserve_entries(&mut decisions, required, StorageResource::ProductEntries)
972            .map_err(|error| map_storage_failure(location, error))?;
973        decisions.push(DecisionEntry {
974            consumer: requirement.consumer_id,
975            witness: ExactDecisionWitness {
976                kind: requirement.decision.kind(),
977                operands: operand_values,
978                value,
979                normal_form_witness: witness,
980            },
981        });
982    }
983    Ok(DecidedExactNumericContext {
984        normalized,
985        decisions,
986    })
987}
988
989pub fn resolve_certified_f64(
990    decided: DecidedExactNumericContext,
991) -> Result<ResolvedExactNumericContext, NecoFailure> {
992    #[cfg(test)]
993    if let Some(error) = injected_operation_failure(FailureOperation::Resolve) {
994        return Err(error);
995    }
996    struct CachedResolution {
997        expr: ExprId,
998        bits: AbsoluteBits,
999        value: CertifiedF64,
1000    }
1001    let mut cache: Vec<CachedResolution> = Vec::new();
1002    let mut isolation = IsolationCache::new();
1003    let mut bundles = Vec::new();
1004    for requirement in all_requirements(&decided.normalized.allocated.input) {
1005        let location = FailureLocation::operation(FailureOperation::Resolve)
1006            .with_consumer(requirement.consumer_id);
1007        let mut values = Vec::new();
1008        reserve_entries(
1009            &mut values,
1010            requirement.expressions.len(),
1011            StorageResource::ProductResolutionEntries,
1012        )
1013        .map_err(|error| map_storage_failure(location, error))?;
1014        for expression in &requirement.expressions {
1015            let certified = match cache
1016                .iter()
1017                .find(|entry| entry.expr == *expression && entry.bits == requirement.precision)
1018            {
1019                Some(entry) => entry.value.try_clone().map_err(|error| {
1020                    map_resolve_failure(
1021                        location.with_expr(*expression),
1022                        ResolveError::Bigint(error),
1023                    )
1024                })?,
1025                None => {
1026                    let exact = decided
1027                        .normalized
1028                        .normal_form(requirement.consumer_id, *expression)
1029                        .ok_or(NecoFailure::UnknownExpression {
1030                            location: location.with_expr(*expression),
1031                        })?;
1032                    let resolved = CertifiedF64::resolve(
1033                        exact,
1034                        *expression,
1035                        requirement.precision,
1036                        &mut isolation,
1037                    )
1038                    .map_err(|error| map_float_failure(location.with_expr(*expression), error))?;
1039                    let cached = resolved.try_clone().map_err(|error| {
1040                        map_resolve_failure(
1041                            location.with_expr(*expression),
1042                            ResolveError::Bigint(error),
1043                        )
1044                    })?;
1045                    let required = cache.len().checked_add(1).ok_or_else(|| {
1046                        map_storage_failure(
1047                            location,
1048                            crate::StorageError::CapacityOverflow {
1049                                resource: StorageResource::ProductResolutionEntries,
1050                            },
1051                        )
1052                    })?;
1053                    reserve_entries(
1054                        &mut cache,
1055                        required,
1056                        StorageResource::ProductResolutionEntries,
1057                    )
1058                    .map_err(|error| map_storage_failure(location, error))?;
1059                    cache.push(CachedResolution {
1060                        expr: *expression,
1061                        bits: requirement.precision,
1062                        value: cached,
1063                    });
1064                    resolved
1065                }
1066            };
1067            values.push(CertifiedF64Expression {
1068                expr: *expression,
1069                certified,
1070            });
1071        }
1072        let required = bundles.len().checked_add(1).ok_or_else(|| {
1073            map_storage_failure(
1074                location,
1075                crate::StorageError::CapacityOverflow {
1076                    resource: StorageResource::ProductEntries,
1077                },
1078            )
1079        })?;
1080        reserve_entries(&mut bundles, required, StorageResource::ProductEntries)
1081            .map_err(|error| map_storage_failure(location, error))?;
1082        bundles.push(CertifiedF64Bundle {
1083            consumer_id: requirement.consumer_id,
1084            values,
1085        });
1086    }
1087    Ok(ResolvedExactNumericContext {
1088        decided,
1089        certified_descents: bundles,
1090        shared_resolution_count: cache.len(),
1091    })
1092}
1093
1094pub fn assemble_exact_computation_product(
1095    resolved: ResolvedExactNumericContext,
1096) -> Result<ExactComputationProduct, NecoFailure> {
1097    let expected = resolved
1098        .decided
1099        .normalized
1100        .allocated
1101        .allocation
1102        .descent_consumers
1103        .len();
1104    if resolved.certified_descents.len() != expected || resolved.decided.decisions.len() != expected
1105    {
1106        return Err(NecoFailure::MissingAssignment {
1107            location: FailureLocation::operation(FailureOperation::Assemble),
1108        });
1109    }
1110    Ok(ExactComputationProduct { resolved })
1111}
1112
1113fn normalize_core(
1114    owner: NumericalOwner,
1115    core: &impl CoreProduct,
1116    output: &mut Vec<NormalFormEntry>,
1117    evaluation_count: &mut usize,
1118) -> Result<(), NecoFailure> {
1119    let mut cache = EvaluationCache::new();
1120    for requirement in core.requirements() {
1121        for expression in requirement.expressions() {
1122            let location = FailureLocation::operation(FailureOperation::Normalize)
1123                .with_consumer(requirement.consumer_id())
1124                .with_expr(*expression);
1125            let before = cache.len();
1126            let value = evaluate_reachable(*expression, core.graph(), core.atoms(), &mut cache)
1127                .map_err(|error| map_evaluation_run_failure(location, error))?;
1128            *evaluation_count = evaluation_count
1129                .checked_add(cache.len() - before)
1130                .ok_or_else(|| {
1131                    map_storage_failure(
1132                        location,
1133                        crate::StorageError::CapacityOverflow {
1134                            resource: StorageResource::ProductEntries,
1135                        },
1136                    )
1137                })?;
1138            let required = output.len().checked_add(1).ok_or_else(|| {
1139                map_storage_failure(
1140                    location,
1141                    crate::StorageError::CapacityOverflow {
1142                        resource: StorageResource::ProductEntries,
1143                    },
1144                )
1145            })?;
1146            reserve_entries(output, required, StorageResource::ProductEntries)
1147                .map_err(|error| map_storage_failure(location, error))?;
1148            output.push(NormalFormEntry {
1149                owner,
1150                consumer: requirement.consumer_id(),
1151                expr: *expression,
1152                value,
1153            });
1154        }
1155    }
1156    Ok(())
1157}
1158
1159trait CoreProduct {
1160    fn graph(&self) -> &ExprGraph;
1161    fn atoms(&self) -> &AtomStore;
1162    fn requirements(&self) -> &[ExactExpressionRequirement];
1163}
1164
1165impl CoreProduct for MfpCoreProduct {
1166    fn graph(&self) -> &ExprGraph {
1167        &self.graph
1168    }
1169    fn atoms(&self) -> &AtomStore {
1170        &self.atoms
1171    }
1172    fn requirements(&self) -> &[ExactExpressionRequirement] {
1173        &self.requirements
1174    }
1175}
1176
1177impl CoreProduct for WavesimDddCoreProduct {
1178    fn graph(&self) -> &ExprGraph {
1179        &self.graph
1180    }
1181    fn atoms(&self) -> &AtomStore {
1182        &self.atoms
1183    }
1184    fn requirements(&self) -> &[ExactExpressionRequirement] {
1185        &self.requirements
1186    }
1187}
1188
1189fn all_requirements(
1190    input: &ExactAllocationInput,
1191) -> impl Iterator<Item = &ExactExpressionRequirement> {
1192    input
1193        .mfp_core
1194        .requirements
1195        .iter()
1196        .chain(input.wavesim_ddd_core.requirements.iter())
1197}
1198
1199fn move_budgets(
1200    target: &mut Vec<NumericalErrorBudget>,
1201    source: &mut Vec<NumericalErrorBudget>,
1202) -> Result<(), NecoFailure> {
1203    let required = target.len().checked_add(source.len()).ok_or_else(|| {
1204        map_storage_failure(
1205            FailureLocation::operation(FailureOperation::Allocate),
1206            crate::StorageError::CapacityOverflow {
1207                resource: StorageResource::ProductEntries,
1208            },
1209        )
1210    })?;
1211    reserve_entries(target, required, StorageResource::ProductEntries).map_err(|error| {
1212        map_storage_failure(
1213            FailureLocation::operation(FailureOperation::Allocate),
1214            error,
1215        )
1216    })?;
1217    target.append(source);
1218    Ok(())
1219}
1220
1221fn map_evaluation_run_failure(location: FailureLocation, error: EvaluationRunError) -> NecoFailure {
1222    match error {
1223        EvaluationRunError::UnknownExpr(expr) => NecoFailure::UnknownExpression {
1224            location: location.with_expr(expr),
1225        },
1226        EvaluationRunError::UnknownAtom { expr, atom } => NecoFailure::UnknownAtom {
1227            location: location.with_expr(expr).with_atom(atom),
1228        },
1229        EvaluationRunError::Evaluation(error) => map_eval_failure(location, error),
1230        EvaluationRunError::Storage(error) => map_storage_failure(location, error),
1231    }
1232}
1233
1234fn map_float_failure(location: FailureLocation, error: FloatError) -> NecoFailure {
1235    match error {
1236        FloatError::OutOfRange => NecoFailure::FloatOutOfRange { location },
1237        FloatError::Bigint(error) => map_resolve_failure(location, ResolveError::Bigint(error)),
1238        FloatError::Algnum(error) => map_resolve_failure(location, ResolveError::Algnum(error)),
1239        FloatError::Storage(error) => map_storage_failure(location, error),
1240    }
1241}
1242
1243fn decision_operands(decision: ExactDecisionRequest) -> ([ExprId; 2], usize) {
1244    match decision {
1245        ExactDecisionRequest::Zero(expr)
1246        | ExactDecisionRequest::Sign(expr)
1247        | ExactDecisionRequest::Degeneracy(expr) => ([expr, expr], 1),
1248        ExactDecisionRequest::Equality(left, right) => ([left, right], 2),
1249    }
1250}
1251
1252fn operation_name(operation: ExactOperation) -> &'static str {
1253    match operation {
1254        ExactOperation::NormalizeMonomial => "normalize-monomial",
1255        ExactOperation::NormalizeFormSum => "normalize-form-sum",
1256        ExactOperation::NormalizeAlgebraic => "normalize-algebraic",
1257        ExactOperation::DecideZero => "decide-zero",
1258        ExactOperation::DecideEquality => "decide-equality",
1259        ExactOperation::DecideSign => "decide-sign",
1260        ExactOperation::DecideDegeneracy => "decide-degeneracy",
1261        ExactOperation::ResolveCertifiedF64 => "resolve-certified-f64",
1262    }
1263}
1264
1265fn all_exact_inputs() -> Vec<ExactInput> {
1266    alloc::vec![
1267        ExactInput::GeometryIdentity,
1268        ExactInput::GeometryDimension,
1269        ExactInput::SourceNode,
1270        ExactInput::ReceiverNode,
1271        ExactInput::FrequencyBandEndpoints,
1272        ExactInput::ModeLimit,
1273        ExactInput::SamplingCount,
1274        ExactInput::SamplingRate,
1275        ExactInput::ModeIndexOrdering,
1276        ExactInput::ModeRowCardinality,
1277        ExactInput::ModeRowWidth,
1278        ExactInput::DampingDefinition,
1279        ExactInput::SystemIdentity,
1280        ExactInput::SubsystemIdentity,
1281        ExactInput::StateShape,
1282        ExactInput::StateExtents,
1283        ExactInput::InitialStateIndex,
1284        ExactInput::TimeDomainEndpoints,
1285        ExactInput::CalibrationInterval,
1286        ExactInput::HeldOutInterval,
1287        ExactInput::ConditionIdentity,
1288        ExactInput::CouplingTopology,
1289        ExactInput::CouplingSelector,
1290        ExactInput::ComparatorDirection,
1291        ExactInput::AcceptanceDomainBound,
1292    ]
1293}
1294
1295fn all_exact_decisions() -> Vec<ExactDecisionAssignment> {
1296    alloc::vec![
1297        ExactDecisionAssignment::ProvenanceNonempty,
1298        ExactDecisionAssignment::SourceReceiverIdentityValidity,
1299        ExactDecisionAssignment::ModeSetNonempty,
1300        ExactDecisionAssignment::ModeIdentityEqualityOrdering,
1301        ExactDecisionAssignment::ModeShapeCardinalityAxisEquality,
1302        ExactDecisionAssignment::SamplingDomainValidity,
1303        ExactDecisionAssignment::ZeroDivisionGuard,
1304        ExactDecisionAssignment::Rt60RoundTripEquality,
1305        ExactDecisionAssignment::MfpBranchIdentity,
1306        ExactDecisionAssignment::StateShapeEquality,
1307        ExactDecisionAssignment::CalibrationHeldOutDisjointness,
1308        ExactDecisionAssignment::ConditionSetCompleteness,
1309        ExactDecisionAssignment::SubsystemIdentityEquality,
1310        ExactDecisionAssignment::FiniteNonNegative,
1311        ExactDecisionAssignment::EnergyBalance,
1312        ExactDecisionAssignment::SingularityZeroDenominator,
1313        ExactDecisionAssignment::PredictionIndependenceEquality,
1314        ExactDecisionAssignment::R2LowerBound,
1315        ExactDecisionAssignment::AssemblyFailureSetEmptiness,
1316    ]
1317}
1318
1319fn all_numerical_operations() -> Vec<NumericalOperation> {
1320    alloc::vec![
1321        NumericalOperation::ModeFrequencyEvaluation,
1322        NumericalOperation::ModeShapeEvaluation,
1323        NumericalOperation::DampingRateCalculation,
1324        NumericalOperation::ModeContributionCalculation,
1325        NumericalOperation::ModeSum,
1326        NumericalOperation::ReceivedSeriesSamplingAccumulation,
1327        NumericalOperation::TranscendentalEvaluationFem,
1328        NumericalOperation::ModalRhsEvaluation,
1329        NumericalOperation::InitialStateNumericalConstruction,
1330        NumericalOperation::OdeIntegration,
1331        NumericalOperation::EnergyObservation,
1332        NumericalOperation::DddRegressionEstimation,
1333        NumericalOperation::SeaRegressionEstimation,
1334        NumericalOperation::HeldOutPredictionComparison,
1335    ]
1336}
1337
1338#[cfg(test)]
1339#[derive(Clone, Copy)]
1340enum InjectedOperationFailure {
1341    InvalidIsolation,
1342    MultipleTargetRoots,
1343    MissingAssignment(ConsumerId),
1344    FloatOutOfRange(ConsumerId, ExprId),
1345}
1346
1347#[cfg(test)]
1348std::thread_local! {
1349    static INJECTED_OPERATION_FAILURE: core::cell::Cell<Option<InjectedOperationFailure>> = const { core::cell::Cell::new(None) };
1350}
1351
1352#[cfg(test)]
1353fn injected_operation_failure(operation: FailureOperation) -> Option<NecoFailure> {
1354    INJECTED_OPERATION_FAILURE.with(|configured| {
1355        let failure = configured.take()?;
1356        let location = FailureLocation::operation(operation);
1357        Some(match failure {
1358            InjectedOperationFailure::InvalidIsolation => map_eval_failure(
1359                location,
1360                crate::EvalError::Algnum(neco_algnum::AlgnumError::InvalidIsolation),
1361            ),
1362            InjectedOperationFailure::MultipleTargetRoots => map_eval_failure(
1363                location,
1364                crate::EvalError::Algnum(neco_algnum::AlgnumError::MultipleTargetRoots),
1365            ),
1366            InjectedOperationFailure::MissingAssignment(consumer) => {
1367                map_resolve_failure(location, ResolveError::MissingAssignment { consumer })
1368            }
1369            InjectedOperationFailure::FloatOutOfRange(consumer, expr) => {
1370                map_resolve_failure(location, ResolveError::FloatOutOfRange { consumer, expr })
1371            }
1372        })
1373    })
1374}
1375
1376#[cfg(test)]
1377fn with_injected_operation_failure<R>(
1378    failure: InjectedOperationFailure,
1379    operation: impl FnOnce() -> R,
1380) -> R {
1381    INJECTED_OPERATION_FAILURE.with(|configured| configured.set(Some(failure)));
1382    let result = operation();
1383    INJECTED_OPERATION_FAILURE.with(|configured| configured.set(None));
1384    result
1385}
1386
1387#[cfg(test)]
1388mod proof_vectors {
1389    use alloc::vec;
1390
1391    use neco_monomial::Monomial;
1392
1393    use super::*;
1394    use crate::storage::{with_injected_failure, InjectedFailure};
1395    use crate::{AtomId, ExactValue, ExprNode, StorageError, StorageFailurePayload};
1396
1397    const OPERATIONS: [ExactOperation; 8] = [
1398        ExactOperation::NormalizeMonomial,
1399        ExactOperation::NormalizeFormSum,
1400        ExactOperation::NormalizeAlgebraic,
1401        ExactOperation::DecideZero,
1402        ExactOperation::DecideEquality,
1403        ExactOperation::DecideSign,
1404        ExactOperation::DecideDegeneracy,
1405        ExactOperation::ResolveCertifiedF64,
1406    ];
1407
1408    fn domain(atom: Option<ExactValue>) -> (ExprGraph, AtomStore, ExprId) {
1409        let mut graph = ExprGraph::new();
1410        let expr = graph.push(ExprNode::Atom(AtomId::new(0))).unwrap();
1411        let mut atoms = AtomStore::new();
1412        if let Some(value) = atom {
1413            atoms.insert(AtomId::new(0), value).unwrap();
1414        }
1415        (graph, atoms, expr)
1416    }
1417
1418    fn requirement(consumer: u32, expr: ExprId) -> ExactExpressionRequirement {
1419        ExactExpressionRequirement::new(
1420            ConsumerId::new(consumer),
1421            &[expr],
1422            ExactDecisionRequest::Zero(expr),
1423            AbsoluteBits::new(20),
1424        )
1425        .unwrap()
1426    }
1427
1428    fn input_with_domain(graph: ExprGraph, atoms: AtomStore, expr: ExprId) -> ExactAllocationInput {
1429        let mfp = MfpCoreProduct::new(graph, atoms, vec![requirement(0, expr)], vec![]).unwrap();
1430        let (wavesim_graph, wavesim_atoms, _) = domain(Some(ExactValue::Monomial(Monomial::one())));
1431        let wavesim =
1432            WavesimDddCoreProduct::new(wavesim_graph, wavesim_atoms, vec![], vec![]).unwrap();
1433        ExactAllocationInput::new(
1434            mfp,
1435            wavesim,
1436            NecoObservedCapability::current(&OPERATIONS).unwrap(),
1437            NecoImplementationSource::current(),
1438        )
1439    }
1440
1441    fn allocated_with_value(value: Option<ExactValue>) -> AllocatedExactNumericContext {
1442        let (graph, atoms, expr) = domain(value);
1443        allocate_exact_numeric(
1444            read_exact_numeric_inputs(input_with_domain(graph, atoms, expr)).unwrap(),
1445        )
1446        .unwrap()
1447    }
1448
1449    fn normalized() -> NormalizedExactNumericContext {
1450        normalize_exact_expressions(allocated_with_value(Some(ExactValue::Monomial(
1451            Monomial::one(),
1452        ))))
1453        .unwrap()
1454    }
1455
1456    fn decided() -> DecidedExactNumericContext {
1457        decide_exact_properties(normalized()).unwrap()
1458    }
1459
1460    #[test]
1461    fn allocation_storage_failure_preserves_operation_location_and_payload() {
1462        let (graph, atoms, expr) = domain(Some(ExactValue::Monomial(Monomial::one())));
1463        let input = read_exact_numeric_inputs(input_with_domain(graph, atoms, expr)).unwrap();
1464        let result = with_injected_failure(
1465            StorageResource::ProductEntries,
1466            InjectedFailure::Allocation,
1467            || allocate_exact_numeric(input),
1468        );
1469        assert_eq!(
1470            result,
1471            Err(NecoFailure::StorageFailure {
1472                location: FailureLocation::operation(FailureOperation::Allocate),
1473                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1474                    resource: StorageResource::ProductEntries,
1475                    requested_elements: 1,
1476                }),
1477            })
1478        );
1479    }
1480
1481    #[test]
1482    fn normalize_operation_failure_vectors_are_executable() {
1483        let (graph, atoms, expr) = domain(None);
1484        let unknown_atom = normalize_exact_expressions(
1485            allocate_exact_numeric(
1486                read_exact_numeric_inputs(input_with_domain(graph, atoms, expr)).unwrap(),
1487            )
1488            .unwrap(),
1489        );
1490        assert!(matches!(
1491            unknown_atom,
1492            Err(NecoFailure::UnknownAtom { location })
1493                if location.operation_kind() == FailureOperation::Normalize
1494                    && location.expr() == Some(expr)
1495                    && location.atom() == Some(AtomId::new(0))
1496        ));
1497
1498        let mut malformed = allocated_with_value(Some(ExactValue::Monomial(Monomial::one())));
1499        malformed.input.mfp_core.requirements[0].expressions[0] = ExprId::new(99);
1500        assert!(matches!(
1501            normalize_exact_expressions(malformed),
1502            Err(NecoFailure::UnknownExpression { location })
1503                if location.operation_kind() == FailureOperation::Normalize
1504                    && location.expr() == Some(ExprId::new(99))
1505        ));
1506
1507        let mut graph = ExprGraph::new();
1508        let zero = graph.push(ExprNode::Atom(AtomId::new(0))).unwrap();
1509        let division = graph.push(ExprNode::Div(zero, zero)).unwrap();
1510        let mut atoms = AtomStore::new();
1511        atoms
1512            .insert(AtomId::new(0), ExactValue::Monomial(Monomial::zero()))
1513            .unwrap();
1514        assert!(matches!(
1515            normalize_exact_expressions(
1516                allocate_exact_numeric(
1517                    read_exact_numeric_inputs(input_with_domain(graph, atoms, division)).unwrap(),
1518                )
1519                .unwrap(),
1520            ),
1521            Err(NecoFailure::DivisionByZero { location })
1522                if location.operation_kind() == FailureOperation::Normalize
1523        ));
1524
1525        let mut graph = ExprGraph::new();
1526        let zero = graph.push(ExprNode::Atom(AtomId::new(0))).unwrap();
1527        let power = graph
1528            .push(ExprNode::Pow {
1529                base: zero,
1530                exponent: neco_bigint::ReducedRational::from_bigint(neco_bigint::BigInt::zero())
1531                    .unwrap(),
1532            })
1533            .unwrap();
1534        let mut atoms = AtomStore::new();
1535        atoms
1536            .insert(AtomId::new(0), ExactValue::Monomial(Monomial::zero()))
1537            .unwrap();
1538        assert!(matches!(
1539            normalize_exact_expressions(
1540                allocate_exact_numeric(
1541                    read_exact_numeric_inputs(input_with_domain(graph, atoms, power)).unwrap(),
1542                )
1543                .unwrap(),
1544            ),
1545            Err(NecoFailure::UndefinedPower { location })
1546                if location.operation_kind() == FailureOperation::Normalize
1547        ));
1548
1549        let invalid_isolation =
1550            with_injected_operation_failure(InjectedOperationFailure::InvalidIsolation, || {
1551                normalize_exact_expressions(allocated_with_value(Some(ExactValue::Monomial(
1552                    Monomial::one(),
1553                ))))
1554            });
1555        assert!(matches!(
1556            invalid_isolation,
1557            Err(NecoFailure::InvalidIsolation { location })
1558                if location.operation_kind() == FailureOperation::Normalize
1559        ));
1560
1561        let storage = with_injected_failure(
1562            StorageResource::EvaluationEntries,
1563            InjectedFailure::Allocation,
1564            || {
1565                normalize_exact_expressions(allocated_with_value(Some(ExactValue::Monomial(
1566                    Monomial::one(),
1567                ))))
1568            },
1569        );
1570        assert!(matches!(
1571            storage,
1572            Err(NecoFailure::StorageFailure {
1573                location,
1574                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1575                    resource: StorageResource::EvaluationEntries,
1576                    ..
1577                }),
1578            }) if location.operation_kind() == FailureOperation::Normalize
1579        ));
1580    }
1581
1582    #[test]
1583    fn decide_operation_failure_vectors_are_executable() {
1584        let invalid_input = normalized();
1585        let invalid =
1586            with_injected_operation_failure(InjectedOperationFailure::InvalidIsolation, || {
1587                decide_exact_properties(invalid_input)
1588            });
1589        assert!(matches!(
1590            invalid,
1591            Err(NecoFailure::InvalidIsolation { location })
1592                if location.operation_kind() == FailureOperation::Decide
1593        ));
1594        let multiple_input = normalized();
1595        let multiple =
1596            with_injected_operation_failure(InjectedOperationFailure::MultipleTargetRoots, || {
1597                decide_exact_properties(multiple_input)
1598            });
1599        assert!(matches!(
1600            multiple,
1601            Err(NecoFailure::MultipleTargetRoots { location })
1602                if location.operation_kind() == FailureOperation::Decide
1603        ));
1604        let storage_input = normalized();
1605        let storage = with_injected_failure(
1606            StorageResource::ProductEntries,
1607            InjectedFailure::Allocation,
1608            || decide_exact_properties(storage_input),
1609        );
1610        assert!(matches!(
1611            storage,
1612            Err(NecoFailure::StorageFailure {
1613                location,
1614                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1615                    resource: StorageResource::ProductEntries,
1616                    ..
1617                }),
1618            }) if location.operation_kind() == FailureOperation::Decide
1619        ));
1620    }
1621
1622    #[test]
1623    fn resolve_operation_failure_vectors_are_executable() {
1624        let consumer = ConsumerId::new(7);
1625        let missing_input = decided();
1626        let missing = with_injected_operation_failure(
1627            InjectedOperationFailure::MissingAssignment(consumer),
1628            || resolve_certified_f64(missing_input),
1629        );
1630        assert!(matches!(
1631            missing,
1632            Err(NecoFailure::MissingAssignment { location })
1633                if location.operation_kind() == FailureOperation::Resolve
1634                    && location.consumer() == Some(consumer)
1635        ));
1636        let expr = ExprId::new(3);
1637        let out_of_range_input = decided();
1638        let out_of_range = with_injected_operation_failure(
1639            InjectedOperationFailure::FloatOutOfRange(consumer, expr),
1640            || resolve_certified_f64(out_of_range_input),
1641        );
1642        assert!(matches!(
1643            out_of_range,
1644            Err(NecoFailure::FloatOutOfRange { location })
1645                if location.operation_kind() == FailureOperation::Resolve
1646                    && location.consumer() == Some(consumer)
1647                    && location.expr() == Some(expr)
1648        ));
1649        let storage = with_injected_failure(
1650            StorageResource::ProductResolutionEntries,
1651            InjectedFailure::Allocation,
1652            || resolve_certified_f64(decided()),
1653        );
1654        assert!(matches!(
1655            storage,
1656            Err(NecoFailure::StorageFailure {
1657                location,
1658                payload: StorageFailurePayload::Storage(StorageError::AllocationFailure {
1659                    resource: StorageResource::ProductResolutionEntries,
1660                    ..
1661                }),
1662            }) if location.operation_kind() == FailureOperation::Resolve
1663        ));
1664    }
1665
1666    #[test]
1667    fn missing_domain_assembly_returns_failure_without_partial_product() {
1668        let mut resolved = resolve_certified_f64(decided()).unwrap();
1669        resolved.certified_descents.clear();
1670        let result = assemble_exact_computation_product(resolved);
1671        assert!(matches!(
1672            result,
1673            Err(NecoFailure::MissingAssignment { location })
1674                if location.operation_kind() == FailureOperation::Assemble
1675        ));
1676    }
1677}