Skip to content
Durable Workflowrust

durable_workflow/testing/
runner.rs

1use super::{TestingError, WorkflowEnvironment, WorkflowHistory};
2use crate::{
3    decode_task_avro_arguments, encode_typed_envelope, json, local_activity,
4    normalize_avro_arguments, ActivityContext, ActivityError, AvroValue, Error, HistoryEvent,
5    PreparedWorkflowTask, Result, Value, Worker, DEFAULT_CODEC,
6};
7use serde::Serialize;
8use std::task::Poll;
9
10struct Turn {
11    commands: Vec<Value>,
12    result: Option<Result<AvroValue>>,
13}
14
15struct Budget {
16    remaining: usize,
17    limit: usize,
18}
19
20impl Budget {
21    fn spend(&mut self) -> Result<()> {
22        if self.remaining == 0 {
23            return Err(TestingError::StepLimit(self.limit).into());
24        }
25        self.remaining -= 1;
26        Ok(())
27    }
28}
29
30impl WorkflowEnvironment {
31    /// Run one registered activity attempt, including its normal argument/result
32    /// conversion. Heartbeats are captured locally. This method does not retry;
33    /// workflow execution applies the workflow's activity retry policy.
34    pub async fn run_activity<T: Serialize>(&self, name: &str, input: T) -> Result<Value> {
35        self.run_activity_avro_value(name, AvroValue::from_serialize(&input)?)
36            .await?
37            .into_json()
38    }
39
40    pub async fn run_activity_avro_value(&self, name: &str, input: AvroValue) -> Result<AvroValue> {
41        self.worker.validate_registration()?;
42        activity_attempt(
43            &self.worker,
44            name,
45            input,
46            crate::ActivityRetryInfo::new(1, None),
47            "offline-activity",
48            &self.worker.task_queue,
49            false,
50        )
51        .await
52    }
53
54    /// Run a new workflow without a Server, returning its result or original
55    /// typed failure. Each durable turn uses the worker's cold-replay engine.
56    /// Activity retry delays and durable timers are skipped. Registered activity
57    /// handlers run normally and may be replaced by test callbacks.
58    ///
59    /// External services, signals, child workflows, sessions, cancellation and
60    /// activity timeout simulation require a live integration test; unsupported
61    /// commands fail explicitly. Parallel activity handlers run in command order.
62    pub async fn run_workflow<T: Serialize>(&mut self, name: &str, input: T) -> Result<Value> {
63        self.last_history = None;
64        self.run_workflow_avro_value(name, AvroValue::from_serialize(&input)?)
65            .await?
66            .into_json()
67    }
68
69    pub async fn run_workflow_avro_value(
70        &mut self,
71        name: &str,
72        input: AvroValue,
73    ) -> Result<AvroValue> {
74        self.last_history = None;
75        self.worker.validate_registration()?;
76        let input = encode_typed_envelope(&normalize_avro_arguments(input), DEFAULT_CODEC)?;
77        let mut history = WorkflowHistory::from_history(name, (), json!([]))?
78            .task_queue(self.worker.task_queue.clone());
79        history.task.arguments = Some(input.clone());
80        history.task.workflow_id = Some("offline-workflow".into());
81        history.task.run_id = Some("offline-run".into());
82        append(
83            &mut history,
84            "WorkflowStarted",
85            json!({
86                "workflow_type":name, "arguments":input, "task_queue":self.worker.task_queue,
87            }),
88        )?;
89        let mut budget = Budget {
90            remaining: self.max_steps,
91            limit: self.max_steps,
92        };
93        let result = self.drive(&mut history, &mut budget).await;
94        self.last_history = Some(history);
95        result
96    }
97
98    async fn drive(&self, history: &mut WorkflowHistory, budget: &mut Budget) -> Result<AvroValue> {
99        let mut sequence = 1;
100        loop {
101            budget.spend()?;
102            let turn = self.workflow_turn(history)?;
103            if turn.commands.is_empty() && turn.result.is_none() {
104                return Err(TestingError::WorkflowBlocked.into());
105            }
106            for command in turn.commands {
107                if command["type"] == "complete_workflow" {
108                    append(
109                        history,
110                        "WorkflowCompleted",
111                        json!({"output":command["result"]}),
112                    )?;
113                } else {
114                    self.record(history, command, sequence, budget).await?;
115                    sequence += 1;
116                }
117            }
118            if let Some(result) = turn.result {
119                if let Err(error) = &result {
120                    append(
121                        history,
122                        "WorkflowFailed",
123                        json!({"message":error.to_string()}),
124                    )?;
125                }
126                return result;
127            }
128        }
129    }
130
131    fn workflow_turn(&self, history: &WorkflowHistory) -> Result<Turn> {
132        let prepared = self
133            .worker
134            .prepare_workflow_task_execution(history.task.clone(), None)?;
135        let PreparedWorkflowTask::Execution {
136            task,
137            context,
138            mut future,
139        } = prepared
140        else {
141            return Err(TestingError::UnsupportedCommand("workflow update".into()).into());
142        };
143        let outcome = Worker::poll_workflow_future(&context, &mut future)?;
144        // The live supervisor resolves local calls under its lease. Offline
145        // execution records the outcome and cold replays without that transport.
146        context
147            .state
148            .lock()
149            .map_err(|_| Error::WorkflowStatePoisoned)?
150            .local_activity_requests
151            .clear();
152        match outcome {
153            Poll::Ready(Err(error)) => {
154                if crate::workflow_task_integrity_error(&error) {
155                    return Err(error);
156                }
157                if matches!(error, Error::ContinueAsNew(_)) {
158                    return Err(TestingError::UnsupportedCommand("continue_as_new".into()).into());
159                }
160                context.ensure_history_consumed()?;
161                Ok(Turn {
162                    commands: context.take_commands()?,
163                    result: Some(Err(error)),
164                })
165            }
166            other => {
167                let result = match &other {
168                    Poll::Ready(Ok(value)) => Some(Ok(value.clone())),
169                    _ => None,
170                };
171                let decision = self
172                    .worker
173                    .finish_workflow_task_execution(&task, &context, other)?;
174                Ok(Turn {
175                    commands: decision.commands,
176                    result,
177                })
178            }
179        }
180    }
181
182    async fn record(
183        &self,
184        history: &mut WorkflowHistory,
185        command: Value,
186        sequence: u64,
187        budget: &mut Budget,
188    ) -> Result<()> {
189        budget.spend()?;
190        let kind = command["type"].as_str().unwrap_or_default();
191        let mut payload = command.clone();
192        payload
193            .as_object_mut()
194            .expect("worker command object")
195            .remove("type");
196        payload["sequence"] = json!(sequence);
197        match kind {
198            "schedule_activity" | "record_local_activity" => {
199                self.record_activity(history, &command, payload, sequence, budget)
200                    .await
201            }
202            "start_timer" => {
203                payload["timer_id"] = json!(format!("offline-timer-{sequence}"));
204                append(history, "TimerScheduled", payload.clone())?;
205                append(history, "TimerFired", payload)
206            }
207            "record_side_effect" => append(history, "SideEffectRecorded", payload),
208            "record_version_marker" => append(history, "VersionMarkerRecorded", payload),
209            "upsert_memo" => record_memo(history, payload),
210            "upsert_search_attributes" => append(history, "SearchAttributesUpserted", payload),
211            _ => Err(TestingError::UnsupportedCommand(kind.into()).into()),
212        }
213    }
214    async fn record_activity(
215        &self,
216        history: &mut WorkflowHistory,
217        command: &Value,
218        mut payload: Value,
219        sequence: u64,
220        budget: &mut Budget,
221    ) -> Result<()> {
222        validate_activity_command(command)?;
223        let local = command["type"] == "record_local_activity";
224        let fallback = if local {
225            "RustActivityError"
226        } else {
227            "RustActivityFailure"
228        };
229        let name = command["activity_type"].as_str().unwrap_or_default();
230        let identity = format!("offline-activity-{sequence}");
231        payload["activity_execution_id"] = json!(identity);
232        payload["activity"] = json!({
233            "queue":command.get("queue").cloned().unwrap_or_else(||json!(self.worker.task_queue)),
234            "retry_policy":{
235                "snapshot_version":1,"max_attempts":command["retry_policy"]["max_attempts"].as_u64().unwrap_or(1),
236                "backoff_seconds":command["retry_policy"].get("backoff_seconds").cloned().unwrap_or_else(||json!([])),
237                "non_retryable_error_types":command["retry_policy"].get("non_retryable_error_types").cloned().unwrap_or_else(||json!([])),
238                "start_to_close_timeout":null,"schedule_to_start_timeout":null,
239                "schedule_to_close_timeout":null,"heartbeat_timeout":null,
240            },
241            "execution_mode":if local {Some("local")} else {None},
242        });
243        append(history, "ActivityScheduled", payload.clone())?;
244        let args = decode_task_avro_arguments(command.get("arguments"), DEFAULT_CODEC)?;
245        let policy = &command["retry_policy"];
246        let attempts = policy["max_attempts"].as_u64().unwrap_or(1);
247        let mut local_messages = Vec::new();
248        let mut local_attempts = Vec::new();
249        for attempt in 1..=attempts {
250            budget.spend()?;
251            let result = activity_attempt(
252                &self.worker,
253                name,
254                args.clone(),
255                crate::ActivityRetryInfo::new(
256                    attempt,
257                    if local {
258                        None
259                    } else {
260                        Some(payload["activity"]["retry_policy"].clone())
261                    },
262                ),
263                &identity,
264                command["queue"].as_str().unwrap_or(&self.worker.task_queue),
265                local,
266            )
267            .await;
268            payload["attempt_number"] = json!(attempt);
269            payload["activity_attempt_id"] = json!(format!("{identity}-attempt-{attempt}"));
270            let Err(error) = result else {
271                payload["result"] = encode_typed_envelope(&result?, DEFAULT_CODEC)?;
272                return append(history, "ActivityCompleted", payload);
273            };
274            let mut failure = ActivityError::from_error(&error, fallback);
275            failure.non_retryable |= excluded_failure(policy, &failure.exception_type);
276            if local {
277                local_messages.push((
278                    local_attempts.len(),
279                    crate::failure_reporting::LocalText::new(&failure.message),
280                ));
281                local_attempts.push(json!({"message":failure.message}));
282            }
283            if attempt < attempts && !failure.non_retryable {
284                append(
285                    history,
286                    "ActivityRetryScheduled",
287                    json!({
288                        "sequence":sequence,"attempt_number":attempt,"activity_type":name,
289                        "activity_execution_id":identity,
290                    }),
291                )?;
292                continue;
293            }
294            if local {
295                let mut body = json!({"commands":[{"type":"record_local_activity","message":failure.message,"attempts":local_attempts}]});
296                crate::failure_reporting::fit_local(
297                    &mut body,
298                    0,
299                    &local_messages,
300                    crate::failure_reporting::REQUEST_BYTES,
301                )?;
302                payload["message"] = json!(crate::failure_reporting::committed_message(
303                    body["commands"][0]["message"]
304                        .as_str()
305                        .expect("local failure message")
306                ));
307            } else {
308                let mut body = json!({"failure":{"message":failure.message,"type":failure.exception_type,"non_retryable":failure.non_retryable}});
309                let mut report = crate::failure_reporting::Prepared::new(
310                    &mut body,
311                    "/worker/activity-tasks/offline/fail",
312                    crate::failure_reporting::REQUEST_BYTES,
313                )?
314                .expect("activity report");
315                report.encode(&mut body, crate::failure_reporting::REQUEST_BYTES)?;
316                payload["message"] = json!(crate::failure_reporting::committed_message(
317                    body["failure"]["message"]
318                        .as_str()
319                        .expect("activity failure message")
320                ));
321                if let Some(diagnostics) = body["failure"].get("diagnostics") {
322                    payload["diagnostics"] = diagnostics.clone();
323                }
324            }
325            payload["exception_type"] = json!(failure.exception_type);
326            payload["non_retryable"] = json!(failure.non_retryable);
327            payload["failure_category"] = json!("activity");
328            return append(history, "ActivityFailed", payload);
329        }
330        Err(TestingError::InvalidHistory("activity retry policy has zero attempts".into()).into())
331    }
332}
333
334fn record_memo(history: &mut WorkflowHistory, mut payload: Value) -> Result<()> {
335    let previous = history
336        .events()
337        .iter()
338        .rev()
339        .find(|event| event.event_type == "MemoUpserted");
340    let mut merged = match previous {
341        Some(event) => crate::decode_memo_history_map(&event.payload["merged"], false)?,
342        None => AvroValue::Map(Default::default()),
343    };
344    let AvroValue::Map(values) = &mut merged else {
345        unreachable!("validated memo map");
346    };
347    let AvroValue::Map(entries) = crate::decode_memo_history_map(&payload["entries"], true)? else {
348        unreachable!("validated memo entries");
349    };
350    for (key, value) in entries {
351        if value == AvroValue::Null {
352            values.remove(&key);
353        } else {
354            values.insert(key, value);
355        }
356    }
357    payload["merged"] = encode_typed_envelope(&merged, DEFAULT_CODEC)?;
358    append(history, "MemoUpserted", payload)
359}
360
361fn excluded_failure(policy: &Value, exception_type: &str) -> bool {
362    policy["non_retryable_error_types"]
363        .as_array()
364        .is_some_and(|types| {
365            types
366                .iter()
367                .any(|value| value.as_str() == Some(exception_type))
368        })
369}
370
371fn validate_activity_command(command: &Value) -> Result<()> {
372    if command.get("worker_session").is_some() || command.get("cancellation_policy").is_some() {
373        return Err(
374            TestingError::UnsupportedCommand("activity session/cancellation".into()).into(),
375        );
376    }
377    if [
378        "start_to_close_timeout",
379        "schedule_to_start_timeout",
380        "schedule_to_close_timeout",
381        "heartbeat_timeout",
382    ]
383    .iter()
384    .any(|field| command.get(*field).is_some())
385    {
386        return Err(TestingError::UnsupportedCommand("activity timeout simulation".into()).into());
387    }
388    if command["parallel_group_mode"] == "select"
389        || command["parallel_group_path"]
390            .as_array()
391            .is_some_and(|path| {
392                path.iter()
393                    .any(|entry| entry["parallel_group_mode"] == "select")
394            })
395    {
396        return Err(TestingError::UnsupportedCommand(
397            "select execution (use recorded replay)".into(),
398        )
399        .into());
400    }
401    Ok(())
402}
403
404async fn activity_attempt(
405    worker: &Worker,
406    name: &str,
407    args: AvroValue,
408    retry_info: crate::ActivityRetryInfo,
409    identity: &str,
410    queue: &str,
411    local: bool,
412) -> Result<AvroValue> {
413    let handler = worker
414        .activities
415        .get(name)
416        .ok_or_else(|| Error::ActivityNotRegistered(name.into()))?;
417    let (heartbeats, _close) = local_activity::Heartbeats::captured_attempt();
418    let attempt = retry_info.attempt_number();
419    let context = ActivityContext {
420        client: worker.client.clone(),
421        task_id: identity.into(),
422        activity_attempt_id: format!("{identity}-attempt-{attempt}"),
423        lease_owner: "offline".into(),
424        activity_type: name.into(),
425        attempt_number: attempt,
426        retry_info,
427        heartbeat_resume: Default::default(),
428        activity_execution_id: None,
429        workflow_id: None,
430        run_id: None,
431        task_queue: queue.into(),
432        worker_id: worker.worker_id.clone(),
433        claim_guard: None,
434        local_heartbeats: Some(heartbeats),
435        worker_session: None,
436    };
437    worker
438        .activity_callback(handler, context, normalize_avro_arguments(args), local)
439        .await
440}
441
442fn append(history: &mut WorkflowHistory, kind: &str, payload: Value) -> Result<()> {
443    let event: HistoryEvent = serde_json::from_value(json!({"event_type":kind,"payload":payload}))?;
444    history.task.history_events.push(event);
445    Ok(())
446}