Skip to main content

aion/engine/
builder.rs

1//! `EngineBuilder` and build wiring.
2
3use std::{num::NonZeroUsize, path::PathBuf, sync::Arc, time::Duration};
4
5use chrono::Utc;
6
7use aion_core::SearchAttributeSchema;
8use aion_package::Package;
9use aion_store::visibility::VisibilityStore;
10use aion_store::{EventStore, InMemoryStore};
11
12use crate::{
13    ActivityServing, EngineError, Registry, RuntimeConfig, RuntimeHandle, SignalDeliveryConfig,
14    SupervisionTree,
15    activity::bridge::ActivityDispatcher,
16    durability::ActiveWorkflowRecoverySeam,
17    runtime::{NifEntry, NifRegistration},
18    signal::SignalResumeHandoff,
19};
20
21use super::api::{Engine, EngineComponents};
22use super::builder_assembly::{
23    ChildBridgeAssembly, assemble_startup_catalog, claim_owned_shards, install_engine_nif_seams,
24    install_workflow_nif_bridges, maybe_spawn_visibility_reconciliation,
25};
26use super::delegated::{DelegatedSeams, EventPublisher, QueryService, SignalRouter};
27use super::seams::{
28    SeamAssembly, SignalRouterFactory, assemble_delegated_seams, wrap_event_streaming,
29};
30use super::startup::{StartupRecoveryContext, resolve_startup_recovery};
31
32/// Source for a workflow package collected before `build()` performs fallible
33/// loading and runtime registration.
34#[derive(Clone, Debug)]
35pub enum WorkflowPackageSource {
36    /// Load a package from this `.aion` archive path during `build()`.
37    Path(PathBuf),
38    /// Use an already-loaded package value.
39    Package(Box<Package>),
40}
41
42impl From<Package> for WorkflowPackageSource {
43    fn from(package: Package) -> Self {
44        Self::Package(Box::new(package))
45    }
46}
47
48impl From<PathBuf> for WorkflowPackageSource {
49    fn from(path: PathBuf) -> Self {
50        Self::Path(path)
51    }
52}
53
54impl From<&std::path::Path> for WorkflowPackageSource {
55    fn from(path: &std::path::Path) -> Self {
56        Self::Path(path.to_path_buf())
57    }
58}
59
60impl From<&str> for WorkflowPackageSource {
61    fn from(path: &str) -> Self {
62        Self::Path(PathBuf::from(path))
63    }
64}
65
66impl From<String> for WorkflowPackageSource {
67    fn from(path: String) -> Self {
68        Self::Path(PathBuf::from(path))
69    }
70}
71
72/// Tracks which optional engine seams the caller explicitly overrode, so
73/// `build()` can detect mutually-exclusive configuration (e.g. an event
74/// publisher set both directly and via event streaming). Grouped so the builder
75/// keeps its boolean configuration flags few and named.
76#[derive(Default)]
77struct SeamOverrides {
78    /// The caller installed an explicit event-publisher seam.
79    event_publisher: bool,
80    /// The caller installed an explicit query-service seam.
81    query_service: bool,
82}
83
84/// Builder for the embedded, transport-agnostic workflow engine.
85pub struct EngineBuilder {
86    store: Option<Arc<dyn EventStore>>,
87    visibility_store: Option<Arc<dyn VisibilityStore>>,
88    scheduler_threads: Option<usize>,
89    signal_delivery: SignalDeliveryConfig,
90    completion_retry: crate::runtime::CompletionRetryConfig,
91    outbox_enabled: bool,
92    bootstrap_schedule_coordinator: bool,
93    owned_shards: Option<Vec<usize>>,
94    workflow_sources: Vec<WorkflowPackageSource>,
95    host_nifs: Vec<NifEntry>,
96    recovery: Option<Arc<dyn ActiveWorkflowRecoverySeam>>,
97    delegated: DelegatedSeams,
98    signal_router_factory: Option<SignalRouterFactory>,
99    activity_dispatcher: Option<Arc<dyn ActivityDispatcher>>,
100    activity_serving: ActivityServing,
101    active_registry: Option<Arc<Registry>>,
102    visibility_reconciliation_interval: Option<Duration>,
103    search_attribute_schema: SearchAttributeSchema,
104    event_streaming_capacity: Option<NonZeroUsize>,
105    query_timeout: Option<Duration>,
106    seam_overrides: SeamOverrides,
107    defer_startup_recovery: bool,
108}
109
110impl Default for EngineBuilder {
111    fn default() -> Self {
112        Self::new()
113    }
114}
115
116impl EngineBuilder {
117    /// Create a builder with no store, no scheduler-thread override, no loaded
118    /// workflows, and no host NIFs.
119    #[must_use]
120    pub fn new() -> Self {
121        Self {
122            store: None,
123            visibility_store: None,
124            scheduler_threads: None,
125            signal_delivery: SignalDeliveryConfig::default(),
126            completion_retry: crate::runtime::CompletionRetryConfig::default(),
127            outbox_enabled: false,
128            // The only field that defaults true: single-node engines seed the
129            // schedule coordinator. A multi-node deployment disables it on nodes
130            // that do not own the coordinator's shard (see the builder method).
131            bootstrap_schedule_coordinator: true,
132            // No shard restriction by default: the store owns ALL shards, which
133            // is byte-identical to single-node behaviour. `build()` only ever
134            // touches owned-shard scoping when a deployment sets this.
135            owned_shards: None,
136            workflow_sources: Vec::new(),
137            host_nifs: Vec::new(),
138            recovery: None,
139            delegated: DelegatedSeams::default(),
140            signal_router_factory: None,
141            activity_dispatcher: None,
142            activity_serving: ActivityServing::QueueRouted,
143            active_registry: None,
144            visibility_reconciliation_interval: None,
145            search_attribute_schema: SearchAttributeSchema::new(),
146            event_streaming_capacity: None,
147            query_timeout: None,
148            seam_overrides: SeamOverrides::default(),
149            defer_startup_recovery: false,
150        }
151    }
152
153    /// Record the caller-supplied workflow query reply timeout.
154    ///
155    /// Setting a timeout installs the concrete query-dispatch seam during
156    /// `build()` (unless [`Self::query_service`] overrides it) and enables
157    /// the in-engine `dispatch_query` NIF. There is no default: without this
158    /// call the query seam stays deferred and `Engine::query` fails typed
159    /// with its "not configured" error.
160    #[must_use]
161    pub const fn query_timeout(mut self, timeout: Duration) -> Self {
162        self.query_timeout = Some(timeout);
163        self
164    }
165
166    /// Inspect the configured workflow query reply timeout.
167    #[must_use]
168    pub const fn configured_query_timeout(&self) -> Option<Duration> {
169        self.query_timeout
170    }
171
172    /// Opt in to live event streaming with a caller-provided broadcast capacity.
173    ///
174    /// `build()` wraps the configured store in a
175    /// [`PublishingEventStore`](crate::publish::PublishingEventStore) before any
176    /// recorder, recovery, or NIF bridge captures the store — so every
177    /// successful append publishes — and installs the matching
178    /// [`BroadcastEventPublisher`](crate::publish::BroadcastEventPublisher) as
179    /// the event-publisher seam behind [`Engine::subscribe`]. Without this call
180    /// the deferred publisher remains installed and subscriptions are empty.
181    #[must_use]
182    pub const fn event_streaming(mut self, capacity: NonZeroUsize) -> Self {
183        self.event_streaming_capacity = Some(capacity);
184        self
185    }
186
187    /// Supply the search attribute schema validating every recorded attribute.
188    ///
189    /// The default schema is empty, which rejects all search attributes: a
190    /// deployment must declare each attribute name and type before workflows
191    /// can record values for it.
192    #[must_use]
193    pub fn search_attribute_schema(mut self, schema: SearchAttributeSchema) -> Self {
194        self.search_attribute_schema = schema;
195        self
196    }
197
198    /// Supply the event store used by the engine.
199    #[must_use]
200    pub fn store<S>(mut self, store: S) -> Self
201    where
202        S: EventStore,
203    {
204        self.store = Some(Arc::new(store));
205        self
206    }
207
208    /// Supply an already type-erased event store.
209    #[must_use]
210    pub fn store_arc(mut self, store: Arc<dyn EventStore>) -> Self {
211        self.store = Some(store);
212        self
213    }
214
215    /// Supply the visibility store used by the engine for workflow projections.
216    #[must_use]
217    pub fn visibility_store<S>(mut self, visibility_store: S) -> Self
218    where
219        S: VisibilityStore,
220    {
221        self.visibility_store = Some(Arc::new(visibility_store));
222        self
223    }
224
225    /// Supply an already type-erased visibility store.
226    #[must_use]
227    pub fn visibility_store_arc(mut self, visibility_store: Arc<dyn VisibilityStore>) -> Self {
228        self.visibility_store = Some(visibility_store);
229        self
230    }
231
232    /// Explicitly opt in to an ephemeral in-memory visibility store.
233    ///
234    /// This is intended for tests and local scenarios that do not need durable
235    /// visibility projections. Visibility data stored this way does not survive
236    /// process restarts.
237    #[must_use]
238    pub fn in_memory_visibility(mut self) -> Self {
239        self.visibility_store = Some(Arc::new(InMemoryStore::default()));
240        self
241    }
242
243    /// Record the caller-supplied scheduler thread count.
244    ///
245    /// If this setter is never called, `None` is passed through to beamr.
246    #[must_use]
247    pub const fn scheduler_threads(mut self, threads: usize) -> Self {
248        self.scheduler_threads = Some(threads);
249        self
250    }
251
252    /// Record the caller-supplied periodic visibility reconciliation interval.
253    ///
254    /// If this setter is never called, no periodic background reconciliation task is spawned.
255    #[must_use]
256    pub const fn visibility_reconciliation_interval(mut self, interval: Duration) -> Self {
257        self.visibility_reconciliation_interval = Some(interval);
258        self
259    }
260
261    /// Record the caller-supplied signal delivery readiness and retry policy.
262    #[must_use]
263    pub const fn signal_delivery(mut self, signal_delivery: SignalDeliveryConfig) -> Self {
264        self.signal_delivery = signal_delivery;
265        self
266    }
267
268    /// Record the caller-supplied durable completion-retry backoff ladder.
269    ///
270    /// Separate from [`Self::signal_delivery`] because the completion retry is
271    /// unbounded by attempts and sleeps between durable store round-trips; see
272    /// [`crate::runtime::CompletionRetryConfig`] for why sharing one ladder
273    /// between the two was a defect.
274    #[must_use]
275    pub const fn completion_retry(
276        mut self,
277        completion_retry: crate::runtime::CompletionRetryConfig,
278    ) -> Self {
279        self.completion_retry = completion_retry;
280        self
281    }
282
283    /// Record whether the durable-outbox fan-out dispatch path is enabled.
284    #[must_use]
285    pub fn outbox_enabled(mut self, enabled: bool) -> Self {
286        self.outbox_enabled = enabled;
287        self
288    }
289
290    /// Control whether `build()` seeds the schedule-coordinator history.
291    ///
292    /// Default `true` (single-node). Under multi-shard active-active the
293    /// coordinator stream is owned by exactly ONE shard; a deployment sets this
294    /// `false` on every node that does NOT own that shard, so only the owner
295    /// seeds (and serves) it — a non-owner would otherwise try to write the
296    /// coordinator stream and race or fence the real owner.
297    #[must_use]
298    pub const fn bootstrap_schedule_coordinator(mut self, enabled: bool) -> Self {
299        self.bootstrap_schedule_coordinator = enabled;
300        self
301    }
302
303    /// Restrict this engine's store to the distribution shards this node owns.
304    ///
305    /// Under multi-shard active-active a node serves only a SUBSET of the
306    /// cluster's shards. `build()` calls
307    /// [`ReadableEventStore::set_owned_shards`](aion_store::ReadableEventStore::set_owned_shards)
308    /// with this set BEFORE startup recovery, so the node recovers and
309    /// enumerates only the workflows / timers / outbox rows that live on its
310    /// shards. The set is deduplicated and ordered by the store.
311    ///
312    /// Not calling this leaves the store owning ALL shards — the single-node
313    /// default, which is byte-identical to today's behaviour (`build()` never
314    /// touches the scoping hook). The single-shard in-memory backend ignores the
315    /// call regardless, since it owns everything unconditionally; haematite
316    /// honours it.
317    #[must_use]
318    pub fn owned_shards(mut self, shards: impl IntoIterator<Item = usize>) -> Self {
319        self.owned_shards = Some(shards.into_iter().collect());
320        self
321    }
322
323    /// Inspect the configured owned-shard set (`None` = own all shards).
324    #[must_use]
325    pub fn configured_owned_shards(&self) -> Option<&[usize]> {
326        self.owned_shards.as_deref()
327    }
328
329    /// Add one workflow package source to load during `build()`.
330    #[must_use]
331    pub fn load_workflows(mut self, source: impl Into<WorkflowPackageSource>) -> Self {
332        self.workflow_sources.push(source.into());
333        self
334    }
335
336    /// Add many workflow package sources to load during `build()`.
337    #[must_use]
338    pub fn load_workflow_sources<I, S>(mut self, sources: I) -> Self
339    where
340        I: IntoIterator<Item = S>,
341        S: Into<WorkflowPackageSource>,
342    {
343        self.workflow_sources
344            .extend(sources.into_iter().map(Into::into));
345        self
346    }
347
348    /// Collect host-supplied NIF entries to install before workflow modules load.
349    #[must_use]
350    pub fn register_nifs(mut self, entries: impl IntoIterator<Item = NifEntry>) -> Self {
351        self.host_nifs.extend(entries);
352        self
353    }
354
355    /// Override the AD recovery seam used while repopulating active workflows.
356    #[must_use]
357    pub fn recovery_seam(mut self, recovery: Arc<dyn ActiveWorkflowRecoverySeam>) -> Self {
358        self.recovery = Some(recovery);
359        self
360    }
361
362    /// Use the production AD recovery seam created after runtime/package loading.
363    #[must_use]
364    pub fn production_recovery_seam(mut self) -> Self {
365        self.recovery = None;
366        self
367    }
368
369    /// Defer the four startup-recovery steps out of `build()` (#266).
370    ///
371    /// Recovery replay re-dispatches every in-flight activity through the
372    /// configured activity dispatcher the moment it runs. A host that
373    /// decorates that dispatcher with collaborators it can only install once
374    /// the engine exists (the server's declared-body source) must therefore
375    /// build first, install its seams, and only then run recovery — by
376    /// calling [`Engine::run_startup_recovery`] exactly once. Without this
377    /// call, `build()` runs recovery itself, byte-identically to before this
378    /// seam existed, and `run_startup_recovery` refuses typed.
379    #[must_use]
380    pub fn defer_startup_recovery(mut self) -> Self {
381        self.defer_startup_recovery = true;
382        self
383    }
384
385    /// Override the AT signal-routing seam.
386    #[must_use]
387    pub fn signal_router(mut self, signal_router: Arc<dyn SignalRouter>) -> Self {
388        self.signal_router_factory = None;
389        self.delegated = DelegatedSeams::new(
390            signal_router,
391            self.delegated.query_service_arc(),
392            self.delegated.event_publisher_arc(),
393        );
394        self
395    }
396
397    /// Override the AT signal-routing seam after the runtime is assembled.
398    #[must_use]
399    pub fn signal_router_factory<F>(mut self, factory: F) -> Self
400    where
401        F: Fn(Arc<RuntimeHandle>, Arc<SignalResumeHandoff>) -> Arc<dyn SignalRouter>
402            + Send
403            + Sync
404            + 'static,
405    {
406        self.signal_router_factory = Some(Arc::new(factory));
407        self
408    }
409
410    /// Override the AT query-dispatch seam.
411    ///
412    /// An explicit override wins over the concrete service that
413    /// [`Self::query_timeout`] would otherwise install during `build()`.
414    #[must_use]
415    pub fn query_service(mut self, query_service: Arc<dyn QueryService>) -> Self {
416        self.seam_overrides.query_service = true;
417        self.delegated = DelegatedSeams::new(
418            self.delegated.signal_router_arc(),
419            query_service,
420            self.delegated.event_publisher_arc(),
421        );
422        self
423    }
424
425    /// Override the AD/AT live event-publisher seam.
426    ///
427    /// Mutually exclusive with [`Self::event_streaming`], which installs the
428    /// broadcast publisher itself; configuring both fails `build()`.
429    #[must_use]
430    pub fn event_publisher(mut self, event_publisher: Arc<dyn EventPublisher>) -> Self {
431        self.seam_overrides.event_publisher = true;
432        self.delegated = DelegatedSeams::new(
433            self.delegated.signal_router_arc(),
434            self.delegated.query_service_arc(),
435            event_publisher,
436        );
437        self
438    }
439
440    /// Supply the activity dispatcher that backs activity dispatch NIFs.
441    ///
442    /// When set, the dispatcher is installed in the global bridge before
443    /// workflow modules are loaded. Without a dispatcher, `dispatch_activity`
444    /// returns an error to workflow code instead of crashing the process.
445    #[must_use]
446    pub fn activity_dispatcher(mut self, dispatcher: Arc<dyn ActivityDispatcher>) -> Self {
447        self.activity_dispatcher = Some(dispatcher);
448        self
449    }
450
451    /// Declare that the configured in-process [`ActivityDispatcher`] fulfils
452    /// every activity this engine dispatches — the embedded posture.
453    ///
454    /// This gates ONLY the structural queue-service admission check: with
455    /// in-process serving declared, a package whose contract retains
456    /// unscoped (legacy-manifest) activities is admitted at start, because
457    /// no queue exists to be unserved — dispatch runs on the configured
458    /// dispatcher immediately, and a missing dispatcher fails loudly at
459    /// dispatch. The `.v4` identity floor is unconditional either way. The
460    /// server never declares this: its dispatcher routes to task queues, so
461    /// it keeps the fail-closed queue-routed default.
462    #[must_use]
463    pub const fn in_process_activity_serving(mut self) -> Self {
464        self.activity_serving = ActivityServing::InProcess;
465        self
466    }
467
468    /// Supply the active workflow registry used by the built engine.
469    ///
470    /// Server-owned dispatchers that run behind raw NIFs use this to correlate a
471    /// calling BEAM pid to the same workflow handle the engine registers.
472    #[must_use]
473    pub fn active_registry(mut self, registry: Arc<Registry>) -> Self {
474        self.active_registry = Some(registry);
475        self
476    }
477
478    /// Inspect the configured scheduler thread count.
479    #[must_use]
480    pub const fn scheduler_thread_count(&self) -> Option<usize> {
481        self.scheduler_threads
482    }
483
484    /// Inspect the configured periodic visibility reconciliation interval.
485    #[must_use]
486    pub const fn configured_visibility_reconciliation_interval(&self) -> Option<Duration> {
487        self.visibility_reconciliation_interval
488    }
489
490    /// Assemble the runtime configuration from the builder-supplied scheduler,
491    /// signal delivery, completion-retry, and outbox knobs.
492    fn runtime_config(&self) -> RuntimeConfig {
493        RuntimeConfig::new(self.scheduler_threads)
494            .with_signal_delivery(self.signal_delivery)
495            .with_completion_retry(self.completion_retry)
496            .with_outbox_enabled(self.outbox_enabled)
497    }
498
499    /// Start the runtime and install the engine plus host NIFs.
500    fn start_runtime_with_nifs(
501        runtime_config: RuntimeConfig,
502        host_nifs: Vec<NifEntry>,
503    ) -> Result<Arc<RuntimeHandle>, EngineError> {
504        let runtime = Arc::new(RuntimeHandle::new(runtime_config)?);
505        let mut nifs = NifRegistration::new();
506        nifs.add_engine_nifs().add_host_nifs(host_nifs);
507        runtime.install_nifs(nifs)?;
508        Ok(runtime)
509    }
510
511    /// Construct the live engine.
512    ///
513    /// # Errors
514    ///
515    /// Returns typed [`EngineError`] variants for missing store, runtime startup,
516    /// NIF registration, package loading, store reads, registry/supervision lock
517    /// poison, or deferred AD recovery failures for active histories.
518    pub async fn build(self) -> Result<Engine, EngineError> {
519        let runtime_config = self.runtime_config();
520        let (store, streaming_publisher) = wrap_event_streaming(
521            self.store.ok_or(EngineError::MissingStore)?,
522            self.event_streaming_capacity,
523            self.seam_overrides.event_publisher,
524        )?;
525        let visibility_store = self
526            .visibility_store
527            .ok_or(EngineError::MissingVisibilityStore)?;
528        claim_owned_shards(store.as_ref(), self.owned_shards.as_deref())?;
529
530        let runtime = Self::start_runtime_with_nifs(runtime_config, self.host_nifs)?;
531
532        // Persisted runtime deploys must be resident before startup recovery
533        // below resolves any run's recorded pinned version — this is the
534        // restart half of the deploy durability promise.
535        let catalog = assemble_startup_catalog(
536            runtime.as_ref(),
537            store.as_ref(),
538            self.workflow_sources,
539            self.activity_serving,
540        )
541        .await?;
542
543        let registry = self
544            .active_registry
545            .unwrap_or_else(|| Arc::new(Registry::default()));
546        let nif_state = Arc::clone(runtime.nif_state());
547        let query_mailbox_engine = install_engine_nif_seams(
548            &nif_state,
549            &registry,
550            &store,
551            &runtime,
552            self.activity_dispatcher,
553            self.query_timeout,
554        );
555        let supervision = Arc::new(SupervisionTree::new());
556        let search_attribute_schema = Arc::new(self.search_attribute_schema);
557        let signal_handoff = Arc::new(SignalResumeHandoff::new());
558
559        let delegated = assemble_delegated_seams(SeamAssembly {
560            configured: self.delegated,
561            signal_router_factory: self.signal_router_factory,
562            runtime: Arc::clone(&runtime),
563            signal_handoff: Arc::clone(&signal_handoff),
564            streaming_publisher,
565            query_mailbox_engine,
566            query_timeout: self.query_timeout,
567            query_service_overridden: self.seam_overrides.query_service,
568        });
569
570        // Startup recovery re-spawns active workflow processes, and those
571        // processes begin replaying on scheduler threads immediately. Replay
572        // re-executes workflow code through the engine NIFs, so every NIF
573        // bridge (signal, child) must be installed before the first recovered
574        // process can run, or an early replayed spawn_child/receive_signal
575        // call fails with a missing-bridge error.
576        install_workflow_nif_bridges(
577            &ChildBridgeAssembly {
578                nif_state: &nif_state,
579                store: &store,
580                visibility_store: &visibility_store,
581                runtime: &runtime,
582                catalog: &catalog,
583                registry: &registry,
584                supervision: &supervision,
585                signal_handoff: &signal_handoff,
586                search_attribute_schema: &search_attribute_schema,
587                watch_backoff: self.signal_delivery,
588            },
589            &delegated,
590        )?;
591
592        // A deferred build (#266) skips the recovery steps and stows what the
593        // host owes [`Engine::run_startup_recovery`]; see
594        // [`resolve_startup_recovery`].
595        let deferred_startup_recovery = resolve_startup_recovery(
596            self.defer_startup_recovery,
597            &nif_state,
598            StartupRecoveryContext {
599                store: Arc::clone(&store),
600                visibility_store: Arc::clone(&visibility_store),
601                runtime: Arc::clone(&runtime),
602                catalog: Arc::clone(&catalog),
603                registry: Arc::clone(&registry),
604                supervision: Arc::clone(&supervision),
605                recovery: self.recovery,
606                search_attribute_schema: Arc::clone(&search_attribute_schema),
607                bootstrap_schedule_coordinator: self.bootstrap_schedule_coordinator,
608            },
609        )
610        .await?;
611
612        let visibility_reconciliation_task = maybe_spawn_visibility_reconciliation(
613            self.visibility_reconciliation_interval,
614            &store,
615            &visibility_store,
616        );
617
618        let deferred = deferred_startup_recovery.is_some();
619        let engine = Engine::new(EngineComponents {
620            store,
621            visibility_store,
622            runtime,
623            catalog,
624            registry,
625            supervision,
626            delegated,
627            signal_handoff,
628            search_attribute_schema,
629            visibility_reconciliation_task,
630            deferred_startup_recovery,
631        });
632        if !deferred {
633            engine.catchup_schedule_coordinator().await?;
634            engine.recover_schedules_on_startup(Utc::now()).await?;
635        }
636        Ok(engine)
637    }
638}
639
640#[cfg(test)]
641mod tests {
642    // 🔴 #125. This was a hand-rolled twelve-line gate announcing its skip with
643    // `println!` — the exact pattern task #74 replaced, because the harness
644    // captures `println!` on a PASSING test and a gated skip always passes, so
645    // the announcement was invisible in precisely the case it existed for.
646    //
647    // #74's cure landed in `tests/test_support/gleam.rs` and is pinned across
648    // four byte-identical copies. This file is `src/`, so a sweep over `tests/`
649    // could never see it — and the correct copy was already sitting in THIS
650    // crate's own `tests/` directory. A fix's search space is part of the fix.
651    //
652    // Reusing the canonical file by path rather than copying it, per the
653    // precedent in `aion-package/src/structure/mod.rs`: a third copy would look
654    // right in isolation and drift silently. It is DECLARED in `engine/mod.rs`
655    // because `#[path]` resolves against the declaring module's directory and
656    // `src/engine/builder/` does not exist.
657    use super::super::gleam_test_support;
658
659    use std::{num::NonZeroUsize, path::PathBuf, process::Command, sync::Arc, time::Duration};
660
661    use aion_core::{Event, EventEnvelope, Payload, WorkflowId, WorkflowStatus};
662    use aion_package::{
663        BeamModule, BeamSet, CURRENT_FORMAT_VERSION, DeclaredActivity, ExtractionLimits, Manifest,
664        ManifestVersion, Package, PackageBuilder,
665    };
666    use aion_store::visibility::{ListWorkflowsFilter, VisibilityStore};
667    use aion_store::{InMemoryStore, ReadableEventStore, WritableEventStore, WriteToken};
668    use chrono::Utc;
669    use futures::StreamExt;
670    use serde_json::json;
671
672    use crate::engine::api_schedule::{
673        schedule_coordinator_run_id, schedule_coordinator_workflow_id,
674        schedule_coordinator_workflow_type,
675    };
676    use crate::runtime::{Determinism, Mfa, NifEntry};
677
678    use super::EngineBuilder;
679    use crate::EngineError;
680
681    fn payload() -> Result<Payload, aion_core::PayloadError> {
682        Payload::from_json(&json!({ "input": true }))
683    }
684
685    fn started(
686        workflow_id: &WorkflowId,
687        workflow_type: &str,
688    ) -> Result<Event, aion_core::PayloadError> {
689        Ok(Event::WorkflowStarted {
690            envelope: EventEnvelope {
691                seq: 1,
692                recorded_at: Utc::now(),
693                workflow_id: workflow_id.clone(),
694            },
695            workflow_type: workflow_type.to_owned(),
696            input: payload()?,
697            run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
698            parent_run_id: None,
699            package_version: aion_core::PackageVersion::new("a".repeat(64)),
700        })
701    }
702
703    fn completed(workflow_id: &WorkflowId) -> Result<Event, aion_core::PayloadError> {
704        Ok(Event::WorkflowCompleted {
705            envelope: EventEnvelope {
706                seq: 2,
707                recorded_at: Utc::now(),
708                workflow_id: workflow_id.clone(),
709            },
710            result: payload()?,
711        })
712    }
713
714    fn package_manifest() -> Manifest {
715        Manifest {
716            entry_module: "counter".to_owned(),
717            entry_function: "version".to_owned(),
718            input_schema: json!({ "type": "object" }),
719            output_schema: json!({ "type": "integer" }),
720            timeout: Some(Duration::from_secs(30)),
721            activities: vec![DeclaredActivity {
722                activity_type: "activity/test".to_owned(),
723            }],
724            version: ManifestVersion::new("test"),
725            format_version: CURRENT_FORMAT_VERSION,
726            additional_workflows: Vec::new(),
727        }
728    }
729
730    fn compile_counter_beam() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
731        let temp_dir =
732            std::env::temp_dir().join(format!("aion-engine-builder-{}", uuid::Uuid::new_v4()));
733        std::fs::create_dir(&temp_dir)?;
734        let source_path = temp_dir.join("counter.erl");
735        let beam_path = temp_dir.join("counter.beam");
736        std::fs::write(
737            &source_path,
738            "-module(counter).\n-export([version/0]).\nversion() -> 1.\n",
739        )?;
740        let status = Command::new("erlc")
741            .arg("-o")
742            .arg(&temp_dir)
743            .arg(&source_path)
744            .status()?;
745        if !status.success() {
746            let cleanup_result = std::fs::remove_dir_all(&temp_dir);
747            drop(cleanup_result);
748            return Err(format!("erlc failed with status {status}").into());
749        }
750        let bytes = std::fs::read(beam_path)?;
751        std::fs::remove_dir_all(temp_dir)?;
752        Ok(bytes)
753    }
754
755    fn fixture_package() -> Result<Package, Box<dyn std::error::Error>> {
756        let beams = BeamSet::new(vec![BeamModule::new("counter", compile_counter_beam()?)])?;
757        let archive = PackageBuilder::new(package_manifest(), beams).write_to_bytes()?;
758        Ok(Package::load_from_bytes(
759            archive,
760            ExtractionLimits::unbounded(),
761        )?)
762    }
763
764    fn write_fixture_package(package: &Package) -> Result<PathBuf, Box<dyn std::error::Error>> {
765        let path =
766            std::env::temp_dir().join(format!("aion-engine-builder-{}.aion", uuid::Uuid::new_v4()));
767        PackageBuilder::new(package.manifest().clone(), package.beams().clone())
768            .write_to_path(&path)?;
769        Ok(path)
770    }
771
772    #[tokio::test]
773    async fn build_without_store_returns_missing_store() {
774        let error = EngineBuilder::new().build().await.err();
775
776        assert!(matches!(error, Some(EngineError::MissingStore)));
777    }
778
779    #[tokio::test]
780    async fn build_without_visibility_store_returns_missing_visibility_store() {
781        let error = EngineBuilder::new()
782            .store(InMemoryStore::default())
783            .build()
784            .await
785            .err();
786
787        assert!(matches!(error, Some(EngineError::MissingVisibilityStore)));
788    }
789
790    #[tokio::test]
791    async fn in_memory_visibility_allows_build_without_visibility_store() -> Result<(), EngineError>
792    {
793        let engine = EngineBuilder::new()
794            .store(InMemoryStore::default())
795            .in_memory_visibility()
796            .build()
797            .await?;
798
799        engine.shutdown()?;
800        Ok(())
801    }
802
803    /// 🔴 M-1. Releasing an engine WITHOUT shutting it down closes the epoch.
804    ///
805    /// `RuntimeHandle::shutdown` covers the explicit path. This covers the other
806    /// one, and it is not hypothetical: a completion retry appends terminal
807    /// events, so an engine dropped on an error path with a retry still armed
808    /// would keep writing to histories nobody believes this process still owns.
809    ///
810    /// The refcount backstop cannot serve here, which is the whole reason this
811    /// `Drop` exists. `EngineTaskRuntime::drop` fires only when the last strong
812    /// reference goes, and an in-flight attempt holds one for the entire attempt
813    /// — so at the instant the hazard is real, the backstop is pinned shut. This
814    /// gate is set by a `Drop` that runs regardless of who else holds a handle.
815    ///
816    /// The first assertion is the control: an engine that never opened the epoch
817    /// would satisfy the second trivially.
818    ///
819    /// 🔴 THE ENGINE IS BUILT WITH A RECONCILIATION INTERVAL, AND THAT IS NOT
820    /// INCIDENTAL. Its first form used a bare fixture with no interval, so no
821    /// reconciliation task was ever spawned — and a fixture that never starts
822    /// the thing under test cannot see whether releasing the engine stops it.
823    /// It could not: `Drop` did not abort `visibility_reconciliation_task`, and
824    /// dropping a `JoinHandle` DETACHES rather than cancels, so a released
825    /// engine left an unbounded loop holding both stores and calling
826    /// `reconcile_visibility`, which WRITES. Two properties are pinned here
827    /// because one `Drop` owns both: the epoch closes, and the writer stops.
828    ///
829    /// The writer half is measured by counting the loop's own ticks —
830    /// `reconcile_visibility` reads `list_workflows` unconditionally on every
831    /// pass — through a wrapper that delegates everything to a real store, so
832    /// what is observed is the production loop and not a stand-in for it. The
833    /// wait for two ticks before the drop is the positive control: it fails the
834    /// test if the loop was never running, which is the exact way the first
835    /// form of this test was vacuous.
836    #[tokio::test]
837    async fn dropping_an_engine_without_shutdown_closes_the_completion_retry_epoch()
838    -> Result<(), EngineError> {
839        let visibility = Arc::new(TickCountingVisibilityStore::default());
840        let engine = EngineBuilder::new()
841            .store(InMemoryStore::default())
842            .visibility_store_arc(Arc::clone(&visibility) as Arc<dyn VisibilityStore>)
843            .visibility_reconciliation_interval(Duration::from_millis(10))
844            .build()
845            .await?;
846        // Taken before the drop and held across it: reading through the engine
847        // afterwards is impossible, and reading a fresh handle would observe a
848        // different runtime.
849        let tasks = engine.runtime().engine_tasks();
850        assert!(
851            tasks.is_epoch_open(),
852            "control: a live engine's epoch must be open, or the assertion below is trivially \
853             satisfied"
854        );
855
856        // Positive control for the writer half: the loop must be observably
857        // running BEFORE the drop, or "it stopped" is a statement about a task
858        // that never started. Bounded so a stalled loop fails rather than hangs.
859        let ticking = tokio::time::timeout(Duration::from_secs(10), async {
860            while visibility.ticks() < 2 {
861                tokio::time::sleep(Duration::from_millis(5)).await;
862            }
863        })
864        .await;
865        assert!(
866            ticking.is_ok(),
867            "control: the periodic reconciliation loop must be running before the engine is \
868             dropped, or this test measures nothing; it reached {} ticks",
869            visibility.ticks()
870        );
871
872        drop(engine);
873
874        assert!(
875            !tasks.is_epoch_open(),
876            "an engine released without an explicit shutdown must still close the epoch, or a \
877             completion retry can append a terminal for a run this process no longer owns"
878        );
879
880        // `abort` is asynchronous: it schedules cancellation, so give the
881        // runtime a window several intervals wide to deliver it before reading
882        // the baseline. Anything after that baseline is a task still looping.
883        tokio::time::sleep(Duration::from_millis(200)).await;
884        let after_abort = visibility.ticks();
885        tokio::time::sleep(Duration::from_millis(200)).await;
886        assert_eq!(
887            visibility.ticks(),
888            after_abort,
889            "an engine released without an explicit shutdown must also stop the visibility \
890             reconciliation loop; it ticked again over twenty intervals after the drop, which \
891             means a detached task is still WRITING to a visibility store this process no longer \
892             owns"
893        );
894        Ok(())
895    }
896
897    /// How far ahead of "now" the shared wheel-timer fixture arms its deadline.
898    ///
899    /// 🔴 THIS IS A RACE MARGIN, NOT A TASTE. The release test has to reach
900    /// `drop(engine)` while the timer is still pending; if the deadline passes
901    /// first, the timer fires LEGITIMATELY and the test's own message blames
902    /// `Drop` for a surviving task that never survived — a red that reassigns
903    /// blame, which is worse than no test. The margin buys a window that the
904    /// two atomic reads and one drop between arming and release cannot
905    /// plausibly exhaust, and the release test asserts it was still inside that
906    /// window rather than assuming it.
907    const WHEEL_TIMER_ARMING_MARGIN: std::time::Duration = std::time::Duration::from_secs(2);
908
909    /// How far past the deadline both wheel-timer tests observe before reading
910    /// history — the fire path is asynchronous, so the deadline arriving is not
911    /// the same as the append having landed.
912    const WHEEL_TIMER_OBSERVATION_SLACK: std::time::Duration = std::time::Duration::from_secs(1);
913
914    /// A resident run with one live wheel timer, armed through the production
915    /// path, shared by the release test and its positive control. Returns the
916    /// workflow and the deadline it armed, because the release test has to
917    /// check it is still inside the arming window before it can attribute
918    /// anything to the release.
919    ///
920    /// 🔴 ONE FIXTURE, DELIBERATELY. The control's whole job is to show that
921    /// THIS arrangement's timer reaches the store; a second copy that drifted —
922    /// a different residency, a different timer name, a different deadline —
923    /// would control nothing while still reading as a control.
924    ///
925    /// The deadline has to arrive INSIDE the test. The hazard a released engine
926    /// leaves behind is a parked task that later wakes and records, so a
927    /// deadline beyond the test's own lifetime makes "nothing fired" true for a
928    /// reason that has nothing to do with the release. That is what
929    /// [`WHEEL_TIMER_ARMING_MARGIN`] trades against: near enough to observe,
930    /// far enough not to race the drop.
931    async fn arm_resident_run_with_wheel_timer(
932        engine: &crate::Engine,
933        store: &Arc<InMemoryStore>,
934    ) -> Result<(WorkflowId, chrono::DateTime<Utc>), Box<dyn std::error::Error>> {
935        use aion_store::EventStore;
936
937        use crate::durability::{Recorder, WorkflowStartRecord};
938        use crate::registry::{
939            CompletionNotifier, HandleResidency, WorkflowHandle, WorkflowHandleParts,
940        };
941
942        // The wheel is armed only for a workflow the registry resolves as
943        // `Resident`, and `TimerService::schedule` is the production path that
944        // arms it.
945        let workflow_id = WorkflowId::new_v4();
946        let run_id = aion_core::RunId::new_v4();
947        let timer_id = aion_core::TimerId::named("sleep")?;
948        let mut recorder = Recorder::new(
949            workflow_id.clone(),
950            Arc::clone(store) as Arc<dyn EventStore>,
951        );
952        recorder
953            .record_workflow_started(
954                Utc::now(),
955                WorkflowStartRecord {
956                    workflow_type: "checkout".to_owned(),
957                    input: payload()?,
958                    run_id: run_id.clone(),
959                    parent_run_id: None,
960                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
961                },
962            )
963            .await?;
964        recorder
965            .record_timer_started(Utc::now(), timer_id.clone(), Utc::now())
966            .await?;
967        engine.registry().insert(
968            (workflow_id.clone(), run_id.clone()),
969            WorkflowHandle::new(WorkflowHandleParts {
970                workflow_id: workflow_id.clone(),
971                run_id,
972                pid: 1,
973                workflow_type: "checkout".to_owned(),
974                namespace: String::from("default"),
975                loaded_version: aion_package::ContentHash::from_bytes([9; 32]),
976                cached_status: WorkflowStatus::Running,
977                residency: HandleResidency::Resident,
978                recorder,
979                completion: CompletionNotifier::new(),
980            }),
981        )?;
982
983        let fire_at = Utc::now() + chrono::Duration::from_std(WHEEL_TIMER_ARMING_MARGIN)?;
984        crate::runtime::nif_timer_bridge::installed_timer_service(engine.runtime().nif_state())
985            .map_err(|error| format!("the engine installed no timer service: {error}"))?
986            .schedule(workflow_id.clone(), timer_id, fire_at)
987            .await?;
988        Ok((workflow_id, fire_at))
989    }
990
991    /// 🔴 M-1's THIRD WRITER, AND
992    /// `dropping_an_engine_without_shutdown_closes_the_completion_retry_epoch`
993    /// IS BLIND TO IT.
994    ///
995    /// `Drop for Engine` disarms the live timer wheel as well as closing the
996    /// engine-task epoch and aborting the reconciliation loop. That sibling's
997    /// fixture never arms a wheel timer, so deleting `shutdown_timer_wheel` from
998    /// `Drop` leaves every one of its assertions green — a fixture that never
999    /// starts the thing under test cannot see whether releasing the engine stops
1000    /// it, which is the same defect that test's own comment records having had.
1001    ///
1002    /// The wheel is a DURABLE writer: a fired wheel timer records `TimerFired`
1003    /// through the run's recorder. An engine released with one still armed
1004    /// therefore appends to a history this process no longer owns — the #119
1005    /// failover race reached through a different door, because
1006    /// `RuntimeHandle::shutdown` stops the beamr scheduler while the armed tasks
1007    /// live on the tokio runtime and are not reached by it. On the release path
1008    /// there is no shutdown at all, so `Drop` is the only thing that can.
1009    ///
1010    /// The count is read through an `Arc<EngineNifState>` held ACROSS the drop,
1011    /// so the release is the only variable between the two readings. The
1012    /// pre-drop assertion is the control and it is not decoration: it is the
1013    /// exact vacuity this test exists to close.
1014    #[tokio::test]
1015    async fn dropping_an_engine_without_shutdown_disarms_the_live_timer_wheel()
1016    -> Result<(), Box<dyn std::error::Error>> {
1017        use aion_store::EventStore;
1018
1019        let store = Arc::new(InMemoryStore::default());
1020        let engine = EngineBuilder::new()
1021            .store_arc(Arc::clone(&store) as Arc<dyn EventStore>)
1022            .visibility_store(InMemoryStore::default())
1023            .build()
1024            .await?;
1025        // Held across the drop; see `EngineNifState::armed_wheel_timers`.
1026        let nif_state = Arc::clone(engine.runtime().nif_state());
1027        let (workflow_id, fire_at) = arm_resident_run_with_wheel_timer(&engine, &store).await?;
1028        assert_eq!(
1029            nif_state.armed_wheel_timers(),
1030            1,
1031            "control: the fixture must have actually armed a wheel timer, or the assertions below \
1032             are satisfied by an engine that never had one — the exact way the sibling test above \
1033             is blind to this half of `Drop`"
1034        );
1035
1036        // 🔴 FIXTURE GUARD, NOT A CLAIM ABOUT `Drop`. Everything below reads a
1037        // timer that has NOT yet fired; if the deadline has already passed, a
1038        // `TimerFired` in history is the timer doing its job, and the decisive
1039        // assertion would report it as a task that survived the release. That is
1040        // a red which reassigns blame — the failure mode this guard exists to
1041        // make impossible to mistake. Both readings are taken before the drop,
1042        // so neither can be explained by it.
1043        let before_drop = Utc::now();
1044        assert!(
1045            before_drop < fire_at,
1046            "fixture: the arming window closed before the release was reached ({before_drop} is \
1047             not before {fire_at}). This is a FIXTURE timing failure — most likely a loaded box — \
1048             and NOT evidence about cancellation. Widen `WHEEL_TIMER_ARMING_MARGIN`; do not read \
1049             this as `Drop` leaking a task."
1050        );
1051        let armed = store.read_history(&workflow_id).await?;
1052        assert!(
1053            !armed
1054                .iter()
1055                .any(|event| matches!(event, Event::TimerFired { .. })),
1056            "fixture: the timer already fired before the engine was released, so this run cannot \
1057             say anything about cancellation. Same remedy as above — widen the margin: {armed:#?}"
1058        );
1059
1060        drop(engine);
1061
1062        assert_eq!(
1063            nif_state.armed_wheel_timers(),
1064            0,
1065            "an engine released without an explicit shutdown must empty its live timer wheel"
1066        );
1067
1068        // 🔴 AND THE TASK ITSELF IS GONE, WHICH THE COUNT ABOVE CANNOT SEE.
1069        // `shutdown_timer_wheel` both removes the entry and aborts the handle;
1070        // the count observes only the removal, so deleting the abort leaves it
1071        // green while an armed task lives on. This waits past the deadline and
1072        // reads the durable record, which is where a surviving task would show
1073        // up — and the sibling test
1074        // `a_live_wheel_timer_fires_when_the_engine_is_not_released` is its
1075        // positive control: it proves this same fixture's timer DOES reach the
1076        // store when nothing disarms it, so an empty reading here is a
1077        // cancellation rather than a timer that was never going to arrive.
1078        tokio::time::sleep(WHEEL_TIMER_ARMING_MARGIN + WHEEL_TIMER_OBSERVATION_SLACK).await;
1079        let history = store.read_history(&workflow_id).await?;
1080        assert!(
1081            !history
1082                .iter()
1083                .any(|event| matches!(event, Event::TimerFired { .. })),
1084            "an engine released without an explicit shutdown must CANCEL its wheel tasks, not \
1085             merely forget them: a surviving task records `TimerFired` for a run this process no \
1086             longer owns, which is a second writer for one workflow: {history:#?}"
1087        );
1088        Ok(())
1089    }
1090
1091    /// 🔴 AND A DRAIN IS NOT A GATE. The test above proves the wheel is EMPTIED
1092    /// by the release; this one proves it stays empty.
1093    ///
1094    /// `Drop for Engine` deliberately leaves the beamr scheduler running and the
1095    /// engine seams installed, so a workflow process still runnable can reach
1096    /// `sleep` a moment AFTER the drain and arm a fresh task — whose body is
1097    /// `fire_wheel_timer`, a durable `TimerFired` append against a run a
1098    /// successor engine may already own. That is the same second-writer breach
1099    /// the drain exists to prevent, reached one instant later, and until
1100    /// 2026-08-07 `arm_timer` had no check of any kind: it spawned
1101    /// unconditionally.
1102    ///
1103    /// The scheduling call is the PRODUCTION path, not a direct poke at the
1104    /// bridge, and it is made through an `Arc<EngineNifState>` held across the
1105    /// drop — the same instrument the sibling above uses, and available for the
1106    /// same reason (the drop does not clear the seams).
1107    ///
1108    /// Two controls, because refusal has two boring explanations. The first
1109    /// schedule succeeds BEFORE the drop, so the fixture demonstrably reaches
1110    /// the arming path at all; and the count is asserted `1` then `0` around the
1111    /// release, so the post-drop `Err` cannot be a fixture that was never able
1112    /// to arm anything.
1113    #[tokio::test]
1114    async fn arming_a_wheel_timer_after_the_engine_is_released_is_refused()
1115    -> Result<(), Box<dyn std::error::Error>> {
1116        use aion_store::EventStore;
1117
1118        let store = Arc::new(InMemoryStore::default());
1119        let engine = EngineBuilder::new()
1120            .store_arc(Arc::clone(&store) as Arc<dyn EventStore>)
1121            .visibility_store(InMemoryStore::default())
1122            .build()
1123            .await?;
1124        let nif_state = Arc::clone(engine.runtime().nif_state());
1125        // CONTROL 1: this fixture can arm. The call below is the same
1126        // `TimerService::schedule` the post-drop attempt makes, and it succeeds.
1127        let (workflow_id, _fire_at) = arm_resident_run_with_wheel_timer(&engine, &store).await?;
1128        assert_eq!(
1129            nif_state.armed_wheel_timers(),
1130            1,
1131            "control: the fixture must have armed a wheel timer through the production path, or \
1132             the refusal below is satisfied by a fixture that could never arm one"
1133        );
1134
1135        drop(engine);
1136
1137        // CONTROL 2: the release emptied the wheel, so what follows is measured
1138        // against a torn-down wheel rather than a busy one.
1139        assert_eq!(nif_state.armed_wheel_timers(), 0);
1140
1141        let refused = crate::runtime::nif_timer_bridge::installed_timer_service(&nif_state)
1142            .map_err(|error| format!("the released engine's timer seam is gone: {error}"))?
1143            .schedule(
1144                workflow_id,
1145                aion_core::TimerId::named("sleep-after-release")?,
1146                Utc::now() + chrono::Duration::from_std(WHEEL_TIMER_ARMING_MARGIN)?,
1147            )
1148            .await;
1149        let Err(error) = refused else {
1150            return Err(
1151                "arming a wheel timer through a released engine must be REFUSED: the task \
1152                        it spawns appends a durable `TimerFired` for a run this process no longer \
1153                        owns, which is a second writer for one workflow"
1154                    .into(),
1155            );
1156        };
1157        assert!(
1158            error.to_string().contains("torn down"),
1159            "the refusal must say WHY, so an operator reading it is not sent looking for a \
1160             missing workflow or a bad timer id: {error}"
1161        );
1162        assert_eq!(
1163            nif_state.armed_wheel_timers(),
1164            0,
1165            "the refused arm must leave nothing behind: a wheel entry inserted before the refusal \
1166             would be a durable writer with no owner to cancel it"
1167        );
1168        Ok(())
1169    }
1170
1171    /// The positive control for the assertion above: this fixture's wheel timer
1172    /// really does reach the durable record when nothing disarms it.
1173    ///
1174    /// Without this, "no `TimerFired` after the drop" is equally well explained
1175    /// by a fixture whose timer could never fire at all — a registry entry the
1176    /// fire path rejects, a seam that was never installed, a deadline that never
1177    /// arrives. An absence is only evidence when its presence has been shown
1178    /// reachable by the same means.
1179    #[tokio::test]
1180    async fn a_live_wheel_timer_fires_when_the_engine_is_not_released()
1181    -> Result<(), Box<dyn std::error::Error>> {
1182        use aion_store::EventStore;
1183
1184        let store = Arc::new(InMemoryStore::default());
1185        let engine = EngineBuilder::new()
1186            .store_arc(Arc::clone(&store) as Arc<dyn EventStore>)
1187            .visibility_store(InMemoryStore::default())
1188            .build()
1189            .await?;
1190        let (workflow_id, _) = arm_resident_run_with_wheel_timer(&engine, &store).await?;
1191
1192        tokio::time::sleep(WHEEL_TIMER_ARMING_MARGIN + WHEEL_TIMER_OBSERVATION_SLACK).await;
1193
1194        let history = store.read_history(&workflow_id).await?;
1195        assert!(
1196            history
1197                .iter()
1198                .any(|event| matches!(event, Event::TimerFired { .. })),
1199            "the fixture's wheel timer must reach the store when the engine is still held, or \
1200             the sibling test's absence proves nothing: {history:#?}"
1201        );
1202        drop(engine);
1203        Ok(())
1204    }
1205
1206    /// A visibility store that counts the periodic reconciliation loop's passes.
1207    ///
1208    /// Delegates every method to a real [`InMemoryStore`] so the loop under
1209    /// observation does the same work it does in production; the counter is the
1210    /// only addition. `list_workflows` is the tick site because
1211    /// `reconcile_visibility` calls it unconditionally at the top of every pass,
1212    /// so the count cannot be lowered by the store happening to be consistent.
1213    #[derive(Default)]
1214    struct TickCountingVisibilityStore {
1215        inner: InMemoryStore,
1216        list_calls: std::sync::atomic::AtomicUsize,
1217    }
1218
1219    impl TickCountingVisibilityStore {
1220        fn ticks(&self) -> usize {
1221            self.list_calls.load(std::sync::atomic::Ordering::Acquire)
1222        }
1223    }
1224
1225    #[async_trait::async_trait]
1226    impl VisibilityStore for TickCountingVisibilityStore {
1227        async fn record_visibility(
1228            &self,
1229            record: aion_store::visibility::VisibilityRecord,
1230        ) -> Result<(), aion_store::StoreError> {
1231            self.inner.record_visibility(record).await
1232        }
1233
1234        async fn list_workflows(
1235            &self,
1236            filter: ListWorkflowsFilter,
1237        ) -> Result<Vec<aion_store::visibility::WorkflowSummary>, aion_store::StoreError> {
1238            self.list_calls
1239                .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1240            self.inner.list_workflows(filter).await
1241        }
1242
1243        async fn count_workflows(
1244            &self,
1245            filter: ListWorkflowsFilter,
1246        ) -> Result<u64, aion_store::StoreError> {
1247            self.inner.count_workflows(filter).await
1248        }
1249    }
1250
1251    fn capacity(value: usize) -> Result<NonZeroUsize, Box<dyn std::error::Error>> {
1252        NonZeroUsize::new(value).ok_or_else(|| "capacity must be non-zero".into())
1253    }
1254
1255    #[tokio::test]
1256    async fn event_streaming_delivers_recorder_appends_through_engine_subscribe()
1257    -> Result<(), Box<dyn std::error::Error>> {
1258        let engine = EngineBuilder::new()
1259            .store(InMemoryStore::default())
1260            .in_memory_visibility()
1261            .event_streaming(capacity(8)?)
1262            .build()
1263            .await?;
1264        let workflow_id = WorkflowId::new_v4();
1265        let mut subscription = engine.subscribe(crate::EventFilter {
1266            workflow_id: Some(workflow_id.clone()),
1267            run: None,
1268            family: None,
1269        });
1270
1271        // The production append path: a Recorder over the engine's store,
1272        // which `event_streaming` wrapped before any recorder existed.
1273        let mut recorder = crate::durability::Recorder::new(workflow_id.clone(), engine.store());
1274        recorder
1275            .record_workflow_started(
1276                Utc::now(),
1277                crate::durability::WorkflowStartRecord {
1278                    workflow_type: "checkout".to_owned(),
1279                    input: payload()?,
1280                    run_id: aion_core::RunId::new(uuid::Uuid::from_u128(7)),
1281                    parent_run_id: None,
1282                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
1283                },
1284            )
1285            .await?;
1286
1287        let item = tokio::time::timeout(Duration::from_secs(2), subscription.next())
1288            .await?
1289            .ok_or("subscription ended without delivering the appended event")?;
1290        let event = item?;
1291        assert_eq!(event.workflow_id(), &workflow_id);
1292        assert_eq!(event.seq(), 1);
1293        assert!(matches!(event, Event::WorkflowStarted { .. }));
1294        engine.shutdown()?;
1295        Ok(())
1296    }
1297
1298    #[tokio::test]
1299    async fn without_event_streaming_subscriptions_stay_on_deferred_empty_stream()
1300    -> Result<(), Box<dyn std::error::Error>> {
1301        let engine = EngineBuilder::new()
1302            .store(InMemoryStore::default())
1303            .in_memory_visibility()
1304            .build()
1305            .await?;
1306
1307        let mut subscription = engine.subscribe(crate::EventFilter::default());
1308        let item = tokio::time::timeout(Duration::from_secs(2), subscription.next()).await?;
1309
1310        assert!(item.is_none(), "deferred publisher streams must be empty");
1311        engine.shutdown()?;
1312        Ok(())
1313    }
1314
1315    #[tokio::test]
1316    async fn event_streaming_conflicts_with_explicit_event_publisher()
1317    -> Result<(), Box<dyn std::error::Error>> {
1318        let error = EngineBuilder::new()
1319            .store(InMemoryStore::default())
1320            .in_memory_visibility()
1321            .event_publisher(Arc::new(crate::DeferredEventPublisher))
1322            .event_streaming(capacity(8)?)
1323            .build()
1324            .await
1325            .err();
1326
1327        assert!(matches!(
1328            error,
1329            Some(EngineError::ConflictingEventPublisher)
1330        ));
1331        Ok(())
1332    }
1333
1334    #[test]
1335    fn query_timeout_is_only_set_by_caller() {
1336        assert_eq!(EngineBuilder::new().configured_query_timeout(), None);
1337        assert_eq!(
1338            EngineBuilder::new()
1339                .query_timeout(Duration::from_secs(3))
1340                .configured_query_timeout(),
1341            Some(Duration::from_secs(3))
1342        );
1343    }
1344
1345    async fn insert_running_workflow(
1346        engine: &crate::Engine,
1347    ) -> Result<(WorkflowId, aion_core::RunId), Box<dyn std::error::Error>> {
1348        let workflow_id = WorkflowId::new_v4();
1349        let run_id = aion_core::RunId::new_v4();
1350        let mut recorder = crate::durability::Recorder::new(workflow_id.clone(), engine.store());
1351        recorder
1352            .record_workflow_started(
1353                Utc::now(),
1354                crate::durability::WorkflowStartRecord {
1355                    workflow_type: "checkout".to_owned(),
1356                    input: payload()?,
1357                    run_id: run_id.clone(),
1358                    parent_run_id: None,
1359                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
1360                },
1361            )
1362            .await?;
1363        let handle = crate::registry::WorkflowHandle::new(crate::registry::WorkflowHandleParts {
1364            workflow_id: workflow_id.clone(),
1365            run_id: run_id.clone(),
1366            pid: engine.runtime().spawn_test_process_with_trap_exit(true)?,
1367            workflow_type: "checkout".to_owned(),
1368            namespace: String::from("default"),
1369            loaded_version: aion_package::ContentHash::from_bytes([2; 32]),
1370            cached_status: WorkflowStatus::Running,
1371            residency: crate::registry::HandleResidency::Resident,
1372            recorder,
1373            completion: crate::registry::CompletionNotifier::new(),
1374        });
1375        engine
1376            .registry()
1377            .insert((workflow_id.clone(), run_id.clone()), handle)?;
1378        Ok((workflow_id, run_id))
1379    }
1380
1381    #[tokio::test]
1382    async fn query_timeout_installs_the_concrete_query_seam()
1383    -> Result<(), Box<dyn std::error::Error>> {
1384        let engine = EngineBuilder::new()
1385            .store(InMemoryStore::default())
1386            .in_memory_visibility()
1387            .query_timeout(Duration::from_millis(250))
1388            .build()
1389            .await?;
1390        let (workflow_id, run_id) = insert_running_workflow(&engine).await?;
1391
1392        // The concrete seam reached the query mailbox engine, which answers
1393        // an unregistered name with a typed UnknownQuery — the deferred seam
1394        // would have failed with its "not configured" runtime error instead.
1395        let result = engine
1396            .query(
1397                &workflow_id,
1398                &run_id,
1399                "state",
1400                aion_core::Payload::json_null(),
1401            )
1402            .await;
1403
1404        assert!(matches!(
1405            result,
1406            Err(crate::EngineError::Query(crate::QueryError::UnknownQuery(name))) if name == "state"
1407        ));
1408        engine.shutdown()?;
1409        Ok(())
1410    }
1411
1412    #[tokio::test]
1413    async fn without_query_timeout_the_query_seam_stays_deferred()
1414    -> Result<(), Box<dyn std::error::Error>> {
1415        let engine = EngineBuilder::new()
1416            .store(InMemoryStore::default())
1417            .in_memory_visibility()
1418            .build()
1419            .await?;
1420        let (workflow_id, run_id) = insert_running_workflow(&engine).await?;
1421
1422        let result = engine
1423            .query(
1424                &workflow_id,
1425                &run_id,
1426                "state",
1427                aion_core::Payload::json_null(),
1428            )
1429            .await;
1430
1431        assert!(matches!(
1432            result,
1433            Err(crate::EngineError::Runtime { reason }) if reason.contains("not configured")
1434        ));
1435        engine.shutdown()?;
1436        Ok(())
1437    }
1438
1439    #[test]
1440    fn owned_shards_are_only_set_by_caller() {
1441        // The default builder configures NO shard restriction: `build()` never
1442        // touches the store's scoping hook, so single-node boot owns ALL shards
1443        // and is byte-identical to today.
1444        assert_eq!(EngineBuilder::new().configured_owned_shards(), None);
1445        assert_eq!(
1446            EngineBuilder::new()
1447                .owned_shards([2, 0, 2, 1])
1448                .configured_owned_shards(),
1449            Some([2, 0, 2, 1].as_slice())
1450        );
1451    }
1452
1453    #[test]
1454    fn scheduler_threads_are_only_set_by_caller() {
1455        assert_eq!(EngineBuilder::new().scheduler_thread_count(), None);
1456        assert_eq!(
1457            EngineBuilder::new()
1458                .scheduler_threads(4)
1459                .scheduler_thread_count(),
1460            Some(4)
1461        );
1462    }
1463
1464    /// The completion-retry ladder the caller set is the ladder the runtime is
1465    /// started with.
1466    ///
1467    /// Asserting on `runtime_config()` rather than on a builder accessor is the
1468    /// whole point: an accessor test would pass with the
1469    /// `.with_completion_retry(self.completion_retry)` line deleted, because the
1470    /// field would still hold what the setter put there while the runtime
1471    /// silently ran on the inherited default. This is the only place that link
1472    /// is held.
1473    ///
1474    /// The first assertion is the test's own control. It fixes that the chosen
1475    /// ladder differs from the default, so the equality below cannot be
1476    /// satisfied by a runtime configuration that ignored the builder entirely.
1477    #[test]
1478    fn the_completion_retry_ladder_reaches_the_runtime_configuration()
1479    -> Result<(), Box<dyn std::error::Error>> {
1480        let chosen = crate::runtime::CompletionRetryConfig::try_new(
1481            Duration::from_millis(250),
1482            Duration::from_secs(7),
1483        )?;
1484        assert_ne!(
1485            chosen,
1486            crate::runtime::CompletionRetryConfig::default(),
1487            "a ladder equal to the default could not distinguish wiring from inheritance"
1488        );
1489
1490        assert_eq!(
1491            EngineBuilder::new()
1492                .completion_retry(chosen)
1493                .runtime_config()
1494                .completion_retry,
1495            chosen,
1496            "the runtime must be started with the operator's ladder, not the inherited default"
1497        );
1498        Ok(())
1499    }
1500
1501    #[test]
1502    fn visibility_reconciliation_interval_is_only_set_by_caller() {
1503        let interval = Duration::from_millis(250);
1504
1505        assert_eq!(
1506            EngineBuilder::new().configured_visibility_reconciliation_interval(),
1507            None
1508        );
1509        assert_eq!(
1510            EngineBuilder::new()
1511                .visibility_reconciliation_interval(interval)
1512                .configured_visibility_reconciliation_interval(),
1513            Some(interval)
1514        );
1515    }
1516
1517    #[tokio::test]
1518    async fn duplicate_host_nif_mfa_returns_typed_error() {
1519        let mfa = Mfa::new("host", "zero", 0);
1520        let error = EngineBuilder::new()
1521            .store(InMemoryStore::default())
1522            .in_memory_visibility()
1523            .register_nifs([
1524                NifEntry::new(
1525                    mfa.clone(),
1526                    crate::runtime::nif::test_native_zero,
1527                    Determinism::Pure,
1528                ),
1529                NifEntry::dirty(
1530                    mfa,
1531                    crate::runtime::nif::test_native_zero,
1532                    Determinism::Pure,
1533                ),
1534            ])
1535            .build()
1536            .await
1537            .err();
1538
1539        assert!(matches!(
1540            error,
1541            Some(EngineError::NifRegistration { reason }) if reason.contains("host:zero/0")
1542        ));
1543    }
1544
1545    #[tokio::test]
1546    async fn empty_store_builds_coordinator_history_without_registry_or_supervision()
1547    -> Result<(), EngineError> {
1548        let store = Arc::new(InMemoryStore::default());
1549        let engine = EngineBuilder::new()
1550            .store_arc(store.clone())
1551            .in_memory_visibility()
1552            .build()
1553            .await?;
1554
1555        assert!(engine.registry().list()?.is_empty());
1556        assert_eq!(engine.supervision().type_supervisor_count()?, 1);
1557        assert_eq!(engine.workflow_catalog().workflows()?.len(), 0);
1558
1559        let coordinator_id = schedule_coordinator_workflow_id();
1560        let active = store.list_active().await?;
1561        assert_eq!(active, vec![coordinator_id.clone()]);
1562        let history = store.read_history(&coordinator_id).await?;
1563        let [started] = history.as_slice() else {
1564            return Err(EngineError::Load {
1565                reason: format!(
1566                    "expected exactly one coordinator event, found {}",
1567                    history.len()
1568                ),
1569            });
1570        };
1571        match started {
1572            Event::WorkflowStarted {
1573                workflow_type,
1574                input,
1575                run_id,
1576                parent_run_id,
1577                ..
1578            } => {
1579                assert_eq!(workflow_type, schedule_coordinator_workflow_type());
1580                assert_eq!(
1581                    input,
1582                    &Payload::from_json(&json!({})).map_err(|error| {
1583                        EngineError::Load {
1584                            reason: format!("failed to build expected payload: {error}"),
1585                        }
1586                    })?
1587                );
1588                assert_eq!(run_id, &schedule_coordinator_run_id());
1589                assert!(parent_run_id.is_none());
1590            }
1591            other => {
1592                return Err(EngineError::Load {
1593                    reason: format!("expected coordinator WorkflowStarted, found {other:?}"),
1594                });
1595            }
1596        }
1597
1598        engine.shutdown()?;
1599        let rebuilt = EngineBuilder::new()
1600            .store_arc(store.clone())
1601            .in_memory_visibility()
1602            .build()
1603            .await?;
1604        let rebuilt_history = store.read_history(&coordinator_id).await?;
1605        assert_eq!(rebuilt_history.len(), 1);
1606        rebuilt.shutdown()?;
1607
1608        Ok(())
1609    }
1610
1611    #[tokio::test]
1612    async fn build_loads_already_loaded_package() -> Result<(), Box<dyn std::error::Error>> {
1613        if gleam_test_support::skip_if_unavailable() {
1614            return Ok(());
1615        }
1616        let package = fixture_package()?;
1617        let version = package.content_hash().clone();
1618        let deployed_entry_module = package.deployed_entry_module();
1619
1620        let engine = EngineBuilder::new()
1621            .store(InMemoryStore::default())
1622            .in_memory_visibility()
1623            .load_workflows(package)
1624            .build()
1625            .await?;
1626
1627        let loaded = engine
1628            .workflow_catalog()
1629            .get("counter", &version)?
1630            .ok_or("loaded package record missing")?;
1631        assert_eq!(loaded.deployed_entry_module(), deployed_entry_module);
1632        assert!(
1633            engine
1634                .runtime()
1635                .has_registered_module(&deployed_entry_module)
1636        );
1637        Ok(())
1638    }
1639
1640    #[tokio::test]
1641    async fn startup_reconciliation_backfills_completed_visibility()
1642    -> Result<(), Box<dyn std::error::Error>> {
1643        let store = Arc::new(InMemoryStore::default());
1644        let completed_id = WorkflowId::new_v4();
1645
1646        store
1647            .append(
1648                WriteToken::recorder(),
1649                &completed_id,
1650                &[
1651                    started(&completed_id, "billing")?,
1652                    completed(&completed_id)?,
1653                ],
1654                0,
1655            )
1656            .await?;
1657
1658        let engine = EngineBuilder::new()
1659            .store_arc(store.clone())
1660            .visibility_store_arc(store.clone())
1661            .build()
1662            .await?;
1663
1664        let summaries = store.list_workflows(ListWorkflowsFilter::default()).await?;
1665        let completed_summary = summaries
1666            .iter()
1667            .find(|summary| summary.workflow_id == completed_id)
1668            .ok_or("completed workflow missing from visibility")?;
1669
1670        assert_eq!(completed_summary.status, WorkflowStatus::Completed);
1671        assert!(completed_summary.close_time.is_some());
1672        engine.shutdown()?;
1673        Ok(())
1674    }
1675
1676    #[tokio::test]
1677    async fn periodic_visibility_reconciliation_repairs_gap_after_startup()
1678    -> Result<(), Box<dyn std::error::Error>> {
1679        let store = Arc::new(InMemoryStore::default());
1680        let engine = EngineBuilder::new()
1681            .store_arc(store.clone())
1682            .visibility_store_arc(store.clone())
1683            .visibility_reconciliation_interval(Duration::from_millis(25))
1684            .build()
1685            .await?;
1686        let workflow_id = WorkflowId::new_v4();
1687
1688        store
1689            .append(
1690                WriteToken::recorder(),
1691                &workflow_id,
1692                &[started(&workflow_id, "checkout")?],
1693                0,
1694            )
1695            .await?;
1696
1697        tokio::time::timeout(Duration::from_secs(2), async {
1698            loop {
1699                let summaries = store.list_workflows(ListWorkflowsFilter::default()).await?;
1700                if summaries.iter().any(|summary| {
1701                    summary.workflow_id == workflow_id && summary.status == WorkflowStatus::Running
1702                }) {
1703                    return Ok::<(), aion_store::StoreError>(());
1704                }
1705                tokio::time::sleep(Duration::from_millis(10)).await;
1706            }
1707        })
1708        .await??;
1709
1710        engine.shutdown()?;
1711        Ok(())
1712    }
1713
1714    #[tokio::test]
1715    async fn build_loads_package_from_path() -> Result<(), Box<dyn std::error::Error>> {
1716        if gleam_test_support::skip_if_unavailable() {
1717            return Ok(());
1718        }
1719        let package = fixture_package()?;
1720        let version = package.content_hash().clone();
1721        let path = write_fixture_package(&package)?;
1722
1723        let engine = EngineBuilder::new()
1724            .store(InMemoryStore::default())
1725            .in_memory_visibility()
1726            .load_workflows(path.as_path())
1727            .build()
1728            .await?;
1729        std::fs::remove_file(path)?;
1730
1731        assert!(
1732            engine
1733                .workflow_catalog()
1734                .get("counter", &version)?
1735                .is_some()
1736        );
1737        Ok(())
1738    }
1739}