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 — or durably started
375    /// with no live handle to answer from (a workloop's deferred successor
376    /// between iterations, a run whose engine is gone): the run EXISTS and is
377    /// not running, which is a different answer from unknown (#214).
378    /// [`EngineError::WorkflowNotFound`] when no history names the run,
379    /// [`crate::query::QueryError::InvalidArguments`] when `arguments` is not
380    /// a well-formed JSON document, and other typed errors from the configured
381    /// query seam.
382    pub async fn query(
383        &self,
384        id: &WorkflowId,
385        run: &RunId,
386        name: impl Into<String>,
387        arguments: Payload,
388    ) -> Result<Payload, EngineError> {
389        let handle = if let Some(handle) = self.registry().get(id, run)? {
390            handle
391        } else {
392            // Mirror Engine::signal's registry-miss handling: a completed
393            // workflow is NotRunning per the query contract, never NotFound.
394            let history = self.store().read_history(id).await?;
395            if run_has_terminal_history(&history, run) {
396                return Err(EngineError::Query(crate::query::QueryError::NotRunning(
397                    id.clone(),
398                )));
399            }
400            match self.handle_after_birth_window(id, run, &history).await? {
401                Some(handle) => handle,
402                // No handle after the birth budget. Two different truths hide
403                // behind that `None`, and the query contract owes each its own
404                // answer: a run the history never started is UNKNOWN; a run the
405                // history did start, that is not terminal and still has no
406                // handle, EXISTS and is not running — a workloop's successor
407                // deferred until its next wake (#214), or a run whose engine is
408                // gone. Reporting the second as not-found told the operator a
409                // workloop they could see in the listing did not exist.
410                None if run_segment(&history, run).is_empty() => {
411                    return Err(workflow_not_found(id, run));
412                }
413                None => {
414                    return Err(EngineError::Query(crate::query::QueryError::NotRunning(
415                        id.clone(),
416                    )));
417                }
418            }
419        };
420        self.delegated()
421            .query_service()
422            .query(&handle, name.into(), arguments)
423            .await
424    }
425
426    /// Resolve a registry miss against the registration birth window.
427    ///
428    /// The start path records `WorkflowStarted` durably *before* it inserts
429    /// the registry handle, so an embedder acting on observed history (or on
430    /// a `start_workflow` racing on another task) can legitimately arrive
431    /// here after the record and before the insert. When the requested run
432    /// is durably started and non-terminal, the registry is re-polled within
433    /// the builder-supplied delivery policy budget; `None` after the budget
434    /// means the run truly has no live handle (its start failed or its
435    /// engine is gone) and the caller fails typed.
436    pub(crate) async fn handle_after_birth_window(
437        &self,
438        id: &WorkflowId,
439        run: &RunId,
440        history: &[Event],
441    ) -> Result<Option<WorkflowHandle>, EngineError> {
442        let started = history
443            .iter()
444            .any(|event| matches!(event, Event::WorkflowStarted { run_id, .. } if run_id == run));
445        if !started {
446            return Ok(None);
447        }
448        wait_for_registered_handle(self.registry(), id, run, self.runtime().signal_delivery()).await
449    }
450
451    /// Subscribe to the live event stream through the AD/AT publisher seam.
452    ///
453    /// A subscriber that falls behind receives one `Err(`[`EventStreamLagged`]`)`
454    /// item with the skipped count and then continues with subsequent events.
455    #[must_use]
456    pub fn subscribe(
457        &self,
458        filter: EventFilter,
459    ) -> BoxStream<'static, Result<Event, EventStreamLagged>> {
460        self.delegated().event_publisher().subscribe(filter)
461    }
462}
463
464pub(crate) fn run_has_terminal_history(history: &[Event], run: &RunId) -> bool {
465    // Reset-aware: a run is terminal only if its current lease ended in a
466    // terminal event. A WorkflowReopened after a terminal reopens the run, so a
467    // reopened run is not treated as terminal (it can receive signals and
468    // complete again).
469    current_lease_terminal(run_segment(history, run)).is_some()
470}
471
472/// Poll the registry for `(id, run)` until the handle appears or the
473/// builder-supplied delivery budget is spent.
474///
475/// The budget is the policy's full persistence — `ready_timeout ×
476/// max_enqueue_attempts`, the same product the runtime's enqueue retry
477/// expresses — polled with the policy's backoff ladder. A single
478/// `ready_timeout` is the typical insert latency, but the start thread can
479/// be preempted past it under host oversubscription, and the cost of giving
480/// up early is a typed not-found for a workflow that is durably started.
481pub(crate) async fn wait_for_registered_handle(
482    registry: &crate::registry::Registry,
483    id: &WorkflowId,
484    run: &RunId,
485    policy: crate::runtime::SignalDeliveryConfig,
486) -> Result<Option<WorkflowHandle>, EngineError> {
487    let budget = policy
488        .ready_timeout
489        .saturating_mul(policy.max_enqueue_attempts.max(1));
490    let deadline = std::time::Instant::now() + budget;
491    let mut backoff = policy.initial_backoff;
492    loop {
493        if let Some(handle) = registry.get(id, run)? {
494            return Ok(Some(handle));
495        }
496        if std::time::Instant::now() >= deadline {
497            return Ok(None);
498        }
499        tokio::time::sleep(backoff).await;
500        let doubled = backoff.saturating_mul(2);
501        backoff = if doubled > policy.max_backoff {
502            policy.max_backoff
503        } else {
504            doubled
505        };
506    }
507}
508
509const fn event_family(event: &Event) -> EventFamily {
510    match event {
511        Event::WorkflowStarted { .. }
512        | Event::WorkflowCompleted { .. }
513        | Event::WorkflowFailed { .. }
514        | Event::WorkflowCancelled { .. }
515        | Event::WorkflowTimedOut { .. }
516        | Event::WorkflowContinuedAsNew { .. }
517        | Event::WorkflowReopened { .. }
518        | Event::WorkflowPaused { .. }
519        | Event::WorkflowResumed { .. }
520        | Event::SearchAttributesUpdated { .. }
521        // A hatch is a workflow-level start record — detached, not a child —
522        // so it rides the Workflow family, never ChildWorkflow.
523        | Event::WorkflowHatched { .. } => EventFamily::Workflow,
524        Event::ActivityScheduled { .. }
525        | Event::ActivityStarted { .. }
526        | Event::ActivityLeased { .. }
527        | Event::ActivityAdoptionOffered { .. }
528        | Event::ActivityCompleted { .. }
529        | Event::ActivityFailed { .. }
530        | Event::ActivityAdvisoryExhausted { .. }
531        | Event::ActivityFallbackRouted { .. }
532        | Event::ActivityCancelled { .. } => EventFamily::Activity,
533        Event::TimerStarted { .. }
534        | Event::TimerFired { .. }
535        | Event::TimerCancelled { .. }
536        | Event::WithTimeoutCompleted { .. } => EventFamily::Timer,
537        Event::SignalReceived { .. } | Event::SignalSent { .. } => EventFamily::Signal,
538        Event::ChildWorkflowStarted { .. }
539        | Event::ChildWorkflowCompleted { .. }
540        | Event::ChildWorkflowFailed { .. }
541        | Event::ChildWorkflowCancelled { .. } => EventFamily::ChildWorkflow,
542        Event::ScheduleCreated { .. }
543        | Event::ScheduleUpdated { .. }
544        | Event::SchedulePaused { .. }
545        | Event::ScheduleResumed { .. }
546        | Event::ScheduleDeleted { .. }
547        | Event::ScheduleTriggered { .. } => EventFamily::Schedule,
548        Event::CadenceFired { .. }
549        | Event::IterationClosed { .. }
550        | Event::LoopRetired { .. }
551        | Event::InvariantUnconfirmed { .. } => EventFamily::Workloop,
552    }
553}
554
555#[cfg(test)]
556mod tests {
557    use std::sync::{Arc, Mutex};
558
559    use aion_core::{EventEnvelope, WorkflowStatus};
560    use aion_package::ContentHash;
561    use aion_store::visibility::VisibilityStore;
562    use aion_store::{EventStore, InMemoryStore};
563    use futures::{StreamExt, stream};
564    use serde_json::json;
565
566    use crate::durability::Recorder;
567    use crate::engine::api::EngineComponents;
568    use crate::registry::{CompletionNotifier, HandleResidency, WorkflowHandleParts};
569    use crate::{
570        Registry, RuntimeConfig, RuntimeHandle, SupervisionTree, WorkflowCatalog, WorkflowHandle,
571    };
572
573    use super::*;
574
575    #[derive(Debug, Default)]
576    struct SignalCapture {
577        calls: Mutex<Vec<(u64, String, Payload)>>,
578    }
579
580    #[async_trait]
581    impl SignalRouter for SignalCapture {
582        async fn route(
583            &self,
584            target: &WorkflowHandle,
585            name: String,
586            payload: Payload,
587        ) -> Result<(), EngineError> {
588            self.calls
589                .lock()
590                .map_err(|_| EngineError::RegistryPoisoned)?
591                .push((target.pid(), name, payload));
592            Ok(())
593        }
594    }
595
596    #[derive(Debug)]
597    struct QueryCapture {
598        calls: Mutex<Vec<(u64, String, Payload)>>,
599        reply: Payload,
600    }
601
602    #[async_trait]
603    impl QueryService for QueryCapture {
604        async fn query(
605            &self,
606            target: &WorkflowHandle,
607            name: String,
608            arguments: Payload,
609        ) -> Result<Payload, EngineError> {
610            self.calls
611                .lock()
612                .map_err(|_| EngineError::RegistryPoisoned)?
613                .push((target.pid(), name, arguments));
614            Ok(self.reply.clone())
615        }
616    }
617
618    #[derive(Debug)]
619    struct FakePublisher {
620        events: Vec<Event>,
621    }
622
623    impl EventPublisher for FakePublisher {
624        fn subscribe(
625            &self,
626            filter: EventFilter,
627        ) -> BoxStream<'static, Result<Event, EventStreamLagged>> {
628            let events = self
629                .events
630                .iter()
631                .filter(|event| filter.matches(event))
632                .cloned()
633                .map(Ok)
634                .collect::<Vec<_>>();
635            stream::iter(events).boxed()
636        }
637    }
638
639    fn payload(label: &str) -> Result<Payload, aion_core::PayloadError> {
640        Payload::from_json(&json!({ "label": label }))
641    }
642
643    fn engine_with_seams(
644        signal_router: Arc<dyn SignalRouter>,
645        query_service: Arc<dyn QueryService>,
646        event_publisher: Arc<dyn EventPublisher>,
647    ) -> Result<Engine, EngineError> {
648        let backing = Arc::new(InMemoryStore::default());
649        let store: Arc<dyn EventStore> = Arc::clone(&backing) as _;
650        let visibility_store: Arc<dyn VisibilityStore> = backing;
651        Ok(Engine::new(EngineComponents {
652            store,
653            visibility_store,
654            runtime: Arc::new(RuntimeHandle::new(RuntimeConfig::new(
655                Some(1),
656                crate::runtime::config::TEST_STOP_DRAIN_TIMEOUT,
657            ))?),
658            catalog: Arc::new(WorkflowCatalog::new()),
659            registry: Arc::new(Registry::default()),
660            supervision: Arc::new(SupervisionTree::new()),
661            delegated: DelegatedSeams::new(signal_router, query_service, event_publisher),
662            signal_handoff: Arc::new(crate::signal::SignalResumeHandoff::new()),
663            search_attribute_schema: Arc::new(aion_core::SearchAttributeSchema::new()),
664            visibility_reconciliation_task: None,
665            deferred_startup_recovery: None,
666            workloop: None,
667        }))
668    }
669
670    /// Record `WorkflowStarted` durably and build the matching handle
671    /// without inserting it into the registry — the exact state of the
672    /// registration birth window.
673    async fn recorded_active_handle(
674        engine: &Engine,
675    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
676        let workflow_id = WorkflowId::new_v4();
677        let run_id = RunId::new_v4();
678        let store = engine.store();
679        let mut recorder = Recorder::new(workflow_id.clone(), Arc::clone(&store));
680        recorder
681            .record_workflow_started(
682                chrono::Utc::now(),
683                crate::durability::WorkflowStartRecord {
684                    workflow_type: "checkout".to_owned(),
685                    input: payload("input")?,
686                    run_id: run_id.clone(),
687                    parent_run_id: None,
688                    parent_workflow_id: None,
689                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
690                },
691            )
692            .await?;
693        Ok(WorkflowHandle::new(WorkflowHandleParts {
694            workflow_id,
695            run_id,
696            pid: engine.runtime().spawn_test_process_with_trap_exit(true)?,
697            workflow_type: "checkout".to_owned(),
698            namespace: String::from("default"),
699            loaded_version: ContentHash::from_bytes([1; 32]),
700            cached_status: WorkflowStatus::Running,
701            residency: HandleResidency::Resident,
702            recorder,
703            completion: CompletionNotifier::new(),
704        }))
705    }
706
707    async fn insert_active_handle(
708        engine: &Engine,
709    ) -> Result<WorkflowHandle, Box<dyn std::error::Error>> {
710        let handle = recorded_active_handle(engine).await?;
711        engine.registry().insert(
712            (handle.workflow_id().clone(), handle.run_id().clone()),
713            handle.clone(),
714        )?;
715        Ok(handle)
716    }
717
718    fn envelope(seq: u64, workflow_id: &WorkflowId) -> EventEnvelope {
719        EventEnvelope {
720            seq,
721            recorded_at: chrono::Utc::now(),
722            workflow_id: workflow_id.clone(),
723        }
724    }
725
726    /// Registration birth window (the 1/300 release-signal flake): the start
727    /// path records `WorkflowStarted` durably before it inserts the registry
728    /// handle, so a caller acting on observed history can signal before the
729    /// insert lands. The signal must wait the handle out within the delivery
730    /// policy budget — before the fix it returned `WorkflowNotFound`
731    /// immediately.
732    #[tokio::test(flavor = "multi_thread")]
733    async fn signal_inside_the_registration_birth_window_waits_for_the_handle()
734    -> Result<(), Box<dyn std::error::Error>> {
735        let signal = Arc::new(SignalCapture::default());
736        let engine = Arc::new(engine_with_seams(
737            signal.clone(),
738            Arc::new(DeferredQueryService),
739            Arc::new(DeferredEventPublisher),
740        )?);
741        let handle = recorded_active_handle(&engine).await?;
742
743        // The insert lands mid-wait, exactly as the start thread's does.
744        let late_engine = Arc::clone(&engine);
745        let late_handle = handle.clone();
746        let inserter = tokio::spawn(async move {
747            tokio::time::sleep(std::time::Duration::from_millis(15)).await;
748            late_engine.registry().insert(
749                (
750                    late_handle.workflow_id().clone(),
751                    late_handle.run_id().clone(),
752                ),
753                late_handle,
754            )
755        });
756
757        engine
758            .signal(
759                handle.workflow_id(),
760                handle.run_id(),
761                "approve",
762                payload("birth")?,
763            )
764            .await?;
765        inserter.await??;
766
767        let calls = signal
768            .calls
769            .lock()
770            .map_err(|_| EngineError::RegistryPoisoned)?;
771        assert_eq!(calls.len(), 1, "the signal must reach the routed handle");
772        drop(calls);
773        engine.shutdown()?;
774        Ok(())
775    }
776
777    /// The birth wait is bounded: a durably started run whose handle never
778    /// appears (its start failed, or its engine is gone) still fails typed
779    /// after the policy budget.
780    #[tokio::test(flavor = "multi_thread")]
781    async fn signal_for_a_started_run_with_no_handle_fails_typed_after_the_budget()
782    -> Result<(), Box<dyn std::error::Error>> {
783        let engine = engine_with_seams(
784            Arc::new(SignalCapture::default()),
785            Arc::new(DeferredQueryService),
786            Arc::new(DeferredEventPublisher),
787        )?;
788        let handle = recorded_active_handle(&engine).await?;
789
790        let outcome = engine
791            .signal(
792                handle.workflow_id(),
793                handle.run_id(),
794                "approve",
795                payload("never")?,
796            )
797            .await;
798
799        assert!(matches!(outcome, Err(EngineError::WorkflowNotFound { .. })));
800        engine.shutdown()?;
801        Ok(())
802    }
803
804    #[tokio::test]
805    async fn signal_delegates_to_router_and_unknown_returns_not_found()
806    -> Result<(), Box<dyn std::error::Error>> {
807        let signal = Arc::new(SignalCapture::default());
808        let engine = engine_with_seams(
809            signal.clone(),
810            Arc::new(DeferredQueryService),
811            Arc::new(DeferredEventPublisher),
812        )?;
813        let handle = insert_active_handle(&engine).await?;
814        let sent_payload = payload("signal")?;
815
816        engine
817            .signal(
818                handle.workflow_id(),
819                handle.run_id(),
820                "approve",
821                sent_payload.clone(),
822            )
823            .await?;
824
825        {
826            let calls = signal
827                .calls
828                .lock()
829                .map_err(|_| EngineError::RegistryPoisoned)?;
830            assert_eq!(
831                calls.as_slice(),
832                &[(handle.pid(), "approve".to_owned(), sent_payload)]
833            );
834        }
835        let unknown = engine
836            .signal(
837                &WorkflowId::new_v4(),
838                &RunId::new_v4(),
839                "approve",
840                payload("unknown")?,
841            )
842            .await;
843        assert!(matches!(unknown, Err(EngineError::WorkflowNotFound { .. })));
844        engine.shutdown()?;
845        Ok(())
846    }
847
848    #[tokio::test]
849    async fn query_delegates_to_service_and_returns_payload()
850    -> Result<(), Box<dyn std::error::Error>> {
851        let reply = payload("reply")?;
852        let query = Arc::new(QueryCapture {
853            calls: Mutex::new(Vec::new()),
854            reply: reply.clone(),
855        });
856        let engine = engine_with_seams(
857            Arc::new(DeferredSignalRouter),
858            query.clone(),
859            Arc::new(DeferredEventPublisher),
860        )?;
861        let handle = insert_active_handle(&engine).await?;
862
863        let arguments = payload("arguments")?;
864        let returned = engine
865            .query(
866                handle.workflow_id(),
867                handle.run_id(),
868                "state",
869                arguments.clone(),
870            )
871            .await?;
872
873        assert_eq!(returned, reply);
874        let calls = query
875            .calls
876            .lock()
877            .map_err(|_| EngineError::RegistryPoisoned)?;
878        // The engine resolves the target and forwards the caller's arguments
879        // to the seam verbatim.
880        assert_eq!(
881            calls.as_slice(),
882            &[(handle.pid(), "state".to_owned(), arguments)]
883        );
884        drop(calls);
885        engine.shutdown()?;
886        Ok(())
887    }
888
889    #[tokio::test]
890    async fn query_terminal_run_is_not_running_and_unknown_is_not_found()
891    -> Result<(), Box<dyn std::error::Error>> {
892        let engine = engine_with_seams(
893            Arc::new(DeferredSignalRouter),
894            Arc::new(DeferredQueryService),
895            Arc::new(DeferredEventPublisher),
896        )?;
897        // Durably terminal run with no registry entry: a completed workflow.
898        let workflow_id = WorkflowId::new_v4();
899        let run_id = aion_core::RunId::new_v4();
900        let mut recorder = crate::durability::Recorder::new(workflow_id.clone(), engine.store());
901        recorder
902            .record_workflow_started(
903                chrono::Utc::now(),
904                crate::durability::WorkflowStartRecord {
905                    workflow_type: "checkout".to_owned(),
906                    input: payload("input")?,
907                    run_id: run_id.clone(),
908                    parent_run_id: None,
909                    parent_workflow_id: None,
910                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
911                },
912            )
913            .await?;
914        recorder
915            .record_workflow_completed(chrono::Utc::now(), payload("result")?)
916            .await?;
917
918        let terminal = engine
919            .query(&workflow_id, &run_id, "state", Payload::json_null())
920            .await;
921        assert!(matches!(
922            terminal,
923            Err(EngineError::Query(crate::query::QueryError::NotRunning(id))) if id == workflow_id
924        ));
925
926        let unknown = engine
927            .query(
928                &WorkflowId::new_v4(),
929                &RunId::new_v4(),
930                "state",
931                Payload::json_null(),
932            )
933            .await;
934        assert!(matches!(unknown, Err(EngineError::WorkflowNotFound { .. })));
935        engine.shutdown()?;
936        Ok(())
937    }
938
939    #[tokio::test]
940    async fn subscribe_delegates_to_publisher_stream_with_filter()
941    -> Result<(), Box<dyn std::error::Error>> {
942        let workflow_id = WorkflowId::new_v4();
943        let other_id = WorkflowId::new_v4();
944        let matching = Event::SignalReceived {
945            envelope: envelope(1, &workflow_id),
946            name: "approved".to_owned(),
947            payload: payload("signal")?,
948        };
949        let filtered = Event::WorkflowStarted {
950            envelope: envelope(1, &other_id),
951            workflow_type: "checkout".to_owned(),
952            input: payload("input")?,
953            run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
954            parent_run_id: None,
955            parent_workflow_id: None,
956            package_version: aion_core::PackageVersion::new("a".repeat(64)),
957        };
958        let engine = engine_with_seams(
959            Arc::new(DeferredSignalRouter),
960            Arc::new(DeferredQueryService),
961            Arc::new(FakePublisher {
962                events: vec![matching.clone(), filtered],
963            }),
964        )?;
965
966        let events = engine
967            .subscribe(EventFilter {
968                workflow_id: Some(workflow_id),
969                run: None,
970                family: Some(EventFamily::Signal),
971            })
972            .collect::<Vec<_>>()
973            .await;
974
975        assert_eq!(events, vec![Ok(matching)]);
976        engine.shutdown()?;
977        Ok(())
978    }
979}