Skip to main content

aion/
error.rs

1//! Engine error taxonomy.
2
3use crate::schedule::{ScheduleError, ScheduleEvaluatorError};
4use aion_core::{RunId, ScheduleId, WorkflowId};
5use aion_package::{ContentHash, ContractIdentityError, PackageError};
6use aion_store::StoreError;
7
8use crate::durability::DurabilityError;
9
10/// Errors returned by the embedded workflow engine.
11#[derive(thiserror::Error, Debug)]
12pub enum EngineError {
13    /// The builder was asked to construct an engine without an event store.
14    #[error("engine store is required")]
15    MissingStore,
16
17    /// The builder was asked to construct an engine without a visibility store.
18    #[error(
19        "engine visibility store is required; call EngineBuilder::visibility_store() or EngineBuilder::in_memory_visibility()"
20    )]
21    MissingVisibilityStore,
22
23    /// A workflow package failed to load or validate for engine registration.
24    #[error("workflow package load failed: {reason}")]
25    Load {
26        /// Human-readable load failure reason.
27        reason: String,
28    },
29
30    /// A package offered for deployment declares a contract the engine cannot
31    /// enforce: at least one declared schema does not compile into a validator.
32    ///
33    /// Refused at the door rather than admitted, because the alternative is
34    /// silent: every admission boundary answers an uncompilable schema by
35    /// letting the value through unchecked, so a package that reaches the
36    /// catalog with one runs with that part of its declared contract switched
37    /// off and only a log line to say so.
38    #[error(
39        "workflow package `{workflow_type}` declares {count} type(s) the engine cannot compile into a validator, so nothing it declares there could ever be enforced: {detail}"
40    )]
41    UnenforceableContract {
42        /// Logical workflow type of the refused package.
43        workflow_type: String,
44        /// How many declarations could not be compiled.
45        count: usize,
46        /// Each unenforceable declaration, named, with the compiler's reason.
47        detail: String,
48    },
49
50    /// A route or unload targeted a `(workflow type, version)` that is not loaded.
51    #[error(
52        "workflow `{workflow_type}` version `{version}` is not loaded (loaded versions: {loaded})"
53    )]
54    UnknownVersion {
55        /// Logical workflow type requested by the caller.
56        workflow_type: String,
57        /// Content-hash version requested by the caller.
58        version: ContentHash,
59        /// Comma-separated loaded versions of the type, or `none`.
60        loaded: String,
61    },
62
63    /// An unload was refused because something still pins the version.
64    #[error("cannot unload workflow `{workflow_type}` version `{version}`: {pinned_by}")]
65    VersionPinned {
66        /// Logical workflow type targeted by the unload.
67        workflow_type: String,
68        /// Content-hash version targeted by the unload.
69        version: ContentHash,
70        /// What pins the version, naming the concrete holder.
71        pinned_by: PinHolder,
72    },
73
74    /// An unload was refused because the version is route-active for its type.
75    #[error(
76        "cannot unload workflow `{workflow_type}` version `{version}`: it is the route-active version; route another version first"
77    )]
78    RouteActive {
79        /// Logical workflow type targeted by the unload.
80        workflow_type: String,
81        /// Content-hash version targeted by the unload.
82        version: ContentHash,
83    },
84
85    /// An idempotent re-load presented the resident package identity with a
86    /// different manifest. V4 binds beams and the durable execution contract,
87    /// but not every packaging/admin field, so this remains the wrong-deploy
88    /// tripwire: the resident version is retained and the archive is refused.
89    #[error(
90        "workflow `{workflow_type}` version `{version}` is already loaded with a different manifest (resident digest {resident_digest}, incoming digest {incoming_digest}); rebuild the archive so its complete manifest matches the resident version, or change its contract-bound content"
91    )]
92    ManifestMismatch {
93        /// Logical workflow type targeted by the load.
94        workflow_type: String,
95        /// Content-hash version shared by both archives.
96        version: ContentHash,
97        /// Canonical digest of the resident manifest.
98        resident_digest: String,
99        /// Canonical digest of the incoming manifest.
100        incoming_digest: String,
101    },
102
103    /// The builder was given both `event_streaming` and an explicit event-publisher seam.
104    #[error(
105        "conflicting event publisher configuration: EngineBuilder::event_streaming installs the broadcast publisher and cannot be combined with EngineBuilder::event_publisher"
106    )]
107    ConflictingEventPublisher,
108
109    /// Live event streaming setup failed.
110    #[error("event streaming setup failed: {0}")]
111    EventStreaming(#[from] crate::publish::PublishError),
112
113    /// The configured event store returned an error.
114    #[error("store error: {0}")]
115    Store(#[from] StoreError),
116
117    /// The durability recorder or replay path returned an error.
118    #[error("durability error: {0}")]
119    Durability(#[from] DurabilityError),
120
121    /// A `.aion` package operation returned an error.
122    #[error("package error: {0}")]
123    Package(#[from] PackageError),
124
125    /// The selected package identity predates the `.v4` contract commitment.
126    #[error("workflow `{workflow_type}` cannot start: {source}")]
127    ContractIdentity {
128        /// Workflow type selected for the start.
129        workflow_type: String,
130        /// Typed migration refusal from the package identity boundary.
131        #[source]
132        source: ContractIdentityError,
133    },
134
135    /// The package names activities without a durable queue-scoped contract.
136    #[error(
137        "NO_QUEUE_DECLARATION: workflow `{workflow_type}` version `{version}` has unscoped activities {activities}; re-deploy from a checked AWL contract"
138    )]
139    NoQueueDeclaration {
140        /// Workflow type selected for the start.
141        workflow_type: String,
142        /// Exact `.v4` package identity selected for the run.
143        version: ContentHash,
144        /// Stable comma-separated unscoped activity names.
145        activities: String,
146    },
147
148    /// A start's input did not satisfy the declared input schema of the exact
149    /// package identity the start resolved to.
150    ///
151    /// Returned at the start boundary BEFORE any history is appended and
152    /// before any process is spawned, so a refused start leaves no trace: the
153    /// caller sees their own mistake at the moment they made it, with nothing
154    /// to clean up.
155    #[error(
156        "start input for workflow `{workflow_type}` does not satisfy the input type declared by package version `{version}`: {reason}"
157    )]
158    StartInputRefused {
159        /// Workflow type selected for the start.
160        workflow_type: String,
161        /// Exact `.v4` package identity the start resolved to.
162        version: ContentHash,
163        /// What did not match, naming every field that failed.
164        reason: String,
165    },
166
167    /// A signal was refused at the boundary: its name is not declared by the
168    /// target run's package, or its payload did not satisfy the declared
169    /// payload type.
170    ///
171    /// Returned BEFORE anything is recorded and before the arrival can be
172    /// consumed, so the target run's history is unchanged and it stays parked
173    /// on exactly the wait it was parked on. That ordering is the whole point:
174    /// a signal decoded after being consumed destroys a durable run that a
175    /// refusal merely inconveniences.
176    #[error(
177        "signal `{signal_name}` was refused for workflow `{workflow_id}` run `{run_id}` against the contract declared by package version `{version}`: {reason}"
178    )]
179    SignalRefused {
180        /// Workflow execution the signal targeted.
181        workflow_id: WorkflowId,
182        /// Concrete run the signal targeted.
183        run_id: RunId,
184        /// Signal name the caller sent.
185        signal_name: String,
186        /// Exact `.v4` package identity the target run is pinned to.
187        version: ContentHash,
188        /// Why the signal was refused — an undeclared name, or the fields of
189        /// the payload that did not match the declared type.
190        reason: String,
191    },
192
193    /// The embedded runtime returned an error.
194    #[error("runtime error: {reason}")]
195    Runtime {
196        /// Human-readable runtime failure reason.
197        reason: String,
198    },
199
200    /// A Gate-3 BIF required for tracked local fun spawns was not registered.
201    #[error("required Gate-3 BIF `{module}:{function}/{arity}` was missing during runtime startup")]
202    Gate3BifReplacementMissing {
203        /// Native module containing the required function.
204        module: String,
205        /// Required native function.
206        function: String,
207        /// Required native function arity.
208        arity: u8,
209    },
210
211    /// The runtime-owned cleanup executor's ownership state was poisoned.
212    #[error("process cleanup executor state was poisoned")]
213    CleanupExecutorPoisoned,
214
215    /// The runtime cleanup worker did not stop within the configured bound.
216    #[error("process cleanup executor did not stop within {timeout_millis}ms")]
217    CleanupExecutorShutdownTimedOut {
218        /// Configured shutdown observation bound in milliseconds.
219        timeout_millis: u128,
220    },
221
222    /// The process-exit registry lifecycle lock was poisoned.
223    #[error("process exit registry lifecycle state was poisoned")]
224    ProcessExitRegistryPoisoned,
225
226    /// A process exit record's installation/abort ownership gate was poisoned.
227    #[error("process exit ownership gate for process {process_id} was poisoned")]
228    ProcessExitOwnershipPoisoned {
229        /// Process whose monitor/abort ownership could not be serialized.
230        process_id: u64,
231    },
232
233    /// A process exit record's fan-out state was poisoned.
234    #[error("process exit outcome state for process {process_id} was poisoned")]
235    ProcessExitStatePoisoned {
236        /// Process whose cached exit state could not be accessed.
237        process_id: u64,
238    },
239
240    /// The scheduler's one exit-event subscription was already claimed.
241    #[error("beamr process exit-event subscription is already owned")]
242    ProcessExitSubscriptionUnavailable,
243
244    /// The singleton process-exit drainer could not be spawned.
245    #[error("process exit drainer could not start: {reason}")]
246    ProcessExitDrainerSpawn {
247        /// Operating-system thread creation failure.
248        reason: String,
249    },
250
251    /// The singleton process-exit drainer's ownership lock was poisoned.
252    #[error("process exit drainer state was poisoned")]
253    ProcessExitDrainerPoisoned,
254
255    /// beamr published an exit event without the promised durable outcome.
256    #[error("process {process_id} exit event had no takeable outcome")]
257    ProcessExitOutcomeMissingAfterEvent {
258        /// Process named by the contract-breaking event.
259        process_id: u64,
260    },
261
262    /// beamr disconnected its event publisher while the runtime still owned it.
263    #[error("beamr process exit-event publisher disconnected")]
264    ProcessExitEventStreamDisconnected,
265
266    /// The process-exit drainer did not stop within the configured bound.
267    #[error("process exit drainer did not stop within {timeout_millis}ms")]
268    ProcessExitDrainerShutdownTimedOut {
269        /// Configured shutdown observation bound in milliseconds.
270        timeout_millis: u128,
271    },
272
273    /// The process-exit drainer thread panicked.
274    #[error("process exit drainer terminated unexpectedly")]
275    ProcessExitDrainerPanicked,
276
277    /// The process-exit callback dispatcher's ownership state was poisoned.
278    #[error("process exit callback dispatcher state was poisoned")]
279    ProcessExitCallbackDispatcherPoisoned,
280
281    /// The process-exit callback dispatcher had already stopped.
282    #[error("process exit callback dispatcher is unavailable")]
283    ProcessExitCallbackDispatcherUnavailable,
284
285    /// The process-exit callback dispatcher did not stop within its configured bound.
286    #[error("process exit callback dispatcher did not stop within {timeout_millis}ms")]
287    ProcessExitCallbackDispatcherShutdownTimedOut {
288        /// Configured shutdown observation bound in milliseconds.
289        timeout_millis: u128,
290    },
291
292    /// A retired process generation cannot accept another outcome consumer.
293    #[error("process {process_id} already reached its terminal runtime outcome")]
294    ProcessExitAlreadyTerminal {
295        /// Process generation whose heavyweight exit record was retired.
296        process_id: u64,
297    },
298
299    /// A workflow's activity-delivery synchronization lock was poisoned.
300    #[error("activity delivery lock for process {process_id} was poisoned")]
301    ActivityDeliveryPoisoned {
302        /// Workflow process whose scoped delivery lock was poisoned.
303        process_id: u64,
304    },
305
306    /// The active workflow registry lock was poisoned.
307    #[error("active workflow registry lock was poisoned")]
308    RegistryPoisoned,
309
310    /// The workflow catalog lock was poisoned.
311    #[error("workflow catalog lock was poisoned")]
312    CatalogPoisoned,
313
314    /// A precondition on the target workflow's current state was not met.
315    ///
316    /// Raised by the reopen operation when the target run is not in a reopenable
317    /// state: not terminal, terminal for a non-reopenable reason
318    /// (Completed/`TimedOut`), or already Running. The `reason` names the actual
319    /// status so callers and operators can see why the reopen was rejected. Maps
320    /// to the `INVALID_STATE` wire code (gRPC `FailedPrecondition` / HTTP 409).
321    #[error("invalid workflow state: {reason}")]
322    InvalidState {
323        /// Human-readable precondition-failure reason naming the actual status.
324        reason: String,
325    },
326
327    /// The engine is already shutting down and no new workflow starts are accepted.
328    #[error("engine is shutting down")]
329    ShuttingDown,
330
331    /// No live, durable, or loaded workflow was found for the request.
332    #[error("workflow `{workflow_type}` was not found")]
333    WorkflowNotFound {
334        /// Logical workflow type requested by the caller.
335        workflow_type: String,
336    },
337
338    /// A terminal-writer reservation could not be taken because the workflow
339    /// already has a writer (#117(c)).
340    ///
341    /// The extraordinary cancellation path exists only for a run that can never
342    /// obtain a handle. A workflow that has one — or that another reservation is
343    /// already writing — is not that case, and taking a second writer would
344    /// break the single-writer invariant this refusal protects.
345    #[error("workflow `{workflow_id}` run `{run_id}` cannot take the terminal writer: {holder}")]
346    TerminalWriterUnavailable {
347        /// Workflow whose writer slot is occupied.
348        workflow_id: String,
349        /// Run the refused reservation named.
350        run_id: String,
351        /// What holds the slot, in the operator's terms.
352        holder: String,
353    },
354
355    /// A handle could not be registered because a terminal-writer reservation
356    /// holds this workflow's writer slot (#117(c)).
357    ///
358    /// The mirror of [`Self::TerminalWriterUnavailable`], and transient by
359    /// construction: a reservation lives only across one terminal transition.
360    #[error(
361        "workflow `{workflow_id}` cannot register a handle: run `{run_id}` holds the terminal writer"
362    )]
363    TerminalWriterHeld {
364        /// Workflow whose writer slot is reserved.
365        workflow_id: String,
366        /// Run holding the reservation.
367        run_id: String,
368    },
369
370    /// The extraordinary cancellation path was asked for a run whose pinned
371    /// package resolves right now, so the run is recoverable (#117(c)).
372    ///
373    /// Measured at the moment of the request, never cited from an earlier boot's
374    /// verdict: a redeploy between then and now is exactly the remedy that makes
375    /// the ordinary path work again, and the ordinary path must be used when it
376    /// does.
377    #[error(
378        "workflow `{workflow_id}` run `{run_id}` is recoverable: its pinned package version `{version}` resolves, so it must be recovered and cancelled through the ordinary path"
379    )]
380    RunIsRecoverable {
381        /// Workflow the request named.
382        workflow_id: String,
383        /// Run the request named.
384        run_id: String,
385        /// The pinned package version that resolved.
386        version: String,
387    },
388
389    /// A run holds no handle, cannot obtain one, and this engine has no recorded
390    /// reason why (#117(c)).
391    ///
392    /// Distinct from [`Self::WorkflowNotFound`] on purpose: the run EXISTS and
393    /// its history is readable. What is absent is a verdict from this process's
394    /// startup recovery, so the extraordinary cancellation path — which must
395    /// cite that verdict — has nothing to cite.
396    #[error(
397        "workflow `{workflow_id}` run `{run_id}` is not resident and this engine recorded no reason it could not be made resident; it exists but cannot be cancelled here"
398    )]
399    NoResidencyVerdict {
400        /// Workflow the request named.
401        workflow_id: String,
402        /// Run the request named.
403        run_id: String,
404    },
405
406    /// No durable schedule was found for the request.
407    #[error("schedule `{schedule_id}` was not found")]
408    ScheduleNotFound {
409        /// Schedule identifier requested by the caller.
410        schedule_id: ScheduleId,
411    },
412
413    /// Schedule trigger, projection, or evaluator side effect failed.
414    #[error("schedule error: {reason}")]
415    Schedule {
416        /// Human-readable schedule failure reason.
417        reason: String,
418    },
419
420    /// Native implemented function registration failed.
421    #[error("NIF registration failed: {reason}")]
422    NifRegistration {
423        /// Human-readable native implemented function registration failure reason.
424        reason: String,
425    },
426
427    /// Signal routing failed after the target was resolved.
428    #[error("signal router error: {0}")]
429    SignalRouter(#[from] SignalRouterError),
430
431    /// Live workflow query dispatch failed after the target was resolved.
432    #[error("query error: {0}")]
433    Query(#[from] crate::query::QueryError),
434}
435
436/// What pins a workflow version against unload, naming the concrete holder.
437#[derive(Debug, Clone, PartialEq, Eq)]
438pub enum PinHolder {
439    /// A start resolved this version but has not yet registered a handle.
440    InFlightStart,
441    /// A live, non-terminal run executes on this version.
442    LiveRun {
443        /// Pinning workflow id.
444        workflow_id: WorkflowId,
445        /// Pinning run id.
446        run_id: RunId,
447    },
448    /// A recoverable instance in the store is pinned to this version.
449    RecoverableRun {
450        /// Pinning workflow id.
451        workflow_id: WorkflowId,
452    },
453    /// A recorded-but-never-started child is pinned to this version.
454    RecordedChild {
455        /// Child workflow id pinned to the version.
456        child_workflow_id: WorkflowId,
457        /// Parent workflow whose history records the child.
458        recorded_by: WorkflowId,
459    },
460}
461
462impl std::fmt::Display for PinHolder {
463    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464        match self {
465            Self::InFlightStart => formatter.write_str("an in-flight start is pinned to it"),
466            Self::LiveRun {
467                workflow_id,
468                run_id,
469            } => write!(
470                formatter,
471                "live run `{workflow_id}/{run_id}` is pinned to it"
472            ),
473            Self::RecoverableRun { workflow_id } => {
474                write!(formatter, "recoverable run `{workflow_id}` is pinned to it")
475            }
476            Self::RecordedChild {
477                child_workflow_id,
478                recorded_by,
479            } => write!(
480                formatter,
481                "child `{child_workflow_id}` recorded by `{recorded_by}` is pinned to it and has not started"
482            ),
483        }
484    }
485}
486
487/// Errors surfaced by the signal routing boundary.
488#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
489pub enum SignalRouterError {
490    /// The target workflow is terminal and cannot receive new signals.
491    #[error("workflow {workflow_id}/{run_id} is terminal")]
492    Terminal {
493        /// Target workflow id.
494        workflow_id: WorkflowId,
495        /// Target run id.
496        run_id: RunId,
497    },
498
499    /// The router could not defer a recorded non-resident signal.
500    #[error("signal resume handoff failed: {reason}")]
501    Handoff {
502        /// Human-readable handoff failure reason.
503        reason: String,
504    },
505
506    /// The signal was durably recorded but could not be delivered to the live mailbox.
507    #[error(
508        "signal `{signal_name}` for workflow {workflow_id}/{run_id} could not be delivered to process {process_id}: {reason}"
509    )]
510    DeliveryFailed {
511        /// Target workflow id.
512        workflow_id: WorkflowId,
513        /// Target run id.
514        run_id: RunId,
515        /// Embedded runtime process identifier selected for delivery.
516        process_id: u64,
517        /// Signal name that was recorded and attempted.
518        signal_name: String,
519        /// Human-readable delivery failure reason.
520        reason: String,
521    },
522}
523
524impl From<ScheduleError> for EngineError {
525    fn from(error: ScheduleError) -> Self {
526        Self::Schedule {
527            reason: error.to_string(),
528        }
529    }
530}
531
532impl From<ScheduleEvaluatorError> for EngineError {
533    fn from(error: ScheduleEvaluatorError) -> Self {
534        match error {
535            ScheduleEvaluatorError::ScheduleNotFound { schedule_id } => {
536                Self::ScheduleNotFound { schedule_id }
537            }
538            other => Self::Schedule {
539                reason: other.to_string(),
540            },
541        }
542    }
543}