Skip to main content

aion/engine/
delegated.rs

1//! signal/query/subscribe surface (AT/AD delegation)
2
3use aion_core::{Event, Payload, RunId, WorkflowId, current_lease_terminal, run_segment};
4use async_trait::async_trait;
5use futures::stream::{self, BoxStream};
6use serde::{Deserialize, Serialize};
7use std::sync::Arc;
8
9use crate::{Engine, EngineError, SignalRouterError, WorkflowHandle};
10
11use super::api::workflow_not_found;
12
13/// Live-event subscription filter consumed by the AD/AT publisher seam.
14///
15/// The `run` field is part of the cross-cluster contract even though the
16/// current core [`Event`] envelope does not yet carry run metadata; publisher
17/// implementations that know run residency out-of-band can apply it there.
18#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
19pub struct EventFilter {
20    /// Match events for this workflow execution id.
21    pub workflow_id: Option<WorkflowId>,
22    /// Match events for this run id when the publisher has run metadata.
23    pub run: Option<RunId>,
24    /// Match events belonging to this event family.
25    pub family: Option<EventFamily>,
26}
27
28impl EventFilter {
29    /// Returns whether an event satisfies the constraints visible on [`Event`].
30    ///
31    /// Run filtering is intentionally not decided here because [`Event`] does
32    /// not currently include a [`RunId`]; the publisher seam applies that field
33    /// with its own metadata when available.
34    #[must_use]
35    pub fn matches(&self, event: &Event) -> bool {
36        self.workflow_id
37            .as_ref()
38            .is_none_or(|workflow_id| event.workflow_id() == workflow_id)
39            && self
40                .family
41                .is_none_or(|family| family == event_family(event))
42    }
43}
44
45/// Coarse event families for live subscription filtering.
46#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq)]
47pub enum EventFamily {
48    /// Workflow lifecycle events.
49    Workflow,
50    /// Activity scheduling and completion events.
51    Activity,
52    /// Timer events owned by AT.
53    Timer,
54    /// Signal delivery events owned by AT/AD.
55    Signal,
56    /// Child-workflow lifecycle events.
57    ChildWorkflow,
58    /// Schedule lifecycle and trigger events.
59    Schedule,
60    /// Workloop cadence, iteration, retirement, and alarm events. The trigger
61    /// layer (Leg 3) subscribes here to arm on `InvariantUnconfirmed` causes.
62    Workloop,
63}
64
65/// AT-005/AT-006 signal-routing seam.
66///
67/// Implementations record the signal through the workflow recorder and deliver
68/// it to the target workflow mailbox. The engine only resolves the live target
69/// handle and delegates to this trait.
70#[async_trait]
71pub trait SignalRouter: Send + Sync {
72    /// Route a signal to the already-resolved workflow target.
73    async fn route(
74        &self,
75        target: &WorkflowHandle,
76        name: String,
77        payload: Payload,
78    ) -> Result<(), EngineError>;
79}
80
81/// AT-007 query-dispatch seam.
82///
83/// Implementations dispatch a read-only query to workflow code and map their
84/// query errors into [`EngineError`]. The engine only resolves the live target
85/// handle and delegates to this trait.
86#[async_trait]
87pub trait QueryService: Send + Sync {
88    /// Dispatch a named query, with its caller-supplied arguments, to the
89    /// already-resolved workflow target.
90    ///
91    /// `arguments` is a type-erased [`Payload`] carrying the JSON document the
92    /// workflow's query handler decodes. `null` is the canonical "no
93    /// arguments" document. Arguments are read-only inputs: they are handed to
94    /// the handler and never recorded.
95    async fn query(
96        &self,
97        target: &WorkflowHandle,
98        name: String,
99        arguments: Payload,
100    ) -> Result<Payload, EngineError>;
101}
102
103/// A live subscription fell behind the publisher and skipped events.
104///
105/// Publishers yield this as a stream item — never a silent skip and never a
106/// silent stream end — and then continue with subsequent live events, so the
107/// consumer always learns exactly how many events it missed.
108#[derive(thiserror::Error, Clone, Copy, Debug, PartialEq, Eq)]
109#[error("event subscription lagged behind the live stream and skipped {skipped} events")]
110pub struct EventStreamLagged {
111    /// Number of events the subscriber missed.
112    pub skipped: u64,
113}
114
115/// AD/AT live event publisher seam.
116///
117/// Implementations own event publication and filtering. The engine exposes the
118/// in-process subscription surface without owning publication machinery.
119pub trait EventPublisher: Send + Sync {
120    /// Subscribe to a filtered stream of live workflow events.
121    ///
122    /// A subscriber that falls behind the publisher receives one
123    /// `Err(`[`EventStreamLagged`]`)` item carrying the skipped count and then
124    /// continues with subsequent events; lag never silently drops events and
125    /// never silently ends the stream.
126    fn subscribe(
127        &self,
128        filter: EventFilter,
129    ) -> BoxStream<'static, Result<Event, EventStreamLagged>>;
130}
131
132/// Object-safe delegated seams held by the engine for AT/AD integration.
133#[derive(Clone)]
134pub struct DelegatedSeams {
135    signal_router: Arc<dyn SignalRouter>,
136    query_service: Arc<dyn QueryService>,
137    event_publisher: Arc<dyn EventPublisher>,
138}
139
140impl DelegatedSeams {
141    /// Build a seam bundle from concrete AT/AD implementations.
142    #[must_use]
143    pub const fn new(
144        signal_router: Arc<dyn SignalRouter>,
145        query_service: Arc<dyn QueryService>,
146        event_publisher: Arc<dyn EventPublisher>,
147    ) -> Self {
148        Self {
149            signal_router,
150            query_service,
151            event_publisher,
152        }
153    }
154
155    /// Signal routing seam installed for AT-005/AT-006 delegation.
156    #[must_use]
157    pub fn signal_router(&self) -> &dyn SignalRouter {
158        self.signal_router.as_ref()
159    }
160
161    /// Query dispatch seam installed for AT-007 delegation.
162    #[must_use]
163    pub fn query_service(&self) -> &dyn QueryService {
164        self.query_service.as_ref()
165    }
166
167    /// Live event publisher seam installed for AD/AT delegation.
168    #[must_use]
169    pub fn event_publisher(&self) -> &dyn EventPublisher {
170        self.event_publisher.as_ref()
171    }
172
173    pub(crate) fn signal_router_arc(&self) -> Arc<dyn SignalRouter> {
174        Arc::clone(&self.signal_router)
175    }
176
177    pub(crate) fn query_service_arc(&self) -> Arc<dyn QueryService> {
178        Arc::clone(&self.query_service)
179    }
180
181    pub(crate) fn event_publisher_arc(&self) -> Arc<dyn EventPublisher> {
182        Arc::clone(&self.event_publisher)
183    }
184}
185
186impl Default for DelegatedSeams {
187    fn default() -> Self {
188        Self::new(
189            Arc::new(DeferredSignalRouter),
190            Arc::new(DeferredQueryService),
191            Arc::new(DeferredEventPublisher),
192        )
193    }
194}
195
196/// Deferred signal seam used until AT-005/AT-006 installs a concrete router.
197#[derive(Debug, Default)]
198pub struct DeferredSignalRouter;
199
200#[async_trait]
201impl SignalRouter for DeferredSignalRouter {
202    async fn route(
203        &self,
204        target: &WorkflowHandle,
205        name: String,
206        payload: Payload,
207    ) -> Result<(), EngineError> {
208        let _ = (target, name, payload);
209        Err(EngineError::Runtime {
210            reason: "signal routing seam is not configured".to_owned(),
211        })
212    }
213}
214
215/// Deferred query seam used until AT-007 installs a concrete service.
216#[derive(Debug, Default)]
217pub struct DeferredQueryService;
218
219#[async_trait]
220impl QueryService for DeferredQueryService {
221    async fn query(
222        &self,
223        target: &WorkflowHandle,
224        name: String,
225        arguments: Payload,
226    ) -> Result<Payload, EngineError> {
227        let _ = (target, name, arguments);
228        Err(EngineError::Runtime {
229            reason: "query service seam is not configured".to_owned(),
230        })
231    }
232}
233
234/// Deferred publisher seam used until AD/AT installs a concrete publisher.
235#[derive(Debug, Default)]
236pub struct DeferredEventPublisher;
237
238impl EventPublisher for DeferredEventPublisher {
239    fn subscribe(
240        &self,
241        filter: EventFilter,
242    ) -> BoxStream<'static, Result<Event, EventStreamLagged>> {
243        let _ = filter;
244        Box::pin(stream::empty())
245    }
246}
247
248impl Engine {
249    /// Send a signal to a live workflow run through the AT routing seam.
250    ///
251    /// The signal is admitted against the signal type declared by the EXACT
252    /// package identity the target run is pinned to, BEFORE anything is
253    /// recorded and before the arrival can be consumed. A refused signal
254    /// therefore leaves the run's history byte-identical and the run parked on
255    /// exactly the wait it was parked on — the refusal reaches the caller, not
256    /// the run.
257    ///
258    /// # Errors
259    ///
260    /// Returns [`EngineError::SignalRefused`] when the name is not declared by
261    /// the target's package or the payload does not satisfy the declared type
262    /// (nothing recorded, nothing consumed),
263    /// [`EngineError::WorkflowNotFound`] when the `(workflow, run)` pair is unknown,
264    /// [`SignalRouterError::Terminal`] when it is durably terminal, or other typed errors from
265    /// the configured signal seam.
266    pub async fn signal(
267        &self,
268        id: &WorkflowId,
269        run: &RunId,
270        name: impl Into<String>,
271        payload: Payload,
272    ) -> Result<(), EngineError> {
273        let name = name.into();
274        let handle =
275            if let Some(handle) = self.registry().get(id, run)? {
276                // BOUNDARY ADMISSION (resident): the live handle carries the exact
277                // identity this run resolved at start, so it is the ruler here.
278                crate::signal::admission::admit_against_handle(
279                    self.workflow_catalog(),
280                    &handle,
281                    &name,
282                    &payload,
283                )?;
284                handle
285            } else {
286                let history = self.store().read_history(id).await?;
287                if run_has_terminal_history(&history, run) {
288                    return Err(SignalRouterError::Terminal {
289                        workflow_id: id.clone(),
290                        run_id: run.clone(),
291                    }
292                    .into());
293                }
294                // BOUNDARY ADMISSION (non-resident): the recorded `WorkflowStarted`
295                // pins the same identity the live handle would have carried. This
296                // runs before BOTH remaining record paths below — the paused
297                // one-shot recorder and the birth-window handle's router — so no
298                // branch out of here can record a refused payload.
299                crate::signal::admission::admit_against_history(
300                    self.workflow_catalog(),
301                    id,
302                    run,
303                    &history,
304                    &name,
305                    &payload,
306                )?;
307                // Paused-but-not-resident (crashed while paused, #204): the run is
308                // durably non-terminal but was deliberately excluded from respawn, so
309                // no live handle exists and handle_after_birth_window would time out
310                // with WorkflowNotFound. Durably record SignalReceived through a
311                // one-shot recorder built from the validated read (record-before-
312                // deliver preserved); it takes effect on resume replay.
313                let segment = aion_core::run_segment(&history, run);
314                if matches!(
315                    aion_core::status_from_events(segment),
316                    aion_core::WorkflowStatus::Paused
317                ) {
318                    let head = history.last().map(Event::seq).unwrap_or_default();
319                    let mut recorder =
320                        crate::durability::Recorder::resume_at(id.clone(), self.store(), head)
321                            .with_visibility(run.clone(), self.visibility_store());
322                    recorder
323                        .record_signal_received(chrono::Utc::now(), name, payload)
324                        .await?;
325                    return Ok(());
326                }
327                // A suspended WORKLOOP (registered on the cadence service, no
328                // resident process — the R13.3 idle state): a signal is a FIRE
329                // (R2.4). Record SignalReceived through a one-shot recorder
330                // (record-before-deliver preserved), then wake the generation so
331                // the iteration runs with the signal in its history. Signals not
332                // named in the loop's arming still record — the loop observes
333                // them when it next runs — but only declared signals wake it.
334                if let Some(workloop) = &self.workloop
335                    && let Some(record) = workloop.store.get_workloop(id).await?
336                {
337                    let head = history.last().map(Event::seq).unwrap_or_default();
338                    let mut recorder =
339                        crate::durability::Recorder::resume_at(id.clone(), self.store(), head)
340                            .with_visibility(run.clone(), self.visibility_store());
341                    recorder
342                        .record_signal_received(chrono::Utc::now(), name.clone(), payload)
343                        .await?;
344                    if record.spec.arming().signals().contains(&name) {
345                        workloop.service.wake_now(id).await.map_err(|error| {
346                            EngineError::Runtime {
347                                reason: format!("signal-armed workloop wake failed: {error}"),
348                            }
349                        })?;
350                    }
351                    return Ok(());
352                }
353                self.handle_after_birth_window(id, run, &history)
354                    .await?
355                    .ok_or_else(|| workflow_not_found(id, run))?
356            };
357        self.delegated()
358            .signal_router()
359            .route(&handle, name, payload)
360            .await
361    }
362
363    /// Dispatch a read-only query, with its arguments, to a live workflow run
364    /// through the AT seam.
365    ///
366    /// `arguments` is the type-erased JSON document the workflow's registered
367    /// handler decodes; `null` is the canonical "no arguments" document.
368    /// Nothing on this path records an event — arguments are inputs to a
369    /// read-only handler, never history.
370    ///
371    /// # Errors
372    ///
373    /// Returns [`EngineError::Query`] with [`crate::query::QueryError::NotRunning`]
374    /// when the `(workflow, run)` pair is durably terminal,
375    /// [`EngineError::WorkflowNotFound`] when it is unknown,
376    /// [`crate::query::QueryError::InvalidArguments`] when `arguments` is not
377    /// a well-formed JSON document, and other typed errors from the configured
378    /// query seam.
379    pub async fn query(
380        &self,
381        id: &WorkflowId,
382        run: &RunId,
383        name: impl Into<String>,
384        arguments: Payload,
385    ) -> Result<Payload, EngineError> {
386        let handle = if let Some(handle) = self.registry().get(id, run)? {
387            handle
388        } else {
389            // Mirror Engine::signal's registry-miss handling: a completed
390            // workflow is NotRunning per the query contract, never NotFound.
391            let history = self.store().read_history(id).await?;
392            if run_has_terminal_history(&history, run) {
393                return Err(EngineError::Query(crate::query::QueryError::NotRunning(
394                    id.clone(),
395                )));
396            }
397            self.handle_after_birth_window(id, run, &history)
398                .await?
399                .ok_or_else(|| workflow_not_found(id, run))?
400        };
401        self.delegated()
402            .query_service()
403            .query(&handle, name.into(), arguments)
404            .await
405    }
406
407    /// Resolve a registry miss against the registration birth window.
408    ///
409    /// The start path records `WorkflowStarted` durably *before* it inserts
410    /// the registry handle, so an embedder acting on observed history (or on
411    /// a `start_workflow` racing on another task) can legitimately arrive
412    /// here after the record and before the insert. When the requested run
413    /// is durably started and non-terminal, the registry is re-polled within
414    /// the builder-supplied delivery policy budget; `None` after the budget
415    /// means the run truly has no live handle (its start failed or its
416    /// engine is gone) and the caller fails typed.
417    pub(crate) async fn handle_after_birth_window(
418        &self,
419        id: &WorkflowId,
420        run: &RunId,
421        history: &[Event],
422    ) -> Result<Option<WorkflowHandle>, EngineError> {
423        let started = history
424            .iter()
425            .any(|event| matches!(event, Event::WorkflowStarted { run_id, .. } if run_id == run));
426        if !started {
427            return Ok(None);
428        }
429        wait_for_registered_handle(self.registry(), id, run, self.runtime().signal_delivery()).await
430    }
431
432    /// Subscribe to the live event stream through the AD/AT publisher seam.
433    ///
434    /// A subscriber that falls behind receives one `Err(`[`EventStreamLagged`]`)`
435    /// item with the skipped count and then continues with subsequent events.
436    #[must_use]
437    pub fn subscribe(
438        &self,
439        filter: EventFilter,
440    ) -> BoxStream<'static, Result<Event, EventStreamLagged>> {
441        self.delegated().event_publisher().subscribe(filter)
442    }
443}
444
445pub(crate) fn run_has_terminal_history(history: &[Event], run: &RunId) -> bool {
446    // Reset-aware: a run is terminal only if its current lease ended in a
447    // terminal event. A WorkflowReopened after a terminal reopens the run, so a
448    // reopened run is not treated as terminal (it can receive signals and
449    // complete again).
450    current_lease_terminal(run_segment(history, run)).is_some()
451}
452
453/// Poll the registry for `(id, run)` until the handle appears or the
454/// builder-supplied delivery budget is spent.
455///
456/// The budget is the policy's full persistence — `ready_timeout ×
457/// max_enqueue_attempts`, the same product the runtime's enqueue retry
458/// expresses — polled with the policy's backoff ladder. A single
459/// `ready_timeout` is the typical insert latency, but the start thread can
460/// be preempted past it under host oversubscription, and the cost of giving
461/// up early is a typed not-found for a workflow that is durably started.
462pub(crate) async fn wait_for_registered_handle(
463    registry: &crate::registry::Registry,
464    id: &WorkflowId,
465    run: &RunId,
466    policy: crate::runtime::SignalDeliveryConfig,
467) -> Result<Option<WorkflowHandle>, EngineError> {
468    let budget = policy
469        .ready_timeout
470        .saturating_mul(policy.max_enqueue_attempts.max(1));
471    let deadline = std::time::Instant::now() + budget;
472    let mut backoff = policy.initial_backoff;
473    loop {
474        if let Some(handle) = registry.get(id, run)? {
475            return Ok(Some(handle));
476        }
477        if std::time::Instant::now() >= deadline {
478            return Ok(None);
479        }
480        tokio::time::sleep(backoff).await;
481        let doubled = backoff.saturating_mul(2);
482        backoff = if doubled > policy.max_backoff {
483            policy.max_backoff
484        } else {
485            doubled
486        };
487    }
488}
489
490const fn event_family(event: &Event) -> EventFamily {
491    match event {
492        Event::WorkflowStarted { .. }
493        | Event::WorkflowCompleted { .. }
494        | Event::WorkflowFailed { .. }
495        | Event::WorkflowCancelled { .. }
496        | Event::WorkflowTimedOut { .. }
497        | Event::WorkflowContinuedAsNew { .. }
498        | Event::WorkflowReopened { .. }
499        | Event::WorkflowPaused { .. }
500        | Event::WorkflowResumed { .. }
501        | Event::SearchAttributesUpdated { .. }
502        // A hatch is a workflow-level start record — detached, not a child —
503        // so it rides the Workflow family, never ChildWorkflow.
504        | Event::WorkflowHatched { .. } => EventFamily::Workflow,
505        Event::ActivityScheduled { .. }
506        | Event::ActivityStarted { .. }
507        | Event::ActivityLeased { .. }
508        | Event::ActivityAdoptionOffered { .. }
509        | Event::ActivityCompleted { .. }
510        | Event::ActivityFailed { .. }
511        | Event::ActivityAdvisoryExhausted { .. }
512        | Event::ActivityFallbackRouted { .. }
513        | Event::ActivityCancelled { .. } => EventFamily::Activity,
514        Event::TimerStarted { .. }
515        | Event::TimerFired { .. }
516        | Event::TimerCancelled { .. }
517        | Event::WithTimeoutCompleted { .. } => EventFamily::Timer,
518        Event::SignalReceived { .. } | Event::SignalSent { .. } => EventFamily::Signal,
519        Event::ChildWorkflowStarted { .. }
520        | Event::ChildWorkflowCompleted { .. }
521        | Event::ChildWorkflowFailed { .. }
522        | Event::ChildWorkflowCancelled { .. } => EventFamily::ChildWorkflow,
523        Event::ScheduleCreated { .. }
524        | Event::ScheduleUpdated { .. }
525        | Event::SchedulePaused { .. }
526        | Event::ScheduleResumed { .. }
527        | Event::ScheduleDeleted { .. }
528        | Event::ScheduleTriggered { .. } => EventFamily::Schedule,
529        Event::CadenceFired { .. }
530        | Event::IterationClosed { .. }
531        | Event::LoopRetired { .. }
532        | Event::InvariantUnconfirmed { .. } => EventFamily::Workloop,
533    }
534}
535
536#[cfg(test)]
537mod tests {
538    use std::sync::{Arc, Mutex};
539
540    use aion_core::{EventEnvelope, WorkflowStatus};
541    use aion_package::ContentHash;
542    use aion_store::visibility::VisibilityStore;
543    use aion_store::{EventStore, InMemoryStore};
544    use futures::{StreamExt, stream};
545    use serde_json::json;
546
547    use crate::durability::Recorder;
548    use crate::engine::api::EngineComponents;
549    use crate::registry::{CompletionNotifier, HandleResidency, WorkflowHandleParts};
550    use crate::{
551        Registry, RuntimeConfig, RuntimeHandle, SupervisionTree, WorkflowCatalog, WorkflowHandle,
552    };
553
554    use super::*;
555
556    #[derive(Debug, Default)]
557    struct SignalCapture {
558        calls: Mutex<Vec<(u64, String, Payload)>>,
559    }
560
561    #[async_trait]
562    impl SignalRouter for SignalCapture {
563        async fn route(
564            &self,
565            target: &WorkflowHandle,
566            name: String,
567            payload: Payload,
568        ) -> Result<(), EngineError> {
569            self.calls
570                .lock()
571                .map_err(|_| EngineError::RegistryPoisoned)?
572                .push((target.pid(), name, payload));
573            Ok(())
574        }
575    }
576
577    #[derive(Debug)]
578    struct QueryCapture {
579        calls: Mutex<Vec<(u64, String, Payload)>>,
580        reply: Payload,
581    }
582
583    #[async_trait]
584    impl QueryService for QueryCapture {
585        async fn query(
586            &self,
587            target: &WorkflowHandle,
588            name: String,
589            arguments: Payload,
590        ) -> Result<Payload, EngineError> {
591            self.calls
592                .lock()
593                .map_err(|_| EngineError::RegistryPoisoned)?
594                .push((target.pid(), name, arguments));
595            Ok(self.reply.clone())
596        }
597    }
598
599    #[derive(Debug)]
600    struct FakePublisher {
601        events: Vec<Event>,
602    }
603
604    impl EventPublisher for FakePublisher {
605        fn subscribe(
606            &self,
607            filter: EventFilter,
608        ) -> BoxStream<'static, Result<Event, EventStreamLagged>> {
609            let events = self
610                .events
611                .iter()
612                .filter(|event| filter.matches(event))
613                .cloned()
614                .map(Ok)
615                .collect::<Vec<_>>();
616            stream::iter(events).boxed()
617        }
618    }
619
620    fn payload(label: &str) -> Result<Payload, aion_core::PayloadError> {
621        Payload::from_json(&json!({ "label": label }))
622    }
623
624    fn engine_with_seams(
625        signal_router: Arc<dyn SignalRouter>,
626        query_service: Arc<dyn QueryService>,
627        event_publisher: Arc<dyn EventPublisher>,
628    ) -> Result<Engine, EngineError> {
629        let backing = Arc::new(InMemoryStore::default());
630        let store: Arc<dyn EventStore> = Arc::clone(&backing) as _;
631        let visibility_store: Arc<dyn VisibilityStore> = backing;
632        Ok(Engine::new(EngineComponents {
633            store,
634            visibility_store,
635            runtime: Arc::new(RuntimeHandle::new(RuntimeConfig::new(
636                Some(1),
637                crate::runtime::config::TEST_STOP_DRAIN_TIMEOUT,
638            ))?),
639            catalog: Arc::new(WorkflowCatalog::new()),
640            registry: Arc::new(Registry::default()),
641            supervision: Arc::new(SupervisionTree::new()),
642            delegated: DelegatedSeams::new(signal_router, query_service, event_publisher),
643            signal_handoff: Arc::new(crate::signal::SignalResumeHandoff::new()),
644            search_attribute_schema: Arc::new(aion_core::SearchAttributeSchema::new()),
645            visibility_reconciliation_task: None,
646            deferred_startup_recovery: None,
647            workloop: None,
648        }))
649    }
650
651    /// Record `WorkflowStarted` durably and build the matching handle
652    /// without inserting it into the registry — the exact state of the
653    /// registration birth window.
654    async fn recorded_active_handle(
655        engine: &Engine,
656    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
657        let workflow_id = WorkflowId::new_v4();
658        let run_id = RunId::new_v4();
659        let store = engine.store();
660        let mut recorder = Recorder::new(workflow_id.clone(), Arc::clone(&store));
661        recorder
662            .record_workflow_started(
663                chrono::Utc::now(),
664                crate::durability::WorkflowStartRecord {
665                    workflow_type: "checkout".to_owned(),
666                    input: payload("input")?,
667                    run_id: run_id.clone(),
668                    parent_run_id: None,
669                    parent_workflow_id: None,
670                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
671                },
672            )
673            .await?;
674        Ok(WorkflowHandle::new(WorkflowHandleParts {
675            workflow_id,
676            run_id,
677            pid: engine.runtime().spawn_test_process_with_trap_exit(true)?,
678            workflow_type: "checkout".to_owned(),
679            namespace: String::from("default"),
680            loaded_version: ContentHash::from_bytes([1; 32]),
681            cached_status: WorkflowStatus::Running,
682            residency: HandleResidency::Resident,
683            recorder,
684            completion: CompletionNotifier::new(),
685        }))
686    }
687
688    async fn insert_active_handle(
689        engine: &Engine,
690    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
691        let handle = recorded_active_handle(engine).await?;
692        engine.registry().insert(
693            (handle.workflow_id().clone(), handle.run_id().clone()),
694            handle.clone(),
695        )?;
696        Ok(handle)
697    }
698
699    fn envelope(seq: u64, workflow_id: &WorkflowId) -> EventEnvelope {
700        EventEnvelope {
701            seq,
702            recorded_at: chrono::Utc::now(),
703            workflow_id: workflow_id.clone(),
704        }
705    }
706
707    /// Registration birth window (the 1/300 release-signal flake): the start
708    /// path records `WorkflowStarted` durably before it inserts the registry
709    /// handle, so a caller acting on observed history can signal before the
710    /// insert lands. The signal must wait the handle out within the delivery
711    /// policy budget — before the fix it returned `WorkflowNotFound`
712    /// immediately.
713    #[tokio::test(flavor = "multi_thread")]
714    async fn signal_inside_the_registration_birth_window_waits_for_the_handle()
715    -> Result<(), Box<dyn std::error::Error>> {
716        let signal = Arc::new(SignalCapture::default());
717        let engine = Arc::new(engine_with_seams(
718            signal.clone(),
719            Arc::new(DeferredQueryService),
720            Arc::new(DeferredEventPublisher),
721        )?);
722        let handle = recorded_active_handle(&engine).await?;
723
724        // The insert lands mid-wait, exactly as the start thread's does.
725        let late_engine = Arc::clone(&engine);
726        let late_handle = handle.clone();
727        let inserter = tokio::spawn(async move {
728            tokio::time::sleep(std::time::Duration::from_millis(15)).await;
729            late_engine.registry().insert(
730                (
731                    late_handle.workflow_id().clone(),
732                    late_handle.run_id().clone(),
733                ),
734                late_handle,
735            )
736        });
737
738        engine
739            .signal(
740                handle.workflow_id(),
741                handle.run_id(),
742                "approve",
743                payload("birth")?,
744            )
745            .await?;
746        inserter.await??;
747
748        let calls = signal
749            .calls
750            .lock()
751            .map_err(|_| EngineError::RegistryPoisoned)?;
752        assert_eq!(calls.len(), 1, "the signal must reach the routed handle");
753        drop(calls);
754        engine.shutdown()?;
755        Ok(())
756    }
757
758    /// The birth wait is bounded: a durably started run whose handle never
759    /// appears (its start failed, or its engine is gone) still fails typed
760    /// after the policy budget.
761    #[tokio::test(flavor = "multi_thread")]
762    async fn signal_for_a_started_run_with_no_handle_fails_typed_after_the_budget()
763    -> Result<(), Box<dyn std::error::Error>> {
764        let engine = engine_with_seams(
765            Arc::new(SignalCapture::default()),
766            Arc::new(DeferredQueryService),
767            Arc::new(DeferredEventPublisher),
768        )?;
769        let handle = recorded_active_handle(&engine).await?;
770
771        let outcome = engine
772            .signal(
773                handle.workflow_id(),
774                handle.run_id(),
775                "approve",
776                payload("never")?,
777            )
778            .await;
779
780        assert!(matches!(outcome, Err(EngineError::WorkflowNotFound { .. })));
781        engine.shutdown()?;
782        Ok(())
783    }
784
785    #[tokio::test]
786    async fn signal_delegates_to_router_and_unknown_returns_not_found()
787    -> Result<(), Box<dyn std::error::Error>> {
788        let signal = Arc::new(SignalCapture::default());
789        let engine = engine_with_seams(
790            signal.clone(),
791            Arc::new(DeferredQueryService),
792            Arc::new(DeferredEventPublisher),
793        )?;
794        let handle = insert_active_handle(&engine).await?;
795        let sent_payload = payload("signal")?;
796
797        engine
798            .signal(
799                handle.workflow_id(),
800                handle.run_id(),
801                "approve",
802                sent_payload.clone(),
803            )
804            .await?;
805
806        {
807            let calls = signal
808                .calls
809                .lock()
810                .map_err(|_| EngineError::RegistryPoisoned)?;
811            assert_eq!(
812                calls.as_slice(),
813                &[(handle.pid(), "approve".to_owned(), sent_payload)]
814            );
815        }
816        let unknown = engine
817            .signal(
818                &WorkflowId::new_v4(),
819                &RunId::new_v4(),
820                "approve",
821                payload("unknown")?,
822            )
823            .await;
824        assert!(matches!(unknown, Err(EngineError::WorkflowNotFound { .. })));
825        engine.shutdown()?;
826        Ok(())
827    }
828
829    #[tokio::test]
830    async fn query_delegates_to_service_and_returns_payload()
831    -> Result<(), Box<dyn std::error::Error>> {
832        let reply = payload("reply")?;
833        let query = Arc::new(QueryCapture {
834            calls: Mutex::new(Vec::new()),
835            reply: reply.clone(),
836        });
837        let engine = engine_with_seams(
838            Arc::new(DeferredSignalRouter),
839            query.clone(),
840            Arc::new(DeferredEventPublisher),
841        )?;
842        let handle = insert_active_handle(&engine).await?;
843
844        let arguments = payload("arguments")?;
845        let returned = engine
846            .query(
847                handle.workflow_id(),
848                handle.run_id(),
849                "state",
850                arguments.clone(),
851            )
852            .await?;
853
854        assert_eq!(returned, reply);
855        let calls = query
856            .calls
857            .lock()
858            .map_err(|_| EngineError::RegistryPoisoned)?;
859        // The engine resolves the target and forwards the caller's arguments
860        // to the seam verbatim.
861        assert_eq!(
862            calls.as_slice(),
863            &[(handle.pid(), "state".to_owned(), arguments)]
864        );
865        drop(calls);
866        engine.shutdown()?;
867        Ok(())
868    }
869
870    #[tokio::test]
871    async fn query_terminal_run_is_not_running_and_unknown_is_not_found()
872    -> Result<(), Box<dyn std::error::Error>> {
873        let engine = engine_with_seams(
874            Arc::new(DeferredSignalRouter),
875            Arc::new(DeferredQueryService),
876            Arc::new(DeferredEventPublisher),
877        )?;
878        // Durably terminal run with no registry entry: a completed workflow.
879        let workflow_id = WorkflowId::new_v4();
880        let run_id = aion_core::RunId::new_v4();
881        let mut recorder = crate::durability::Recorder::new(workflow_id.clone(), engine.store());
882        recorder
883            .record_workflow_started(
884                chrono::Utc::now(),
885                crate::durability::WorkflowStartRecord {
886                    workflow_type: "checkout".to_owned(),
887                    input: payload("input")?,
888                    run_id: run_id.clone(),
889                    parent_run_id: None,
890                    parent_workflow_id: None,
891                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
892                },
893            )
894            .await?;
895        recorder
896            .record_workflow_completed(chrono::Utc::now(), payload("result")?)
897            .await?;
898
899        let terminal = engine
900            .query(&workflow_id, &run_id, "state", Payload::json_null())
901            .await;
902        assert!(matches!(
903            terminal,
904            Err(EngineError::Query(crate::query::QueryError::NotRunning(id))) if id == workflow_id
905        ));
906
907        let unknown = engine
908            .query(
909                &WorkflowId::new_v4(),
910                &RunId::new_v4(),
911                "state",
912                Payload::json_null(),
913            )
914            .await;
915        assert!(matches!(unknown, Err(EngineError::WorkflowNotFound { .. })));
916        engine.shutdown()?;
917        Ok(())
918    }
919
920    #[tokio::test]
921    async fn subscribe_delegates_to_publisher_stream_with_filter()
922    -> Result<(), Box<dyn std::error::Error>> {
923        let workflow_id = WorkflowId::new_v4();
924        let other_id = WorkflowId::new_v4();
925        let matching = Event::SignalReceived {
926            envelope: envelope(1, &workflow_id),
927            name: "approved".to_owned(),
928            payload: payload("signal")?,
929        };
930        let filtered = Event::WorkflowStarted {
931            envelope: envelope(1, &other_id),
932            workflow_type: "checkout".to_owned(),
933            input: payload("input")?,
934            run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
935            parent_run_id: None,
936            parent_workflow_id: None,
937            package_version: aion_core::PackageVersion::new("a".repeat(64)),
938        };
939        let engine = engine_with_seams(
940            Arc::new(DeferredSignalRouter),
941            Arc::new(DeferredQueryService),
942            Arc::new(FakePublisher {
943                events: vec![matching.clone(), filtered],
944            }),
945        )?;
946
947        let events = engine
948            .subscribe(EventFilter {
949                workflow_id: Some(workflow_id),
950                run: None,
951                family: Some(EventFamily::Signal),
952            })
953            .collect::<Vec<_>>()
954            .await;
955
956        assert_eq!(events, vec![Ok(matching)]);
957        engine.shutdown()?;
958        Ok(())
959    }
960}