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 parent_workflow_id: None,
235 package_version: aion_core::PackageVersion::new("a".repeat(64)),
236 })
237 }
238
239 fn completed(seq: u64) -> Result<Event, aion_core::PayloadError> {
240 Ok(Event::WorkflowCompleted {
241 envelope: envelope(seq),
242 result: payload()?,
243 })
244 }
245
246 fn failed(seq: u64) -> Event {
247 Event::WorkflowFailed {
248 envelope: envelope(seq),
249 error: aion_core::WorkflowError {
250 message: "boom".to_owned(),
251 details: None,
252 },
253 }
254 }
255
256 fn renamed(seq: u64) -> Event {
257 Event::SearchAttributesUpdated {
258 envelope: envelope(seq),
259 workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
260 attributes: std::collections::HashMap::from([(
261 aion_core::DISPLAY_NAME_ATTRIBUTE.to_owned(),
262 aion_core::SearchAttributeValue::String("Nightly settlement".to_owned()),
263 )]),
264 }
265 }
266
267 /// The start-time attribute stamp: what the engine records ATOMICALLY with
268 /// `WorkflowStarted` for every start that carries a namespace, task queue,
269 /// or display name — which, through the server, is every start.
270 fn start_stamp(seq: u64) -> Event {
271 Event::SearchAttributesUpdated {
272 envelope: envelope(seq),
273 workflow_id: WorkflowId::new(uuid::Uuid::from_u128(1)),
274 attributes: std::collections::HashMap::from([
275 (
276 crate::namespace::NAMESPACE_ATTRIBUTE.to_owned(),
277 aion_core::SearchAttributeValue::String("default".to_owned()),
278 ),
279 (
280 crate::namespace::TASK_QUEUE_ATTRIBUTE.to_owned(),
281 aion_core::SearchAttributeValue::String("settlement".to_owned()),
282 ),
283 (
284 aion_core::DISPLAY_NAME_ATTRIBUTE.to_owned(),
285 aion_core::SearchAttributeValue::String("Nightly settlement".to_owned()),
286 ),
287 ]),
288 }
289 }
290
291 /// #211, the OTHER `SearchAttributesUpdated`: the start-time stamp is NOT a
292 /// rename and must not inherit the rename's status-blindness.
293 ///
294 /// `record_workflow_started_with_attributes` appends this event in the same
295 /// atomic batch as `WorkflowStarted`, so on a server-embedded engine every
296 /// start emits one. Passing it to every status selector would hand a
297 /// `status=Completed` subscriber an attribute frame for every workflow
298 /// STARTING in the namespace — a delivery widening far past the rename this
299 /// exemption was written for, and on a busy namespace the highest-volume
300 /// event class there is.
301 ///
302 /// It genuinely accompanies a start, so it projects `Running` like the
303 /// `WorkflowStarted` it ships with.
304 #[test]
305 fn a_start_time_attribute_stamp_stays_in_the_running_bucket() {
306 let running = SubscriptionSelector {
307 workflow_type: None,
308 status: Some(WorkflowStatus::Running),
309 };
310 assert!(
311 running.matches(&start_stamp(2), Some("checkout")),
312 "the start-time stamp accompanies a start, so it belongs to Running"
313 );
314
315 for status in [
316 WorkflowStatus::Completed,
317 WorkflowStatus::Failed,
318 WorkflowStatus::Cancelled,
319 WorkflowStatus::TimedOut,
320 WorkflowStatus::ContinuedAsNew,
321 WorkflowStatus::Paused,
322 ] {
323 let selector = SubscriptionSelector {
324 workflow_type: None,
325 status: Some(status),
326 };
327 assert!(
328 !selector.matches(&start_stamp(2), Some("checkout")),
329 "a status={status:?} subscriber must not receive an attribute frame for every \
330 workflow STARTING in the namespace"
331 );
332 }
333
334 // CONTROL: the narrowing must not swallow the rename exemption it sits
335 // beside. A label-only update still reaches a terminal subscriber —
336 // without this, deleting the exemption entirely would pass the above.
337 let completed_only = SubscriptionSelector {
338 workflow_type: None,
339 status: Some(WorkflowStatus::Completed),
340 };
341 assert!(
342 completed_only.matches(&renamed(1), Some("checkout")),
343 "a label-only rename must still reach every status subscriber"
344 );
345 }
346
347 /// #211: a rename is a LABEL change, not a lifecycle event, so it reaches
348 /// EVERY status subscriber.
349 ///
350 /// Renames legally record on terminal and paused runs, which broke the old
351 /// "every non-terminal event belongs to a running workflow" premise two
352 /// ways at once: a `Running` subscriber was handed the rename of a
353 /// finished run (wrong bucket), and a `Completed` subscriber never saw
354 /// renames of the very runs it was displaying (a name that goes stale
355 /// until a refetch). Status selectors are about LIFECYCLE, and a label
356 /// change has no lifecycle meaning — so it passes the status arm whatever
357 /// the selector asks for.
358 #[test]
359 fn a_rename_reaches_every_status_subscriber() -> Result<(), Box<dyn std::error::Error>> {
360 for status in [
361 WorkflowStatus::Running,
362 WorkflowStatus::Completed,
363 WorkflowStatus::Failed,
364 WorkflowStatus::Cancelled,
365 WorkflowStatus::TimedOut,
366 WorkflowStatus::ContinuedAsNew,
367 WorkflowStatus::Paused,
368 ] {
369 let selector = SubscriptionSelector {
370 workflow_type: None,
371 status: Some(status),
372 };
373 assert!(
374 selector.matches(&renamed(1), Some("checkout")),
375 "a rename must reach a status={status:?} subscriber"
376 );
377 }
378
379 // CONTROL: bypassing the status arm must not bypass the TYPE arm, and
380 // must not make every other event status-blind either — without these
381 // the assertions above would also pass if `matches` had started
382 // returning `true` unconditionally.
383 let typed = SubscriptionSelector {
384 workflow_type: Some("checkout".to_owned()),
385 status: Some(WorkflowStatus::Completed),
386 };
387 assert!(!typed.matches(&renamed(1), Some("payments")));
388 assert!(!typed.matches(&signal(2)?, Some("checkout")));
389 Ok(())
390 }
391
392 #[test]
393 fn unrestricted_selector_matches_everything() -> Result<(), Box<dyn std::error::Error>> {
394 let selector = SubscriptionSelector::unrestricted();
395
396 assert!(selector.matches(&signal(1)?, None));
397 assert!(selector.matches(&completed(2)?, Some("checkout")));
398 Ok(())
399 }
400
401 #[test]
402 fn type_selector_matches_only_the_recorded_type() -> Result<(), Box<dyn std::error::Error>> {
403 let selector = SubscriptionSelector {
404 workflow_type: Some("checkout".to_owned()),
405 status: None,
406 };
407
408 assert!(selector.matches(&signal(1)?, Some("checkout")));
409 assert!(!selector.matches(&signal(1)?, Some("fulfillment")));
410 assert!(
411 !selector.matches(&signal(1)?, None),
412 "a workflow with no recorded type never matches a type selector"
413 );
414 Ok(())
415 }
416
417 #[test]
418 fn status_selector_matches_per_event_kind() -> Result<(), Box<dyn std::error::Error>> {
419 let running = SubscriptionSelector {
420 workflow_type: None,
421 status: Some(WorkflowStatus::Running),
422 };
423 let completed_only = SubscriptionSelector {
424 workflow_type: None,
425 status: Some(WorkflowStatus::Completed),
426 };
427 let failed_only = SubscriptionSelector {
428 workflow_type: None,
429 status: Some(WorkflowStatus::Failed),
430 };
431
432 // Running matches every non-terminal event, including WorkflowStarted.
433 assert!(running.matches(&started(1)?, Some("checkout")));
434 assert!(running.matches(&signal(2)?, Some("checkout")));
435 assert!(!running.matches(&completed(3)?, Some("checkout")));
436
437 // Each terminal status matches exactly its terminal event kind.
438 assert!(completed_only.matches(&completed(3)?, Some("checkout")));
439 assert!(!completed_only.matches(&failed(3), Some("checkout")));
440 assert!(!completed_only.matches(&signal(2)?, Some("checkout")));
441 assert!(failed_only.matches(&failed(3), Some("checkout")));
442 assert!(!failed_only.matches(&completed(3)?, Some("checkout")));
443 Ok(())
444 }
445
446 fn timed_out(seq: u64) -> Event {
447 Event::WorkflowTimedOut {
448 envelope: envelope(seq),
449 timeout: "workflow".to_owned(),
450 }
451 }
452
453 #[test]
454 fn status_selector_projects_workflow_timed_out_to_timed_out()
455 -> Result<(), Box<dyn std::error::Error>> {
456 // The ops-console stream selector must surface a `WorkflowTimedOut`
457 // terminal as `TimedOut`: a `TimedOut` subscription admits it, a
458 // `Running` subscription rejects it (it is terminal), and a `Failed`
459 // subscription does not confuse it for a failure.
460 let timed_out_only = SubscriptionSelector {
461 workflow_type: None,
462 status: Some(WorkflowStatus::TimedOut),
463 };
464 let running = SubscriptionSelector {
465 workflow_type: None,
466 status: Some(WorkflowStatus::Running),
467 };
468 let failed_only = SubscriptionSelector {
469 workflow_type: None,
470 status: Some(WorkflowStatus::Failed),
471 };
472
473 assert!(timed_out_only.matches(&timed_out(4), Some("checkout")));
474 assert!(!timed_out_only.matches(&completed(3)?, Some("checkout")));
475 assert!(!running.matches(&timed_out(4), Some("checkout")));
476 assert!(!failed_only.matches(&timed_out(4), Some("checkout")));
477 Ok(())
478 }
479
480 #[test]
481 fn combined_selectors_and_together() -> Result<(), Box<dyn std::error::Error>> {
482 let selector = SubscriptionSelector {
483 workflow_type: Some("checkout".to_owned()),
484 status: Some(WorkflowStatus::Completed),
485 };
486
487 assert!(selector.matches(&completed(3)?, Some("checkout")));
488 assert!(
489 !selector.matches(&completed(3)?, Some("fulfillment")),
490 "matching status with mismatched type must not pass"
491 );
492 assert!(
493 !selector.matches(&signal(2)?, Some("checkout")),
494 "matching type with mismatched status must not pass"
495 );
496 Ok(())
497 }
498}