Skip to main content

aion_server/stream/
selector.rs

1//! Server-side selector filtering for filtered subscriptions.
2//!
3//! `FilteredSubscription` advertises optional `workflow_type` and `status`
4//! selectors. The engine's `EventFilter` has no type or status dimension, so
5//! the selection runs at the socket seam, after the namespace gate proved
6//! ownership and resolved the workflow's recorded type from the same durable
7//! read.
8//!
9//! Selector semantics (documented in `docs/API.md`):
10//!
11//! - `workflow_type` matches when the event's workflow has that recorded type
12//!   at the time the namespace gate resolved it: the initial durable read
13//!   returns the head-of-history `WorkflowStarted` type at read time, which on
14//!   a continue-as-new chain can briefly run ahead of an older delivered event
15//!   (a one-event-loop forward-skew window) until the stream's own
16//!   `WorkflowStarted` refresh self-heals the cached type. A workflow whose
17//!   history records no started run never matches a type selector.
18//! - `status` matches per event kind: each terminal lifecycle event matches
19//!   exactly its projected status (`WorkflowCompleted` → `Completed`,
20//!   `WorkflowFailed` → `Failed`, `WorkflowCancelled` → `Cancelled`,
21//!   `WorkflowTimedOut` → `TimedOut`, `WorkflowContinuedAsNew` →
22//!   `ContinuedAsNew`); every other LIFECYCLE event — including
23//!   `WorkflowStarted` — matches `Running`. A LABEL-ONLY
24//!   `SearchAttributesUpdated` (a rename) is not a lifecycle event (#211) and
25//!   matches ANY status selector, because a workflow's display name changes in
26//!   every status and both forcing it into `Running` and withholding it from
27//!   the other buckets would be wrong. The `SearchAttributesUpdated` carrying a
28//!   run's PLACEMENT is recorded atomically with `WorkflowStarted` and matches
29//!   `Running` with it, so a terminal-status subscriber is not sent an
30//!   attribute frame for every workflow starting in the namespace.
31//! - When both selectors are present they AND together.
32
33use aion_core::{Event, WorkflowStatus};
34
35use crate::namespace::{NAMESPACE_ATTRIBUTE, TASK_QUEUE_ATTRIBUTE};
36
37/// Validated subscription selectors applied before frame encoding.
38#[derive(Clone, Debug, Default, Eq, PartialEq)]
39pub struct SubscriptionSelector {
40    /// Deliver only events of workflows with this recorded type.
41    pub workflow_type: Option<String>,
42    /// Deliver only events whose kind projects to this status.
43    pub status: Option<WorkflowStatus>,
44}
45
46impl SubscriptionSelector {
47    /// Selector that admits every event (per-workflow and firehose
48    /// subscriptions carry no selectors).
49    #[must_use]
50    pub const fn unrestricted() -> Self {
51        Self {
52            workflow_type: None,
53            status: None,
54        }
55    }
56
57    /// Decide whether an event passes the selector. `workflow_type` is the
58    /// event's workflow's recorded type as resolved by the namespace gate.
59    #[must_use]
60    pub fn matches(&self, event: &Event, workflow_type: Option<&str>) -> bool {
61        if let Some(selected_type) = &self.workflow_type {
62            // No recorded type (no started run) can never satisfy a type
63            // selector — absence is not a wildcard.
64            if workflow_type != Some(selected_type.as_str()) {
65                return false;
66            }
67        }
68        if let Some(selected_status) = self.status {
69            // `None` is an event with NO lifecycle meaning (a rename): it
70            // passes every status selector rather than being forced into one.
71            if event_status(event).is_some_and(|status| status != selected_status) {
72                return false;
73            }
74        }
75        true
76    }
77}
78
79/// The lifecycle status a single event's kind projects, or `None` when the
80/// event carries no lifecycle meaning at all.
81///
82/// Terminal lifecycle events project exactly their terminal status; the rest
83/// belong to a running workflow at the moment they were recorded — with ONE
84/// exception, which is why this returns an `Option` rather than a status.
85///
86/// A LABEL-ONLY `SearchAttributesUpdated` (#211: a rename) has no lifecycle
87/// meaning, and the label belongs to the WORKFLOW rather than to any one run —
88/// it is folded over the whole history, so a completed run's row shows a name as
89/// legitimate as a running one's, and a rename recorded now retitles every run
90/// of that workflow at once. Projecting it as `Running`, as this function once
91/// did, was wrong in both directions: a `Running` subscriber received the rename
92/// of a finished run, and a `Completed` subscriber never received renames of the
93/// runs it was actually displaying, so the name it showed went stale until a
94/// refetch. Status selectors are about LIFECYCLE, so an event with no lifecycle
95/// meaning answers `None` and passes every status selector instead of being
96/// forced into a bucket it does not belong to.
97///
98/// That exemption is scoped to label-only updates, and deliberately no wider.
99/// The engine also records a `SearchAttributesUpdated` in the same ATOMIC batch
100/// as `WorkflowStarted` (`record_workflow_started_with_attributes`), stamping
101/// the run's placement — so on a server-embedded engine every start emits one.
102/// Exempting that one too would hand a `status=Completed` subscriber an
103/// attribute frame for every workflow STARTING in the namespace: a delivery
104/// widening with no rename to justify it, over what is often the highest-volume
105/// event class there is. It accompanies a start, so it projects `Running`
106/// exactly like the `WorkflowStarted` it ships with. See
107/// [`is_start_time_stamp`] for how the two are told apart.
108///
109/// Returning `Option` rather than special-casing the caller is deliberate: it
110/// puts the exception in the type, so a future event kind with no lifecycle
111/// meaning cannot be given a wrong status by default.
112fn event_status(event: &Event) -> Option<WorkflowStatus> {
113    match event {
114        Event::WorkflowCompleted { .. } => Some(WorkflowStatus::Completed),
115        Event::WorkflowFailed { .. } => Some(WorkflowStatus::Failed),
116        Event::WorkflowCancelled { .. } => Some(WorkflowStatus::Cancelled),
117        Event::WorkflowTimedOut { .. } => Some(WorkflowStatus::TimedOut),
118        Event::WorkflowContinuedAsNew { .. } => Some(WorkflowStatus::ContinuedAsNew),
119        // A pause projects Paused at the moment it is recorded (#204).
120        Event::WorkflowPaused { .. } => Some(WorkflowStatus::Paused),
121        // A LABEL change is not a lifecycle transition (#211): no status. The
122        // start-time placement stamp is not a label change — it ships with the
123        // start, so it keeps the start's status.
124        Event::SearchAttributesUpdated { attributes, .. } => {
125            if is_start_time_stamp(attributes) {
126                Some(WorkflowStatus::Running)
127            } else {
128                None
129            }
130        }
131        Event::WorkflowStarted { .. }
132        // A reopen returns the workflow to Running at the moment it is recorded.
133        | Event::WorkflowReopened { .. }
134        // A resume returns the workflow to Running at the moment it is recorded.
135        | Event::WorkflowResumed { .. }
136        | Event::ActivityScheduled { .. }
137        | Event::ActivityStarted { .. }
138        | Event::ActivityAdoptionOffered { .. }
139        | Event::ActivityCompleted { .. }
140        | Event::ActivityFailed { .. }
141        // A side channel exhausted its budget; the workflow it warns about
142        // is still running.
143        | Event::ActivityAdvisoryExhausted { .. }
144        | Event::ActivityCancelled { .. }
145        | Event::TimerStarted { .. }
146        | Event::TimerFired { .. }
147        | Event::TimerCancelled { .. }
148        | Event::WithTimeoutCompleted { .. }
149        | Event::SignalReceived { .. }
150        | Event::SignalSent { .. }
151        | Event::ChildWorkflowStarted { .. }
152        | Event::ChildWorkflowCompleted { .. }
153        | Event::ChildWorkflowFailed { .. }
154        | Event::ChildWorkflowCancelled { .. }
155        | Event::ScheduleCreated { .. }
156        | Event::ScheduleUpdated { .. }
157        | Event::SchedulePaused { .. }
158        | Event::ScheduleResumed { .. }
159        | Event::ScheduleDeleted { .. }
160        | Event::ScheduleTriggered { .. } => Some(WorkflowStatus::Running),
161    }
162}
163
164/// Whether a `SearchAttributesUpdated` is the PLACEMENT stamp the engine records
165/// atomically with `WorkflowStarted`, rather than a label change.
166///
167/// The two are told apart by the attributes they carry, which is exact rather
168/// than a heuristic because only two sites in the tree record this event:
169///
170/// * `lifecycle::start` stamps the run's placement, and the server's
171///   `start_search_attributes` ALWAYS writes [`NAMESPACE_ATTRIBUTE`] (the task
172///   queue and display name are conditional, the namespace is not);
173/// * `lifecycle::rename` records the display-name attribute and nothing else.
174///
175/// Both placement attributes are start-time-only by construction — the rename
176/// verb cannot write either, and no verb updates a namespace or task queue after
177/// the fact — so an update carrying one is the start stamp and an update
178/// carrying neither is a label change.
179///
180/// A caller embedding the engine directly could record a start whose attributes
181/// carry no placement at all; that stamp reads as a label change, so it answers
182/// `None` and passes every status selector.
183///
184/// Name that honestly: it is a WIDENING, not a preservation. Before #211 this
185/// function did not exist and EVERY `SearchAttributesUpdated` projected
186/// `Running`, so a placement-less start stamp reached only `status=Running`
187/// subscribers; now it reaches all of them. The widening is confined to
188/// DELIVERY — `event_status` feeds subscription filtering only, and
189/// `WorkflowStatus` itself is projected from history elsewhere and is untouched
190/// — and it costs one extra attribute frame to status-filtered subscribers of
191/// an embedded engine that stamps no placement, which the server's own
192/// `start_search_attributes` never does. Narrowing it back would require the
193/// selector to see the whole atomic batch rather than one event, which this
194/// call site cannot; that is the reason it stands, not that nothing changed.
195fn is_start_time_stamp(
196    attributes: &std::collections::HashMap<String, aion_core::SearchAttributeValue>,
197) -> bool {
198    attributes.contains_key(NAMESPACE_ATTRIBUTE) || attributes.contains_key(TASK_QUEUE_ATTRIBUTE)
199}
200
201#[cfg(test)]
202mod tests {
203    use aion_core::{Event, EventEnvelope, Payload, WorkflowId, WorkflowStatus};
204
205    use super::SubscriptionSelector;
206
207    fn envelope(seq: u64) -> EventEnvelope {
208        EventEnvelope {
209            seq,
210            recorded_at: chrono::Utc::now(),
211            workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
212        }
213    }
214
215    fn payload() -> Result<Payload, aion_core::PayloadError> {
216        Payload::from_json(&serde_json::json!({ "label": "x" }))
217    }
218
219    fn signal(seq: u64) -> Result<Event, aion_core::PayloadError> {
220        Ok(Event::SignalReceived {
221            envelope: envelope(seq),
222            name: "ship".to_owned(),
223            payload: payload()?,
224        })
225    }
226
227    fn started(seq: u64) -> Result<Event, aion_core::PayloadError> {
228        Ok(Event::WorkflowStarted {
229            envelope: envelope(seq),
230            workflow_type: "checkout".to_owned(),
231            input: payload()?,
232            run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
233            parent_run_id: None,
234            package_version: aion_core::PackageVersion::new("a".repeat(64)),
235        })
236    }
237
238    fn completed(seq: u64) -> Result<Event, aion_core::PayloadError> {
239        Ok(Event::WorkflowCompleted {
240            envelope: envelope(seq),
241            result: payload()?,
242        })
243    }
244
245    fn failed(seq: u64) -> Event {
246        Event::WorkflowFailed {
247            envelope: envelope(seq),
248            error: aion_core::WorkflowError {
249                message: "boom".to_owned(),
250                details: None,
251            },
252        }
253    }
254
255    fn renamed(seq: u64) -> Event {
256        Event::SearchAttributesUpdated {
257            envelope: envelope(seq),
258            workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
259            attributes: std::collections::HashMap::from([(
260                aion_core::DISPLAY_NAME_ATTRIBUTE.to_owned(),
261                aion_core::SearchAttributeValue::String("Nightly settlement".to_owned()),
262            )]),
263        }
264    }
265
266    /// The start-time attribute stamp: what the engine records ATOMICALLY with
267    /// `WorkflowStarted` for every start that carries a namespace, task queue,
268    /// or display name — which, through the server, is every start.
269    fn start_stamp(seq: u64) -> Event {
270        Event::SearchAttributesUpdated {
271            envelope: envelope(seq),
272            workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
273            attributes: std::collections::HashMap::from([
274                (
275                    crate::namespace::NAMESPACE_ATTRIBUTE.to_owned(),
276                    aion_core::SearchAttributeValue::String("default".to_owned()),
277                ),
278                (
279                    crate::namespace::TASK_QUEUE_ATTRIBUTE.to_owned(),
280                    aion_core::SearchAttributeValue::String("settlement".to_owned()),
281                ),
282                (
283                    aion_core::DISPLAY_NAME_ATTRIBUTE.to_owned(),
284                    aion_core::SearchAttributeValue::String("Nightly settlement".to_owned()),
285                ),
286            ]),
287        }
288    }
289
290    /// #211, the OTHER `SearchAttributesUpdated`: the start-time stamp is NOT a
291    /// rename and must not inherit the rename's status-blindness.
292    ///
293    /// `record_workflow_started_with_attributes` appends this event in the same
294    /// atomic batch as `WorkflowStarted`, so on a server-embedded engine every
295    /// start emits one. Passing it to every status selector would hand a
296    /// `status=Completed` subscriber an attribute frame for every workflow
297    /// STARTING in the namespace — a delivery widening far past the rename this
298    /// exemption was written for, and on a busy namespace the highest-volume
299    /// event class there is.
300    ///
301    /// It genuinely accompanies a start, so it projects `Running` like the
302    /// `WorkflowStarted` it ships with.
303    #[test]
304    fn a_start_time_attribute_stamp_stays_in_the_running_bucket() {
305        let running = SubscriptionSelector {
306            workflow_type: None,
307            status: Some(WorkflowStatus::Running),
308        };
309        assert!(
310            running.matches(&start_stamp(2), Some("checkout")),
311            "the start-time stamp accompanies a start, so it belongs to Running"
312        );
313
314        for status in [
315            WorkflowStatus::Completed,
316            WorkflowStatus::Failed,
317            WorkflowStatus::Cancelled,
318            WorkflowStatus::TimedOut,
319            WorkflowStatus::ContinuedAsNew,
320            WorkflowStatus::Paused,
321        ] {
322            let selector = SubscriptionSelector {
323                workflow_type: None,
324                status: Some(status),
325            };
326            assert!(
327                !selector.matches(&start_stamp(2), Some("checkout")),
328                "a status={status:?} subscriber must not receive an attribute frame for every \
329                 workflow STARTING in the namespace"
330            );
331        }
332
333        // CONTROL: the narrowing must not swallow the rename exemption it sits
334        // beside. A label-only update still reaches a terminal subscriber —
335        // without this, deleting the exemption entirely would pass the above.
336        let completed_only = SubscriptionSelector {
337            workflow_type: None,
338            status: Some(WorkflowStatus::Completed),
339        };
340        assert!(
341            completed_only.matches(&renamed(1), Some("checkout")),
342            "a label-only rename must still reach every status subscriber"
343        );
344    }
345
346    /// #211: a rename is a LABEL change, not a lifecycle event, so it reaches
347    /// EVERY status subscriber.
348    ///
349    /// Renames legally record on terminal and paused runs, which broke the old
350    /// "every non-terminal event belongs to a running workflow" premise two
351    /// ways at once: a `Running` subscriber was handed the rename of a
352    /// finished run (wrong bucket), and a `Completed` subscriber never saw
353    /// renames of the very runs it was displaying (a name that goes stale
354    /// until a refetch). Status selectors are about LIFECYCLE, and a label
355    /// change has no lifecycle meaning — so it passes the status arm whatever
356    /// the selector asks for.
357    #[test]
358    fn a_rename_reaches_every_status_subscriber() -> Result<(), Box<dyn std::error::Error>> {
359        for status in [
360            WorkflowStatus::Running,
361            WorkflowStatus::Completed,
362            WorkflowStatus::Failed,
363            WorkflowStatus::Cancelled,
364            WorkflowStatus::TimedOut,
365            WorkflowStatus::ContinuedAsNew,
366            WorkflowStatus::Paused,
367        ] {
368            let selector = SubscriptionSelector {
369                workflow_type: None,
370                status: Some(status),
371            };
372            assert!(
373                selector.matches(&renamed(1), Some("checkout")),
374                "a rename must reach a status={status:?} subscriber"
375            );
376        }
377
378        // CONTROL: bypassing the status arm must not bypass the TYPE arm, and
379        // must not make every other event status-blind either — without these
380        // the assertions above would also pass if `matches` had started
381        // returning `true` unconditionally.
382        let typed = SubscriptionSelector {
383            workflow_type: Some("checkout".to_owned()),
384            status: Some(WorkflowStatus::Completed),
385        };
386        assert!(!typed.matches(&renamed(1), Some("payments")));
387        assert!(!typed.matches(&signal(2)?, Some("checkout")));
388        Ok(())
389    }
390
391    #[test]
392    fn unrestricted_selector_matches_everything() -> Result<(), Box<dyn std::error::Error>> {
393        let selector = SubscriptionSelector::unrestricted();
394
395        assert!(selector.matches(&signal(1)?, None));
396        assert!(selector.matches(&completed(2)?, Some("checkout")));
397        Ok(())
398    }
399
400    #[test]
401    fn type_selector_matches_only_the_recorded_type() -> Result<(), Box<dyn std::error::Error>> {
402        let selector = SubscriptionSelector {
403            workflow_type: Some("checkout".to_owned()),
404            status: None,
405        };
406
407        assert!(selector.matches(&signal(1)?, Some("checkout")));
408        assert!(!selector.matches(&signal(1)?, Some("fulfillment")));
409        assert!(
410            !selector.matches(&signal(1)?, None),
411            "a workflow with no recorded type never matches a type selector"
412        );
413        Ok(())
414    }
415
416    #[test]
417    fn status_selector_matches_per_event_kind() -> Result<(), Box<dyn std::error::Error>> {
418        let running = SubscriptionSelector {
419            workflow_type: None,
420            status: Some(WorkflowStatus::Running),
421        };
422        let completed_only = SubscriptionSelector {
423            workflow_type: None,
424            status: Some(WorkflowStatus::Completed),
425        };
426        let failed_only = SubscriptionSelector {
427            workflow_type: None,
428            status: Some(WorkflowStatus::Failed),
429        };
430
431        // Running matches every non-terminal event, including WorkflowStarted.
432        assert!(running.matches(&started(1)?, Some("checkout")));
433        assert!(running.matches(&signal(2)?, Some("checkout")));
434        assert!(!running.matches(&completed(3)?, Some("checkout")));
435
436        // Each terminal status matches exactly its terminal event kind.
437        assert!(completed_only.matches(&completed(3)?, Some("checkout")));
438        assert!(!completed_only.matches(&failed(3), Some("checkout")));
439        assert!(!completed_only.matches(&signal(2)?, Some("checkout")));
440        assert!(failed_only.matches(&failed(3), Some("checkout")));
441        assert!(!failed_only.matches(&completed(3)?, Some("checkout")));
442        Ok(())
443    }
444
445    fn timed_out(seq: u64) -> Event {
446        Event::WorkflowTimedOut {
447            envelope: envelope(seq),
448            timeout: "workflow".to_owned(),
449        }
450    }
451
452    #[test]
453    fn status_selector_projects_workflow_timed_out_to_timed_out()
454    -> Result<(), Box<dyn std::error::Error>> {
455        // The ops-console stream selector must surface a `WorkflowTimedOut`
456        // terminal as `TimedOut`: a `TimedOut` subscription admits it, a
457        // `Running` subscription rejects it (it is terminal), and a `Failed`
458        // subscription does not confuse it for a failure.
459        let timed_out_only = SubscriptionSelector {
460            workflow_type: None,
461            status: Some(WorkflowStatus::TimedOut),
462        };
463        let running = SubscriptionSelector {
464            workflow_type: None,
465            status: Some(WorkflowStatus::Running),
466        };
467        let failed_only = SubscriptionSelector {
468            workflow_type: None,
469            status: Some(WorkflowStatus::Failed),
470        };
471
472        assert!(timed_out_only.matches(&timed_out(4), Some("checkout")));
473        assert!(!timed_out_only.matches(&completed(3)?, Some("checkout")));
474        assert!(!running.matches(&timed_out(4), Some("checkout")));
475        assert!(!failed_only.matches(&timed_out(4), Some("checkout")));
476        Ok(())
477    }
478
479    #[test]
480    fn combined_selectors_and_together() -> Result<(), Box<dyn std::error::Error>> {
481        let selector = SubscriptionSelector {
482            workflow_type: Some("checkout".to_owned()),
483            status: Some(WorkflowStatus::Completed),
484        };
485
486        assert!(selector.matches(&completed(3)?, Some("checkout")));
487        assert!(
488            !selector.matches(&completed(3)?, Some("fulfillment")),
489            "matching status with mismatched type must not pass"
490        );
491        assert!(
492            !selector.matches(&signal(2)?, Some("checkout")),
493            "matching type with mismatched status must not pass"
494        );
495        Ok(())
496    }
497}