Skip to main content

aion/engine/
api.rs

1//! `Engine` start, cancel, result, list, and shutdown support.
2
3use std::sync::Arc;
4
5use aion_core::{Event, RunId, SearchAttributeSchema, WorkflowId};
6use tokio::sync::Mutex as AsyncMutex;
7use tokio::task::JoinHandle;
8
9use crate::durability::Recorder;
10use crate::schedule::ScheduleEvaluator;
11use aion_store::EventStore;
12use aion_store::visibility::VisibilityStore;
13
14use crate::registry::TerminalOutcome;
15use crate::{
16    EngineError, Registry, RuntimeHandle, SupervisionTree, WorkflowCatalog,
17    signal::SignalResumeHandoff,
18};
19
20use super::api_schedule::{
21    ScheduleRuntimeDeps, default_schedule_evaluator, schedule_coordinator_workflow_id,
22};
23use super::delegated::DelegatedSeams;
24use super::shutdown_gate::ShutdownGate;
25
26/// Live embedded workflow engine assembled by [`crate::EngineBuilder`].
27pub struct Engine {
28    pub(super) store: Arc<dyn EventStore>,
29    pub(super) visibility_store: Arc<dyn VisibilityStore>,
30    pub(super) schedule_recorder: Arc<AsyncMutex<Recorder>>,
31    pub(super) schedule_evaluator: Arc<AsyncMutex<ScheduleEvaluator>>,
32    pub(super) schedule_coordinator_workflow_id: WorkflowId,
33    pub(super) runtime: Arc<RuntimeHandle>,
34    pub(super) catalog: Arc<WorkflowCatalog>,
35    pub(super) registry: Arc<Registry>,
36    pub(super) supervision: Arc<SupervisionTree>,
37    delegated: DelegatedSeams,
38    pub(super) signal_handoff: Arc<SignalResumeHandoff>,
39    pub(super) search_attribute_schema: Arc<SearchAttributeSchema>,
40    pub(super) shutdown_gate: ShutdownGate,
41    /// Serializes the deploy mutations (load / route / unload) end-to-end
42    /// across BOTH the catalog commit and its store persistence write, so
43    /// the persisted package set and route pointers can never disagree with
44    /// the catalog through interleaving (for example a concurrent re-deploy
45    /// re-persisting a version an unload just deleted). Workflow dispatch
46    /// never takes this lock.
47    pub(super) deploy_mutations: AsyncMutex<()>,
48    visibility_reconciliation_task: Option<JoinHandle<()>>,
49    /// Shared dispatch-hold set for durable pause (#204): the workflow ids whose
50    /// outbox rows are held `Pending` while paused. Mutated by pause/resume/cancel
51    /// and rebuilt from [`EventStore::list_paused`] at startup/adoption; read by
52    /// the outbox dispatcher at claim time.
53    pub(super) paused_runs: crate::lifecycle::PausedRuns,
54}
55
56impl Drop for Engine {
57    /// Close the engine-task epoch when the engine is released, whether or not
58    /// [`Engine::shutdown`] was ever called or ever succeeded.
59    ///
60    /// Without this, an engine dropped without a successful shutdown left
61    /// completion retries armed and appending terminal events. They could not
62    /// be stopped by `EngineTaskRuntime::drop` either: an attempt in flight
63    /// upgrades its weak reference and holds the `RuntimeHandle` strongly for
64    /// the length of the attempt, so the refcount never reaches zero and that
65    /// backstop is unreachable for precisely the span of the append it exists
66    /// to stop. This drop runs before the engine's own fields are released, so
67    /// it does not depend on that refcount at all.
68    ///
69    /// Uses the non-blocking `EngineTaskRuntime::begin_close` rather than the
70    /// full shutdown:
71    /// a `Drop` may run inside a host async context, where a blocking join
72    /// panics. It therefore **gates and aborts, it does not await** — an
73    /// attempt already past the append boundary is cancelled at its next await
74    /// point. The gate is the load-bearing half: the append boundary reads it
75    /// through `is_epoch_open` and refuses.
76    ///
77    /// # The visibility reconciliation task is aborted here for the same reason
78    ///
79    /// It runs on the HOST runtime, not the engine-task executor, so the epoch
80    /// gate does not reach it — and dropping its `JoinHandle` detaches rather
81    /// than cancels. It is an unbounded loop holding the event store and the
82    /// visibility store, and `reconcile_visibility` WRITES. Left detached, an
83    /// engine released without `shutdown` went on upserting visibility rows for
84    /// the life of the process, against a store a successor engine may already
85    /// own. `Engine::shutdown` aborts it as its first act; this does the same,
86    /// so the two paths agree.
87    ///
88    /// # The live timer wheel is disarmed here for the third time, same reason
89    ///
90    /// 🔴 THIS WAS MISSING, AND IT LEFT A DURABLE WRITER ARMED. Live-wheel
91    /// timer tasks are `tokio::spawn`ed on the HOST runtime
92    /// (`runtime/nif_timer_bridge.rs`), so — exactly like the reconciliation
93    /// loop — the engine-task epoch gate does not reach them. Their body is
94    /// `fire_wheel_timer`, which records a durable `TimerFired`. They hold a
95    /// `Weak<EngineNifState>`, and this drop deliberately does NOT clear the
96    /// seams (see below), so that upgrade succeeds and the fire proceeds.
97    ///
98    /// An engine released without `shutdown` therefore kept a durable-append
99    /// path armed for the life of the process. `Engine::shutdown` names the
100    /// consequence precisely: across a failover, the dead owner's orphaned
101    /// wheel task races the survivor's adoption-armed timer and can record the
102    /// one durable `TimerFired` first, leaving the survivor's resident sleeper
103    /// parked forever. That is the single-writer invariant, and nothing about
104    /// it cares whether the engine was shut down or dropped.
105    ///
106    /// Safe in a `Drop`: `shutdown_timer_wheel` sets a flag and then performs a
107    /// `DashMap` drain plus `abort()` — non-blocking, structurally identical to
108    /// the `visibility_reconciliation_task.abort()` above. The async-context
109    /// objection that justifies `begin_close` over the full shutdown does not
110    /// apply to it.
111    ///
112    /// 🔴 AND IT IS A GATE, NOT ONLY A DRAIN — which it had to become for this
113    /// `Drop` to be worth anything. A drain closes the set of timers armed at
114    /// one instant; this `Drop` deliberately leaves the beamr scheduler and the
115    /// engine seams alive, so a workflow process still runnable could reach
116    /// `sleep` a moment later and arm a fresh durable `TimerFired` writer
117    /// through a wheel this drop believed it had emptied. `arm_timer` now
118    /// refuses once the flag is set (`nif_timer_bridge.rs`, `shut_down`), so
119    /// the guarantee below is a property of the wheel from here on rather than
120    /// of one instant.
121    ///
122    /// # 🔴 WHAT THIS DOES NOT DO, STATED SO NOBODY READS MORE INTO IT
123    ///
124    /// It does not clear the engine NIF seams. Those hold `Arc`s back to the
125    /// `RuntimeHandle`, so until `clear_engine_seams` runs the handle, its
126    /// beamr scheduler and every store clone they reach outlive this drop.
127    /// `Engine::shutdown` clears them only after the scheduler has stopped and
128    /// the child-task and timer-wheel epochs have closed; none of that has
129    /// happened here, and a NIF could still read a slot this drop cleared.
130    /// Trading a leak for a use-after-clear is the wrong direction, so the leak
131    /// stands and is named: **an engine released without `shutdown` still holds
132    /// its runtime.** What this drop guarantees is narrower and is the part
133    /// that matters for durability — **no durable writer this drop can reach
134    /// keeps writing, and no writer it cannot reach can end a run.** The first
135    /// clause covers FOUR BACKGROUND writers, stopped in two different ways:
136    ///
137    /// 1. anything armed on the **engine-task epoch** — `begin_close()` below;
138    /// 2. the **visibility reconciliation loop** — `abort()` below;
139    /// 3. the **live timer wheel** — `shutdown_timer_wheel()` below, which
140    ///    gates and drains, *and* refuses at the point of writing, because
141    ///    `abort` cannot stop a task already inside a poll. That refusal is in
142    ///    TWO places, not one, and the second is easy to miss: an ordinary timer
143    ///    is refused at the bridge's append boundary
144    ///    (`nif_timer_bridge.rs`, `record_workflow_event`), but a reserved
145    ///    `deadline:{run}` fire never reaches that boundary — `fire_timer_guarded`
146    ///    demuxes it to the deadline handler first — so it is refused inside
147    ///    [`crate::lifecycle::deadline::WorkflowDeadlineHandler`] instead, off
148    ///    the same latch;
149    /// 4. the **activity completion / retry task**
150    ///    ([`crate::runtime::nif_activity_retry_dispatch::spawn_completion_task`]),
151    ///    which this drop **cannot reach at all**: its `JoinHandle` is
152    ///    discarded, so it is detached on the host runtime and nothing here
153    ///    registers or aborts it. It is stopped instead at its append boundary,
154    ///    which reads `is_epoch_open()` under the recorder lock — so step 1's
155    ///    `begin_close()` is what silences it, one indirection away.
156    ///
157    /// # 🔴 AND THERE IS A FIFTH, WHICH IS NOT A BACKGROUND WRITER AT ALL
158    ///
159    /// The four above are things the engine spawned; this drop stops them
160    /// because it can reach them. The fifth is the **workflow process itself**,
161    /// and this drop deliberately does not stop it — it leaves the beamr
162    /// scheduler running and the NIF seams installed, which is exactly what the
163    /// section above says it is trading for. A still-runnable workflow process
164    /// therefore keeps calling NIFs after the `Engine` is gone, and **13 of the
165    /// 24 registered engine NIFs perform durable writes** — `dispatch_activity`,
166    /// `dispatch_activity_in_vm`, `await_activity_result`, `sleep`,
167    /// `start_timer`, `cancel_timer`, `with_timeout`, `continue_as_new`,
168    /// `send_signal`, `spawn_child`, `collect_all`, `collect_race`,
169    /// `collect_map`. The other 11 read or reply and record nothing. The
170    /// registration table is `runtime::engine_nifs::engine_nif_entries`, whose
171    /// own test asserts the total, so both halves of that split are checkable
172    /// against a closed set rather than taken on trust — which is the point,
173    /// since the first draft of this paragraph carried a transposed count.
174    /// None of the 13 consults the engine-task epoch, and
175    /// nothing in the append path does either: `NifContext::block_on_recorder`
176    /// takes the recorder lock and nothing else, and `Recorder::append_one`
177    /// goes straight to `store.append`.
178    ///
179    /// An earlier revision of this doc said "there are FOUR" full stop, and was
180    /// wrong in the way that matters most: it did not omit an obscure writer, it
181    /// omitted **the one that executes user code**.
182    ///
183    /// What has been closed is the part that can END A RUN.
184    /// `WorkflowContinuedAsNew` is a TERMINAL, it was the ONE terminal this
185    /// fifth writer could still record, and it is now refused off the same epoch
186    /// (`runtime::nif_continue_as_new::record_continuation`). The reason it had
187    /// to be, in one line: **the successor run that terminal obliges was already
188    /// refused** at `completion::start_continuation_replacement`, so the two
189    /// halves of one transition disagreed and the run was left terminal with no
190    /// continuation. Every other terminal reachable from workflow code was
191    /// already gated — process exit at the completion append boundary,
192    /// `WorkflowTimedOut` off the timer bridge's stand-down latch.
193    ///
194    /// **And the refusal ENDS THE PROCESS, which is the half that makes it a
195    /// gain rather than a trade.** Before the gate, the recorder call either
196    /// succeeded or aborted the NIF, and the success path always reached
197    /// `cancel_pid` — that instruction is where this fifth writer died. A
198    /// refusal that merely returned early would have removed it, leaving the
199    /// process runnable and free to make every ungated write listed below. So
200    /// `runtime::nif_continue_as_new` terminates on the epoch refusal too — and,
201    /// of the refusals, on that one ONLY. A pre-terminal store fault is an
202    /// ordinary error workflow code may handle, and killing a process for it
203    /// would turn a transient blip into a dead run; an already-terminal run is
204    /// spared for a different reason — its terminal was recorded by a seam
205    /// that owns its own teardown, and of those owners some end the pid (a
206    /// second `cancel_pid` from here would race them) while some only
207    /// deregister (a kill from here would usurp them). The predicate's doc
208    /// carries that split; the "Five ordinary terminal paths" paragraph in
209    /// `lifecycle/completion.rs` carries the one enumeration of the owners.
210    /// It ALSO terminates whenever the terminal actually landed, including
211    /// the half-completed case where the terminal is durable but the deadline
212    /// retirement that follows it failed — because the question that decides
213    /// this is "did the terminal land", not "was there an error". The
214    /// predicate is `outcome_must_end_the_process`, pinned by a test with both
215    /// negative controls.
216    ///
217    /// The cost, stated because it is not zero: the refusal returns before
218    /// `retire_run_deadline`, so the predecessor's deadline row stays armed. A
219    /// restart gap longer than the run's remaining budget times the run out
220    /// instead of continuing it. That is the same exposure every other in-flight
221    /// run already carries across an outage; the old path escaped it only by
222    /// recording a terminal for a transition that never completed.
223    ///
224    /// # 🔴 WHAT IS STILL OPEN, AND WHY IT IS NOT CLOSED HERE
225    ///
226    /// A workflow process refused by the EPOCH gate is now stopped, so the
227    /// writes below are not reachable from that path. Say "the epoch gate" and
228    /// not "was refused": the other refusals deliberately leave the process
229    /// alive, so a reader who takes this sentence at its widest reading would
230    /// believe an exposure is closed that is open by design.
231    ///
232    /// They remain fully open on every other path — a process that never calls
233    /// `continue_as_new` is untouched by any of this and keeps writing.
234    ///
235    /// The fifth writer's NON-terminal durable writes are ungated and remain so:
236    /// `TimerStarted` plus a durable timer row (`sleep`, `start_timer`,
237    /// `with_timeout` — `TimerService::schedule` writes the row and only then
238    /// arms, so the wheel's refusal lands after both), activity schedule/start
239    /// and completion records, `spawn_child`'s whole child-start chain, and
240    /// `send_signal`, which writes into a THIRD workflow's history.
241    ///
242    /// Two things bound that, and neither is what a reader might assume:
243    /// - `WriteToken` fences NOTHING. It is a zero-sized marker with a public
244    ///   `recorder()` constructor and no engine, epoch, lease or node identity;
245    ///   two engines over one store both mint valid ones. Its own doc says so —
246    ///   it exists to stop an `Arc<dyn EventStore>` alone being write authority.
247    /// - `SequenceConflict` catches only the LOSER of a head race, and a
248    ///   released engine is structurally positioned to be the winner: its
249    ///   Recorder is the one already at the current head, because it is the one
250    ///   that has been appending. If it writes first, its write succeeds and the
251    ///   SUCCESSOR takes the conflict.
252    ///
253    /// So the remaining exposure is real and is stated rather than denied. It is
254    /// not closed here because **no flag in this crate distinguishes "released"
255    /// from "shutting down"** — `begin_close` sets one bit and both `Engine::drop`
256    /// and `Engine::shutdown` set it. A gate on that bit at a workflow-process
257    /// write path would therefore also fire during an ORDINARY graceful
258    /// shutdown, for the whole unbounded span between `begin_close()` and
259    /// `runtime.shutdown()` further down this file, and there the failure is an
260    /// `{error, _}` returned INSIDE running workflow code — a failed `sleep`, a
261    /// failed `spawn_child` — on runs the shutdown was trying to leave intact.
262    /// The terminal was worth that trade because its successor was already
263    /// refused at `start_continuation_replacement`: recording it could only
264    /// produce a run that is terminal with no continuation.
265    ///
266    /// ⚠️ **Refusing it is not free, and an earlier revision of this sentence
267    /// said it was.** It read "refusing cost nothing that was not already lost",
268    /// which is the exact claim `runtime::nif_continue_as_new`'s own
269    /// documentation exists to retract — and which the "cost, stated because it
270    /// is not zero" paragraph above already contradicts. The price is stated
271    /// there and holds here: the refusal returns before `retire_run_deadline`,
272    /// so the predecessor's deadline stays armed and a long enough outage
273    /// times the run out instead of continuing it. What makes the trade worth
274    /// taking is not that it is free but that the alternative bought its
275    /// exemption with a false terminal.
276    ///
277    /// Refusing ordinary progress is a different bargain and needs a latch that
278    /// means what it says. Do not add one of these gates without adding that
279    /// latch.
280    ///
281    /// 🔴 THAT LIST IS A CLAIM ABOUT DURABLE WRITERS AND IT IS ONLY AS GOOD AS
282    /// ITS ENUMERATION — four times proven. An earlier revision named two and
283    /// was wrong: the timer wheel was the third, and it was armed. The revision
284    /// after that named three and was also wrong: the completion task was the
285    /// fourth, it had no epoch check of any kind, and it sleeps an
286    /// SDK-declared backoff with no ceiling between attempts. And the revision
287    /// after THAT — the one that added the wheel's append-boundary refusal —
288    /// wrote entry 3 as though that boundary covered the whole wheel, when the
289    /// deadline path is demuxed away before it and had no refusal at all: an
290    /// engine released without `shutdown` could still record a durable
291    /// `WorkflowTimedOut` and tear a run down. **The enumeration was right and
292    /// the mechanism named under it was not**, which is the harder failure to
293    /// see, because the list looked complete.
294    ///
295    /// And the FOURTH time is the section above: every revision so far had
296    /// enumerated only what this drop *reaches*, and then written a guarantee
297    /// over every writer that *exists*. The workflow process is not on any list
298    /// of things a `Recorder` grep or a `spawn` grep produces, because nobody
299    /// spawned it here and it holds no handle this file can see — it is reached
300    /// through an installed NIF seam by code the operator wrote. **A search
301    /// shaped like the mechanism you already know will not find the writer you
302    /// do not.** That is why the method below now starts from the NIF
303    /// registration table, which is a closed set that something asserts the size
304    /// of, rather than from a grep whose completeness nothing checks.
305    ///
306    /// The way to check this list is: take
307    /// `runtime::engine_nifs::engine_nif_entries` and account for every entry;
308    /// grep the crate for every construction of a `Recorder` handle and every
309    /// detached `spawn`; and then, for each writer either search yields, follow
310    /// the ACTUAL route from the wake to the append and confirm the named gate
311    /// sits on it. Not to re-read this sentence and find it plausible.
312    fn drop(&mut self) {
313        if let Some(task) = &self.visibility_reconciliation_task {
314            task.abort();
315        }
316        self.runtime.nif_state().shutdown_timer_wheel();
317        self.runtime.engine_tasks().begin_close();
318    }
319}
320
321/// Components required to construct an [`Engine`].
322pub(crate) struct EngineComponents {
323    pub(crate) store: Arc<dyn EventStore>,
324    pub(crate) visibility_store: Arc<dyn VisibilityStore>,
325    pub(crate) runtime: Arc<RuntimeHandle>,
326    pub(crate) catalog: Arc<WorkflowCatalog>,
327    pub(crate) registry: Arc<Registry>,
328    pub(crate) supervision: Arc<SupervisionTree>,
329    pub(crate) delegated: DelegatedSeams,
330    pub(crate) signal_handoff: Arc<SignalResumeHandoff>,
331    pub(crate) search_attribute_schema: Arc<SearchAttributeSchema>,
332    pub(crate) visibility_reconciliation_task: Option<JoinHandle<()>>,
333}
334
335impl Engine {
336    /// Construct an engine from already-assembled components.
337    #[must_use]
338    pub(crate) fn new(components: EngineComponents) -> Self {
339        let EngineComponents {
340            store,
341            visibility_store,
342            runtime,
343            catalog,
344            registry,
345            supervision,
346            delegated,
347            signal_handoff,
348            search_attribute_schema,
349            visibility_reconciliation_task,
350        } = components;
351        let schedule_coordinator_workflow_id = schedule_coordinator_workflow_id();
352        let schedule_recorder = Arc::new(AsyncMutex::new(Recorder::new(
353            schedule_coordinator_workflow_id.clone(),
354            Arc::clone(&store),
355        )));
356        let runtime_arc = runtime;
357        let registry_arc = registry;
358        let supervision_arc = supervision;
359        let schedule_evaluator = Arc::new(AsyncMutex::new(default_schedule_evaluator(
360            schedule_coordinator_workflow_id.clone(),
361            Arc::clone(&schedule_recorder),
362            ScheduleRuntimeDeps {
363                store: Arc::clone(&store),
364                visibility_store: Arc::clone(&visibility_store),
365                runtime: Arc::clone(&runtime_arc),
366                catalog: Arc::clone(&catalog),
367                registry: Arc::clone(&registry_arc),
368                supervision: Arc::clone(&supervision_arc),
369                search_attribute_schema: Arc::clone(&search_attribute_schema),
370            },
371        )));
372        Self {
373            store,
374            visibility_store,
375            schedule_recorder,
376            schedule_evaluator,
377            schedule_coordinator_workflow_id,
378            runtime: runtime_arc,
379            catalog,
380            registry: registry_arc,
381            supervision: supervision_arc,
382            delegated,
383            signal_handoff,
384            search_attribute_schema,
385            shutdown_gate: ShutdownGate::default(),
386            deploy_mutations: AsyncMutex::new(()),
387            visibility_reconciliation_task,
388            paused_runs: crate::lifecycle::PausedRuns::default(),
389        }
390    }
391
392    /// Advance the schedule coordinator's recorder head to match persisted
393    /// events so that a rebuilt engine resumes appending at the correct
394    /// sequence rather than conflicting at head 0.
395    ///
396    /// # Errors
397    ///
398    /// Returns store read errors.
399    pub(crate) async fn catchup_schedule_coordinator(&self) -> Result<(), EngineError> {
400        let history = self
401            .store
402            .read_history(&self.schedule_coordinator_workflow_id)
403            .await?;
404        let head = u64::try_from(history.len()).unwrap_or(u64::MAX);
405        if head > 0 {
406            let mut recorder = self.schedule_recorder.lock().await;
407            *recorder = Recorder::resume_at(
408                self.schedule_coordinator_workflow_id.clone(),
409                Arc::clone(&self.store),
410                head,
411            );
412        }
413        Ok(())
414    }
415
416    /// Event store used by lifecycle and delegated AD/AT operations.
417    #[must_use]
418    pub fn store(&self) -> Arc<dyn EventStore> {
419        Arc::clone(&self.store)
420    }
421
422    /// Visibility store used for workflow summary projections.
423    #[must_use]
424    pub fn visibility_store(&self) -> Arc<dyn VisibilityStore> {
425        Arc::clone(&self.visibility_store)
426    }
427
428    /// Runtime boundary assembled for this engine.
429    #[must_use]
430    pub fn runtime(&self) -> &RuntimeHandle {
431        &self.runtime
432    }
433
434    /// Shared workflow package catalog: loaded versions and routing.
435    #[must_use]
436    pub fn workflow_catalog(&self) -> &Arc<WorkflowCatalog> {
437        &self.catalog
438    }
439
440    /// Active execution registry.
441    #[must_use]
442    pub fn registry(&self) -> &Registry {
443        &self.registry
444    }
445
446    /// Supervision tree snapshot/model.
447    #[must_use]
448    pub fn supervision(&self) -> &SupervisionTree {
449        &self.supervision
450    }
451
452    /// Delegated signal/query/subscribe seams installed for AT/AD integration.
453    #[must_use]
454    pub const fn delegated(&self) -> &DelegatedSeams {
455        &self.delegated
456    }
457
458    /// Shared in-memory handoff for already-recorded non-resident signals.
459    #[must_use]
460    pub fn signal_handoff(&self) -> Arc<SignalResumeHandoff> {
461        Arc::clone(&self.signal_handoff)
462    }
463
464    /// Absorb a dead peer's distribution shards into this LIVE engine and resume
465    /// their orphaned workflows — the SS-5 failover entry point.
466    ///
467    /// This is the production failover step a cluster supervisor invokes when it
468    /// observes a peer gone (membership loss). It is the post-boot counterpart to
469    /// the boot path's `EngineBuilder::owned_shards` election + recovery, run
470    /// against an already-running engine:
471    ///
472    /// 1. **Elect + union-merge.** `acquire_owned_shards` wins the per-shard
473    ///    election for each `shards` entry (fencing the dead owner) and
474    ///    `become_live` union-merges that shard's committed history locally, so
475    ///    every event the dead node had quorum-committed is now present on this
476    ///    node. The election is blocking and runs off the tokio runtime inside the
477    ///    store seam, honouring haematite's no-blocking-election-in-async
478    ///    constraint, so this `async` method may call it directly.
479    /// 2. **Widen the scope.** `extend_owned_shards` unions `shards` into this
480    ///    node's owned-enumeration set so the adopted workflows, timers, and
481    ///    outbox rows become visible to enumeration WITHOUT dropping this node's
482    ///    own shards.
483    /// 3. **Publish ownership.** `publish_shard_owner` records this node as each
484    ///    adopted shard's current owner in the cluster's quorum-replicated
485    ///    shard-owner directory (SS-3), so a request reaching a DIFFERENT survivor
486    ///    routes to this adopter rather than mis-resolving to the dead declared
487    ///    owner. The publish is fenced by the election just won, so only the true
488    ///    adopter writes it; a non-distributed store no-ops it.
489    /// 4. **Re-resident.** Re-run the idempotent active-workflow recovery and
490    ///    timer recovery, which re-spawn every adopted workflow from the
491    ///    union-merged history through the same production recovery seam the boot
492    ///    path uses, skipping the workflows this node already owns.
493    ///
494    /// Detection of the peer's death is the CALLER's responsibility (a cluster
495    /// supervisor / membership-loss trigger); this method performs the
496    /// re-acquisition and resume once that decision is made. It is idempotent:
497    /// adopting a shard this node already serves re-acquires (a no-op on the
498    /// fence it already holds) and recovers nothing new.
499    ///
500    /// # Errors
501    ///
502    /// Returns [`EngineError::ShuttingDown`] after shutdown begins, store errors
503    /// from the election / union-merge ([`EngineError::Durability`]), and any
504    /// typed recovery error from re-residenting an adopted workflow.
505    pub async fn adopt_shards(&self, shards: &[usize]) -> Result<(), EngineError> {
506        let operation = self.shutdown_gate.begin_start()?;
507        let result = self.adopt_shards_inner(shards).await;
508        drop(operation);
509        result
510    }
511
512    /// Body of [`Self::adopt_shards`]: acquire+publish each shard as a UNIT under
513    /// the double-adoption fence (ADR-021 clean-partial), then widen scope and
514    /// recover over EXACTLY the shards that survived BOTH steps.
515    ///
516    /// ## Ordering invariant (the fix)
517    ///
518    /// For each shard the publish-fence happens BEFORE the shard contributes to
519    /// `extend_owned_shards` AND before it is recovered. The pre-fix order
520    /// (extend → publish) let a survivor that won the election but was then
521    /// deposed at publish-time still widen its scope and recover the shard, so two
522    /// survivors could both execute its workflows. Here, a `NotOwner` from EITHER
523    /// `acquire_owned_shard` OR `publish_shard_owner` DROPS that shard: it never
524    /// reaches `extend_owned_shards`, is never recovered, and is NEVER a hard
525    /// `Durability` error. A deposed survivor therefore leaves ZERO widened
526    /// owned-shards scope and recovers nothing.
527    async fn adopt_shards_inner(&self, shards: &[usize]) -> Result<(), EngineError> {
528        // 1-3. Drive the double-adoption fence in the FIXED order (acquire →
529        //      publish per shard as a UNIT, then re-assert ownership and widen the
530        //      enumeration scope ONCE) and learn which shards survived it. A shard
531        //      deposed at acquire OR publish (or in the residual window) is dropped
532        //      cleanly — never extended, never recovered, never a hard error. The
533        //      planner GUARANTEES each survivor's publish-fence precedes both the
534        //      scope widening and (below) recovery. A single-node store no-ops
535        //      every step, so this path stays byte-identical there.
536        // The returned survivor set is already reflected in the store's widened
537        // owned-shard scope (the planner's single `extend`), which is what recovery
538        // enumerates over; the value is bound only to make that contract explicit.
539        let _recoverable = super::fence::plan_adopted_shards(
540            &super::fence::StoreFenceSeam {
541                store: &*self.store,
542            },
543            shards,
544        )?;
545        // 3b. Rebuild the pause dispatch-hold for the newly-adopted shards (#204).
546        //     The fence above widened the owned-shard scope, so `list_paused` now
547        //     sees the adopted shards' durably-`Paused` runs. `extend` (not replace)
548        //     preserves the holds for shards this node already owned. A run paused on
549        //     an adopted shard keeps its outbox rows held after failover; without this
550        //     the adopting node's dispatcher would claim and dispatch them. A store
551        //     error is logged, not fatal: the adoption itself is durable and the next
552        //     startup/rebuild repopulates the hold.
553        match self.store.list_paused().await {
554            Ok(paused) => self.paused_runs.extend(paused),
555            Err(error) => {
556                tracing::warn!(%error, "failed to rebuild paused-runs dispatch hold at shard adoption");
557            }
558        }
559        // 4. Re-resident the adopted workflows through the production recovery
560        //    seam (idempotent: this node's own workflows are skipped). Recovery
561        //    enumerates over the owned scope, which now contains only shards that
562        //    survived the fence.
563        super::startup::recover_adopted_shards(super::startup::StartupRecoveryContext {
564            store: Arc::clone(&self.store),
565            visibility_store: Arc::clone(&self.visibility_store),
566            runtime: Arc::clone(&self.runtime),
567            catalog: Arc::clone(&self.catalog),
568            registry: Arc::clone(&self.registry),
569            supervision: Arc::clone(&self.supervision),
570            recovery: None,
571            search_attribute_schema: Arc::clone(&self.search_attribute_schema),
572            bootstrap_schedule_coordinator: false,
573        })
574        .await?;
575        // 5. Re-arm durable timers for the adopted workflows — the SAME step the
576        //    boot path runs after `recover_active_workflows_on_startup` (see
577        //    `EngineBuilder::build`). This is LOAD-BEARING for a workflow PARKED on
578        //    a durable timer (#119): step 4 replays it and re-parks it, but the
579        //    replay of a not-yet-fired sleep does NOT re-arm the live wheel (only a
580        //    first, non-replay arrival does — see `nif_timer::sleep`'s `ResumeLive`
581        //    branch). Without this call the adopted workflow stays parked forever:
582        //    `recover_due` fires already-expired timers and
583        //    `rearm_future_from_active_histories` re-arms still-future ones onto the
584        //    now-resident process. Removing it reproduces the #119 symptom (a
585        //    survivor adopts the shard but the parked timer never reaches the
586        //    resumed workflow). Guarded by `tests/adoption_parked_timer_e2e.rs`
587        //    (single-process) and `tests/adoption_parked_timer_xnode_e2e.rs`
588        //    (real cross-node failover).
589        super::startup::recover_timers_on_startup(self.runtime.nif_state(), Arc::clone(&self.store))
590            .await
591    }
592
593    /// Gracefully stop accepting new starts and shut down the embedded runtime.
594    ///
595    /// # Errors
596    ///
597    /// Returns registry poison or runtime shutdown failures as typed errors.
598    pub fn shutdown(&self) -> Result<(), EngineError> {
599        if let Some(task) = &self.visibility_reconciliation_task {
600            task.abort();
601        }
602        // 🔴 THE EPOCH CLOSES FIRST, BEFORE ANY WAIT.
603        //
604        // The first cut put the unconditional close in `RuntimeHandle::shutdown`
605        // — one level BELOW the call the shipped server actually makes — and
606        // left this function short-circuiting above it. Two ways that lost the
607        // property it was written to guarantee:
608        //
609        //   1. `close_and_wait` returns `Err` on registry poison, so `?` here
610        //      returned before the epoch was ever gated and completion retries
611        //      stayed armed.
612        //   2. `close_and_wait` is a condvar wait with NO timeout. A lifecycle
613        //      operation stuck on a degraded store — precisely the condition
614        //      that arms completion retries in the first place — blocks this
615        //      function indefinitely, and the operator reasonably concludes the
616        //      node is wedged and brings up a successor while this process is
617        //      still appending terminals.
618        //
619        // Gating costs nothing, cannot fail, and is idempotent. Doing it first
620        // means no path through this function leaves retries armed. Everything
621        // after is teardown that still needs to run.
622        //
623        // 🔴 WHAT THIS ORDERING COSTS, STATED WHERE THE ORDERING IS CHOSEN.
624        // Process-exit callbacks are still admitted for the whole span between
625        // this line and `process_exits.begin_shutdown()` below, and the
626        // completion path refuses every one of them because the epoch is
627        // already closed. A run exiting in that window records no terminal and
628        // stays `Running` in the store, with one `error!` line naming it. The
629        // span is UNBOUNDED — `close_and_wait` is a condvar wait with no
630        // timeout — and it is longest under exactly the degraded-store
631        // condition the completion retries exist for. That window is the price
632        // of the two properties above and is argued in full at the refusal site
633        // (`lifecycle::completion`, at `refuse_if_epoch_closed`); it is
634        // repeated here because a reader deciding to move this line would
635        // otherwise not know a cost had been accepted.
636        self.runtime.engine_tasks().begin_close();
637        // Every step below runs on every path, and the FIRST error is returned
638        // at the end. A `?` here would skip the timer-wheel shutdown and the
639        // seam clearing, whose consequences are spelled out at their own call
640        // sites — an orphaned wheel task racing a survivor's adoption timer, and
641        // a durable backend's writer lock held past shutdown. Neither is
642        // something to trade for reporting an earlier error sooner.
643        //
644        // 🔴 THE SEAM CLEARING IS THE HALF WITH NO BACKSTOP, AND THAT IS THE
645        // WHOLE REASON. An earlier revision said `Drop for Engine` "backstops
646        // neither", which stopped being true in this same file when `Drop`
647        // gained `shutdown_timer_wheel` (see it above) — so the wheel half IS
648        // backstopped, and a reader checking only that half would conclude the
649        // `?` costs nothing. It does: `clear_engine_seams` runs from
650        // `Engine::shutdown` and NOWHERE else, by design — it may only run once
651        // the scheduler has stopped and both epochs are closed, which `Drop`
652        // cannot establish. Skip it and the `RuntimeHandle` ↔ `EngineNifState`
653        // cycle is never broken, so every store clone reached through the seams
654        // outlives the process's interest in them and a durable backend's
655        // cross-process writer lock is held until exit.
656        //
657        // 🔴 THE THIRD COST, STATED BECAUSE EVERY OTHER ONE IN THIS FUNCTION IS.
658        // `ShutdownGate::close_and_wait` returns `Err` on exactly one condition
659        // — mutex poison — and continuing past it means the gate's DRAIN
660        // guarantee is skipped, not merely its error deferred: a lifecycle
661        // operation admitted before the poison may still be in flight when
662        // `runtime.shutdown()` stops the scheduler and `clear_engine_seams()`
663        // nulls the seam slots. That is not a memory hazard (the slots are
664        // `Option`-shaped and a NIF reading a cleared one gets a typed error),
665        // and no NEW operation can be admitted either, because `begin_start`
666        // and `begin_operation` share the same poisoned `state()`. What is lost
667        // is the promise that nothing was still running when teardown began.
668        // Accepted for the same reason as the rest: the alternative is skipping
669        // the seam clearing, which is unbacked-up and permanent.
670        let mut first_error: Option<EngineError> = None;
671        // Scoped so the closure's unique borrow of `first_error` visibly ends
672        // before the value is read. (`drop(closure)` would end it just as
673        // surely — this crate is edition 2024, and under NLL a borrow ends at
674        // its last use — so this is a readability choice, not a soundness one.
675        // An earlier revision of this comment argued the opposite and was
676        // describing pre-NLL lexical scoping.)
677        {
678            // 🔴 THE SECOND ERROR IS REPORTED, NOT DISCARDED. Only one
679            // `EngineError` can be returned, but accumulate-and-continue means
680            // more than one step can fail — and at HEAD that could not happen
681            // at all, because `?` meant a later step never ran. Keeping only
682            // the first and dropping the rest would trade a skipped teardown
683            // for a swallowed failure, which is the same defect wearing the
684            // other hat: an operator seeing `RegistryPoisoned` would have no
685            // signal that the runtime teardown ALSO failed. Each subsequent
686            // failure is emitted at `error` level with the position that made
687            // it subsequent, so the log carries what the return value cannot.
688            let mut failed_steps = 0_u32;
689            let mut keep = |step: &'static str, result: Result<(), EngineError>| {
690                if let Err(error) = result {
691                    failed_steps += 1;
692                    if first_error.is_none() {
693                        first_error = Some(error);
694                    } else {
695                        tracing::error!(
696                            step,
697                            failed_steps,
698                            error = %error,
699                            "a further engine-shutdown step failed after an earlier one; only \
700                             the first failure can be returned, so this one is reported here"
701                        );
702                    }
703                }
704            };
705            keep(
706                "shutdown_gate.close_and_wait",
707                self.shutdown_gate.close_and_wait(),
708            );
709            // Epoch close for engine background tasks (F4): every watcher,
710            // spawn-recovery task and process-exit completion retry is aborted AND
711            // awaited to quiescence — a task still mid-record after shutdown could
712            // double-write a history a successor engine over the same store also
713            // records into. Arming is additionally gated inside the task registry
714            // the moment shutdown begins.
715            //
716            // `runtime.shutdown()` performs that close itself, because the
717            // completion retry is a core lifecycle path and its epoch close must not
718            // depend on whether an optional bridge was installed. The bridge call
719            // that follows is idempotent and kept only so an installed bridge
720            // participates explicitly.
721            keep("runtime.shutdown", self.runtime.shutdown());
722        }
723        self.runtime.nif_state().shutdown_engine_tasks();
724        // Abort armed live-wheel timer tasks (#119): they run on the tokio
725        // runtime, not the beamr scheduler, so `runtime.shutdown()` does not
726        // reach them. A timer this engine armed must NOT fire after the engine
727        // has stopped owning the workflow — otherwise, across a failover, the
728        // dead owner's orphaned wheel task races the survivor's adoption-armed
729        // timer and can record the one durable `TimerFired` first, leaving the
730        // survivor's resident sleeper parked forever.
731        self.runtime.nif_state().shutdown_timer_wheel();
732        // Break the RuntimeHandle <-> EngineNifState reference cycle (see
733        // EngineNifState::clear_engine_seams). The engine-scoped NIF seams each
734        // hold an Arc back to the runtime and/or clones of the event store and
735        // registry; without releasing them here the runtime, its NIF state, and
736        // every store clone they reach would outlive the dropped Engine
737        // forever, keeping a durable backend's writer lock held past shutdown.
738        // Safe now: the scheduler has stopped and the child-task and timer-wheel
739        // epochs have closed, so no NIF or background task can still read a slot.
740        self.runtime.nif_state().clear_engine_seams();
741        match first_error {
742            Some(error) => Err(error),
743            None => Ok(()),
744        }
745    }
746}
747
748pub(crate) fn terminal_outcome_from_history(events: &[Event]) -> Option<TerminalOutcome> {
749    // Reset-aware via the shared single-source predicate: the current lease's
750    // terminal event, where a reopen (WorkflowReopened) supersedes any earlier
751    // terminal.
752    match aion_core::current_lease_terminal(events)? {
753        Event::WorkflowCompleted { result, .. } => Some(TerminalOutcome::Completed(result.clone())),
754        Event::WorkflowFailed { error, .. } => Some(TerminalOutcome::Failed(error.clone())),
755        Event::WorkflowCancelled { reason, .. } => Some(TerminalOutcome::Cancelled(reason.clone())),
756        Event::WorkflowTimedOut { timeout, .. } => Some(TerminalOutcome::TimedOut(timeout.clone())),
757        Event::WorkflowContinuedAsNew {
758            input,
759            workflow_type,
760            parent_run_id,
761            ..
762        } => Some(TerminalOutcome::ContinuedAsNew {
763            input: input.clone(),
764            workflow_type: workflow_type.clone(),
765            parent_run_id: parent_run_id.clone(),
766        }),
767        _ => None,
768    }
769}
770
771pub(crate) fn workflow_not_found(id: &WorkflowId, run: &RunId) -> EngineError {
772    EngineError::WorkflowNotFound {
773        workflow_type: format!("{id}/{run}"),
774    }
775}
776
777#[cfg(test)]
778mod tests {
779    use std::sync::Arc;
780    use std::time::Duration;
781
782    use aion_core::{
783        Event, EventEnvelope, PackageVersion, Payload, RunId, SearchAttributeSchema,
784        TimerCancelCause, TimerId, WorkflowFilter, WorkflowId, WorkflowStatus,
785    };
786    use aion_package::ContentHash;
787    use aion_store::visibility::VisibilityStore;
788    use aion_store::{EventStore, InMemoryStore, ReadableEventStore};
789    use serde_json::json;
790
791    use std::collections::HashMap;
792
793    use super::{DelegatedSeams, Engine, EngineComponents};
794    use crate::durability::Recorder;
795    use crate::lifecycle::terminate::{self, TerminateWorkflowContext};
796    use crate::registry::{CompletionNotifier, HandleResidency, WorkflowHandleParts};
797    use crate::time::TimerRecovery;
798    use crate::time::timer_service::live_timers_in_active_segment;
799    use crate::{
800        EngineError, Registry, RuntimeConfig, RuntimeHandle, SupervisionTree, WorkflowCatalog,
801        WorkflowHandle,
802    };
803
804    fn payload(label: &str) -> Result<Payload, aion_core::PayloadError> {
805        Payload::from_json(&json!({ "label": label }))
806    }
807
808    fn workflow_error(message: &str) -> aion_core::WorkflowError {
809        aion_core::WorkflowError {
810            message: message.to_owned(),
811            details: None,
812        }
813    }
814
815    fn workflow_catalog(workflow_type: &str, deployed_module: &str) -> Arc<WorkflowCatalog> {
816        let catalog = Arc::new(WorkflowCatalog::new());
817        catalog.note_loaded_workflow_for_test(
818            workflow_type,
819            deployed_module,
820            "run",
821            ContentHash::from_bytes([5; 32]),
822        );
823        catalog
824    }
825
826    fn engine_with_loaded_workflow(
827        store: Arc<dyn EventStore>,
828        workflow_type: &str,
829        deployed_module: &str,
830    ) -> Result<Engine, EngineError> {
831        let runtime = RuntimeHandle::new(RuntimeConfig::new(Some(1)))?;
832        runtime.register_waiting_test_module(deployed_module, "run");
833        let visibility_store: Arc<dyn VisibilityStore> = Arc::new(InMemoryStore::default());
834        Ok(Engine::new(EngineComponents {
835            store,
836            visibility_store,
837            runtime: Arc::new(runtime),
838            catalog: workflow_catalog(workflow_type, deployed_module),
839            registry: Arc::new(Registry::default()),
840            supervision: Arc::new(SupervisionTree::new()),
841            delegated: DelegatedSeams::default(),
842            signal_handoff: Arc::new(crate::signal::SignalResumeHandoff::new()),
843            search_attribute_schema: Arc::new(SearchAttributeSchema::new()),
844            visibility_reconciliation_task: None,
845        }))
846    }
847
848    fn termination_context(engine: &Engine) -> TerminateWorkflowContext<'_> {
849        TerminateWorkflowContext {
850            runtime: engine.runtime(),
851            store: engine.store(),
852            visibility_store: engine.visibility_store(),
853            registry: engine.registry(),
854            catalog: engine.workflow_catalog(),
855        }
856    }
857
858    async fn insert_active_handle(
859        engine: &Engine,
860        store: Arc<dyn EventStore>,
861        workflow_type: &str,
862    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
863        let workflow_id = aion_core::WorkflowId::new_v4();
864        let run_id = aion_core::RunId::new_v4();
865        let mut recorder = Recorder::new(workflow_id.clone(), store);
866        recorder
867            .record_workflow_started(
868                chrono::Utc::now(),
869                crate::durability::WorkflowStartRecord {
870                    workflow_type: workflow_type.to_owned(),
871                    input: payload("input")?,
872                    run_id: run_id.clone(),
873                    parent_run_id: None,
874                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
875                },
876            )
877            .await?;
878        let pid = engine.runtime().spawn_test_process_with_trap_exit(true)?;
879        let handle = WorkflowHandle::new(WorkflowHandleParts {
880            workflow_id: workflow_id.clone(),
881            run_id: run_id.clone(),
882            pid,
883            workflow_type: workflow_type.to_owned(),
884            namespace: String::from("default"),
885            loaded_version: ContentHash::from_bytes([9; 32]),
886            cached_status: WorkflowStatus::Running,
887            residency: HandleResidency::Resident,
888            recorder,
889            completion: CompletionNotifier::new(),
890        });
891        engine
892            .registry()
893            .insert((workflow_id, run_id), handle.clone())?;
894        Ok(handle)
895    }
896
897    #[tokio::test]
898    async fn start_then_cancel_records_started_then_cancelled()
899    -> Result<(), Box<dyn std::error::Error>> {
900        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
901        let engine =
902            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
903        let handle = engine
904            .start_workflow(
905                "checkout",
906                payload("input")?,
907                HashMap::new(),
908                String::from("default"),
909            )
910            .await?;
911
912        engine
913            .cancel(
914                handle.workflow_id(),
915                handle.run_id(),
916                "caller requested cancellation",
917            )
918            .await?;
919
920        let history = store.read_history(handle.workflow_id()).await?;
921        match history.as_slice() {
922            [
923                Event::WorkflowStarted { .. },
924                Event::WorkflowCancelled { reason, .. },
925            ] => {
926                assert_eq!(reason, "caller requested cancellation");
927            }
928            other => return Err(format!("expected started then cancelled, found {other:?}").into()),
929        }
930        engine.shutdown()?;
931        Ok(())
932    }
933
934    fn test_envelope(workflow_id: &WorkflowId, seq: u64) -> EventEnvelope {
935        EventEnvelope {
936            seq,
937            recorded_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap_or_default(),
938            workflow_id: workflow_id.clone(),
939        }
940    }
941
942    fn started_event(workflow_id: &WorkflowId, seq: u64) -> Event {
943        Event::WorkflowStarted {
944            envelope: test_envelope(workflow_id, seq),
945            workflow_type: String::from("checkout"),
946            input: Payload::new(aion_core::ContentType::Json, b"{}".to_vec()),
947            run_id: RunId::new_v4(),
948            parent_run_id: None,
949            package_version: PackageVersion::new("a".repeat(64)),
950        }
951    }
952
953    fn timer_started_event(workflow_id: &WorkflowId, seq: u64, timer_id: &TimerId) -> Event {
954        Event::TimerStarted {
955            envelope: test_envelope(workflow_id, seq),
956            timer_id: timer_id.clone(),
957            fire_at: chrono::DateTime::from_timestamp(1_700_000_500, 0).unwrap_or_default(),
958        }
959    }
960
961    fn timer_fired_event(workflow_id: &WorkflowId, seq: u64, timer_id: &TimerId) -> Event {
962        Event::TimerFired {
963            envelope: test_envelope(workflow_id, seq),
964            timer_id: timer_id.clone(),
965        }
966    }
967
968    fn timer_cancelled_event(workflow_id: &WorkflowId, seq: u64, timer_id: &TimerId) -> Event {
969        Event::TimerCancelled {
970            envelope: test_envelope(workflow_id, seq),
971            timer_id: timer_id.clone(),
972            cause: TimerCancelCause::WorkflowIntent,
973        }
974    }
975
976    #[test]
977    fn live_timers_lists_started_and_unterminated() {
978        let workflow_id = WorkflowId::new_v4();
979        let first = TimerId::anonymous(0);
980        let second = TimerId::anonymous(1);
981        let history = vec![
982            started_event(&workflow_id, 0),
983            timer_started_event(&workflow_id, 1, &first),
984            timer_started_event(&workflow_id, 2, &second),
985        ];
986        assert_eq!(
987            live_timers_in_active_segment(&history),
988            vec![first, second],
989            "both started, unterminated timers should be live, in start order"
990        );
991    }
992
993    #[test]
994    fn live_timers_excludes_fired_and_cancelled() {
995        let workflow_id = WorkflowId::new_v4();
996        let fired = TimerId::anonymous(0);
997        let cancelled = TimerId::anonymous(1);
998        let live = TimerId::anonymous(2);
999        let history = vec![
1000            started_event(&workflow_id, 0),
1001            timer_started_event(&workflow_id, 1, &fired),
1002            timer_started_event(&workflow_id, 2, &cancelled),
1003            timer_started_event(&workflow_id, 3, &live),
1004            timer_fired_event(&workflow_id, 4, &fired),
1005            timer_cancelled_event(&workflow_id, 5, &cancelled),
1006        ];
1007        assert_eq!(
1008            live_timers_in_active_segment(&history),
1009            vec![live],
1010            "only the timer with no terminal event remains live"
1011        );
1012    }
1013
1014    #[test]
1015    fn live_timers_dedups_repeated_start() {
1016        let workflow_id = WorkflowId::new_v4();
1017        let timer = TimerId::anonymous(0);
1018        let history = vec![
1019            started_event(&workflow_id, 0),
1020            timer_started_event(&workflow_id, 1, &timer),
1021            timer_started_event(&workflow_id, 2, &timer),
1022        ];
1023        assert_eq!(live_timers_in_active_segment(&history), vec![timer]);
1024    }
1025
1026    #[test]
1027    fn live_timers_scopes_to_active_run_segment() {
1028        // A timer started in a prior run (before a continue-as-new
1029        // `WorkflowStarted`) must not be surfaced for the replacement run.
1030        let workflow_id = WorkflowId::new_v4();
1031        let prior_run = TimerId::anonymous(0);
1032        let current_run = TimerId::anonymous(0);
1033        let history = vec![
1034            started_event(&workflow_id, 0),
1035            timer_started_event(&workflow_id, 1, &prior_run),
1036            started_event(&workflow_id, 2),
1037            timer_started_event(&workflow_id, 3, &current_run),
1038        ];
1039        assert_eq!(
1040            live_timers_in_active_segment(&history),
1041            vec![current_run],
1042            "only timers from the latest WorkflowStarted segment are live"
1043        );
1044    }
1045
1046    #[test]
1047    fn live_timers_empty_history_is_empty() {
1048        assert!(live_timers_in_active_segment(&[]).is_empty());
1049    }
1050
1051    /// Build an engine whose runtime has the production timer NIF bridge
1052    /// installed against the given store + registry, so `Engine::cancel`'s timer
1053    /// cleanup exercises the real `TimerService` path (not a fake). Must be
1054    /// called from within a tokio runtime (`Handle::current()`).
1055    fn engine_with_timer_bridge(
1056        store: Arc<dyn EventStore>,
1057        registry: Arc<Registry>,
1058    ) -> Result<Engine, EngineError> {
1059        let runtime = RuntimeHandle::new(RuntimeConfig::new(Some(1)))?;
1060        runtime.register_waiting_test_module("checkout_deployed", "run");
1061        crate::runtime::nif_timer_bridge::install_timer_nif_bridge(
1062            runtime.nif_state(),
1063            Arc::clone(&registry),
1064            Arc::clone(&store),
1065            tokio::runtime::Handle::current(),
1066            crate::runtime::SignalDeliveryConfig::default(),
1067        );
1068        let visibility_store: Arc<dyn VisibilityStore> = Arc::new(InMemoryStore::default());
1069        Ok(Engine::new(EngineComponents {
1070            store,
1071            visibility_store,
1072            runtime: Arc::new(runtime),
1073            catalog: workflow_catalog("checkout", "checkout_deployed"),
1074            registry,
1075            supervision: Arc::new(SupervisionTree::new()),
1076            delegated: DelegatedSeams::default(),
1077            signal_handoff: Arc::new(crate::signal::SignalResumeHandoff::new()),
1078            search_attribute_schema: Arc::new(SearchAttributeSchema::new()),
1079            visibility_reconciliation_task: None,
1080        }))
1081    }
1082
1083    /// Root-cause regression: cancelling a workflow with a live durable timer
1084    /// must record `TimerCancelled` (before the terminal `WorkflowCancelled`),
1085    /// so the timer is dead in history and recovery never fires it as an
1086    /// orphan. Drives the real `Engine::cancel` against a runtime with the
1087    /// production timer bridge installed.
1088    #[tokio::test(flavor = "multi_thread")]
1089    async fn cancel_records_timer_cancelled_before_workflow_cancelled()
1090    -> Result<(), Box<dyn std::error::Error>> {
1091        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1092        let registry = Arc::new(Registry::default());
1093        let engine = engine_with_timer_bridge(Arc::clone(&store), Arc::clone(&registry))?;
1094
1095        let handle = engine
1096            .start_workflow(
1097                "checkout",
1098                payload("input")?,
1099                HashMap::new(),
1100                String::from("default"),
1101            )
1102            .await?;
1103
1104        // Arm a live durable timer for the resident run and record its
1105        // `TimerStarted`, exactly as the resume-live handoff would in production.
1106        let timer_id = TimerId::anonymous(0);
1107        let fire_at = chrono::Utc::now() + chrono::Duration::hours(1);
1108        handle
1109            .recorder()
1110            .lock()
1111            .await
1112            .record_timer_started(chrono::Utc::now(), timer_id.clone(), fire_at)
1113            .await?;
1114        let timer_service =
1115            crate::runtime::nif_timer_bridge::installed_timer_service(engine.runtime().nif_state())
1116                .map_err(|error| format!("timer service unavailable: {error}"))?;
1117        timer_service
1118            .schedule(handle.workflow_id().clone(), timer_id.clone(), fire_at)
1119            .await?;
1120
1121        engine
1122            .cancel(
1123                handle.workflow_id(),
1124                handle.run_id(),
1125                "caller requested cancellation",
1126            )
1127            .await?;
1128
1129        let history = store.read_history(handle.workflow_id()).await?;
1130        match history.as_slice() {
1131            [
1132                Event::WorkflowStarted { .. },
1133                Event::TimerStarted {
1134                    timer_id: started, ..
1135                },
1136                Event::TimerCancelled {
1137                    timer_id: cancelled,
1138                    ..
1139                },
1140                Event::WorkflowCancelled { reason, .. },
1141            ] => {
1142                assert_eq!(started, &timer_id);
1143                assert_eq!(cancelled, &timer_id, "the live timer must be cancelled");
1144                assert_eq!(reason, "caller requested cancellation");
1145            }
1146            other => {
1147                return Err(format!(
1148                    "expected [started, timer-started, timer-cancelled, cancelled], found {other:?}"
1149                )
1150                .into());
1151            }
1152        }
1153        engine.shutdown()?;
1154        Ok(())
1155    }
1156
1157    /// All live timers (not just one) are cancelled, in start order, before the
1158    /// terminal `WorkflowCancelled`.
1159    #[tokio::test(flavor = "multi_thread")]
1160    async fn cancel_cancels_multiple_live_timers() -> Result<(), Box<dyn std::error::Error>> {
1161        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1162        let registry = Arc::new(Registry::default());
1163        let engine = engine_with_timer_bridge(Arc::clone(&store), Arc::clone(&registry))?;
1164        let handle = engine
1165            .start_workflow(
1166                "checkout",
1167                payload("input")?,
1168                HashMap::new(),
1169                String::from("default"),
1170            )
1171            .await?;
1172
1173        let first = TimerId::anonymous(0);
1174        let second = TimerId::anonymous(1);
1175        let fire_at = chrono::Utc::now() + chrono::Duration::hours(1);
1176        {
1177            let recorder = handle.recorder();
1178            let mut recorder = recorder.lock().await;
1179            recorder
1180                .record_timer_started(chrono::Utc::now(), first.clone(), fire_at)
1181                .await?;
1182            recorder
1183                .record_timer_started(chrono::Utc::now(), second.clone(), fire_at)
1184                .await?;
1185        }
1186
1187        engine
1188            .cancel(handle.workflow_id(), handle.run_id(), "stop")
1189            .await?;
1190
1191        let history = store.read_history(handle.workflow_id()).await?;
1192        match history.as_slice() {
1193            [
1194                Event::WorkflowStarted { .. },
1195                Event::TimerStarted {
1196                    timer_id: started_first,
1197                    ..
1198                },
1199                Event::TimerStarted {
1200                    timer_id: started_second,
1201                    ..
1202                },
1203                Event::TimerCancelled {
1204                    timer_id: cancelled_first,
1205                    ..
1206                },
1207                Event::TimerCancelled {
1208                    timer_id: cancelled_second,
1209                    ..
1210                },
1211                Event::WorkflowCancelled { .. },
1212            ] => {
1213                assert_eq!(started_first, &first);
1214                assert_eq!(started_second, &second);
1215                assert_eq!(cancelled_first, &first, "first live timer cancelled first");
1216                assert_eq!(
1217                    cancelled_second, &second,
1218                    "second live timer cancelled second"
1219                );
1220            }
1221            other => {
1222                return Err(format!(
1223                    "expected two timer-cancels before workflow-cancel, found {other:?}"
1224                )
1225                .into());
1226            }
1227        }
1228        engine.shutdown()?;
1229        Ok(())
1230    }
1231
1232    /// End-to-end source-of-bug proof: a cancelled workflow leaves no orphan for
1233    /// startup recovery. With a past-due durable timer row (the exact shape that
1234    /// bricked startup before the fix), recovery surfaces no `UnknownWorkflow`
1235    /// and fires nothing — because cancel recorded `TimerCancelled`, so the
1236    /// timer is dead in history. Complements the committed `recover_due` defense
1237    /// test by proving the orphan is gone *at the source*.
1238    #[tokio::test(flavor = "multi_thread")]
1239    async fn cancelled_workflow_leaves_no_orphan_for_recovery()
1240    -> Result<(), Box<dyn std::error::Error>> {
1241        let concrete: Arc<InMemoryStore> = Arc::new(InMemoryStore::default());
1242        let store: Arc<dyn EventStore> = concrete.clone();
1243        let registry = Arc::new(Registry::default());
1244        let engine = engine_with_timer_bridge(Arc::clone(&store), Arc::clone(&registry))?;
1245        let handle = engine
1246            .start_workflow(
1247                "checkout",
1248                payload("input")?,
1249                HashMap::new(),
1250                String::from("default"),
1251            )
1252            .await?;
1253        let workflow_id = handle.workflow_id().clone();
1254
1255        // A live timer whose durable row is already past-due, inserted directly
1256        // (no wheel arm, so nothing races the cancel).
1257        let timer_id = TimerId::anonymous(0);
1258        let fire_at = chrono::Utc::now() - chrono::Duration::hours(1);
1259        handle
1260            .recorder()
1261            .lock()
1262            .await
1263            .record_timer_started(chrono::Utc::now(), timer_id.clone(), fire_at)
1264            .await?;
1265        concrete
1266            .schedule_timer(&workflow_id, &timer_id, fire_at)
1267            .await?;
1268
1269        let timer_service =
1270            crate::runtime::nif_timer_bridge::installed_timer_service(engine.runtime().nif_state())
1271                .map_err(|error| format!("timer service unavailable: {error}"))?;
1272
1273        engine.cancel(&workflow_id, handle.run_id(), "stop").await?;
1274
1275        // Cancel removed the workflow from the registry and the durable row is
1276        // now past-due — exactly the orphan scenario. Recovery must handle it
1277        // cleanly: the recorded `TimerCancelled` makes `fire_timer` a no-op, so
1278        // no `TimerFired` and (critically) no `UnknownWorkflow`.
1279        let readable: Arc<dyn ReadableEventStore> = concrete.clone();
1280        TimerRecovery::new(readable, timer_service, Duration::ZERO)
1281            .recover_on_startup(chrono::Utc::now())
1282            .await?;
1283
1284        let history = concrete.read_history(&workflow_id).await?;
1285        assert!(
1286            !history
1287                .iter()
1288                .any(|event| matches!(event, Event::TimerFired { .. })),
1289            "no timer should fire for a cancelled workflow during recovery"
1290        );
1291        assert!(
1292            history
1293                .iter()
1294                .any(|event| matches!(event, Event::TimerCancelled { .. })),
1295            "cancel must have recorded TimerCancelled at the source"
1296        );
1297        engine.shutdown()?;
1298        Ok(())
1299    }
1300
1301    #[tokio::test]
1302    async fn result_returns_completed_payload() -> Result<(), Box<dyn std::error::Error>> {
1303        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1304        let engine =
1305            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
1306        let handle = engine
1307            .start_workflow(
1308                "checkout",
1309                payload("input")?,
1310                HashMap::new(),
1311                String::from("default"),
1312            )
1313            .await?;
1314        let result_payload = payload("result")?;
1315
1316        terminate::complete(
1317            termination_context(&engine),
1318            handle.workflow_id(),
1319            handle.run_id(),
1320            result_payload.clone(),
1321        )
1322        .await?;
1323
1324        assert_eq!(
1325            engine.result(handle.workflow_id(), handle.run_id()).await?,
1326            Ok(result_payload)
1327        );
1328        engine.shutdown()?;
1329        Ok(())
1330    }
1331
1332    #[tokio::test]
1333    async fn result_returns_failed_workflow_error() -> Result<(), Box<dyn std::error::Error>> {
1334        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1335        let engine =
1336            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
1337        let handle = engine
1338            .start_workflow(
1339                "checkout",
1340                payload("input")?,
1341                HashMap::new(),
1342                String::from("default"),
1343            )
1344            .await?;
1345        let error = workflow_error("workflow failed");
1346
1347        terminate::fail(
1348            termination_context(&engine),
1349            handle.workflow_id(),
1350            handle.run_id(),
1351            error.clone(),
1352        )
1353        .await?;
1354
1355        assert_eq!(
1356            engine.result(handle.workflow_id(), handle.run_id()).await?,
1357            Err(error)
1358        );
1359        engine.shutdown()?;
1360        Ok(())
1361    }
1362
1363    #[tokio::test]
1364    async fn result_unknown_workflow_returns_not_found() -> Result<(), Box<dyn std::error::Error>> {
1365        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1366        let engine = engine_with_loaded_workflow(store, "checkout", "checkout_deployed")?;
1367        let workflow_id = aion_core::WorkflowId::new_v4();
1368        let run_id = aion_core::RunId::new_v4();
1369
1370        let result = engine.result(&workflow_id, &run_id).await;
1371
1372        assert!(matches!(result, Err(EngineError::WorkflowNotFound { .. })));
1373        engine.shutdown()?;
1374        Ok(())
1375    }
1376
1377    /// F5: `Engine::shutdown`'s SECOND failing step must be reported.
1378    ///
1379    /// Its two fallible steps both go through `keep`, which returns the first
1380    /// and emits every later one at `error` level. That `else` arm IS the fix
1381    /// for the swallowed-second-error defect, and nothing asserted on it: the
1382    /// sibling below arms only the drain, which fails the SECOND step, so
1383    /// `first_error` is still `None` when `keep` sees it and the `else` is
1384    /// never taken.
1385    ///
1386    /// Reaching it needs BOTH steps to fail, which is why `ShutdownGate` gained
1387    /// its own injection seam. The gate's only real failure is mutex poison, so
1388    /// the injected error is `RegistryPoisoned` — a fault wearing the label its
1389    /// injection point can actually issue.
1390    ///
1391    /// Killing mutation: replace the `else` body inside `keep` with `{}`. No
1392    /// `error!` is emitted and the capture assertion fails.
1393    #[tokio::test]
1394    async fn a_second_failing_engine_shutdown_step_is_reported_not_swallowed()
1395    -> Result<(), Box<dyn std::error::Error>> {
1396        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1397        let engine = engine_with_loaded_workflow(store, "checkout", "checkout_deployed")?;
1398
1399        // Both steps fail: the gate first (so it is the returned error), the
1400        // runtime drain second (so it lands in the `else`).
1401        engine.shutdown_gate.force_close_failure();
1402        engine.runtime().force_process_exit_drain_failure();
1403
1404        let (captured, subscriber) = crate::log_capture::LogCapture::new()?;
1405        let returned = {
1406            let _installed = tracing::subscriber::set_default(subscriber);
1407            engine.shutdown()
1408        };
1409
1410        let error = returned
1411            .err()
1412            .ok_or("both steps failed, so shutdown must not return Ok")?;
1413        assert!(
1414            matches!(error, EngineError::RegistryPoisoned),
1415            "control: the FIRST failure is the one returned, and it is the gate's: {error:?}"
1416        );
1417
1418        let reported: Vec<_> = captured
1419            .at_level("ERROR")?
1420            .into_iter()
1421            .filter(|event| event.mentions("a further engine-shutdown step failed"))
1422            .collect();
1423        assert!(
1424            !reported.is_empty(),
1425            "the second failing step must be reported — a teardown failure with no trace at all \
1426             is a swallowed Result, which this codebase forbids outright"
1427        );
1428        assert!(
1429            reported
1430                .iter()
1431                .any(|event| event.field("step") == Some("runtime.shutdown")),
1432            "the report must NAME the step, or the operator cannot tell which half failed: \
1433             {reported:?}"
1434        );
1435        Ok(())
1436    }
1437
1438    /// 🔴 A FAILING TEARDOWN STEP DOES NOT CANCEL THE STEPS AFTER IT.
1439    ///
1440    /// `shutdown` used to be a chain of `?`, so the first step that failed
1441    /// returned and every later step — the runtime drain, and the three
1442    /// `nif_state` teardowns that release the engine's installed seams — simply
1443    /// never ran. The process then exited with a catalog still installed and an
1444    /// engine reference still reachable from the NIF table: the exact leak the
1445    /// function exists to prevent, produced by the error path of the function
1446    /// itself.
1447    ///
1448    /// The reason this went unmeasured is that no drain failure in here can be
1449    /// produced on demand, so no test ever took the error path at all.
1450    ///
1451    /// 🔴 WHY THAT SET IS UNREACHABLE IS STATED IN EXACTLY ONE PLACE, AND IT IS
1452    /// NOT HERE. See [`crate::RuntimeHandle::shutdown`].
1453    ///
1454    /// This comment has now been wrong twice about it, in two different ways —
1455    /// first "every one is timeout-shaped", then "the shared PRECONDITION: each
1456    /// needs a worker thread or a beamr publisher in a state no test can
1457    /// arrange". The second is false for `ProcessExitOutcomeMissingAfterEvent`,
1458    /// which is a beamr contract breach surfaced through `registry.process_event`
1459    /// and needs neither. It also reasons from a shared property, which is the
1460    /// move `RuntimeHandle::shutdown` explicitly forbids — the set is OPEN, so
1461    /// no property shared by today's members is safe to state about it.
1462    ///
1463    /// Two wrong answers in two revisions is what a rule known in two places
1464    /// does, and the cure is subtraction rather than a third attempt: the
1465    /// characterisation lives at the one site that owns the drain, and this one
1466    /// points at it. All that is needed locally is that
1467    /// `force_process_exit_drain_failure` is the named `#[cfg(test)]` seam that
1468    /// makes the path reachable at all, and that it cannot reach a shipped
1469    /// binary.
1470    ///
1471    /// **The decisive observable is (c), not (a).** That the error still reaches
1472    /// the caller is true of the old chain too — it is what the old chain did
1473    /// *instead of* finishing. Only `installed_workflow_catalog() == None` can
1474    /// tell "the later steps ran" from "the function returned early", because
1475    /// `clear_engine_seams` is ordered after the failing step. A test asserting
1476    /// only the error would pass against the defect.
1477    #[tokio::test]
1478    async fn a_failing_teardown_step_does_not_skip_the_ones_after_it()
1479    -> Result<(), Box<dyn std::error::Error>> {
1480        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1481        let engine = engine_with_loaded_workflow(store, "checkout", "checkout_deployed")?;
1482
1483        // Installed explicitly, because `engine_with_loaded_workflow` calls
1484        // `Engine::new` directly and only `EngineBuilder::build` installs the NIF
1485        // seams. Without this the assertion below would hold on an engine that
1486        // never had a catalog to clear — a pass measuring nothing. The control
1487        // that follows is what caught exactly that on the first cut of this test.
1488        engine
1489            .runtime()
1490            .nif_state()
1491            .set_workflow_catalog(Arc::clone(engine.workflow_catalog()));
1492
1493        // Control: the seam under (c) is genuinely installed before the call, so
1494        // a `None` afterwards is the teardown's doing and not the absence of
1495        // anything to tear down.
1496        assert!(
1497            engine
1498                .runtime()
1499                .nif_state()
1500                .installed_workflow_catalog()
1501                .is_some(),
1502            "control: the catalog must be installed before shutdown, or asserting it is \
1503             cleared afterwards measures nothing"
1504        );
1505
1506        engine.runtime().force_process_exit_drain_failure();
1507        let error = engine
1508            .shutdown()
1509            .err()
1510            .ok_or("an injected drain failure must be reported, not swallowed")?;
1511
1512        assert!(
1513            matches!(error, EngineError::ProcessExitRegistryPoisoned),
1514            "(a) the failure must reach the caller as itself: {error:?}"
1515        );
1516        assert!(
1517            !engine.runtime().engine_tasks().is_epoch_open(),
1518            "(b) the epoch must be closed — it is closed FIRST, so a shutdown that failed \
1519             later must still leave it shut"
1520        );
1521        assert!(
1522            engine
1523                .runtime()
1524                .nif_state()
1525                .installed_workflow_catalog()
1526                .is_none(),
1527            "(c) THE DECISIVE ONE: `clear_engine_seams` is ordered AFTER the step that \
1528             failed, so a still-installed catalog means the failure returned early and \
1529             the engine leaked its seams"
1530        );
1531        Ok(())
1532    }
1533
1534    #[tokio::test]
1535    async fn continue_as_new_unknown_workflow_returns_not_found()
1536    -> Result<(), Box<dyn std::error::Error>> {
1537        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1538        let engine = engine_with_loaded_workflow(store, "checkout", "checkout_deployed")?;
1539        let workflow_id = aion_core::WorkflowId::new_v4();
1540        let run_id = aion_core::RunId::new_v4();
1541
1542        let result = engine
1543            .continue_as_new(&workflow_id, &run_id, payload("next")?, None)
1544            .await;
1545
1546        assert!(matches!(result, Err(EngineError::WorkflowNotFound { .. })));
1547        engine.shutdown()?;
1548        Ok(())
1549    }
1550
1551    #[tokio::test]
1552    async fn list_workflows_merges_live_and_terminal_without_duplicates()
1553    -> Result<(), Box<dyn std::error::Error>> {
1554        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1555        let engine =
1556            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
1557        let running = insert_active_handle(&engine, Arc::clone(&store), "checkout").await?;
1558        let completed = engine
1559            .start_workflow(
1560                "checkout",
1561                payload("input")?,
1562                HashMap::new(),
1563                String::from("default"),
1564            )
1565            .await?;
1566        terminate::complete(
1567            termination_context(&engine),
1568            completed.workflow_id(),
1569            completed.run_id(),
1570            payload("result")?,
1571        )
1572        .await?;
1573
1574        let summaries = engine.list_workflows(WorkflowFilter::default()).await?;
1575        assert_eq!(summaries.len(), 2);
1576        assert!(summaries.iter().any(|summary| {
1577            &summary.workflow_id == running.workflow_id()
1578                && summary.status == WorkflowStatus::Running
1579        }));
1580        assert!(summaries.iter().any(|summary| {
1581            &summary.workflow_id == completed.workflow_id()
1582                && summary.status == WorkflowStatus::Completed
1583        }));
1584
1585        let completed_only = engine
1586            .list_workflows(WorkflowFilter {
1587                status: Some(WorkflowStatus::Completed),
1588                ..WorkflowFilter::default()
1589            })
1590            .await?;
1591        assert_eq!(completed_only.len(), 1);
1592        assert_eq!(&completed_only[0].workflow_id, completed.workflow_id());
1593        engine.shutdown()?;
1594        Ok(())
1595    }
1596
1597    #[tokio::test]
1598    async fn shutdown_rejects_subsequent_starts() -> Result<(), Box<dyn std::error::Error>> {
1599        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1600        let engine =
1601            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
1602        let handle = engine
1603            .start_workflow(
1604                "checkout",
1605                payload("input")?,
1606                HashMap::new(),
1607                String::from("default"),
1608            )
1609            .await?;
1610        terminate::complete(
1611            termination_context(&engine),
1612            handle.workflow_id(),
1613            handle.run_id(),
1614            payload("result")?,
1615        )
1616        .await?;
1617
1618        engine.shutdown()?;
1619        let result = engine
1620            .start_workflow(
1621                "checkout",
1622                payload("after-shutdown")?,
1623                HashMap::new(),
1624                String::from("default"),
1625            )
1626            .await;
1627
1628        assert!(matches!(result, Err(EngineError::ShuttingDown)));
1629        Ok(())
1630    }
1631
1632    #[tokio::test]
1633    async fn shutdown_is_idempotent() -> Result<(), Box<dyn std::error::Error>> {
1634        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1635        let engine =
1636            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
1637        let handle = engine
1638            .start_workflow(
1639                "checkout",
1640                payload("input")?,
1641                HashMap::new(),
1642                String::from("default"),
1643            )
1644            .await?;
1645        terminate::complete(
1646            termination_context(&engine),
1647            handle.workflow_id(),
1648            handle.run_id(),
1649            payload("result")?,
1650        )
1651        .await?;
1652
1653        engine.shutdown()?;
1654        let second = engine.shutdown();
1655
1656        assert!(
1657            second.is_ok(),
1658            "double shutdown should succeed; got {second:?}"
1659        );
1660        Ok(())
1661    }
1662
1663    #[tokio::test]
1664    async fn shutdown_rejects_schedule_creation() -> Result<(), Box<dyn std::error::Error>> {
1665        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
1666        let engine =
1667            engine_with_loaded_workflow(Arc::clone(&store), "checkout", "checkout_deployed")?;
1668        let handle = engine
1669            .start_workflow(
1670                "checkout",
1671                payload("input")?,
1672                HashMap::new(),
1673                String::from("default"),
1674            )
1675            .await?;
1676        terminate::complete(
1677            termination_context(&engine),
1678            handle.workflow_id(),
1679            handle.run_id(),
1680            payload("result")?,
1681        )
1682        .await?;
1683        engine.shutdown()?;
1684
1685        let config = aion_core::ScheduleConfig {
1686            trigger: aion_core::TriggerSpec::Interval {
1687                period: Duration::from_secs(60),
1688            },
1689            overlap_policy: aion_core::OverlapPolicy::Skip,
1690            catch_up_policy: aion_core::CatchUpPolicy::Skip,
1691            workflow_type: String::from("checkout"),
1692            input: payload("scheduled")?,
1693            search_attributes: HashMap::new(),
1694        };
1695        let result = engine.create_schedule(config).await;
1696
1697        assert!(
1698            matches!(result, Err(EngineError::ShuttingDown)),
1699            "create_schedule after shutdown should return ShuttingDown; got {result:?}"
1700        );
1701        Ok(())
1702    }
1703}