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    /// [`crate::Engine::run_startup_recovery`] was called on an engine whose
212    /// build was not deferred — `build()` already ran startup recovery, and
213    /// running it twice would re-dispatch every in-flight activity.
214    #[error(
215        "startup recovery was not deferred: EngineBuilder::build() already ran it \
216         (call defer_startup_recovery() on the builder to take ownership of the steps)"
217    )]
218    StartupRecoveryNotDeferred,
219
220    /// [`crate::Engine::run_startup_recovery`] was called a second time.
221    #[error("startup recovery already ran: run_startup_recovery() is one-shot")]
222    StartupRecoveryAlreadyRan,
223
224    /// The deferred-startup-recovery slot lock was poisoned.
225    #[error("deferred startup recovery slot was poisoned")]
226    StartupRecoverySlotPoisoned,
227
228    /// The runtime-owned cleanup executor's ownership state was poisoned.
229    #[error("process cleanup executor state was poisoned")]
230    CleanupExecutorPoisoned,
231
232    /// The runtime cleanup worker did not stop within the configured bound.
233    #[error("process cleanup executor did not stop within {timeout_millis}ms")]
234    CleanupExecutorShutdownTimedOut {
235        /// Configured shutdown observation bound in milliseconds.
236        timeout_millis: u128,
237    },
238
239    /// The process-exit registry lifecycle lock was poisoned.
240    #[error("process exit registry lifecycle state was poisoned")]
241    ProcessExitRegistryPoisoned,
242
243    /// A process exit record's installation/abort ownership gate was poisoned.
244    #[error("process exit ownership gate for process {process_id} was poisoned")]
245    ProcessExitOwnershipPoisoned {
246        /// Process whose monitor/abort ownership could not be serialized.
247        process_id: u64,
248    },
249
250    /// A process exit record's fan-out state was poisoned.
251    #[error("process exit outcome state for process {process_id} was poisoned")]
252    ProcessExitStatePoisoned {
253        /// Process whose cached exit state could not be accessed.
254        process_id: u64,
255    },
256
257    /// The scheduler's one exit-event subscription was already claimed.
258    #[error("beamr process exit-event subscription is already owned")]
259    ProcessExitSubscriptionUnavailable,
260
261    /// The singleton process-exit drainer could not be spawned.
262    #[error("process exit drainer could not start: {reason}")]
263    ProcessExitDrainerSpawn {
264        /// Operating-system thread creation failure.
265        reason: String,
266    },
267
268    /// The singleton process-exit drainer's ownership lock was poisoned.
269    #[error("process exit drainer state was poisoned")]
270    ProcessExitDrainerPoisoned,
271
272    /// beamr published an exit event without the promised durable outcome.
273    #[error("process {process_id} exit event had no takeable outcome")]
274    ProcessExitOutcomeMissingAfterEvent {
275        /// Process named by the contract-breaking event.
276        process_id: u64,
277    },
278
279    /// beamr disconnected its event publisher while the runtime still owned it.
280    #[error("beamr process exit-event publisher disconnected")]
281    ProcessExitEventStreamDisconnected,
282
283    /// The process-exit drainer did not stop within the configured bound.
284    #[error("process exit drainer did not stop within {timeout_millis}ms")]
285    ProcessExitDrainerShutdownTimedOut {
286        /// Configured shutdown observation bound in milliseconds.
287        timeout_millis: u128,
288    },
289
290    /// The process-exit drainer thread panicked.
291    #[error("process exit drainer terminated unexpectedly")]
292    ProcessExitDrainerPanicked,
293
294    /// The process-exit callback dispatcher's ownership state was poisoned.
295    #[error("process exit callback dispatcher state was poisoned")]
296    ProcessExitCallbackDispatcherPoisoned,
297
298    /// The process-exit callback dispatcher had already stopped.
299    #[error("process exit callback dispatcher is unavailable")]
300    ProcessExitCallbackDispatcherUnavailable,
301
302    /// The process-exit callback dispatcher did not stop within its configured bound.
303    #[error("process exit callback dispatcher did not stop within {timeout_millis}ms")]
304    ProcessExitCallbackDispatcherShutdownTimedOut {
305        /// Configured shutdown observation bound in milliseconds.
306        timeout_millis: u128,
307    },
308
309    /// A retired process generation cannot accept another outcome consumer.
310    #[error("process {process_id} already reached its terminal runtime outcome")]
311    ProcessExitAlreadyTerminal {
312        /// Process generation whose heavyweight exit record was retired.
313        process_id: u64,
314    },
315
316    /// A workflow's activity-delivery synchronization lock was poisoned.
317    #[error("activity delivery lock for process {process_id} was poisoned")]
318    ActivityDeliveryPoisoned {
319        /// Workflow process whose scoped delivery lock was poisoned.
320        process_id: u64,
321    },
322
323    /// The active workflow registry lock was poisoned.
324    #[error("active workflow registry lock was poisoned")]
325    RegistryPoisoned,
326
327    /// The workflow catalog lock was poisoned.
328    #[error("workflow catalog lock was poisoned")]
329    CatalogPoisoned,
330
331    /// A precondition on the target workflow's current state was not met.
332    ///
333    /// Raised by the reopen operation when the target run is not in a reopenable
334    /// state: not terminal, terminal for a non-reopenable reason
335    /// (Completed/`TimedOut`), or already Running. The `reason` names the actual
336    /// status so callers and operators can see why the reopen was rejected. Maps
337    /// to the `INVALID_STATE` wire code (gRPC `FailedPrecondition` / HTTP 409).
338    #[error("invalid workflow state: {reason}")]
339    InvalidState {
340        /// Human-readable precondition-failure reason naming the actual status.
341        reason: String,
342    },
343
344    /// The engine is already shutting down and no new workflow starts are accepted.
345    #[error("engine is shutting down")]
346    ShuttingDown,
347
348    /// No live, durable, or loaded workflow was found for the request.
349    #[error("workflow `{workflow_type}` was not found")]
350    WorkflowNotFound {
351        /// Logical workflow type requested by the caller.
352        workflow_type: String,
353    },
354
355    /// A terminal-writer reservation could not be taken because the workflow
356    /// already has a writer (#117(c)).
357    ///
358    /// The extraordinary cancellation path exists only for a run that can never
359    /// obtain a handle. A workflow that has one — or that another reservation is
360    /// already writing — is not that case, and taking a second writer would
361    /// break the single-writer invariant this refusal protects.
362    #[error("workflow `{workflow_id}` run `{run_id}` cannot take the terminal writer: {holder}")]
363    TerminalWriterUnavailable {
364        /// Workflow whose writer slot is occupied.
365        workflow_id: String,
366        /// Run the refused reservation named.
367        run_id: String,
368        /// What holds the slot, in the operator's terms.
369        holder: String,
370    },
371
372    /// A handle could not be registered because a terminal-writer reservation
373    /// holds this workflow's writer slot (#117(c)).
374    ///
375    /// The mirror of [`Self::TerminalWriterUnavailable`], and transient by
376    /// construction: a reservation lives only across one terminal transition.
377    #[error(
378        "workflow `{workflow_id}` cannot register a handle: run `{run_id}` holds the terminal writer"
379    )]
380    TerminalWriterHeld {
381        /// Workflow whose writer slot is reserved.
382        workflow_id: String,
383        /// Run holding the reservation.
384        run_id: String,
385    },
386
387    /// A terminal event was about to be appended after the engine-task epoch
388    /// had already closed.
389    ///
390    /// Raised at the append boundary itself, which is the only instant at which
391    /// the hazard it guards is real. The engine that owned this run has been
392    /// shut down or released, so this process is no longer that workflow's
393    /// single writer (invariant 3). Appending here risks two writers.
394    ///
395    /// # This is not only the successor case
396    ///
397    /// The obvious reading — a successor engine is already recovering the same
398    /// history — is the *eventual* case, not the whole of it. `Engine::shutdown`
399    /// closes the epoch as its FIRST act and only stops admitting process-exit
400    /// callbacks several steps later, so this error is also raised for runs that
401    /// exit during **this** engine's own graceful teardown, while no successor
402    /// exists yet. Saying "a successor may already be recovering" would tell an
403    /// operator reading the message during a clean shutdown to go looking for a
404    /// second node that is not there.
405    ///
406    /// Deliberately **not** transient: no later attempt re-opens a closed
407    /// epoch. In both cases the run stays `Running` and a startup sweep — the
408    /// successor's, or this node's own on restart — re-installs a monitor,
409    /// which is the mechanism that actually repairs it.
410    #[error(
411        "run `{run_id}` of workflow `{workflow_id}` could not append its terminal event: the \
412         engine-task epoch closed first, so this engine is no longer the run's single writer"
413    )]
414    EngineTaskEpochClosed {
415        /// Workflow whose terminal event was refused.
416        workflow_id: String,
417        /// Run whose terminal event was refused.
418        run_id: String,
419    },
420
421    /// The extraordinary cancellation path was asked for a run whose pinned
422    /// package resolves right now, so the run is recoverable (#117(c)).
423    ///
424    /// Measured at the moment of the request, never cited from an earlier boot's
425    /// verdict: a redeploy between then and now is exactly the remedy that makes
426    /// the ordinary path work again, and the ordinary path must be used when it
427    /// does.
428    #[error(
429        "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"
430    )]
431    RunIsRecoverable {
432        /// Workflow the request named.
433        workflow_id: String,
434        /// Run the request named.
435        run_id: String,
436        /// The pinned package version that resolved.
437        version: String,
438    },
439
440    /// A run holds no handle, cannot obtain one, and this engine has no recorded
441    /// reason why (#117(c)).
442    ///
443    /// Distinct from [`Self::WorkflowNotFound`] on purpose: the run EXISTS and
444    /// its history is readable. What is absent is a verdict from this process's
445    /// startup recovery, so the extraordinary cancellation path — which must
446    /// cite that verdict — has nothing to cite.
447    #[error(
448        "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"
449    )]
450    NoResidencyVerdict {
451        /// Workflow the request named.
452        workflow_id: String,
453        /// Run the request named.
454        run_id: String,
455    },
456
457    /// No durable schedule was found for the request.
458    #[error("schedule `{schedule_id}` was not found")]
459    ScheduleNotFound {
460        /// Schedule identifier requested by the caller.
461        schedule_id: ScheduleId,
462    },
463
464    /// Schedule trigger, projection, or evaluator side effect failed.
465    #[error("schedule error: {reason}")]
466    Schedule {
467        /// Human-readable schedule failure reason.
468        reason: String,
469    },
470
471    /// Native implemented function registration failed.
472    #[error("NIF registration failed: {reason}")]
473    NifRegistration {
474        /// Human-readable native implemented function registration failure reason.
475        reason: String,
476    },
477
478    /// Signal routing failed after the target was resolved.
479    #[error("signal router error: {0}")]
480    SignalRouter(#[from] SignalRouterError),
481
482    /// Live workflow query dispatch failed after the target was resolved.
483    #[error("query error: {0}")]
484    Query(#[from] crate::query::QueryError),
485}
486
487/// What pins a workflow version against unload, naming the concrete holder.
488#[derive(Debug, Clone, PartialEq, Eq)]
489pub enum PinHolder {
490    /// A start resolved this version but has not yet registered a handle.
491    InFlightStart,
492    /// A live, non-terminal run executes on this version.
493    LiveRun {
494        /// Pinning workflow id.
495        workflow_id: WorkflowId,
496        /// Pinning run id.
497        run_id: RunId,
498    },
499    /// A recoverable instance in the store is pinned to this version.
500    RecoverableRun {
501        /// Pinning workflow id.
502        workflow_id: WorkflowId,
503    },
504    /// A recorded-but-never-started child is pinned to this version.
505    RecordedChild {
506        /// Child workflow id pinned to the version.
507        child_workflow_id: WorkflowId,
508        /// Parent workflow whose history records the child.
509        recorded_by: WorkflowId,
510    },
511}
512
513impl std::fmt::Display for PinHolder {
514    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        match self {
516            Self::InFlightStart => formatter.write_str("an in-flight start is pinned to it"),
517            Self::LiveRun {
518                workflow_id,
519                run_id,
520            } => write!(
521                formatter,
522                "live run `{workflow_id}/{run_id}` is pinned to it"
523            ),
524            Self::RecoverableRun { workflow_id } => {
525                write!(formatter, "recoverable run `{workflow_id}` is pinned to it")
526            }
527            Self::RecordedChild {
528                child_workflow_id,
529                recorded_by,
530            } => write!(
531                formatter,
532                "child `{child_workflow_id}` recorded by `{recorded_by}` is pinned to it and has not started"
533            ),
534        }
535    }
536}
537
538/// Errors surfaced by the signal routing boundary.
539#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
540pub enum SignalRouterError {
541    /// The target workflow is terminal and cannot receive new signals.
542    #[error("workflow {workflow_id}/{run_id} is terminal")]
543    Terminal {
544        /// Target workflow id.
545        workflow_id: WorkflowId,
546        /// Target run id.
547        run_id: RunId,
548    },
549
550    /// The router could not defer a recorded non-resident signal.
551    #[error("signal resume handoff failed: {reason}")]
552    Handoff {
553        /// Human-readable handoff failure reason.
554        reason: String,
555    },
556
557    /// The signal was durably recorded but could not be delivered to the live mailbox.
558    #[error(
559        "signal `{signal_name}` for workflow {workflow_id}/{run_id} could not be delivered to process {process_id}: {reason}"
560    )]
561    DeliveryFailed {
562        /// Target workflow id.
563        workflow_id: WorkflowId,
564        /// Target run id.
565        run_id: RunId,
566        /// Embedded runtime process identifier selected for delivery.
567        process_id: u64,
568        /// Signal name that was recorded and attempted.
569        signal_name: String,
570        /// Human-readable delivery failure reason.
571        reason: String,
572    },
573}
574
575impl From<ScheduleError> for EngineError {
576    fn from(error: ScheduleError) -> Self {
577        Self::Schedule {
578            reason: error.to_string(),
579        }
580    }
581}
582
583impl From<ScheduleEvaluatorError> for EngineError {
584    fn from(error: ScheduleEvaluatorError) -> Self {
585        match error {
586            ScheduleEvaluatorError::ScheduleNotFound { schedule_id } => {
587                Self::ScheduleNotFound { schedule_id }
588            }
589            other => Self::Schedule {
590                reason: other.to_string(),
591            },
592        }
593    }
594}