Skip to main content

earthsci_ast/simulate/
errors.rs

1use super::*;
2
3// ============================================================================
4// Errors
5// ============================================================================
6
7// `CompileError` is defined in the non-gated `crate::compile_error` module so
8// the WASM-compiled `faq` / `join` passes can name it; re-exported here
9// to preserve the native `crate::simulate::CompileError` path.
10pub use crate::compile_error::CompileError;
11
12/// Errors raised building an [`crate::problem::EsmProblem`] or running
13/// [`crate::problem::solve`].
14#[derive(Error, Debug)]
15pub enum SimulateError {
16    /// Wraps a CompileError raised by [`crate::problem::esm_problem`]
17    /// before solving even starts.
18    #[error("Compile failed: {0}")]
19    Compile(#[from] CompileError),
20
21    /// diffsol returned a solver-internal error (build failure, step failure,
22    /// etc.).
23    #[error("diffsol error: {details}")]
24    DiffsolError {
25        /// The underlying diffsol error message.
26        details: String,
27    },
28
29    /// The integrator could not satisfy the requested tolerances.
30    #[error("Tolerance not met")]
31    ToleranceNotMet,
32
33    /// [`crate::problem::solve`] was called on a EsmProblem whose document
34    /// declares no differential equations, so there is nothing to integrate.
35    /// Its build-time products are still readable with
36    /// [`crate::problem::observed_field`].
37    #[error("Nothing to integrate: {details}")]
38    NotDynamic {
39        /// Why the EsmProblem carries no integrable right-hand side.
40        details: String,
41    },
42
43    /// [`crate::problem::ProblemOptions::compiler`] named a value that is in
44    /// API_SPEC §5.8's closed vocabulary but that this binding, this build or
45    /// this process cannot provide (esm-spec §9.6.6 `compiler_unavailable`).
46    ///
47    /// Never answered by building with a different compiler: the whole point
48    /// of naming one is that the caller knows which ran. `details` names what
49    /// would have to be loaded or built.
50    #[error(
51        "{code}: compiler '{compiler}' is not available here: {details}",
52        code = crate::diagnostic::codes::COMPILER_UNAVAILABLE
53    )]
54    CompilerUnavailable {
55        /// The vocabulary spelling the caller asked for.
56        compiler: &'static str,
57        /// What would have to be loaded or built to provide it.
58        details: String,
59    },
60
61    /// A range-restricted or operator-restricted right-hand side (API_SPEC
62    /// §5.8: `select`, `halo`, `tile`, `lanes`) was refused. `code` is one of
63    /// `range_halo_insufficient`, `range_global_locality`,
64    /// `range_selection_writes_incomplete` or `range_box_invalid`, and
65    /// `message` names the rule, variable and axis involved.
66    #[error("{code}: {message}")]
67    RangeRestriction {
68        /// The diagnostic code.
69        code: &'static str,
70        /// What was refused, naming the rule, variable and axis.
71        message: String,
72    },
73
74    /// A DATA-FED parameter — one whose `update` is `kind: "data"` (esm-spec
75    /// §5.4, §8.5) — reached a build with NOTHING bound to it: no provider,
76    /// no loaded array, and no caller-supplied `p` value (esm-spec §9.6.6
77    /// `data_source_unbound`, CONFORMANCE_SPEC §5.46).
78    ///
79    /// Raised at CONSTRUCTION, before any right-hand side is built, so the
80    /// answer does not depend on the compiler: this asks whether the
81    /// DOCUMENT's inputs are bound, not what a compiler can lower. A compiler
82    /// that additionally cannot lower a read of the forcing channel reports
83    /// that separately as [`CompileError::CompilerRefusedRule`](crate::CompileError::CompilerRefusedRule).
84    ///
85    /// Refused rather than evaluated at the parameter's `default`, which is
86    /// not a fallback value but a placeholder: a forcing at its default
87    /// integrates to a complete, smooth trajectory reported under the label of
88    /// a quantity the document says is read from a file.
89    #[error(
90        "{code}: parameter '{parameter}' is fed by the data source '{data_source}' (an `update` of kind \"data\"), and nothing bound it: no provider, no loaded array, and no `p` value. Pass a `providers` entry for '{parameter}' to supply the data, or `p` to pin a value. The build will not fall back to the parameter's `default`: a forcing at its default produces a whole trajectory that looks like an answer",
91        code = crate::diagnostic::codes::DATA_SOURCE_UNBOUND
92    )]
93    DataSourceUnbound {
94        /// The flattened parameter nothing bound.
95        parameter: String,
96        /// The `data_sources` key its `update` names. Spelled `data_source`
97        /// rather than `source`, which `thiserror` reserves for an error's
98        /// CAUSE — a `String` cannot be one.
99        data_source: String,
100    },
101
102    /// A build progress observer asked [`crate::problem::esm_problem`] to
103    /// stop (returned [`Flow::Cancel`]).
104    ///
105    /// Distinct from every other variant in that nothing went wrong: it is the
106    /// caller's own decision. It stays an ERROR — unlike a cancelled *solve*,
107    /// which is [`ReturnCode::Terminated`] with a partial trajectory — because a
108    /// half-built EsmProblem is not a usable result.
109    #[error("Cancelled by the caller during the build: {details}")]
110    Cancelled {
111        /// The phase and item the build stopped at.
112        details: String,
113    },
114
115    /// [`crate::problem::remake`] was asked to substitute a binding the
116    /// EsmProblem cannot honour without redoing part of construction.
117    ///
118    /// Raised rather than silently rebuilding or silently ignoring the
119    /// substitution (`esm-libraries-spec.md` §2.5.5): the name and the class
120    /// that makes it un-substitutable are both reported so the caller knows to
121    /// build a fresh EsmProblem instead.
122    #[error("Cannot remake '{name}': {class}")]
123    UnsubstitutableBinding {
124        /// The binding the caller tried to substitute.
125        name: String,
126        /// The class that makes it un-substitutable.
127        class: String,
128    },
129
130    /// The caller supplied a time span whose start or end is not a finite
131    /// number — `NaN`, `+∞` or `−∞`.
132    ///
133    /// A document cannot spell one: the schema's `TimeSpan` bounds are JSON
134    /// numbers, and esm-spec §6.6.4 records that "JSON has no infinite
135    /// literal". So this is a caller-supplied argument of a solve,
136    /// validated alongside the parameter and initial-condition maps of the same
137    /// call.
138    ///
139    /// Refused rather than interpreted. Every ordering test against `NaN` is
140    /// false, so a `NaN` endpoint reads as a run that cannot advance and would
141    /// hand back the initial state as though it were a trajectory; an infinite
142    /// end gives the solver loop a stop time it can never reach.
143    #[error("Invalid time span ({start}, {end}): start and end must both be finite")]
144    InvalidTimeSpan {
145        /// The requested start of the interval.
146        start: f64,
147        /// The requested end of the interval.
148        end: f64,
149    },
150
151    /// The user supplied a parameter name that does not appear in the
152    /// flattened system.
153    #[error("Invalid parameter '{name}'")]
154    InvalidParameter {
155        /// The unknown parameter name.
156        name: String,
157    },
158
159    /// The user supplied a key that two or more of the flattened system's
160    /// parameters carry as a DOTTED SUFFIX — a shared local name (`gain` for
161    /// `Left.gain` and `Right.gain`) or a shared partial qualification
162    /// (`sub.g` for `Left.sub.g` and `Right.sub.g`), esm-spec §6.6.2 rule 4.
163    /// Distinct from [`SimulateError::InvalidParameter`]: the name exists, it
164    /// just does not identify ONE parameter, and binding it to either
165    /// candidate would be a wrong answer rather than a missing one.
166    #[error(
167        "Ambiguous parameter '{name}': carried as a suffix by {candidates:?} — qualify it further with its owning component"
168    )]
169    AmbiguousParameter {
170        /// The ambiguous local or partially qualified name.
171        name: String,
172        /// The qualified parameters that carry it.
173        candidates: Vec<String>,
174    },
175
176    /// Two or more NON-EXACT `parameter_overrides` keys designate the one
177    /// flattened parameter (esm-spec §6.6.2): a bare local spelling and a
178    /// more-qualified one (`solo` and `Doc.Left.solo` both landing on
179    /// `Left.solo`), or two more-qualified ones (`A.M.g` and `B.M.g` both
180    /// landing on `M.g`). The caller wrote two overrides and only one can take
181    /// effect, so picking a winner would be a wrong answer rather than a
182    /// missing one. An EXACT key is never part of a collision — it identifies
183    /// its parameter outright and wins over any suffix or bare claim on it.
184    #[error(
185        "parameter_overrides: {} keys designate the parameter '{name}' ({}). Supply exactly one override key per name (esm-spec §6.6.2).",
186        .keys.len(), .keys.join(", ")
187    )]
188    CollidingParameterKeys {
189        /// The flattened parameter every colliding key designates.
190        name: String,
191        /// The colliding keys, sorted.
192        keys: Vec<String>,
193    },
194
195    /// The user supplied an initial condition for a name that is not a state
196    /// variable, or a state variable has no initial value (no entry in
197    /// `initial_conditions` and no `default` on the `ModelVariable`).
198    #[error("Invalid initial condition '{name}'")]
199    InvalidInitialCondition {
200        /// The variable name.
201        name: String,
202    },
203
204    /// The user supplied a key that two or more of the flattened system's
205    /// states carry as a DOTTED SUFFIX (esm-spec §6.6.2 rule 4). The
206    /// state-side counterpart of [`SimulateError::AmbiguousParameter`].
207    #[error(
208        "Ambiguous initial condition '{name}': carried as a suffix by {candidates:?} — qualify it further with its owning component"
209    )]
210    AmbiguousInitialCondition {
211        /// The ambiguous local or partially qualified name.
212        name: String,
213        /// The qualified states that carry it.
214        candidates: Vec<String>,
215    },
216
217    /// Two or more NON-EXACT `initial_conditions` keys designate the one state
218    /// element (esm-spec §6.6.2). The state-side counterpart of
219    /// [`SimulateError::CollidingParameterKeys`].
220    #[error(
221        "initial_conditions: {} keys designate the state '{name}' ({}). Supply exactly one override key per name (esm-spec §6.6.2).",
222        .keys.len(), .keys.join(", ")
223    )]
224    CollidingInitialConditionKeys {
225        /// The state element every colliding key designates.
226        name: String,
227        /// The colliding keys, sorted.
228        keys: Vec<String>,
229    },
230
231    /// An `ic(target)` field initial condition could not be resolved to a
232    /// per-cell value. Carries the `ic(...)` target state name plus a
233    /// diagnostic saying why (wrong field rank, unresolvable RHS, ...), so
234    /// the name field stays a plain identifier.
235    #[error("Invalid field initial condition for '{name}': {details}")]
236    InvalidFieldInitialCondition {
237        /// The `ic(...)` target state name.
238        name: String,
239        /// Why the initial condition could not be resolved.
240        details: String,
241    },
242
243    /// A data provider bound in [`crate::problem::ProblemOptions`] failed to
244    /// materialize its loader field, or produced the wrong number of fields for
245    /// its target forcing variable.
246    #[error("Provider for '{name}': {details}")]
247    ProviderError {
248        /// The forcing variable the provider was bound to.
249        name: String,
250        /// What went wrong.
251        details: String,
252    },
253}
254
255impl SimulateError {
256    /// Whether this is a build progress observer's own [`Flow::Cancel`] rather
257    /// than something going wrong — the counterpart of reading
258    /// [`ReturnCode::Terminated`] off a [`Solution`].
259    pub fn is_cancelled(&self) -> bool {
260        matches!(self, SimulateError::Cancelled { .. })
261    }
262}