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    /// A terminal event was about to be appended after the engine-task epoch
371    /// had already closed.
372    ///
373    /// Raised at the append boundary itself, which is the only instant at which
374    /// the hazard it guards is real. The engine that owned this run has been
375    /// shut down or released, so this process is no longer that workflow's
376    /// single writer (invariant 3). Appending here risks two writers.
377    ///
378    /// # This is not only the successor case
379    ///
380    /// The obvious reading — a successor engine is already recovering the same
381    /// history — is the *eventual* case, not the whole of it. `Engine::shutdown`
382    /// closes the epoch as its FIRST act and only stops admitting process-exit
383    /// callbacks several steps later, so this error is also raised for runs that
384    /// exit during **this** engine's own graceful teardown, while no successor
385    /// exists yet. Saying "a successor may already be recovering" would tell an
386    /// operator reading the message during a clean shutdown to go looking for a
387    /// second node that is not there.
388    ///
389    /// Deliberately **not** transient: no later attempt re-opens a closed
390    /// epoch. In both cases the run stays `Running` and a startup sweep — the
391    /// successor's, or this node's own on restart — re-installs a monitor,
392    /// which is the mechanism that actually repairs it.
393    #[error(
394        "run `{run_id}` of workflow `{workflow_id}` could not append its terminal event: the \
395         engine-task epoch closed first, so this engine is no longer the run's single writer"
396    )]
397    EngineTaskEpochClosed {
398        /// Workflow whose terminal event was refused.
399        workflow_id: String,
400        /// Run whose terminal event was refused.
401        run_id: String,
402    },
403
404    /// The extraordinary cancellation path was asked for a run whose pinned
405    /// package resolves right now, so the run is recoverable (#117(c)).
406    ///
407    /// Measured at the moment of the request, never cited from an earlier boot's
408    /// verdict: a redeploy between then and now is exactly the remedy that makes
409    /// the ordinary path work again, and the ordinary path must be used when it
410    /// does.
411    #[error(
412        "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"
413    )]
414    RunIsRecoverable {
415        /// Workflow the request named.
416        workflow_id: String,
417        /// Run the request named.
418        run_id: String,
419        /// The pinned package version that resolved.
420        version: String,
421    },
422
423    /// A run holds no handle, cannot obtain one, and this engine has no recorded
424    /// reason why (#117(c)).
425    ///
426    /// Distinct from [`Self::WorkflowNotFound`] on purpose: the run EXISTS and
427    /// its history is readable. What is absent is a verdict from this process's
428    /// startup recovery, so the extraordinary cancellation path — which must
429    /// cite that verdict — has nothing to cite.
430    #[error(
431        "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"
432    )]
433    NoResidencyVerdict {
434        /// Workflow the request named.
435        workflow_id: String,
436        /// Run the request named.
437        run_id: String,
438    },
439
440    /// No durable schedule was found for the request.
441    #[error("schedule `{schedule_id}` was not found")]
442    ScheduleNotFound {
443        /// Schedule identifier requested by the caller.
444        schedule_id: ScheduleId,
445    },
446
447    /// Schedule trigger, projection, or evaluator side effect failed.
448    #[error("schedule error: {reason}")]
449    Schedule {
450        /// Human-readable schedule failure reason.
451        reason: String,
452    },
453
454    /// Native implemented function registration failed.
455    #[error("NIF registration failed: {reason}")]
456    NifRegistration {
457        /// Human-readable native implemented function registration failure reason.
458        reason: String,
459    },
460
461    /// Signal routing failed after the target was resolved.
462    #[error("signal router error: {0}")]
463    SignalRouter(#[from] SignalRouterError),
464
465    /// Live workflow query dispatch failed after the target was resolved.
466    #[error("query error: {0}")]
467    Query(#[from] crate::query::QueryError),
468}
469
470/// What pins a workflow version against unload, naming the concrete holder.
471#[derive(Debug, Clone, PartialEq, Eq)]
472pub enum PinHolder {
473    /// A start resolved this version but has not yet registered a handle.
474    InFlightStart,
475    /// A live, non-terminal run executes on this version.
476    LiveRun {
477        /// Pinning workflow id.
478        workflow_id: WorkflowId,
479        /// Pinning run id.
480        run_id: RunId,
481    },
482    /// A recoverable instance in the store is pinned to this version.
483    RecoverableRun {
484        /// Pinning workflow id.
485        workflow_id: WorkflowId,
486    },
487    /// A recorded-but-never-started child is pinned to this version.
488    RecordedChild {
489        /// Child workflow id pinned to the version.
490        child_workflow_id: WorkflowId,
491        /// Parent workflow whose history records the child.
492        recorded_by: WorkflowId,
493    },
494}
495
496impl std::fmt::Display for PinHolder {
497    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
498        match self {
499            Self::InFlightStart => formatter.write_str("an in-flight start is pinned to it"),
500            Self::LiveRun {
501                workflow_id,
502                run_id,
503            } => write!(
504                formatter,
505                "live run `{workflow_id}/{run_id}` is pinned to it"
506            ),
507            Self::RecoverableRun { workflow_id } => {
508                write!(formatter, "recoverable run `{workflow_id}` is pinned to it")
509            }
510            Self::RecordedChild {
511                child_workflow_id,
512                recorded_by,
513            } => write!(
514                formatter,
515                "child `{child_workflow_id}` recorded by `{recorded_by}` is pinned to it and has not started"
516            ),
517        }
518    }
519}
520
521/// Errors surfaced by the signal routing boundary.
522#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
523pub enum SignalRouterError {
524    /// The target workflow is terminal and cannot receive new signals.
525    #[error("workflow {workflow_id}/{run_id} is terminal")]
526    Terminal {
527        /// Target workflow id.
528        workflow_id: WorkflowId,
529        /// Target run id.
530        run_id: RunId,
531    },
532
533    /// The router could not defer a recorded non-resident signal.
534    #[error("signal resume handoff failed: {reason}")]
535    Handoff {
536        /// Human-readable handoff failure reason.
537        reason: String,
538    },
539
540    /// The signal was durably recorded but could not be delivered to the live mailbox.
541    #[error(
542        "signal `{signal_name}` for workflow {workflow_id}/{run_id} could not be delivered to process {process_id}: {reason}"
543    )]
544    DeliveryFailed {
545        /// Target workflow id.
546        workflow_id: WorkflowId,
547        /// Target run id.
548        run_id: RunId,
549        /// Embedded runtime process identifier selected for delivery.
550        process_id: u64,
551        /// Signal name that was recorded and attempted.
552        signal_name: String,
553        /// Human-readable delivery failure reason.
554        reason: String,
555    },
556}
557
558impl From<ScheduleError> for EngineError {
559    fn from(error: ScheduleError) -> Self {
560        Self::Schedule {
561            reason: error.to_string(),
562        }
563    }
564}
565
566impl From<ScheduleEvaluatorError> for EngineError {
567    fn from(error: ScheduleEvaluatorError) -> Self {
568        match error {
569            ScheduleEvaluatorError::ScheduleNotFound { schedule_id } => {
570                Self::ScheduleNotFound { schedule_id }
571            }
572            other => Self::Schedule {
573                reason: other.to_string(),
574            },
575        }
576    }
577}