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::ActivityFallbackRouted { .. }
145 | Event::ActivityCancelled { .. }
146 | Event::TimerStarted { .. }
147 | Event::TimerFired { .. }
148 | Event::TimerCancelled { .. }
149 | Event::WithTimeoutCompleted { .. }
150 | Event::SignalReceived { .. }
151 | Event::SignalSent { .. }
152 | Event::ChildWorkflowStarted { .. }
153 | Event::ChildWorkflowCompleted { .. }
154 | Event::ChildWorkflowFailed { .. }
155 | Event::ChildWorkflowCancelled { .. }
156 | Event::ScheduleCreated { .. }
157 | Event::ScheduleUpdated { .. }
158 | Event::SchedulePaused { .. }
159 | Event::ScheduleResumed { .. }
160 | Event::ScheduleDeleted { .. }
161 | Event::ScheduleTriggered { .. } => Some(WorkflowStatus::Running),
162 }
163}
164
165/// Whether a `SearchAttributesUpdated` is the PLACEMENT stamp the engine records
166/// atomically with `WorkflowStarted`, rather than a label change.
167///
168/// The two are told apart by the attributes they carry, which is exact rather
169/// than a heuristic because only two sites in the tree record this event:
170///
171/// * `lifecycle::start` stamps the run's placement, and the server's
172/// `start_search_attributes` ALWAYS writes [`NAMESPACE_ATTRIBUTE`] (the task
173/// queue and display name are conditional, the namespace is not);
174/// * `lifecycle::rename` records the display-name attribute and nothing else.
175///
176/// Both placement attributes are start-time-only by construction — the rename
177/// verb cannot write either, and no verb updates a namespace or task queue after
178/// the fact — so an update carrying one is the start stamp and an update
179/// carrying neither is a label change.
180///
181/// A caller embedding the engine directly could record a start whose attributes
182/// carry no placement at all; that stamp reads as a label change, so it answers
183/// `None` and passes every status selector.
184///
185/// Name that honestly: it is a WIDENING, not a preservation. Before #211 this
186/// function did not exist and EVERY `SearchAttributesUpdated` projected
187/// `Running`, so a placement-less start stamp reached only `status=Running`
188/// subscribers; now it reaches all of them. The widening is confined to
189/// DELIVERY — `event_status` feeds subscription filtering only, and
190/// `WorkflowStatus` itself is projected from history elsewhere and is untouched
191/// — and it costs one extra attribute frame to status-filtered subscribers of
192/// an embedded engine that stamps no placement, which the server's own
193/// `start_search_attributes` never does. Narrowing it back would require the
194/// selector to see the whole atomic batch rather than one event, which this
195/// call site cannot; that is the reason it stands, not that nothing changed.
196fn is_start_time_stamp(
197 attributes: &std::collections::HashMap<String, aion_core::SearchAttributeValue>,
198) -> bool {
199 attributes.contains_key(NAMESPACE_ATTRIBUTE) || attributes.contains_key(TASK_QUEUE_ATTRIBUTE)
200}
201
202#[cfg(test)]
203mod tests {
204 use aion_core::{Event, EventEnvelope, Payload, WorkflowId, WorkflowStatus};
205
206 use super::SubscriptionSelector;
207
208 fn envelope(seq: u64) -> EventEnvelope {
209 EventEnvelope {
210 seq,
211 recorded_at: chrono::Utc::now(),
212 workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
213 }
214 }
215
216 fn payload() -> Result<Payload, aion_core::PayloadError> {
217 Payload::from_json(&serde_json::json!({ "label": "x" }))
218 }
219
220 fn signal(seq: u64) -> Result<Event, aion_core::PayloadError> {
221 Ok(Event::SignalReceived {
222 envelope: envelope(seq),
223 name: "ship".to_owned(),
224 payload: payload()?,
225 })
226 }
227
228 fn started(seq: u64) -> Result<Event, aion_core::PayloadError> {
229 Ok(Event::WorkflowStarted {
230 envelope: envelope(seq),
231 workflow_type: "checkout".to_owned(),
232 input: payload()?,
233 run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
234 parent_run_id: None,
235 parent_workflow_id: None,
236 package_version: aion_core::PackageVersion::new("a".repeat(64)),
237 })
238 }
239
240 fn completed(seq: u64) -> Result<Event, aion_core::PayloadError> {
241 Ok(Event::WorkflowCompleted {
242 envelope: envelope(seq),
243 result: payload()?,
244 })
245 }
246
247 fn failed(seq: u64) -> Event {
248 Event::WorkflowFailed {
249 envelope: envelope(seq),
250 error: aion_core::WorkflowError {
251 message: "boom".to_owned(),
252 details: None,
253 },
254 }
255 }
256
257 fn renamed(seq: u64) -> Event {
258 Event::SearchAttributesUpdated {
259 envelope: envelope(seq),
260 workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
261 attributes: std::collections::HashMap::from([(
262 aion_core::DISPLAY_NAME_ATTRIBUTE.to_owned(),
263 aion_core::SearchAttributeValue::String("Nightly settlement".to_owned()),
264 )]),
265 }
266 }
267
268 /// The start-time attribute stamp: what the engine records ATOMICALLY with
269 /// `WorkflowStarted` for every start that carries a namespace, task queue,
270 /// or display name — which, through the server, is every start.
271 fn start_stamp(seq: u64) -> Event {
272 Event::SearchAttributesUpdated {
273 envelope: envelope(seq),
274 workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
275 attributes: std::collections::HashMap::from([
276 (
277 crate::namespace::NAMESPACE_ATTRIBUTE.to_owned(),
278 aion_core::SearchAttributeValue::String("default".to_owned()),
279 ),
280 (
281 crate::namespace::TASK_QUEUE_ATTRIBUTE.to_owned(),
282 aion_core::SearchAttributeValue::String("settlement".to_owned()),
283 ),
284 (
285 aion_core::DISPLAY_NAME_ATTRIBUTE.to_owned(),
286 aion_core::SearchAttributeValue::String("Nightly settlement".to_owned()),
287 ),
288 ]),
289 }
290 }
291
292 /// #211, the OTHER `SearchAttributesUpdated`: the start-time stamp is NOT a
293 /// rename and must not inherit the rename's status-blindness.
294 ///
295 /// `record_workflow_started_with_attributes` appends this event in the same
296 /// atomic batch as `WorkflowStarted`, so on a server-embedded engine every
297 /// start emits one. Passing it to every status selector would hand a
298 /// `status=Completed` subscriber an attribute frame for every workflow
299 /// STARTING in the namespace — a delivery widening far past the rename this
300 /// exemption was written for, and on a busy namespace the highest-volume
301 /// event class there is.
302 ///
303 /// It genuinely accompanies a start, so it projects `Running` like the
304 /// `WorkflowStarted` it ships with.
305 #[test]
306 fn a_start_time_attribute_stamp_stays_in_the_running_bucket() {
307 let running = SubscriptionSelector {
308 workflow_type: None,
309 status: Some(WorkflowStatus::Running),
310 };
311 assert!(
312 running.matches(&start_stamp(2), Some("checkout")),
313 "the start-time stamp accompanies a start, so it belongs to Running"
314 );
315
316 for status in [
317 WorkflowStatus::Completed,
318 WorkflowStatus::Failed,
319 WorkflowStatus::Cancelled,
320 WorkflowStatus::TimedOut,
321 WorkflowStatus::ContinuedAsNew,
322 WorkflowStatus::Paused,
323 ] {
324 let selector = SubscriptionSelector {
325 workflow_type: None,
326 status: Some(status),
327 };
328 assert!(
329 !selector.matches(&start_stamp(2), Some("checkout")),
330 "a status={status:?} subscriber must not receive an attribute frame for every \
331 workflow STARTING in the namespace"
332 );
333 }
334
335 // CONTROL: the narrowing must not swallow the rename exemption it sits
336 // beside. A label-only update still reaches a terminal subscriber —
337 // without this, deleting the exemption entirely would pass the above.
338 let completed_only = SubscriptionSelector {
339 workflow_type: None,
340 status: Some(WorkflowStatus::Completed),
341 };
342 assert!(
343 completed_only.matches(&renamed(1), Some("checkout")),
344 "a label-only rename must still reach every status subscriber"
345 );
346 }
347
348 /// #211: a rename is a LABEL change, not a lifecycle event, so it reaches
349 /// EVERY status subscriber.
350 ///
351 /// Renames legally record on terminal and paused runs, which broke the old
352 /// "every non-terminal event belongs to a running workflow" premise two
353 /// ways at once: a `Running` subscriber was handed the rename of a
354 /// finished run (wrong bucket), and a `Completed` subscriber never saw
355 /// renames of the very runs it was displaying (a name that goes stale
356 /// until a refetch). Status selectors are about LIFECYCLE, and a label
357 /// change has no lifecycle meaning — so it passes the status arm whatever
358 /// the selector asks for.
359 #[test]
360 fn a_rename_reaches_every_status_subscriber() -> Result<(), Box<dyn std::error::Error>> {
361 for status in [
362 WorkflowStatus::Running,
363 WorkflowStatus::Completed,
364 WorkflowStatus::Failed,
365 WorkflowStatus::Cancelled,
366 WorkflowStatus::TimedOut,
367 WorkflowStatus::ContinuedAsNew,
368 WorkflowStatus::Paused,
369 ] {
370 let selector = SubscriptionSelector {
371 workflow_type: None,
372 status: Some(status),
373 };
374 assert!(
375 selector.matches(&renamed(1), Some("checkout")),
376 "a rename must reach a status={status:?} subscriber"
377 );
378 }
379
380 // CONTROL: bypassing the status arm must not bypass the TYPE arm, and
381 // must not make every other event status-blind either — without these
382 // the assertions above would also pass if `matches` had started
383 // returning `true` unconditionally.
384 let typed = SubscriptionSelector {
385 workflow_type: Some("checkout".to_owned()),
386 status: Some(WorkflowStatus::Completed),
387 };
388 assert!(!typed.matches(&renamed(1), Some("payments")));
389 assert!(!typed.matches(&signal(2)?, Some("checkout")));
390 Ok(())
391 }
392
393 #[test]
394 fn unrestricted_selector_matches_everything() -> Result<(), Box<dyn std::error::Error>> {
395 let selector = SubscriptionSelector::unrestricted();
396
397 assert!(selector.matches(&signal(1)?, None));
398 assert!(selector.matches(&completed(2)?, Some("checkout")));
399 Ok(())
400 }
401
402 #[test]
403 fn type_selector_matches_only_the_recorded_type() -> Result<(), Box<dyn std::error::Error>> {
404 let selector = SubscriptionSelector {
405 workflow_type: Some("checkout".to_owned()),
406 status: None,
407 };
408
409 assert!(selector.matches(&signal(1)?, Some("checkout")));
410 assert!(!selector.matches(&signal(1)?, Some("fulfillment")));
411 assert!(
412 !selector.matches(&signal(1)?, None),
413 "a workflow with no recorded type never matches a type selector"
414 );
415 Ok(())
416 }
417
418 #[test]
419 fn status_selector_matches_per_event_kind() -> Result<(), Box<dyn std::error::Error>> {
420 let running = SubscriptionSelector {
421 workflow_type: None,
422 status: Some(WorkflowStatus::Running),
423 };
424 let completed_only = SubscriptionSelector {
425 workflow_type: None,
426 status: Some(WorkflowStatus::Completed),
427 };
428 let failed_only = SubscriptionSelector {
429 workflow_type: None,
430 status: Some(WorkflowStatus::Failed),
431 };
432
433 // Running matches every non-terminal event, including WorkflowStarted.
434 assert!(running.matches(&started(1)?, Some("checkout")));
435 assert!(running.matches(&signal(2)?, Some("checkout")));
436 assert!(!running.matches(&completed(3)?, Some("checkout")));
437
438 // Each terminal status matches exactly its terminal event kind.
439 assert!(completed_only.matches(&completed(3)?, Some("checkout")));
440 assert!(!completed_only.matches(&failed(3), Some("checkout")));
441 assert!(!completed_only.matches(&signal(2)?, Some("checkout")));
442 assert!(failed_only.matches(&failed(3), Some("checkout")));
443 assert!(!failed_only.matches(&completed(3)?, Some("checkout")));
444 Ok(())
445 }
446
447 fn timed_out(seq: u64) -> Event {
448 Event::WorkflowTimedOut {
449 envelope: envelope(seq),
450 timeout: "workflow".to_owned(),
451 }
452 }
453
454 #[test]
455 fn status_selector_projects_workflow_timed_out_to_timed_out()
456 -> Result<(), Box<dyn std::error::Error>> {
457 // The ops-console stream selector must surface a `WorkflowTimedOut`
458 // terminal as `TimedOut`: a `TimedOut` subscription admits it, a
459 // `Running` subscription rejects it (it is terminal), and a `Failed`
460 // subscription does not confuse it for a failure.
461 let timed_out_only = SubscriptionSelector {
462 workflow_type: None,
463 status: Some(WorkflowStatus::TimedOut),
464 };
465 let running = SubscriptionSelector {
466 workflow_type: None,
467 status: Some(WorkflowStatus::Running),
468 };
469 let failed_only = SubscriptionSelector {
470 workflow_type: None,
471 status: Some(WorkflowStatus::Failed),
472 };
473
474 assert!(timed_out_only.matches(&timed_out(4), Some("checkout")));
475 assert!(!timed_out_only.matches(&completed(3)?, Some("checkout")));
476 assert!(!running.matches(&timed_out(4), Some("checkout")));
477 assert!(!failed_only.matches(&timed_out(4), Some("checkout")));
478 Ok(())
479 }
480
481 #[test]
482 fn combined_selectors_and_together() -> Result<(), Box<dyn std::error::Error>> {
483 let selector = SubscriptionSelector {
484 workflow_type: Some("checkout".to_owned()),
485 status: Some(WorkflowStatus::Completed),
486 };
487
488 assert!(selector.matches(&completed(3)?, Some("checkout")));
489 assert!(
490 !selector.matches(&completed(3)?, Some("fulfillment")),
491 "matching status with mismatched type must not pass"
492 );
493 assert!(
494 !selector.matches(&signal(2)?, Some("checkout")),
495 "matching type with mismatched status must not pass"
496 );
497 Ok(())
498 }
499}