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::ActivityAdoptionOffered { .. }
508        | Event::ActivityCompleted { .. }
509        | Event::ActivityFailed { .. }
510        | Event::ActivityAdvisoryExhausted { .. }
511        | Event::ActivityFallbackRouted { .. }
512        | Event::ActivityCancelled { .. } => EventFamily::Activity,
513        Event::TimerStarted { .. }
514        | Event::TimerFired { .. }
515        | Event::TimerCancelled { .. }
516        | Event::WithTimeoutCompleted { .. } => EventFamily::Timer,
517        Event::SignalReceived { .. } | Event::SignalSent { .. } => EventFamily::Signal,
518        Event::ChildWorkflowStarted { .. }
519        | Event::ChildWorkflowCompleted { .. }
520        | Event::ChildWorkflowFailed { .. }
521        | Event::ChildWorkflowCancelled { .. } => EventFamily::ChildWorkflow,
522        Event::ScheduleCreated { .. }
523        | Event::ScheduleUpdated { .. }
524        | Event::SchedulePaused { .. }
525        | Event::ScheduleResumed { .. }
526        | Event::ScheduleDeleted { .. }
527        | Event::ScheduleTriggered { .. } => EventFamily::Schedule,
528        Event::CadenceFired { .. }
529        | Event::IterationClosed { .. }
530        | Event::LoopRetired { .. }
531        | Event::InvariantUnconfirmed { .. } => EventFamily::Workloop,
532    }
533}
534
535#[cfg(test)]
536mod tests {
537    use std::sync::{Arc, Mutex};
538
539    use aion_core::{EventEnvelope, WorkflowStatus};
540    use aion_package::ContentHash;
541    use aion_store::visibility::VisibilityStore;
542    use aion_store::{EventStore, InMemoryStore};
543    use futures::{StreamExt, stream};
544    use serde_json::json;
545
546    use crate::durability::Recorder;
547    use crate::engine::api::EngineComponents;
548    use crate::registry::{CompletionNotifier, HandleResidency, WorkflowHandleParts};
549    use crate::{
550        Registry, RuntimeConfig, RuntimeHandle, SupervisionTree, WorkflowCatalog, WorkflowHandle,
551    };
552
553    use super::*;
554
555    #[derive(Debug, Default)]
556    struct SignalCapture {
557        calls: Mutex<Vec<(u64, String, Payload)>>,
558    }
559
560    #[async_trait]
561    impl SignalRouter for SignalCapture {
562        async fn route(
563            &self,
564            target: &WorkflowHandle,
565            name: String,
566            payload: Payload,
567        ) -> Result<(), EngineError> {
568            self.calls
569                .lock()
570                .map_err(|_| EngineError::RegistryPoisoned)?
571                .push((target.pid(), name, payload));
572            Ok(())
573        }
574    }
575
576    #[derive(Debug)]
577    struct QueryCapture {
578        calls: Mutex<Vec<(u64, String, Payload)>>,
579        reply: Payload,
580    }
581
582    #[async_trait]
583    impl QueryService for QueryCapture {
584        async fn query(
585            &self,
586            target: &WorkflowHandle,
587            name: String,
588            arguments: Payload,
589        ) -> Result<Payload, EngineError> {
590            self.calls
591                .lock()
592                .map_err(|_| EngineError::RegistryPoisoned)?
593                .push((target.pid(), name, arguments));
594            Ok(self.reply.clone())
595        }
596    }
597
598    #[derive(Debug)]
599    struct FakePublisher {
600        events: Vec<Event>,
601    }
602
603    impl EventPublisher for FakePublisher {
604        fn subscribe(
605            &self,
606            filter: EventFilter,
607        ) -> BoxStream<'static, Result<Event, EventStreamLagged>> {
608            let events = self
609                .events
610                .iter()
611                .filter(|event| filter.matches(event))
612                .cloned()
613                .map(Ok)
614                .collect::<Vec<_>>();
615            stream::iter(events).boxed()
616        }
617    }
618
619    fn payload(label: &str) -> Result<Payload, aion_core::PayloadError> {
620        Payload::from_json(&json!({ "label": label }))
621    }
622
623    fn engine_with_seams(
624        signal_router: Arc<dyn SignalRouter>,
625        query_service: Arc<dyn QueryService>,
626        event_publisher: Arc<dyn EventPublisher>,
627    ) -> Result<Engine, EngineError> {
628        let backing = Arc::new(InMemoryStore::default());
629        let store: Arc<dyn EventStore> = Arc::clone(&backing) as _;
630        let visibility_store: Arc<dyn VisibilityStore> = backing;
631        Ok(Engine::new(EngineComponents {
632            store,
633            visibility_store,
634            runtime: Arc::new(RuntimeHandle::new(RuntimeConfig::new(Some(1)))?),
635            catalog: Arc::new(WorkflowCatalog::new()),
636            registry: Arc::new(Registry::default()),
637            supervision: Arc::new(SupervisionTree::new()),
638            delegated: DelegatedSeams::new(signal_router, query_service, event_publisher),
639            signal_handoff: Arc::new(crate::signal::SignalResumeHandoff::new()),
640            search_attribute_schema: Arc::new(aion_core::SearchAttributeSchema::new()),
641            visibility_reconciliation_task: None,
642            deferred_startup_recovery: None,
643            workloop: None,
644        }))
645    }
646
647    /// Record `WorkflowStarted` durably and build the matching handle
648    /// without inserting it into the registry — the exact state of the
649    /// registration birth window.
650    async fn recorded_active_handle(
651        engine: &Engine,
652    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
653        let workflow_id = WorkflowId::new_v4();
654        let run_id = RunId::new_v4();
655        let store = engine.store();
656        let mut recorder = Recorder::new(workflow_id.clone(), Arc::clone(&store));
657        recorder
658            .record_workflow_started(
659                chrono::Utc::now(),
660                crate::durability::WorkflowStartRecord {
661                    workflow_type: "checkout".to_owned(),
662                    input: payload("input")?,
663                    run_id: run_id.clone(),
664                    parent_run_id: None,
665                    parent_workflow_id: None,
666                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
667                },
668            )
669            .await?;
670        Ok(WorkflowHandle::new(WorkflowHandleParts {
671            workflow_id,
672            run_id,
673            pid: engine.runtime().spawn_test_process_with_trap_exit(true)?,
674            workflow_type: "checkout".to_owned(),
675            namespace: String::from("default"),
676            loaded_version: ContentHash::from_bytes([1; 32]),
677            cached_status: WorkflowStatus::Running,
678            residency: HandleResidency::Resident,
679            recorder,
680            completion: CompletionNotifier::new(),
681        }))
682    }
683
684    async fn insert_active_handle(
685        engine: &Engine,
686    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
687        let handle = recorded_active_handle(engine).await?;
688        engine.registry().insert(
689            (handle.workflow_id().clone(), handle.run_id().clone()),
690            handle.clone(),
691        )?;
692        Ok(handle)
693    }
694
695    fn envelope(seq: u64, workflow_id: &WorkflowId) -> EventEnvelope {
696        EventEnvelope {
697            seq,
698            recorded_at: chrono::Utc::now(),
699            workflow_id: workflow_id.clone(),
700        }
701    }
702
703    /// Registration birth window (the 1/300 release-signal flake): the start
704    /// path records `WorkflowStarted` durably before it inserts the registry
705    /// handle, so a caller acting on observed history can signal before the
706    /// insert lands. The signal must wait the handle out within the delivery
707    /// policy budget — before the fix it returned `WorkflowNotFound`
708    /// immediately.
709    #[tokio::test(flavor = "multi_thread")]
710    async fn signal_inside_the_registration_birth_window_waits_for_the_handle()
711    -> Result<(), Box<dyn std::error::Error>> {
712        let signal = Arc::new(SignalCapture::default());
713        let engine = Arc::new(engine_with_seams(
714            signal.clone(),
715            Arc::new(DeferredQueryService),
716            Arc::new(DeferredEventPublisher),
717        )?);
718        let handle = recorded_active_handle(&engine).await?;
719
720        // The insert lands mid-wait, exactly as the start thread's does.
721        let late_engine = Arc::clone(&engine);
722        let late_handle = handle.clone();
723        let inserter = tokio::spawn(async move {
724            tokio::time::sleep(std::time::Duration::from_millis(15)).await;
725            late_engine.registry().insert(
726                (
727                    late_handle.workflow_id().clone(),
728                    late_handle.run_id().clone(),
729                ),
730                late_handle,
731            )
732        });
733
734        engine
735            .signal(
736                handle.workflow_id(),
737                handle.run_id(),
738                "approve",
739                payload("birth")?,
740            )
741            .await?;
742        inserter.await??;
743
744        let calls = signal
745            .calls
746            .lock()
747            .map_err(|_| EngineError::RegistryPoisoned)?;
748        assert_eq!(calls.len(), 1, "the signal must reach the routed handle");
749        drop(calls);
750        engine.shutdown()?;
751        Ok(())
752    }
753
754    /// The birth wait is bounded: a durably started run whose handle never
755    /// appears (its start failed, or its engine is gone) still fails typed
756    /// after the policy budget.
757    #[tokio::test(flavor = "multi_thread")]
758    async fn signal_for_a_started_run_with_no_handle_fails_typed_after_the_budget()
759    -> Result<(), Box<dyn std::error::Error>> {
760        let engine = engine_with_seams(
761            Arc::new(SignalCapture::default()),
762            Arc::new(DeferredQueryService),
763            Arc::new(DeferredEventPublisher),
764        )?;
765        let handle = recorded_active_handle(&engine).await?;
766
767        let outcome = engine
768            .signal(
769                handle.workflow_id(),
770                handle.run_id(),
771                "approve",
772                payload("never")?,
773            )
774            .await;
775
776        assert!(matches!(outcome, Err(EngineError::WorkflowNotFound { .. })));
777        engine.shutdown()?;
778        Ok(())
779    }
780
781    #[tokio::test]
782    async fn signal_delegates_to_router_and_unknown_returns_not_found()
783    -> Result<(), Box<dyn std::error::Error>> {
784        let signal = Arc::new(SignalCapture::default());
785        let engine = engine_with_seams(
786            signal.clone(),
787            Arc::new(DeferredQueryService),
788            Arc::new(DeferredEventPublisher),
789        )?;
790        let handle = insert_active_handle(&engine).await?;
791        let sent_payload = payload("signal")?;
792
793        engine
794            .signal(
795                handle.workflow_id(),
796                handle.run_id(),
797                "approve",
798                sent_payload.clone(),
799            )
800            .await?;
801
802        {
803            let calls = signal
804                .calls
805                .lock()
806                .map_err(|_| EngineError::RegistryPoisoned)?;
807            assert_eq!(
808                calls.as_slice(),
809                &[(handle.pid(), "approve".to_owned(), sent_payload)]
810            );
811        }
812        let unknown = engine
813            .signal(
814                &WorkflowId::new_v4(),
815                &RunId::new_v4(),
816                "approve",
817                payload("unknown")?,
818            )
819            .await;
820        assert!(matches!(unknown, Err(EngineError::WorkflowNotFound { .. })));
821        engine.shutdown()?;
822        Ok(())
823    }
824
825    #[tokio::test]
826    async fn query_delegates_to_service_and_returns_payload()
827    -> Result<(), Box<dyn std::error::Error>> {
828        let reply = payload("reply")?;
829        let query = Arc::new(QueryCapture {
830            calls: Mutex::new(Vec::new()),
831            reply: reply.clone(),
832        });
833        let engine = engine_with_seams(
834            Arc::new(DeferredSignalRouter),
835            query.clone(),
836            Arc::new(DeferredEventPublisher),
837        )?;
838        let handle = insert_active_handle(&engine).await?;
839
840        let arguments = payload("arguments")?;
841        let returned = engine
842            .query(
843                handle.workflow_id(),
844                handle.run_id(),
845                "state",
846                arguments.clone(),
847            )
848            .await?;
849
850        assert_eq!(returned, reply);
851        let calls = query
852            .calls
853            .lock()
854            .map_err(|_| EngineError::RegistryPoisoned)?;
855        // The engine resolves the target and forwards the caller's arguments
856        // to the seam verbatim.
857        assert_eq!(
858            calls.as_slice(),
859            &[(handle.pid(), "state".to_owned(), arguments)]
860        );
861        drop(calls);
862        engine.shutdown()?;
863        Ok(())
864    }
865
866    #[tokio::test]
867    async fn query_terminal_run_is_not_running_and_unknown_is_not_found()
868    -> Result<(), Box<dyn std::error::Error>> {
869        let engine = engine_with_seams(
870            Arc::new(DeferredSignalRouter),
871            Arc::new(DeferredQueryService),
872            Arc::new(DeferredEventPublisher),
873        )?;
874        // Durably terminal run with no registry entry: a completed workflow.
875        let workflow_id = WorkflowId::new_v4();
876        let run_id = aion_core::RunId::new_v4();
877        let mut recorder = crate::durability::Recorder::new(workflow_id.clone(), engine.store());
878        recorder
879            .record_workflow_started(
880                chrono::Utc::now(),
881                crate::durability::WorkflowStartRecord {
882                    workflow_type: "checkout".to_owned(),
883                    input: payload("input")?,
884                    run_id: run_id.clone(),
885                    parent_run_id: None,
886                    parent_workflow_id: None,
887                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
888                },
889            )
890            .await?;
891        recorder
892            .record_workflow_completed(chrono::Utc::now(), payload("result")?)
893            .await?;
894
895        let terminal = engine
896            .query(&workflow_id, &run_id, "state", Payload::json_null())
897            .await;
898        assert!(matches!(
899            terminal,
900            Err(EngineError::Query(crate::query::QueryError::NotRunning(id))) if id == workflow_id
901        ));
902
903        let unknown = engine
904            .query(
905                &WorkflowId::new_v4(),
906                &RunId::new_v4(),
907                "state",
908                Payload::json_null(),
909            )
910            .await;
911        assert!(matches!(unknown, Err(EngineError::WorkflowNotFound { .. })));
912        engine.shutdown()?;
913        Ok(())
914    }
915
916    #[tokio::test]
917    async fn subscribe_delegates_to_publisher_stream_with_filter()
918    -> Result<(), Box<dyn std::error::Error>> {
919        let workflow_id = WorkflowId::new_v4();
920        let other_id = WorkflowId::new_v4();
921        let matching = Event::SignalReceived {
922            envelope: envelope(1, &workflow_id),
923            name: "approved".to_owned(),
924            payload: payload("signal")?,
925        };
926        let filtered = Event::WorkflowStarted {
927            envelope: envelope(1, &other_id),
928            workflow_type: "checkout".to_owned(),
929            input: payload("input")?,
930            run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
931            parent_run_id: None,
932            parent_workflow_id: None,
933            package_version: aion_core::PackageVersion::new("a".repeat(64)),
934        };
935        let engine = engine_with_seams(
936            Arc::new(DeferredSignalRouter),
937            Arc::new(DeferredQueryService),
938            Arc::new(FakePublisher {
939                events: vec![matching.clone(), filtered],
940            }),
941        )?;
942
943        let events = engine
944            .subscribe(EventFilter {
945                workflow_id: Some(workflow_id),
946                run: None,
947                family: Some(EventFamily::Signal),
948            })
949            .collect::<Vec<_>>()
950            .await;
951
952        assert_eq!(events, vec![Ok(matching)]);
953        engine.shutdown()?;
954        Ok(())
955    }
956}