Skip to main content

durable_workflow/
parallel_policy.rs

1use super::{invalid_recorded_history, recorded_parallel_group_entry, Error, HistoryEvent, Result};
2use serde::{Deserialize, Serialize};
3use serde_json::{json, Value};
4use std::collections::HashMap;
5
6pub(super) const CAPABILITY: &str = "parallel_group_policies";
7pub(super) const FIELD: &str = "parallel_group_policy";
8const CAUSE: &str = "parallel_group_cancellation";
9
10/// Failure behavior for an explicitly qualified durable parallel group.
11#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
12#[serde(rename_all = "snake_case")]
13pub enum ParallelFailurePolicy {
14    /// Raise the first failure in recorded event order.
15    Propagate,
16    /// Raise the first recorded failure after Server cancels eligible siblings.
17    CancelRemaining,
18    /// Return each member's durable result or failure after all members settle.
19    Settle,
20}
21
22impl ParallelFailurePolicy {
23    const ALL: [Self; 3] = [Self::Propagate, Self::CancelRemaining, Self::Settle];
24
25    pub(super) fn as_str(self) -> &'static str {
26        match self {
27            Self::Propagate => "propagate",
28            Self::CancelRemaining => "cancel_remaining",
29            Self::Settle => "settle",
30        }
31    }
32
33    fn bit(self) -> u8 {
34        match self {
35            Self::Propagate => 1,
36            Self::CancelRemaining => 2,
37            Self::Settle => 4,
38        }
39    }
40
41    pub(super) fn parse(value: &Value) -> Option<Self> {
42        let name = value.as_str()?;
43        Self::ALL.into_iter().find(|policy| policy.as_str() == name)
44    }
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub(super) struct Policies(pub(super) u8);
49
50impl Policies {
51    pub(super) fn requested(values: impl IntoIterator<Item = ParallelFailurePolicy>) -> Self {
52        Self(
53            values
54                .into_iter()
55                .fold(0, |bits, policy| bits | policy.bit()),
56        )
57    }
58
59    pub(super) fn contains(self, policy: ParallelFailurePolicy) -> bool {
60        self.0 & policy.bit() != 0
61    }
62
63    pub(super) fn is_empty(self) -> bool {
64        self.0 == 0
65    }
66
67    pub(super) fn intersect(self, other: Self) -> Self {
68        Self(self.0 & other.0)
69    }
70
71    pub(super) fn descriptor(self) -> Value {
72        json!({
73            "supported": true, "version": 1,
74            "policies": ParallelFailurePolicy::ALL.into_iter()
75                .filter(|policy| self.contains(*policy)).map(ParallelFailurePolicy::as_str)
76                .collect::<Vec<_>>(),
77        })
78    }
79
80    pub(super) fn read_descriptor(value: &Value) -> Result<Self> {
81        let invalid =
82            || Error::WorkerLoop("invalid parallel_group_policies version 1 descriptor".into());
83        if !value.as_object().is_some_and(|fields| fields.len() == 3)
84            || value["supported"] != true
85            || value["version"].as_u64() != Some(1)
86        {
87            return Err(invalid());
88        }
89        let names = value["policies"]
90            .as_array()
91            .filter(|names| !names.is_empty())
92            .ok_or_else(invalid)?;
93        let mut policies = Self::default();
94        for name in names {
95            let policy = ParallelFailurePolicy::parse(name).ok_or_else(invalid)?;
96            if policies.contains(policy) {
97                return Err(invalid());
98            }
99            policies.0 |= policy.bit();
100        }
101        Ok(policies)
102    }
103}
104
105#[derive(Clone, Copy, Debug)]
106pub(super) struct FailureOrder {
107    pub(super) ordinal: u64,
108    pub(super) sibling_cancellation: bool,
109}
110
111#[derive(Debug, Default)]
112pub(super) struct Recorded {
113    groups: HashMap<String, Option<ParallelFailurePolicy>>,
114    failures: HashMap<u64, FailureOrder>,
115    completions: HashMap<u64, u64>,
116}
117
118impl Recorded {
119    pub(super) fn read(history: &[HistoryEvent]) -> Result<Self> {
120        let mut recorded = Self::default();
121        let mut initiating = HashMap::new();
122        for event in history {
123            let payload = &event.payload;
124            let path = payload.get("parallel_group_path").and_then(Value::as_array);
125            let explicit = payload.get(FIELD).is_some()
126                || path.is_some_and(|frames| frames.iter().any(|frame| frame.get(FIELD).is_some()));
127            let cause = payload.get(CAUSE);
128            if !explicit && cause.is_none() {
129                for frame in path
130                    .map(Vec::as_slice)
131                    .unwrap_or(std::slice::from_ref(payload))
132                {
133                    if let Some(group) = frame["parallel_group_id"].as_str() {
134                        recorded.insert(
135                            group,
136                            None,
137                            super::durable_event_sequence(event).unwrap_or(0),
138                        )?;
139                    }
140                }
141                continue;
142            }
143
144            let slot = payload["parallel_group_base_sequence"]
145                .as_u64()
146                .zip(payload["parallel_group_index"].as_u64())
147                .and_then(|(base, index)| base.checked_add(index))
148                .ok_or_else(|| malformed(0))?;
149            let ordinal = event
150                .raw
151                .get("sequence")
152                .and_then(Value::as_u64)
153                .filter(|ordinal| *ordinal > 0)
154                .ok_or_else(|| malformed(slot))?;
155            let frames = path
156                .filter(|frames| !frames.is_empty())
157                .ok_or_else(|| malformed(slot))?;
158            let policy =
159                ParallelFailurePolicy::parse(&payload[FIELD]).ok_or_else(|| malformed(slot))?;
160            let root = recorded_parallel_group_entry(&frames[0], slot)?;
161            let inner = recorded_parallel_group_entry(frames.last().expect("nonempty path"), slot)?;
162            if recorded_parallel_group_entry(payload, slot)? != inner {
163                return Err(malformed(slot));
164            }
165            for frame in frames {
166                let metadata = recorded_parallel_group_entry(frame, slot)?;
167                if metadata.parallel_group_mode.is_some()
168                    || ParallelFailurePolicy::parse(&frame[FIELD]) != Some(policy)
169                {
170                    return Err(malformed(slot));
171                }
172                recorded.insert(&metadata.parallel_group_id, Some(policy), slot)?;
173            }
174
175            if let Some(cause) = cause {
176                let failure = cause["failure_event_sequence"]
177                    .as_u64()
178                    .zip(cause["failed_member_index"].as_u64());
179                if policy != ParallelFailurePolicy::CancelRemaining
180                    || !matches!(
181                        event.event_type.as_str(),
182                        "ActivityCancelled"
183                            | "TimerCancelled"
184                            | "ConditionWaitCancelled"
185                            | "SignalWaitCancelled"
186                            | "ChildCancellationRequested"
187                    )
188                    || !cause.as_object().is_some_and(|fields| fields.len() == 4)
189                    || cause["schema"] != "durable-workflow.parallel-group-cancellation/v1"
190                    || cause["policy"] != policy.as_str()
191                    || !failure.is_some_and(|(source, index)| {
192                        source < ordinal && index != root.parallel_group_index as u64
193                    })
194                    || initiating.get(&root.parallel_group_id).copied() != failure
195                {
196                    return Err(invalid_recorded_history(
197                        "parallel_group_cancellation_history_invalid",
198                        slot,
199                        "sibling cancellation linked to the first member failure",
200                        "invalid cause",
201                        "recorded parallel sibling cancellation lacks its initiating failure",
202                    ));
203                }
204            }
205            let initiates = matches!(
206                event.event_type.as_str(),
207                "ActivityFailed"
208                    | "ActivityTimedOut"
209                    | "ChildRunFailed"
210                    | "ChildRunCancelled"
211                    | "ChildRunTerminated"
212            );
213            if initiates && policy == ParallelFailurePolicy::CancelRemaining {
214                initiating
215                    .entry(root.parallel_group_id)
216                    .or_insert((ordinal, root.parallel_group_index as u64));
217            }
218            if matches!(
219                event.event_type.as_str(),
220                "ActivityCompleted"
221                    | "ChildRunCompleted"
222                    | "TimerFired"
223                    | "ConditionWaitSatisfied"
224                    | "ConditionWaitTimedOut"
225            ) && payload["timer_kind"].as_str() != Some("condition_timeout")
226            {
227                recorded.completions.entry(slot).or_insert(ordinal);
228            }
229            if initiates
230                || matches!(
231                    event.event_type.as_str(),
232                    "ActivityCancelled"
233                        | "TimerCancelled"
234                        | "ConditionWaitCancelled"
235                        | "SignalWaitCancelled"
236                )
237            {
238                recorded.failures.entry(slot).or_insert(FailureOrder {
239                    ordinal,
240                    sibling_cancellation: cause.is_some(),
241                });
242            }
243        }
244        Ok(recorded)
245    }
246
247    fn insert(
248        &mut self,
249        group: &str,
250        policy: Option<ParallelFailurePolicy>,
251        slot: u64,
252    ) -> Result<()> {
253        if self
254            .groups
255            .insert(group.to_owned(), policy)
256            .is_some_and(|prior| prior != policy)
257        {
258            return Err(invalid_recorded_history(
259                "parallel_group_history_conflict",
260                slot,
261                "one failure policy for the group",
262                "inconsistent policy",
263                "parallel-group history changes its recorded failure policy",
264            ));
265        }
266        Ok(())
267    }
268
269    pub(super) fn check_supported(&self, policies: Policies) -> Result<()> {
270        if let Some(policy) = ParallelFailurePolicy::ALL.into_iter().find(|policy| {
271            !policies.contains(*policy) && self.groups.values().any(|value| *value == Some(*policy))
272        }) {
273            return Err(Error::ParallelGroupPolicyUnavailable(policy));
274        }
275        Ok(())
276    }
277
278    pub(super) fn match_group(
279        &self,
280        group: &str,
281        slot: u64,
282        authored: Option<ParallelFailurePolicy>,
283    ) -> Result<()> {
284        if self
285            .groups
286            .get(group)
287            .is_some_and(|recorded| *recorded != authored)
288        {
289            return Err(invalid_recorded_history(
290                "parallel_group_policy_changed",
291                slot,
292                "the original group failure policy",
293                "changed policy",
294                "the authored failure policy differs from the recorded group policy",
295            ));
296        }
297        Ok(())
298    }
299
300    pub(super) fn failure(&self, sequence: u64) -> Option<FailureOrder> {
301        self.failures.get(&sequence).copied()
302    }
303
304    pub(super) fn completed_before(&self, sequence: u64, failure_ordinal: u64) -> bool {
305        self.completions
306            .get(&sequence)
307            .is_some_and(|ordinal| *ordinal < failure_ordinal)
308    }
309}
310
311fn malformed(sequence: u64) -> Error {
312    invalid_recorded_history(
313        "parallel_group_metadata_invalid",
314        sequence,
315        "canonical explicit parallel-group path",
316        "invalid policy metadata",
317        "explicit group policy requires canonical metadata and an event ordinal",
318    )
319}
320
321pub(super) fn completion_refused(error: &Error, worker_id: &str, sent: Policies) -> bool {
322    if sent.is_empty() {
323        return false;
324    }
325    let Error::Http { status, body } = error else {
326        return false;
327    };
328    if *status != reqwest::StatusCode::CONFLICT {
329        return false;
330    }
331    let Ok(body) = serde_json::from_str::<Value>(body) else {
332        return false;
333    };
334    body["reason"] == "parallel_group_policy_not_supported"
335        && body["recorded"] == false
336        && body["worker_id"] == worker_id
337        && body["required_capability"] == CAPABILITY
338        && ParallelFailurePolicy::parse(&body[FIELD]).is_some_and(|policy| sent.contains(policy))
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    #[test]
346    fn explicit_parallel_refusal_must_match_submitted_policy_and_current_lease() {
347        let error = |worker, policy, recorded| Error::Http {
348            status: reqwest::StatusCode::CONFLICT,
349            body: json!({
350                "reason": "parallel_group_policy_not_supported",
351                "worker_id": worker,
352                "required_capability": CAPABILITY,
353                "parallel_group_policy": policy,
354                "recorded": recorded,
355            })
356            .to_string(),
357        };
358        let sent = Policies::requested([ParallelFailurePolicy::Settle]);
359        assert!(completion_refused(
360            &error("worker", "settle", false),
361            "worker",
362            sent
363        ));
364        assert!(!completion_refused(
365            &error("other", "settle", false),
366            "worker",
367            sent
368        ));
369        assert!(!completion_refused(
370            &error("worker", "settle", true),
371            "worker",
372            sent
373        ));
374        assert!(!completion_refused(
375            &error("worker", "cancel_remaining", false),
376            "worker",
377            sent
378        ));
379    }
380}