Skip to main content

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            1,
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        for attempt in 1..=attempts {
248            budget.spend()?;
249            let result = activity_attempt(
250                &self.worker,
251                name,
252                args.clone(),
253                attempt,
254                &identity,
255                command["queue"].as_str().unwrap_or(&self.worker.task_queue),
256                local,
257            )
258            .await;
259            payload["attempt_number"] = json!(attempt);
260            payload["activity_attempt_id"] = json!(format!("{identity}-attempt-{attempt}"));
261            let Err(error) = result else {
262                payload["result"] = encode_typed_envelope(&result?, DEFAULT_CODEC)?;
263                return append(history, "ActivityCompleted", payload);
264            };
265            let mut failure = ActivityError::from_error(&error, fallback);
266            failure.non_retryable |= excluded_failure(policy, &failure.exception_type);
267            if attempt < attempts && !failure.non_retryable {
268                append(
269                    history,
270                    "ActivityRetryScheduled",
271                    json!({
272                        "sequence":sequence,"attempt_number":attempt,"activity_type":name,
273                        "activity_execution_id":identity,
274                    }),
275                )?;
276                continue;
277            }
278            payload["message"] = json!(failure.message);
279            payload["exception_type"] = json!(failure.exception_type);
280            payload["non_retryable"] = json!(failure.non_retryable);
281            payload["failure_category"] = json!("activity");
282            return append(history, "ActivityFailed", payload);
283        }
284        Err(TestingError::InvalidHistory("activity retry policy has zero attempts".into()).into())
285    }
286}
287
288fn record_memo(history: &mut WorkflowHistory, mut payload: Value) -> Result<()> {
289    let previous = history
290        .events()
291        .iter()
292        .rev()
293        .find(|event| event.event_type == "MemoUpserted");
294    let mut merged = match previous {
295        Some(event) => crate::decode_memo_history_map(&event.payload["merged"], false)?,
296        None => AvroValue::Map(Default::default()),
297    };
298    let AvroValue::Map(values) = &mut merged else {
299        unreachable!("validated memo map");
300    };
301    let AvroValue::Map(entries) = crate::decode_memo_history_map(&payload["entries"], true)? else {
302        unreachable!("validated memo entries");
303    };
304    for (key, value) in entries {
305        if value == AvroValue::Null {
306            values.remove(&key);
307        } else {
308            values.insert(key, value);
309        }
310    }
311    payload["merged"] = encode_typed_envelope(&merged, DEFAULT_CODEC)?;
312    append(history, "MemoUpserted", payload)
313}
314
315fn excluded_failure(policy: &Value, exception_type: &str) -> bool {
316    policy["non_retryable_error_types"]
317        .as_array()
318        .is_some_and(|types| {
319            types
320                .iter()
321                .any(|value| value.as_str() == Some(exception_type))
322        })
323}
324
325fn validate_activity_command(command: &Value) -> Result<()> {
326    if command.get("worker_session").is_some() || command.get("cancellation_policy").is_some() {
327        return Err(
328            TestingError::UnsupportedCommand("activity session/cancellation".into()).into(),
329        );
330    }
331    if [
332        "start_to_close_timeout",
333        "schedule_to_start_timeout",
334        "schedule_to_close_timeout",
335        "heartbeat_timeout",
336    ]
337    .iter()
338    .any(|field| command.get(*field).is_some())
339    {
340        return Err(TestingError::UnsupportedCommand("activity timeout simulation".into()).into());
341    }
342    if command["parallel_group_mode"] == "select"
343        || command["parallel_group_path"]
344            .as_array()
345            .is_some_and(|path| {
346                path.iter()
347                    .any(|entry| entry["parallel_group_mode"] == "select")
348            })
349    {
350        return Err(TestingError::UnsupportedCommand(
351            "select execution (use recorded replay)".into(),
352        )
353        .into());
354    }
355    Ok(())
356}
357
358async fn activity_attempt(
359    worker: &Worker,
360    name: &str,
361    args: AvroValue,
362    attempt: u64,
363    identity: &str,
364    queue: &str,
365    local: bool,
366) -> Result<AvroValue> {
367    let handler = worker
368        .activities
369        .get(name)
370        .ok_or_else(|| Error::ActivityNotRegistered(name.into()))?;
371    let (heartbeats, _close) = local_activity::Heartbeats::captured_attempt();
372    let context = ActivityContext {
373        client: worker.client.clone(),
374        task_id: identity.into(),
375        activity_attempt_id: format!("{identity}-attempt-{attempt}"),
376        lease_owner: "offline".into(),
377        activity_type: name.into(),
378        attempt_number: attempt,
379        task_queue: queue.into(),
380        worker_id: worker.worker_id.clone(),
381        claim_guard: None,
382        local_heartbeats: Some(heartbeats),
383        worker_session: None,
384    };
385    worker
386        .activity_callback(handler, context, normalize_avro_arguments(args), local)
387        .await
388}
389
390fn append(history: &mut WorkflowHistory, kind: &str, payload: Value) -> Result<()> {
391    let event: HistoryEvent = serde_json::from_value(json!({"event_type":kind,"payload":payload}))?;
392    history.task.history_events.push(event);
393    Ok(())
394}