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 /// A registered run has no `WorkflowStarted` in the history it was
328 /// reconciled against — the registry and the store disagree that it exists.
329 ///
330 /// Raised by registry reconciliation rather than defaulting the projection.
331 /// `status_from_events` returns `Running` for a slice holding no lifecycle
332 /// event, so a run absent from the history it is projected against would
333 /// otherwise be silently cached as RUNNING — a terminal run reported live,
334 /// produced by the reconciliation whose whole job is to stop exactly that.
335 ///
336 /// Not reachable through a normal start: `WorkflowStarted` is recorded
337 /// before the handle is published. It means a genuine invariant breach, so
338 /// it is surfaced rather than absorbed.
339 #[error(
340 "run {run_id} of workflow {workflow_id} is absent from the history it was reconciled against"
341 )]
342 RunNotInHistory {
343 /// Workflow whose history was read.
344 workflow_id: WorkflowId,
345 /// Run that the history does not contain.
346 run_id: RunId,
347 },
348
349 /// The workflow catalog lock was poisoned.
350 #[error("workflow catalog lock was poisoned")]
351 CatalogPoisoned,
352
353 /// A precondition on the target workflow's current state was not met.
354 ///
355 /// Raised by the reopen operation when the target run is not in a reopenable
356 /// state: not terminal, terminal for a non-reopenable reason
357 /// (Completed/`TimedOut`), or already Running. The `reason` names the actual
358 /// status so callers and operators can see why the reopen was rejected. Maps
359 /// to the `INVALID_STATE` wire code (gRPC `FailedPrecondition` / HTTP 409).
360 #[error("invalid workflow state: {reason}")]
361 InvalidState {
362 /// Human-readable precondition-failure reason naming the actual status.
363 reason: String,
364 },
365
366 /// The engine is already shutting down and no new workflow starts are accepted.
367 #[error("engine is shutting down")]
368 ShuttingDown,
369
370 /// No live, durable, or loaded workflow was found for the request.
371 #[error("workflow `{workflow_type}` was not found")]
372 WorkflowNotFound {
373 /// Logical workflow type requested by the caller.
374 workflow_type: String,
375 },
376
377 /// A terminal-writer reservation could not be taken because the workflow
378 /// already has a writer (#117(c)).
379 ///
380 /// The extraordinary cancellation path exists only for a run that can never
381 /// obtain a handle. A workflow that has one — or that another reservation is
382 /// already writing — is not that case, and taking a second writer would
383 /// break the single-writer invariant this refusal protects.
384 #[error("workflow `{workflow_id}` run `{run_id}` cannot take the terminal writer: {holder}")]
385 TerminalWriterUnavailable {
386 /// Workflow whose writer slot is occupied.
387 workflow_id: String,
388 /// Run the refused reservation named.
389 run_id: String,
390 /// What holds the slot, in the operator's terms.
391 holder: String,
392 },
393
394 /// A handle could not be registered because a terminal-writer reservation
395 /// holds this workflow's writer slot (#117(c)).
396 ///
397 /// The mirror of [`Self::TerminalWriterUnavailable`], and transient by
398 /// construction: a reservation lives only across one terminal transition.
399 #[error(
400 "workflow `{workflow_id}` cannot register a handle: run `{run_id}` holds the terminal writer"
401 )]
402 TerminalWriterHeld {
403 /// Workflow whose writer slot is reserved.
404 workflow_id: String,
405 /// Run holding the reservation.
406 run_id: String,
407 },
408
409 /// A terminal event was about to be appended after the engine-task epoch
410 /// had already closed.
411 ///
412 /// Raised at the append boundary itself, which is the only instant at which
413 /// the hazard it guards is real. The engine that owned this run has been
414 /// shut down or released, so this process is no longer that workflow's
415 /// single writer (invariant 3). Appending here risks two writers.
416 ///
417 /// # This is not only the successor case
418 ///
419 /// The obvious reading — a successor engine is already recovering the same
420 /// history — is the *eventual* case, not the whole of it. `Engine::shutdown`
421 /// closes the epoch as its FIRST act and only stops admitting process-exit
422 /// callbacks several steps later, so this error is also raised for runs that
423 /// exit during **this** engine's own graceful teardown, while no successor
424 /// exists yet. Saying "a successor may already be recovering" would tell an
425 /// operator reading the message during a clean shutdown to go looking for a
426 /// second node that is not there.
427 ///
428 /// Deliberately **not** transient: no later attempt re-opens a closed
429 /// epoch. In both cases the run stays `Running` and a startup sweep — the
430 /// successor's, or this node's own on restart — re-installs a monitor,
431 /// which is the mechanism that actually repairs it.
432 #[error(
433 "run `{run_id}` of workflow `{workflow_id}` could not append its terminal event: the \
434 engine-task epoch closed first, so this engine is no longer the run's single writer"
435 )]
436 EngineTaskEpochClosed {
437 /// Workflow whose terminal event was refused.
438 workflow_id: String,
439 /// Run whose terminal event was refused.
440 run_id: String,
441 },
442
443 /// The extraordinary cancellation path was asked for a run whose pinned
444 /// package resolves right now, so the run is recoverable (#117(c)).
445 ///
446 /// Measured at the moment of the request, never cited from an earlier boot's
447 /// verdict: a redeploy between then and now is exactly the remedy that makes
448 /// the ordinary path work again, and the ordinary path must be used when it
449 /// does.
450 #[error(
451 "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"
452 )]
453 RunIsRecoverable {
454 /// Workflow the request named.
455 workflow_id: String,
456 /// Run the request named.
457 run_id: String,
458 /// The pinned package version that resolved.
459 version: String,
460 },
461
462 /// A run holds no handle, cannot obtain one, and this engine has no recorded
463 /// reason why (#117(c)).
464 ///
465 /// Distinct from [`Self::WorkflowNotFound`] on purpose: the run EXISTS and
466 /// its history is readable. What is absent is a verdict from this process's
467 /// startup recovery, so the extraordinary cancellation path — which must
468 /// cite that verdict — has nothing to cite.
469 #[error(
470 "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"
471 )]
472 NoResidencyVerdict {
473 /// Workflow the request named.
474 workflow_id: String,
475 /// Run the request named.
476 run_id: String,
477 },
478
479 /// No durable schedule was found for the request.
480 #[error("schedule `{schedule_id}` was not found")]
481 ScheduleNotFound {
482 /// Schedule identifier requested by the caller.
483 schedule_id: ScheduleId,
484 },
485
486 /// Schedule trigger, projection, or evaluator side effect failed.
487 #[error("schedule error: {reason}")]
488 Schedule {
489 /// Human-readable schedule failure reason.
490 reason: String,
491 },
492
493 /// Native implemented function registration failed.
494 #[error("NIF registration failed: {reason}")]
495 NifRegistration {
496 /// Human-readable native implemented function registration failure reason.
497 reason: String,
498 },
499
500 /// Signal routing failed after the target was resolved.
501 #[error("signal router error: {0}")]
502 SignalRouter(#[from] SignalRouterError),
503
504 /// Live workflow query dispatch failed after the target was resolved.
505 #[error("query error: {0}")]
506 Query(#[from] crate::query::QueryError),
507}
508
509/// What pins a workflow version against unload, naming the concrete holder.
510#[derive(Debug, Clone, PartialEq, Eq)]
511pub enum PinHolder {
512 /// A start resolved this version but has not yet registered a handle.
513 InFlightStart,
514 /// A live, non-terminal run executes on this version.
515 LiveRun {
516 /// Pinning workflow id.
517 workflow_id: WorkflowId,
518 /// Pinning run id.
519 run_id: RunId,
520 },
521 /// A recoverable instance in the store is pinned to this version.
522 RecoverableRun {
523 /// Pinning workflow id.
524 workflow_id: WorkflowId,
525 },
526 /// A recorded-but-never-started child is pinned to this version.
527 RecordedChild {
528 /// Child workflow id pinned to the version.
529 child_workflow_id: WorkflowId,
530 /// Parent workflow whose history records the child.
531 recorded_by: WorkflowId,
532 },
533}
534
535impl std::fmt::Display for PinHolder {
536 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 match self {
538 Self::InFlightStart => formatter.write_str("an in-flight start is pinned to it"),
539 Self::LiveRun {
540 workflow_id,
541 run_id,
542 } => write!(
543 formatter,
544 "live run `{workflow_id}/{run_id}` is pinned to it"
545 ),
546 Self::RecoverableRun { workflow_id } => {
547 write!(formatter, "recoverable run `{workflow_id}` is pinned to it")
548 }
549 Self::RecordedChild {
550 child_workflow_id,
551 recorded_by,
552 } => write!(
553 formatter,
554 "child `{child_workflow_id}` recorded by `{recorded_by}` is pinned to it and has not started"
555 ),
556 }
557 }
558}
559
560/// Errors surfaced by the signal routing boundary.
561#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
562pub enum SignalRouterError {
563 /// The target workflow is terminal and cannot receive new signals.
564 #[error("workflow {workflow_id}/{run_id} is terminal")]
565 Terminal {
566 /// Target workflow id.
567 workflow_id: WorkflowId,
568 /// Target run id.
569 run_id: RunId,
570 },
571
572 /// The router could not defer a recorded non-resident signal.
573 #[error("signal resume handoff failed: {reason}")]
574 Handoff {
575 /// Human-readable handoff failure reason.
576 reason: String,
577 },
578
579 /// The signal was durably recorded but could not be delivered to the live mailbox.
580 #[error(
581 "signal `{signal_name}` for workflow {workflow_id}/{run_id} could not be delivered to process {process_id}: {reason}"
582 )]
583 DeliveryFailed {
584 /// Target workflow id.
585 workflow_id: WorkflowId,
586 /// Target run id.
587 run_id: RunId,
588 /// Embedded runtime process identifier selected for delivery.
589 process_id: u64,
590 /// Signal name that was recorded and attempted.
591 signal_name: String,
592 /// Human-readable delivery failure reason.
593 reason: String,
594 },
595}
596
597impl From<ScheduleError> for EngineError {
598 fn from(error: ScheduleError) -> Self {
599 Self::Schedule {
600 reason: error.to_string(),
601 }
602 }
603}
604
605impl From<ScheduleEvaluatorError> for EngineError {
606 fn from(error: ScheduleEvaluatorError) -> Self {
607 match error {
608 ScheduleEvaluatorError::ScheduleNotFound { schedule_id } => {
609 Self::ScheduleNotFound { schedule_id }
610 }
611 other => Self::Schedule {
612 reason: other.to_string(),
613 },
614 }
615 }
616}