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    /// One-shot slot for deferred startup recovery (#266). `NotDeferred` on a
50    /// default build; `Pending` until [`Engine::run_startup_recovery`]
51    /// consumes it.
52    pub(super) deferred_startup_recovery:
53        std::sync::Mutex<super::startup_deferred::DeferredRecoverySlot>,
54    /// Shared dispatch-hold set for durable pause (#204): the workflow ids whose
55    /// outbox rows are held `Pending` while paused. Mutated by pause/resume/cancel
56    /// and rebuilt from [`EventStore::list_paused`] at startup/adoption; read by
57    /// the outbox dispatcher at claim time.
58    pub(super) paused_runs: crate::lifecycle::PausedRuns,
59}
60
61impl Drop for Engine {
62    /// Close the engine-task epoch when the engine is released, whether or not
63    /// [`Engine::shutdown`] was ever called or ever succeeded.
64    ///
65    /// Without this, an engine dropped without a successful shutdown left
66    /// completion retries armed and appending terminal events. They could not
67    /// be stopped by `EngineTaskRuntime::drop` either: an attempt in flight
68    /// upgrades its weak reference and holds the `RuntimeHandle` strongly for
69    /// the length of the attempt, so the refcount never reaches zero and that
70    /// backstop is unreachable for precisely the span of the append it exists
71    /// to stop. This drop runs before the engine's own fields are released, so
72    /// it does not depend on that refcount at all.
73    ///
74    /// Closes the engine-task epoch with `EngineTaskRuntime::shutdown`, whose
75    /// runtime drop is isolated on a plain joiner thread. That makes joined
76    /// cleanup safe even when this `Drop` runs inside a host async context: the
77    /// epoch is gated, every task is aborted, and the executor's I/O driver is
78    /// released before `Drop` returns. The gate remains load-bearing for an
79    /// attempt already past an await boundary: its append boundary reads
80    /// `is_epoch_open` and refuses.
81    ///
82    /// # The visibility reconciliation task is aborted here for the same reason
83    ///
84    /// It runs on the HOST runtime, not the engine-task executor, so the epoch
85    /// gate does not reach it — and dropping its `JoinHandle` detaches rather
86    /// than cancels. It is an unbounded loop holding the event store and the
87    /// visibility store, and `reconcile_visibility` WRITES. Left detached, an
88    /// engine released without `shutdown` went on upserting visibility rows for
89    /// the life of the process, against a store a successor engine may already
90    /// own. `Engine::shutdown` aborts it as its first act; this does the same,
91    /// so the two paths agree.
92    ///
93    /// # The live timer wheel is disarmed here for the third time, same reason
94    ///
95    /// 🔴 THIS WAS MISSING, AND IT LEFT A DURABLE WRITER ARMED. Live-wheel
96    /// timer tasks are `tokio::spawn`ed on the HOST runtime
97    /// (`runtime/nif_timer_bridge.rs`), so — exactly like the reconciliation
98    /// loop — the engine-task epoch gate does not reach them. Their body is
99    /// `fire_wheel_timer`, which records a durable `TimerFired`. They hold a
100    /// `Weak<EngineNifState>`, and this drop deliberately does NOT clear the
101    /// seams (see below), so that upgrade succeeds and the fire proceeds.
102    ///
103    /// An engine released without `shutdown` therefore kept a durable-append
104    /// path armed for the life of the process. `Engine::shutdown` names the
105    /// consequence precisely: across a failover, the dead owner's orphaned
106    /// wheel task races the survivor's adoption-armed timer and can record the
107    /// one durable `TimerFired` first, leaving the survivor's resident sleeper
108    /// parked forever. That is the single-writer invariant, and nothing about
109    /// it cares whether the engine was shut down or dropped.
110    ///
111    /// Safe in a `Drop`: `shutdown_timer_wheel` sets a flag and then performs a
112    /// `DashMap` drain plus `abort()` — non-blocking, structurally identical to
113    /// the `visibility_reconciliation_task.abort()` above. It therefore remains
114    /// safe before the joined engine-task shutdown below.
115    ///
116    /// 🔴 AND IT IS A GATE, NOT ONLY A DRAIN — which it had to become for this
117    /// `Drop` to be worth anything. A drain closes the set of timers armed at
118    /// one instant; this `Drop` deliberately leaves the beamr scheduler and the
119    /// engine seams alive, so a workflow process still runnable could reach
120    /// `sleep` a moment later and arm a fresh durable `TimerFired` writer
121    /// through a wheel this drop believed it had emptied. `arm_timer` now
122    /// refuses once the flag is set (`nif_timer_bridge.rs`, `shut_down`), so
123    /// the guarantee below is a property of the wheel from here on rather than
124    /// of one instant.
125    ///
126    /// # 🔴 WHAT THIS DOES NOT DO, STATED SO NOBODY READS MORE INTO IT
127    ///
128    /// It does not clear the engine NIF seams. Those hold `Arc`s back to the
129    /// `RuntimeHandle`, so until `clear_engine_seams` runs the handle, its
130    /// beamr scheduler and every store clone they reach outlive this drop.
131    /// `Engine::shutdown` clears them only after the scheduler has stopped and
132    /// the child-task and timer-wheel epochs have closed; none of that has
133    /// happened here, and a NIF could still read a slot this drop cleared.
134    /// Trading a scheduler leak for a use-after-clear is the wrong direction,
135    /// so that leak stands and is named: **an engine released without explicit
136    /// `shutdown` still holds its scheduler and installed seams.** The dedicated
137    /// engine-task executor is different: it is joined below so its I/O driver
138    /// cannot accumulate process descriptors. What this drop guarantees for
139    /// durability is still narrower — **no durable writer this drop can reach
140    /// keeps writing, and no writer it cannot reach can end a run.** The first
141    /// clause covers FOUR BACKGROUND writers, stopped in two different ways:
142    ///
143    /// 1. anything armed on the **engine-task epoch** — `shutdown()` below;
144    /// 2. the **visibility reconciliation loop** — `abort()` below;
145    /// 3. the **live timer wheel** — `shutdown_timer_wheel()` below, which
146    ///    gates and drains, *and* refuses at the point of writing, because
147    ///    `abort` cannot stop a task already inside a poll. That refusal is in
148    ///    TWO places, not one, and the second is easy to miss: an ordinary timer
149    ///    is refused at the bridge's append boundary
150    ///    (`nif_timer_bridge.rs`, `record_workflow_event`), but a reserved
151    ///    `deadline:{run}` fire never reaches that boundary — `fire_timer_guarded`
152    ///    demuxes it to the deadline handler first — so it is refused inside
153    ///    [`crate::lifecycle::deadline::WorkflowDeadlineHandler`] instead, off
154    ///    the same latch;
155    /// 4. the **activity completion / retry task**
156    ///    ([`crate::runtime::nif_activity_retry_dispatch::spawn_completion_task`]),
157    ///    which this drop **cannot reach at all**: its `JoinHandle` is
158    ///    discarded, so it is detached on the host runtime and nothing here
159    ///    registers or aborts it. It is stopped instead at its append boundary,
160    ///    which reads `is_epoch_open()` under the recorder lock — so step 1's
161    ///    the engine-task epoch closure is what silences it, one indirection away.
162    ///
163    /// # 🔴 AND THERE IS A FIFTH, WHICH IS NOT A BACKGROUND WRITER AT ALL
164    ///
165    /// The four above are things the engine spawned; this drop stops them
166    /// because it can reach them. The fifth is the **workflow process itself**,
167    /// and this drop deliberately does not stop it — it leaves the beamr
168    /// scheduler running and the NIF seams installed, which is exactly what the
169    /// section above says it is trading for. A still-runnable workflow process
170    /// therefore keeps calling NIFs after the `Engine` is gone, and **13 of the
171    /// 24 registered engine NIFs perform durable writes** — `dispatch_activity`,
172    /// `dispatch_activity_in_vm`, `await_activity_result`, `sleep`,
173    /// `start_timer`, `cancel_timer`, `with_timeout`, `continue_as_new`,
174    /// `send_signal`, `spawn_child`, `collect_all`, `collect_race`,
175    /// `collect_map`. The other 11 read or reply and record nothing. The
176    /// registration table is `runtime::engine_nifs::engine_nif_entries`, whose
177    /// own test asserts the total, so both halves of that split are checkable
178    /// against a closed set rather than taken on trust — which is the point,
179    /// since the first draft of this paragraph carried a transposed count.
180    /// None of the 13 consults the engine-task epoch, and
181    /// nothing in the append path does either: `NifContext::block_on_recorder`
182    /// takes the recorder lock and nothing else, and `Recorder::append_one`
183    /// goes straight to `store.append`.
184    ///
185    /// An earlier revision of this doc said "there are FOUR" full stop, and was
186    /// wrong in the way that matters most: it did not omit an obscure writer, it
187    /// omitted **the one that executes user code**.
188    ///
189    /// What has been closed is the part that can END A RUN.
190    /// `WorkflowContinuedAsNew` is a TERMINAL, it was the ONE terminal this
191    /// fifth writer could still record, and it is now refused off the same epoch
192    /// (`runtime::nif_continue_as_new::record_continuation`). The reason it had
193    /// to be, in one line: **the successor run that terminal obliges was already
194    /// refused** at `completion::start_continuation_replacement`, so the two
195    /// halves of one transition disagreed and the run was left terminal with no
196    /// continuation. Every other terminal reachable from workflow code was
197    /// already gated — process exit at the completion append boundary,
198    /// `WorkflowTimedOut` off the timer bridge's stand-down latch.
199    ///
200    /// **And the refusal ENDS THE PROCESS, which is the half that makes it a
201    /// gain rather than a trade.** Before the gate, the recorder call either
202    /// succeeded or aborted the NIF, and the success path always reached
203    /// `cancel_pid` — that instruction is where this fifth writer died. A
204    /// refusal that merely returned early would have removed it, leaving the
205    /// process runnable and free to make every ungated write listed below. So
206    /// `runtime::nif_continue_as_new` terminates on the epoch refusal too — and,
207    /// of the refusals, on that one ONLY. A pre-terminal store fault is an
208    /// ordinary error workflow code may handle, and killing a process for it
209    /// would turn a transient blip into a dead run; an already-terminal run is
210    /// spared for a different reason — its terminal was recorded by a seam
211    /// that owns its own teardown, and of those owners some end the pid (a
212    /// second `cancel_pid` from here would race them) while some only
213    /// deregister (a kill from here would usurp them). The predicate's doc
214    /// carries that split; the "Five ordinary terminal paths" paragraph in
215    /// `lifecycle/completion.rs` carries the one enumeration of the owners.
216    /// It ALSO terminates whenever the terminal actually landed, including
217    /// the half-completed case where the terminal is durable but the deadline
218    /// retirement that follows it failed — because the question that decides
219    /// this is "did the terminal land", not "was there an error". The
220    /// predicate is `outcome_must_end_the_process`, pinned by a test with both
221    /// negative controls.
222    ///
223    /// The cost, stated because it is not zero: the refusal returns before
224    /// `retire_run_deadline`, so the predecessor's deadline row stays armed. A
225    /// restart gap longer than the run's remaining budget times the run out
226    /// instead of continuing it. That is the same exposure every other in-flight
227    /// run already carries across an outage; the old path escaped it only by
228    /// recording a terminal for a transition that never completed.
229    ///
230    /// # 🔴 WHAT IS STILL OPEN, AND WHY IT IS NOT CLOSED HERE
231    ///
232    /// A workflow process refused by the EPOCH gate is now stopped, so the
233    /// writes below are not reachable from that path. Say "the epoch gate" and
234    /// not "was refused": the other refusals deliberately leave the process
235    /// alive, so a reader who takes this sentence at its widest reading would
236    /// believe an exposure is closed that is open by design.
237    ///
238    /// They remain fully open on every other path — a process that never calls
239    /// `continue_as_new` is untouched by any of this and keeps writing.
240    ///
241    /// The fifth writer's NON-terminal durable writes are ungated and remain so:
242    /// `TimerStarted` plus a durable timer row (`sleep`, `start_timer`,
243    /// `with_timeout` — `TimerService::schedule` writes the row and only then
244    /// arms, so the wheel's refusal lands after both), activity schedule/start
245    /// and completion records, `spawn_child`'s whole child-start chain, and
246    /// `send_signal`, which writes into a THIRD workflow's history.
247    ///
248    /// Two things bound that, and neither is what a reader might assume:
249    /// - `WriteToken` fences NOTHING. It is a zero-sized marker with a public
250    ///   `recorder()` constructor and no engine, epoch, lease or node identity;
251    ///   two engines over one store both mint valid ones. Its own doc says so —
252    ///   it exists to stop an `Arc<dyn EventStore>` alone being write authority.
253    /// - `SequenceConflict` catches only the LOSER of a head race, and a
254    ///   released engine is structurally positioned to be the winner: its
255    ///   Recorder is the one already at the current head, because it is the one
256    ///   that has been appending. If it writes first, its write succeeds and the
257    ///   SUCCESSOR takes the conflict.
258    ///
259    /// So the remaining exposure is real and is stated rather than denied. It is
260    /// not closed here because **no flag in this crate distinguishes "released"
261    /// from "shutting down"** — `begin_close` sets one bit and both `Engine::drop`
262    /// and `Engine::shutdown` set it. A gate on that bit at a workflow-process
263    /// write path would therefore also fire during an ORDINARY graceful
264    /// shutdown, for the whole unbounded span between `begin_close()` and
265    /// `runtime.shutdown()` further down this file, and there the failure is an
266    /// `{error, _}` returned INSIDE running workflow code — a failed `sleep`, a
267    /// failed `spawn_child` — on runs the shutdown was trying to leave intact.
268    /// The terminal was worth that trade because its successor was already
269    /// refused at `start_continuation_replacement`: recording it could only
270    /// produce a run that is terminal with no continuation.
271    ///
272    /// ⚠️ **Refusing it is not free, and an earlier revision of this sentence
273    /// said it was.** It read "refusing cost nothing that was not already lost",
274    /// which is the exact claim `runtime::nif_continue_as_new`'s own
275    /// documentation exists to retract — and which the "cost, stated because it
276    /// is not zero" paragraph above already contradicts. The price is stated
277    /// there and holds here: the refusal returns before `retire_run_deadline`,
278    /// so the predecessor's deadline stays armed and a long enough outage
279    /// times the run out instead of continuing it. What makes the trade worth
280    /// taking is not that it is free but that the alternative bought its
281    /// exemption with a false terminal.
282    ///
283    /// Refusing ordinary progress is a different bargain and needs a latch that
284    /// means what it says. Do not add one of these gates without adding that
285    /// latch.
286    ///
287    /// 🔴 THAT LIST IS A CLAIM ABOUT DURABLE WRITERS AND IT IS ONLY AS GOOD AS
288    /// ITS ENUMERATION — four times proven. An earlier revision named two and
289    /// was wrong: the timer wheel was the third, and it was armed. The revision
290    /// after that named three and was also wrong: the completion task was the
291    /// fourth, it had no epoch check of any kind, and it sleeps an
292    /// SDK-declared backoff with no ceiling between attempts. And the revision
293    /// after THAT — the one that added the wheel's append-boundary refusal —
294    /// wrote entry 3 as though that boundary covered the whole wheel, when the
295    /// deadline path is demuxed away before it and had no refusal at all: an
296    /// engine released without `shutdown` could still record a durable
297    /// `WorkflowTimedOut` and tear a run down. **The enumeration was right and
298    /// the mechanism named under it was not**, which is the harder failure to
299    /// see, because the list looked complete.
300    ///
301    /// And the FOURTH time is the section above: every revision so far had
302    /// enumerated only what this drop *reaches*, and then written a guarantee
303    /// over every writer that *exists*. The workflow process is not on any list
304    /// of things a `Recorder` grep or a `spawn` grep produces, because nobody
305    /// spawned it here and it holds no handle this file can see — it is reached
306    /// through an installed NIF seam by code the operator wrote. **A search
307    /// shaped like the mechanism you already know will not find the writer you
308    /// do not.** That is why the method below now starts from the NIF
309    /// registration table, which is a closed set that something asserts the size
310    /// of, rather than from a grep whose completeness nothing checks.
311    ///
312    /// The way to check this list is: take
313    /// `runtime::engine_nifs::engine_nif_entries` and account for every entry;
314    /// grep the crate for every construction of a `Recorder` handle and every
315    /// detached `spawn`; and then, for each writer either search yields, follow
316    /// the ACTUAL route from the wake to the append and confirm the named gate
317    /// sits on it. Not to re-read this sentence and find it plausible.
318    fn drop(&mut self) {
319        if let Some(task) = &self.visibility_reconciliation_task {
320            task.abort();
321        }
322        self.runtime.nif_state().shutdown_timer_wheel();
323        self.runtime.engine_tasks().shutdown();
324    }
325}
326
327/// Components required to construct an [`Engine`].
328pub(crate) struct EngineComponents {
329    pub(crate) store: Arc<dyn EventStore>,
330    pub(crate) visibility_store: Arc<dyn VisibilityStore>,
331    pub(crate) runtime: Arc<RuntimeHandle>,
332    pub(crate) catalog: Arc<WorkflowCatalog>,
333    pub(crate) registry: Arc<Registry>,
334    pub(crate) supervision: Arc<SupervisionTree>,
335    pub(crate) delegated: DelegatedSeams,
336    pub(crate) signal_handoff: Arc<SignalResumeHandoff>,
337    pub(crate) search_attribute_schema: Arc<SearchAttributeSchema>,
338    pub(crate) visibility_reconciliation_task: Option<JoinHandle<()>>,
339    /// `Some` when the builder deferred startup recovery (#266): the stowed
340    /// recovery inputs [`Engine::run_startup_recovery`] consumes. `None` when
341    /// `build()` ran recovery itself, as it does by default.
342    pub(crate) deferred_startup_recovery: Option<super::startup_deferred::DeferredStartupRecovery>,
343}
344
345impl Engine {
346    /// Construct an engine from already-assembled components.
347    #[must_use]
348    pub(crate) fn new(components: EngineComponents) -> Self {
349        let EngineComponents {
350            store,
351            visibility_store,
352            runtime,
353            catalog,
354            registry,
355            supervision,
356            delegated,
357            signal_handoff,
358            search_attribute_schema,
359            visibility_reconciliation_task,
360            deferred_startup_recovery,
361        } = components;
362        let schedule_coordinator_workflow_id = schedule_coordinator_workflow_id();
363        let schedule_recorder = Arc::new(AsyncMutex::new(Recorder::new(
364            schedule_coordinator_workflow_id.clone(),
365            Arc::clone(&store),
366        )));
367        let runtime_arc = runtime;
368        let registry_arc = registry;
369        let supervision_arc = supervision;
370        let schedule_evaluator = Arc::new(AsyncMutex::new(default_schedule_evaluator(
371            schedule_coordinator_workflow_id.clone(),
372            Arc::clone(&schedule_recorder),
373            ScheduleRuntimeDeps {
374                store: Arc::clone(&store),
375                visibility_store: Arc::clone(&visibility_store),
376                runtime: Arc::clone(&runtime_arc),
377                catalog: Arc::clone(&catalog),
378                registry: Arc::clone(&registry_arc),
379                supervision: Arc::clone(&supervision_arc),
380                search_attribute_schema: Arc::clone(&search_attribute_schema),
381            },
382        )));
383        Self {
384            store,
385            visibility_store,
386            schedule_recorder,
387            schedule_evaluator,
388            schedule_coordinator_workflow_id,
389            runtime: runtime_arc,
390            catalog,
391            registry: registry_arc,
392            supervision: supervision_arc,
393            delegated,
394            signal_handoff,
395            search_attribute_schema,
396            shutdown_gate: ShutdownGate::default(),
397            deploy_mutations: AsyncMutex::new(()),
398            visibility_reconciliation_task,
399            deferred_startup_recovery: super::startup_deferred::DeferredRecoverySlot::from_build(
400                deferred_startup_recovery,
401            ),
402            paused_runs: crate::lifecycle::PausedRuns::default(),
403        }
404    }
405
406    /// Advance the schedule coordinator's recorder head to match persisted
407    /// events so that a rebuilt engine resumes appending at the correct
408    /// sequence rather than conflicting at head 0.
409    ///
410    /// # Errors
411    ///
412    /// Returns store read errors.
413    pub(crate) async fn catchup_schedule_coordinator(&self) -> Result<(), EngineError> {
414        let history = self
415            .store
416            .read_history(&self.schedule_coordinator_workflow_id)
417            .await?;
418        let head = u64::try_from(history.len()).unwrap_or(u64::MAX);
419        if head > 0 {
420            let mut recorder = self.schedule_recorder.lock().await;
421            *recorder = Recorder::resume_at(
422                self.schedule_coordinator_workflow_id.clone(),
423                Arc::clone(&self.store),
424                head,
425            );
426        }
427        Ok(())
428    }
429
430    /// Event store used by lifecycle and delegated AD/AT operations.
431    #[must_use]
432    pub fn store(&self) -> Arc<dyn EventStore> {
433        Arc::clone(&self.store)
434    }
435
436    /// Visibility store used for workflow summary projections.
437    #[must_use]
438    pub fn visibility_store(&self) -> Arc<dyn VisibilityStore> {
439        Arc::clone(&self.visibility_store)
440    }
441
442    /// Runtime boundary assembled for this engine.
443    #[must_use]
444    pub fn runtime(&self) -> &RuntimeHandle {
445        &self.runtime
446    }
447
448    /// Shared workflow package catalog: loaded versions and routing.
449    #[must_use]
450    pub fn workflow_catalog(&self) -> &Arc<WorkflowCatalog> {
451        &self.catalog
452    }
453
454    /// Active execution registry.
455    #[must_use]
456    pub fn registry(&self) -> &Registry {
457        &self.registry
458    }
459
460    /// Supervision tree snapshot/model.
461    #[must_use]
462    pub fn supervision(&self) -> &SupervisionTree {
463        &self.supervision
464    }
465
466    /// Delegated signal/query/subscribe seams installed for AT/AD integration.
467    #[must_use]
468    pub const fn delegated(&self) -> &DelegatedSeams {
469        &self.delegated
470    }
471
472    /// Shared in-memory handoff for already-recorded non-resident signals.
473    #[must_use]
474    pub fn signal_handoff(&self) -> Arc<SignalResumeHandoff> {
475        Arc::clone(&self.signal_handoff)
476    }
477
478    /// Absorb a dead peer's distribution shards into this LIVE engine and resume
479    /// their orphaned workflows — the SS-5 failover entry point.
480    ///
481    /// This is the production failover step a cluster supervisor invokes when it
482    /// observes a peer gone (membership loss). It is the post-boot counterpart to
483    /// the boot path's `EngineBuilder::owned_shards` election + recovery, run
484    /// against an already-running engine:
485    ///
486    /// 1. **Elect + union-merge.** `acquire_owned_shards` wins the per-shard
487    ///    election for each `shards` entry (fencing the dead owner) and
488    ///    `become_live` union-merges that shard's committed history locally, so
489    ///    every event the dead node had quorum-committed is now present on this
490    ///    node. The election is blocking and runs off the tokio runtime inside the
491    ///    store seam, honouring haematite's no-blocking-election-in-async
492    ///    constraint, so this `async` method may call it directly.
493    /// 2. **Widen the scope.** `extend_owned_shards` unions `shards` into this
494    ///    node's owned-enumeration set so the adopted workflows, timers, and
495    ///    outbox rows become visible to enumeration WITHOUT dropping this node's
496    ///    own shards.
497    /// 3. **Publish ownership.** `publish_shard_owner` records this node as each
498    ///    adopted shard's current owner in the cluster's quorum-replicated
499    ///    shard-owner directory (SS-3), so a request reaching a DIFFERENT survivor
500    ///    routes to this adopter rather than mis-resolving to the dead declared
501    ///    owner. The publish is fenced by the election just won, so only the true
502    ///    adopter writes it; a non-distributed store no-ops it.
503    /// 4. **Re-resident.** Re-run the idempotent active-workflow recovery and
504    ///    timer recovery, which re-spawn every adopted workflow from the
505    ///    union-merged history through the same production recovery seam the boot
506    ///    path uses, skipping the workflows this node already owns.
507    ///
508    /// Detection of the peer's death is the CALLER's responsibility (a cluster
509    /// supervisor / membership-loss trigger); this method performs the
510    /// re-acquisition and resume once that decision is made. It is idempotent:
511    /// adopting a shard this node already serves re-acquires (a no-op on the
512    /// fence it already holds) and recovers nothing new.
513    ///
514    /// # Errors
515    ///
516    /// Returns [`EngineError::ShuttingDown`] after shutdown begins, store errors
517    /// from the election / union-merge ([`EngineError::Durability`]), and any
518    /// typed recovery error from re-residenting an adopted workflow.
519    pub async fn adopt_shards(&self, shards: &[usize]) -> Result<(), EngineError> {
520        let operation = self.shutdown_gate.begin_start()?;
521        let result = self.adopt_shards_inner(shards).await;
522        drop(operation);
523        result
524    }
525
526    /// Body of [`Self::adopt_shards`]: acquire+publish each shard as a UNIT under
527    /// the double-adoption fence (ADR-021 clean-partial), then widen scope and
528    /// recover over EXACTLY the shards that survived BOTH steps.
529    ///
530    /// ## Ordering invariant (the fix)
531    ///
532    /// For each shard the publish-fence happens BEFORE the shard contributes to
533    /// `extend_owned_shards` AND before it is recovered. The pre-fix order
534    /// (extend → publish) let a survivor that won the election but was then
535    /// deposed at publish-time still widen its scope and recover the shard, so two
536    /// survivors could both execute its workflows. Here, a `NotOwner` from EITHER
537    /// `acquire_owned_shard` OR `publish_shard_owner` DROPS that shard: it never
538    /// reaches `extend_owned_shards`, is never recovered, and is NEVER a hard
539    /// `Durability` error. A deposed survivor therefore leaves ZERO widened
540    /// owned-shards scope and recovers nothing.
541    async fn adopt_shards_inner(&self, shards: &[usize]) -> Result<(), EngineError> {
542        // 1-3. Drive the double-adoption fence in the FIXED order (acquire →
543        //      publish per shard as a UNIT, then re-assert ownership and widen the
544        //      enumeration scope ONCE) and learn which shards survived it. A shard
545        //      deposed at acquire OR publish (or in the residual window) is dropped
546        //      cleanly — never extended, never recovered, never a hard error. The
547        //      planner GUARANTEES each survivor's publish-fence precedes both the
548        //      scope widening and (below) recovery. A single-node store no-ops
549        //      every step, so this path stays byte-identical there.
550        // The returned survivor set is already reflected in the store's widened
551        // owned-shard scope (the planner's single `extend`), which is what recovery
552        // enumerates over; the value is bound only to make that contract explicit.
553        let _recoverable = super::fence::plan_adopted_shards(
554            &super::fence::StoreFenceSeam {
555                store: &*self.store,
556            },
557            shards,
558        )?;
559        // 3b. Rebuild the pause dispatch-hold for the newly-adopted shards (#204).
560        //     The fence above widened the owned-shard scope, so `list_paused` now
561        //     sees the adopted shards' durably-`Paused` runs. `extend` (not replace)
562        //     preserves the holds for shards this node already owned. A run paused on
563        //     an adopted shard keeps its outbox rows held after failover; without this
564        //     the adopting node's dispatcher would claim and dispatch them. A store
565        //     error is logged, not fatal: the adoption itself is durable and the next
566        //     startup/rebuild repopulates the hold.
567        match self.store.list_paused().await {
568            Ok(paused) => self.paused_runs.extend(paused),
569            Err(error) => {
570                tracing::warn!(%error, "failed to rebuild paused-runs dispatch hold at shard adoption");
571            }
572        }
573        // 4. Re-resident the adopted workflows through the production recovery
574        //    seam (idempotent: this node's own workflows are skipped). Recovery
575        //    enumerates over the owned scope, which now contains only shards that
576        //    survived the fence.
577        super::startup::recover_adopted_shards(super::startup::StartupRecoveryContext {
578            store: Arc::clone(&self.store),
579            visibility_store: Arc::clone(&self.visibility_store),
580            runtime: Arc::clone(&self.runtime),
581            catalog: Arc::clone(&self.catalog),
582            registry: Arc::clone(&self.registry),
583            supervision: Arc::clone(&self.supervision),
584            recovery: None,
585            search_attribute_schema: Arc::clone(&self.search_attribute_schema),
586            bootstrap_schedule_coordinator: false,
587        })
588        .await?;
589        // 5. Re-arm durable timers for the adopted workflows — the SAME step the
590        //    boot path runs after `recover_active_workflows_on_startup` (see
591        //    `EngineBuilder::build`). This is LOAD-BEARING for a workflow PARKED on
592        //    a durable timer (#119): step 4 replays it and re-parks it, but the
593        //    replay of a not-yet-fired sleep does NOT re-arm the live wheel (only a
594        //    first, non-replay arrival does — see `nif_timer::sleep`'s `ResumeLive`
595        //    branch). Without this call the adopted workflow stays parked forever:
596        //    `recover_due` fires already-expired timers and
597        //    `rearm_future_from_active_histories` re-arms still-future ones onto the
598        //    now-resident process. Removing it reproduces the #119 symptom (a
599        //    survivor adopts the shard but the parked timer never reaches the
600        //    resumed workflow). Guarded by `tests/adoption_parked_timer_e2e.rs`
601        //    (single-process) and `tests/adoption_parked_timer_xnode_e2e.rs`
602        //    (real cross-node failover).
603        super::startup::recover_timers_on_startup(self.runtime.nif_state(), Arc::clone(&self.store))
604            .await
605    }
606
607    /// Gracefully stop accepting new starts and shut down the embedded runtime.
608    ///
609    /// # Errors
610    ///
611    /// Returns registry poison or runtime shutdown failures as typed errors.
612    pub fn shutdown(&self) -> Result<(), EngineError> {
613        if let Some(task) = &self.visibility_reconciliation_task {
614            task.abort();
615        }
616        // 🔴 THE EPOCH CLOSES FIRST, BEFORE ANY WAIT.
617        //
618        // The first cut put the unconditional close in `RuntimeHandle::shutdown`
619        // — one level BELOW the call the shipped server actually makes — and
620        // left this function short-circuiting above it. Two ways that lost the
621        // property it was written to guarantee:
622        //
623        //   1. `close_and_wait` returns `Err` on registry poison, so `?` here
624        //      returned before the epoch was ever gated and completion retries
625        //      stayed armed.
626        //   2. `close_and_wait` is a condvar wait with NO timeout. A lifecycle
627        //      operation stuck on a degraded store — precisely the condition
628        //      that arms completion retries in the first place — blocks this
629        //      function indefinitely, and the operator reasonably concludes the
630        //      node is wedged and brings up a successor while this process is
631        //      still appending terminals.
632        //
633        // Gating costs nothing, cannot fail, and is idempotent. Doing it first
634        // means no path through this function leaves retries armed. Everything
635        // after is teardown that still needs to run.
636        //
637        // 🔴 WHAT THIS ORDERING COSTS, STATED WHERE THE ORDERING IS CHOSEN.
638        // Process-exit callbacks are still admitted for the whole span between
639        // this line and `process_exits.begin_shutdown()` below, and the
640        // completion path refuses every one of them because the epoch is
641        // already closed. A run exiting in that window records no terminal and
642        // stays `Running` in the store, with one `error!` line naming it. The
643        // span is UNBOUNDED — `close_and_wait` is a condvar wait with no
644        // timeout — and it is longest under exactly the degraded-store
645        // condition the completion retries exist for. That window is the price
646        // of the two properties above and is argued in full at the refusal site
647        // (`lifecycle::completion`, at `refuse_if_epoch_closed`); it is
648        // repeated here because a reader deciding to move this line would
649        // otherwise not know a cost had been accepted.
650        self.runtime.engine_tasks().begin_close();
651        // Every step below runs on every path, and the FIRST error is returned
652        // at the end. A `?` here would skip the timer-wheel shutdown and the
653        // seam clearing, whose consequences are spelled out at their own call
654        // sites — an orphaned wheel task racing a survivor's adoption timer, and
655        // a durable backend's writer lock held past shutdown. Neither is
656        // something to trade for reporting an earlier error sooner.
657        //
658        // 🔴 THE SEAM CLEARING IS THE HALF WITH NO BACKSTOP, AND THAT IS THE
659        // WHOLE REASON. An earlier revision said `Drop for Engine` "backstops
660        // neither", which stopped being true in this same file when `Drop`
661        // gained `shutdown_timer_wheel` (see it above) — so the wheel half IS
662        // backstopped, and a reader checking only that half would conclude the
663        // `?` costs nothing. It does: `clear_engine_seams` runs from
664        // `Engine::shutdown` and NOWHERE else, by design — it may only run once
665        // the scheduler has stopped and both epochs are closed, which `Drop`
666        // cannot establish. Skip it and the `RuntimeHandle` ↔ `EngineNifState`
667        // cycle is never broken, so every store clone reached through the seams
668        // outlives the process's interest in them and a durable backend's
669        // cross-process writer lock is held until exit.
670        //
671        // 🔴 THE THIRD COST, STATED BECAUSE EVERY OTHER ONE IN THIS FUNCTION IS.
672        // `ShutdownGate::close_and_wait` returns `Err` on exactly one condition
673        // — mutex poison — and continuing past it means the gate's DRAIN
674        // guarantee is skipped, not merely its error deferred: a lifecycle
675        // operation admitted before the poison may still be in flight when
676        // `runtime.shutdown()` stops the scheduler and `clear_engine_seams()`
677        // nulls the seam slots. That is not a memory hazard (the slots are
678        // `Option`-shaped and a NIF reading a cleared one gets a typed error),
679        // and no NEW operation can be admitted either, because `begin_start`
680        // and `begin_operation` share the same poisoned `state()`. What is lost
681        // is the promise that nothing was still running when teardown began.
682        // Accepted for the same reason as the rest: the alternative is skipping
683        // the seam clearing, which is unbacked-up and permanent.
684        let mut first_error: Option<EngineError> = None;
685        // Scoped so the closure's unique borrow of `first_error` visibly ends
686        // before the value is read. (`drop(closure)` would end it just as
687        // surely — this crate is edition 2024, and under NLL a borrow ends at
688        // its last use — so this is a readability choice, not a soundness one.
689        // An earlier revision of this comment argued the opposite and was
690        // describing pre-NLL lexical scoping.)
691        {
692            // 🔴 THE SECOND ERROR IS REPORTED, NOT DISCARDED. Only one
693            // `EngineError` can be returned, but accumulate-and-continue means
694            // more than one step can fail — and at HEAD that could not happen
695            // at all, because `?` meant a later step never ran. Keeping only
696            // the first and dropping the rest would trade a skipped teardown
697            // for a swallowed failure, which is the same defect wearing the
698            // other hat: an operator seeing `RegistryPoisoned` would have no
699            // signal that the runtime teardown ALSO failed. Each subsequent
700            // failure is emitted at `error` level with the position that made
701            // it subsequent, so the log carries what the return value cannot.
702            let mut failed_steps = 0_u32;
703            let mut keep = |step: &'static str, result: Result<(), EngineError>| {
704                if let Err(error) = result {
705                    failed_steps += 1;
706                    if first_error.is_none() {
707                        first_error = Some(error);
708                    } else {
709                        tracing::error!(
710                            step,
711                            failed_steps,
712                            error = %error,
713                            "a further engine-shutdown step failed after an earlier one; only \
714                             the first failure can be returned, so this one is reported here"
715                        );
716                    }
717                }
718            };
719            keep(
720                "shutdown_gate.close_and_wait",
721                self.shutdown_gate.close_and_wait(),
722            );
723            // Epoch close for engine background tasks (F4): every watcher,
724            // spawn-recovery task and process-exit completion retry is aborted AND
725            // awaited to quiescence — a task still mid-record after shutdown could
726            // double-write a history a successor engine over the same store also
727            // records into. Arming is additionally gated inside the task registry
728            // the moment shutdown begins.
729            //
730            // `runtime.shutdown()` performs that close itself, because the
731            // completion retry is a core lifecycle path and its epoch close must not
732            // depend on whether an optional bridge was installed. The bridge call
733            // that follows is idempotent and kept only so an installed bridge
734            // participates explicitly.
735            keep("runtime.shutdown", self.runtime.shutdown());
736        }
737        self.runtime.nif_state().shutdown_engine_tasks();
738        // Abort armed live-wheel timer tasks (#119): they run on the tokio
739        // runtime, not the beamr scheduler, so `runtime.shutdown()` does not
740        // reach them. A timer this engine armed must NOT fire after the engine
741        // has stopped owning the workflow — otherwise, across a failover, the
742        // dead owner's orphaned wheel task races the survivor's adoption-armed
743        // timer and can record the one durable `TimerFired` first, leaving the
744        // survivor's resident sleeper parked forever.
745        self.runtime.nif_state().shutdown_timer_wheel();
746        // Break the RuntimeHandle <-> EngineNifState reference cycle (see
747        // EngineNifState::clear_engine_seams). The engine-scoped NIF seams each
748        // hold an Arc back to the runtime and/or clones of the event store and
749        // registry; without releasing them here the runtime, its NIF state, and
750        // every store clone they reach would outlive the dropped Engine
751        // forever, keeping a durable backend's writer lock held past shutdown.
752        // Safe now: the scheduler has stopped and the child-task and timer-wheel
753        // epochs have closed, so no NIF or background task can still read a slot.
754        self.runtime.nif_state().clear_engine_seams();
755        match first_error {
756            Some(error) => Err(error),
757            None => Ok(()),
758        }
759    }
760}
761
762pub(crate) fn terminal_outcome_from_history(events: &[Event]) -> Option<TerminalOutcome> {
763    // Reset-aware via the shared single-source predicate: the current lease's
764    // terminal event, where a reopen (WorkflowReopened) supersedes any earlier
765    // terminal.
766    match aion_core::current_lease_terminal(events)? {
767        Event::WorkflowCompleted { result, .. } => Some(TerminalOutcome::Completed(result.clone())),
768        Event::WorkflowFailed { error, .. } => Some(TerminalOutcome::Failed(error.clone())),
769        Event::WorkflowCancelled { reason, .. } => Some(TerminalOutcome::Cancelled(reason.clone())),
770        Event::WorkflowTimedOut { timeout, .. } => Some(TerminalOutcome::TimedOut(timeout.clone())),
771        Event::WorkflowContinuedAsNew {
772            input,
773            workflow_type,
774            parent_run_id,
775            ..
776        } => Some(TerminalOutcome::ContinuedAsNew {
777            input: input.clone(),
778            workflow_type: workflow_type.clone(),
779            parent_run_id: parent_run_id.clone(),
780        }),
781        _ => None,
782    }
783}
784
785pub(crate) fn workflow_not_found(id: &WorkflowId, run: &RunId) -> EngineError {
786    EngineError::WorkflowNotFound {
787        workflow_type: format!("{id}/{run}"),
788    }
789}
790
791#[cfg(test)]
792mod api_tests;