Skip to main content

durable/
ctx.rs

1use std::pin::Pin;
2
3use durable_db::entity::sea_orm_active_enums::TaskStatus;
4use durable_db::entity::task::{
5    ActiveModel as TaskActiveModel, Column as TaskColumn, Entity as Task,
6};
7use sea_orm::{
8    ActiveModelTrait, ColumnTrait, ConnectionTrait, DatabaseConnection, DatabaseTransaction,
9    DbBackend, EntityTrait, Order, PaginatorTrait, QueryFilter, QueryOrder, QuerySelect, Set,
10    Statement, TransactionTrait,
11};
12use serde::Serialize;
13use serde::de::DeserializeOwned;
14use std::sync::atomic::{AtomicI32, Ordering};
15use std::time::Duration;
16use uuid::Uuid;
17
18use crate::error::DurableError;
19
20// ── Retry constants ───────────────────────────────────────────────────────────
21
22const MAX_CHECKPOINT_RETRIES: u32 = 3;
23const CHECKPOINT_RETRY_BASE_MS: u64 = 100;
24
25/// Retry a fallible DB write with exponential backoff.
26///
27/// Calls `f` once immediately. On failure, retries up to `MAX_CHECKPOINT_RETRIES`
28/// times with exponential backoff (100ms, 200ms, 400ms). Returns the FIRST
29/// error if all retries are exhausted.
30async fn retry_db_write<F, Fut>(mut f: F) -> Result<(), DurableError>
31where
32    F: FnMut() -> Fut,
33    Fut: std::future::Future<Output = Result<(), DurableError>>,
34{
35    match f().await {
36        Ok(()) => Ok(()),
37        Err(first_err) => {
38            for i in 0..MAX_CHECKPOINT_RETRIES {
39                tokio::time::sleep(Duration::from_millis(
40                    CHECKPOINT_RETRY_BASE_MS * 2u64.pow(i),
41                ))
42                .await;
43                if f().await.is_ok() {
44                    tracing::warn!(retry = i + 1, "checkpoint write succeeded on retry");
45                    return Ok(());
46                }
47            }
48            Err(first_err)
49        }
50    }
51}
52
53/// Policy for retrying a step on failure.
54pub struct RetryPolicy {
55    pub max_retries: u32,
56    pub initial_backoff: std::time::Duration,
57    pub backoff_multiplier: f64,
58}
59
60impl RetryPolicy {
61    /// No retries — fails immediately on error.
62    pub fn none() -> Self {
63        Self {
64            max_retries: 0,
65            initial_backoff: std::time::Duration::from_secs(0),
66            backoff_multiplier: 1.0,
67        }
68    }
69
70    /// Exponential backoff: backoff doubles each retry.
71    pub fn exponential(max_retries: u32, initial_backoff: std::time::Duration) -> Self {
72        Self {
73            max_retries,
74            initial_backoff,
75            backoff_multiplier: 2.0,
76        }
77    }
78
79    /// Fixed backoff: same duration between all retries.
80    pub fn fixed(max_retries: u32, backoff: std::time::Duration) -> Self {
81        Self {
82            max_retries,
83            initial_backoff: backoff,
84            backoff_multiplier: 1.0,
85        }
86    }
87}
88
89/// Sort order for task listing.
90pub enum TaskSort {
91    CreatedAt(Order),
92    StartedAt(Order),
93    CompletedAt(Order),
94    Name(Order),
95    Status(Order),
96}
97
98/// Builder for filtering, sorting, and paginating task queries.
99///
100/// ```ignore
101/// let query = TaskQuery::default()
102///     .status(TaskStatus::Running)
103///     .kind("WORKFLOW")
104///     .root_only(true)
105///     .sort(TaskSort::CreatedAt(Order::Desc))
106///     .limit(20);
107/// let tasks = Ctx::list(&db, query).await?;
108/// ```
109pub struct TaskQuery {
110    pub status: Option<TaskStatus>,
111    pub kind: Option<String>,
112    pub parent_id: Option<Uuid>,
113    pub root_only: bool,
114    pub name: Option<String>,
115    pub queue_name: Option<String>,
116    pub sort: TaskSort,
117    pub limit: Option<u64>,
118    pub offset: Option<u64>,
119}
120
121impl Default for TaskQuery {
122    fn default() -> Self {
123        Self {
124            status: None,
125            kind: None,
126            parent_id: None,
127            root_only: false,
128            name: None,
129            queue_name: None,
130            sort: TaskSort::CreatedAt(Order::Desc),
131            limit: None,
132            offset: None,
133        }
134    }
135}
136
137impl TaskQuery {
138    /// Filter by status.
139    pub fn status(mut self, status: TaskStatus) -> Self {
140        self.status = Some(status);
141        self
142    }
143
144    /// Filter by kind (e.g. "WORKFLOW", "STEP", "TRANSACTION").
145    pub fn kind(mut self, kind: &str) -> Self {
146        self.kind = Some(kind.to_string());
147        self
148    }
149
150    /// Filter by parent task ID (direct children only).
151    pub fn parent_id(mut self, parent_id: Uuid) -> Self {
152        self.parent_id = Some(parent_id);
153        self
154    }
155
156    /// Only return root tasks (no parent).
157    pub fn root_only(mut self, root_only: bool) -> Self {
158        self.root_only = root_only;
159        self
160    }
161
162    /// Filter by task name.
163    pub fn name(mut self, name: &str) -> Self {
164        self.name = Some(name.to_string());
165        self
166    }
167
168    /// Filter by queue name.
169    pub fn queue_name(mut self, queue: &str) -> Self {
170        self.queue_name = Some(queue.to_string());
171        self
172    }
173
174    /// Set the sort order.
175    pub fn sort(mut self, sort: TaskSort) -> Self {
176        self.sort = sort;
177        self
178    }
179
180    /// Limit the number of results.
181    pub fn limit(mut self, limit: u64) -> Self {
182        self.limit = Some(limit);
183        self
184    }
185
186    /// Skip the first N results.
187    pub fn offset(mut self, offset: u64) -> Self {
188        self.offset = Some(offset);
189        self
190    }
191}
192
193/// Summary of a task returned by `Ctx::list()`.
194#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
195pub struct TaskSummary {
196    pub id: Uuid,
197    pub parent_id: Option<Uuid>,
198    pub name: String,
199    pub handler: Option<String>,
200    pub status: TaskStatus,
201    pub kind: String,
202    pub input: Option<serde_json::Value>,
203    pub output: Option<serde_json::Value>,
204    pub error: Option<String>,
205    pub queue_name: Option<String>,
206    pub created_at: chrono::DateTime<chrono::FixedOffset>,
207    pub started_at: Option<chrono::DateTime<chrono::FixedOffset>>,
208    pub completed_at: Option<chrono::DateTime<chrono::FixedOffset>>,
209}
210
211impl From<durable_db::entity::task::Model> for TaskSummary {
212    fn from(m: durable_db::entity::task::Model) -> Self {
213        Self {
214            id: m.id,
215            parent_id: m.parent_id,
216            name: m.name,
217            handler: m.handler,
218            status: m.status,
219            kind: m.kind,
220            input: m.input,
221            output: m.output,
222            error: m.error,
223            queue_name: m.queue_name,
224            created_at: m.created_at,
225            started_at: m.started_at,
226            completed_at: m.completed_at,
227        }
228    }
229}
230
231/// Context threaded through every workflow and step.
232///
233/// Users never create or manage task IDs. The SDK handles everything
234/// via `(parent_id, name)` lookups — the unique constraint in the schema
235/// guarantees exactly-once step creation.
236pub struct Ctx {
237    db: DatabaseConnection,
238    task_id: Uuid,
239    sequence: AtomicI32,
240    executor_id: Option<String>,
241}
242
243impl Ctx {
244    // ── Workflow lifecycle (user-facing) ──────────────────────────
245
246    /// Start a new root workflow (or attach to an existing one with the same name).
247    ///
248    /// If a RUNNING root task with the same `name` already exists (e.g. recovered
249    /// after a crash), returns a `Ctx` attached to that task (idempotent start).
250    /// Otherwise creates a fresh task.
251    ///
252    /// If [`init`](crate::init) was called, the task is automatically tagged
253    /// with the executor ID for crash recovery. Otherwise `executor_id` is NULL.
254    ///
255    /// To reactivate a paused workflow, use [`Ctx::resume`] instead.
256    ///
257    /// ```ignore
258    /// let ctx = Ctx::start(&db, "ingest", json!({"crawl": "CC-2026"})).await?;
259    /// ```
260    pub async fn start(
261        db: &DatabaseConnection,
262        name: &str,
263        input: Option<serde_json::Value>,
264    ) -> Result<Self, DurableError> {
265        Self::start_with_handler(db, name, input, None).await
266    }
267
268    /// Like [`start`](Self::start) but records the handler function name for
269    /// crash recovery. The `handler` is stored in the `durable.task` row so
270    /// that [`dispatch_recovered`](crate::dispatch_recovered) can look up the
271    /// registered `#[durable::workflow]` function even when `name` differs.
272    ///
273    /// Typically called from macro-generated `start_<fn>` functions rather
274    /// than directly.
275    pub async fn start_with_handler(
276        db: &DatabaseConnection,
277        name: &str,
278        input: Option<serde_json::Value>,
279        handler: Option<&str>,
280    ) -> Result<Self, DurableError> {
281        // ── Idempotent: reuse existing RUNNING root task with same name ──
282        let existing_sql = format!(
283            "SELECT id FROM durable.task \
284             WHERE name = '{}' AND parent_id IS NULL AND status = 'RUNNING' \
285             LIMIT 1",
286            name
287        );
288        if let Some(row) = db
289            .query_one(Statement::from_string(DbBackend::Postgres, existing_sql))
290            .await?
291        {
292            let existing_id: Uuid = row
293                .try_get_by_index(0)
294                .map_err(|e| DurableError::custom(e.to_string()))?;
295            tracing::info!(
296                workflow = name,
297                id = %existing_id,
298                "idempotent start: attaching to existing RUNNING task"
299            );
300            return Self::from_id(db, existing_id).await;
301        }
302
303        let task_id = Uuid::new_v4();
304        let input_json = match &input {
305            Some(v) => serde_json::to_string(v)?,
306            None => "null".to_string(),
307        };
308
309        let executor_id = crate::executor_id();
310
311        let mut extra_cols = String::new();
312        let mut extra_vals = String::new();
313
314        if let Some(eid) = &executor_id {
315            extra_cols.push_str(", executor_id");
316            extra_vals.push_str(&format!(", '{eid}'"));
317        }
318        if let Some(h) = handler {
319            extra_cols.push_str(", handler");
320            extra_vals.push_str(&format!(", '{h}'"));
321        }
322
323        let txn = db.begin().await?;
324        let sql = format!(
325            "INSERT INTO durable.task (id, parent_id, sequence, name, kind, status, input, started_at{extra_cols}) \
326             VALUES ('{task_id}', NULL, NULL, '{name}', 'WORKFLOW', 'RUNNING', '{input_json}', now(){extra_vals})"
327        );
328        txn.execute(Statement::from_string(DbBackend::Postgres, sql))
329            .await?;
330        txn.commit().await?;
331
332        Ok(Self {
333            db: db.clone(),
334            task_id,
335            sequence: AtomicI32::new(0),
336            executor_id,
337        })
338    }
339
340    /// Attach to an existing workflow by task ID. Used to resume a running or
341    /// recovered workflow without creating a new task row.
342    ///
343    /// ```ignore
344    /// let ctx = Ctx::from_id(&db, task_id).await?;
345    /// ```
346    pub async fn from_id(
347        db: &DatabaseConnection,
348        task_id: Uuid,
349    ) -> Result<Self, DurableError> {
350        // Verify the task exists
351        let model = Task::find_by_id(task_id).one(db).await?;
352        let _model =
353            model.ok_or_else(|| DurableError::custom(format!("task {task_id} not found")))?;
354
355        // Claim the task with the current executor_id (if init() was called)
356        let executor_id = crate::executor_id();
357        if let Some(eid) = &executor_id {
358            db.execute(Statement::from_string(
359                DbBackend::Postgres,
360                format!(
361                    "UPDATE durable.task SET executor_id = '{eid}' WHERE id = '{task_id}'"
362                ),
363            ))
364            .await?;
365        }
366
367        // Start sequence at 0 so that replaying steps from the beginning works
368        // correctly. Steps are looked up by (parent_id, sequence), so the caller
369        // will replay completed steps (getting saved outputs) before executing
370        // any new steps.
371        Ok(Self {
372            db: db.clone(),
373            task_id,
374            sequence: AtomicI32::new(0),
375            executor_id,
376        })
377    }
378
379    /// Run a step. If already completed, returns saved output. Otherwise executes
380    /// the closure, saves the result, and returns it.
381    ///
382    /// This method uses no retries (max_retries=0). For retries, use `step_with_retry`.
383    ///
384    /// ```ignore
385    /// let count: u32 = ctx.step("fetch_count", || async { api.get_count().await }).await?;
386    /// ```
387    pub async fn step<T, F, Fut>(&self, name: &str, f: F) -> Result<T, DurableError>
388    where
389        T: Serialize + DeserializeOwned,
390        F: FnOnce() -> Fut,
391        Fut: std::future::Future<Output = Result<T, DurableError>>,
392    {
393        let seq = self.sequence.fetch_add(1, Ordering::SeqCst);
394
395        // Check if workflow is paused or cancelled before executing
396        check_status(&self.db, self.task_id).await?;
397
398        // Check if parent task's deadline has passed before executing
399        check_deadline(&self.db, self.task_id).await?;
400
401        // TX1: Find or create the step row, set RUNNING, release connection.
402        // The RUNNING status acts as a mutex — recovery won't reclaim it
403        // unless this executor's heartbeat goes stale.
404        let txn = self.db.begin().await?;
405        let (step_id, saved_output) = find_or_create_task(
406            &txn,
407            Some(self.task_id),
408            Some(seq),
409            name,
410            "STEP",
411            None,
412            true,
413            Some(0),
414        )
415        .await?;
416
417        if let Some(output) = saved_output {
418            txn.commit().await?;
419            let val: T = serde_json::from_value(output)?;
420            tracing::debug!(step = name, seq, "replaying saved output");
421            return Ok(val);
422        }
423
424        retry_db_write(|| set_status(&txn, step_id, TaskStatus::Running)).await?;
425        txn.commit().await?;
426        // ── connection returned to pool ──
427
428        // Execute the closure with no DB connection held.
429        let result = f().await;
430
431        // TX2: Checkpoint the result (short transaction).
432        match result {
433            Ok(val) => {
434                let json = serde_json::to_value(&val)?;
435                retry_db_write(|| complete_task(&self.db, step_id, json.clone())).await?;
436                tracing::debug!(step = name, seq, "step completed");
437                Ok(val)
438            }
439            Err(e) => {
440                let err_msg = e.to_string();
441                retry_db_write(|| fail_task(&self.db, step_id, &err_msg)).await?;
442                Err(e)
443            }
444        }
445    }
446
447    /// Run a DB-only step inside a single Postgres transaction.
448    ///
449    /// Both the user's DB work and the checkpoint save happen in the same transaction,
450    /// ensuring atomicity. If the closure returns an error, both the user writes and
451    /// the checkpoint are rolled back.
452    ///
453    /// ```ignore
454    /// let count: u32 = ctx.transaction("upsert_batch", |tx| Box::pin(async move {
455    ///     do_db_work(tx).await
456    /// })).await?;
457    /// ```
458    pub async fn transaction<T, F>(&self, name: &str, f: F) -> Result<T, DurableError>
459    where
460        T: Serialize + DeserializeOwned + Send,
461        F: for<'tx> FnOnce(
462                &'tx DatabaseTransaction,
463            ) -> Pin<
464                Box<dyn std::future::Future<Output = Result<T, DurableError>> + Send + 'tx>,
465            > + Send,
466    {
467        let seq = self.sequence.fetch_add(1, Ordering::SeqCst);
468
469        // Check if workflow is paused or cancelled before executing
470        check_status(&self.db, self.task_id).await?;
471
472        // Find or create the step task record OUTSIDE the transaction.
473        // This is idempotent (UNIQUE constraint) and must exist before we begin.
474        let (step_id, saved_output) = find_or_create_task(
475            &self.db,
476            Some(self.task_id),
477            Some(seq),
478            name,
479            "TRANSACTION",
480            None,
481            false,
482            None,
483        )
484        .await?;
485
486        // If already completed, replay from saved output.
487        if let Some(output) = saved_output {
488            let val: T = serde_json::from_value(output)?;
489            tracing::debug!(step = name, seq, "replaying saved transaction output");
490            return Ok(val);
491        }
492
493        // Begin the transaction — set_status, user work, and complete_task all happen atomically.
494        let tx = self.db.begin().await?;
495
496        set_status(&tx, step_id, TaskStatus::Running).await?;
497
498        match f(&tx).await {
499            Ok(val) => {
500                let json = serde_json::to_value(&val)?;
501                complete_task(&tx, step_id, json).await?;
502                tx.commit().await?;
503                tracing::debug!(step = name, seq, "transaction step committed");
504                Ok(val)
505            }
506            Err(e) => {
507                // Rollback happens automatically when tx is dropped.
508                // Record the failure on the main connection (outside the rolled-back tx).
509                drop(tx);
510                fail_task(&self.db, step_id, &e.to_string()).await?;
511                Err(e)
512            }
513        }
514    }
515
516    /// Start or resume a child workflow. Returns a new `Ctx` scoped to the child.
517    ///
518    /// ```ignore
519    /// let child_ctx = ctx.child("embed_batch", json!({"vectors": 1000})).await?;
520    /// // use child_ctx.step(...) for steps inside the child
521    /// child_ctx.complete(json!({"done": true})).await?;
522    /// ```
523    pub async fn child(
524        &self,
525        name: &str,
526        input: Option<serde_json::Value>,
527    ) -> Result<Self, DurableError> {
528        let seq = self.sequence.fetch_add(1, Ordering::SeqCst);
529
530        // Check if workflow is paused or cancelled before executing
531        check_status(&self.db, self.task_id).await?;
532
533        let txn = self.db.begin().await?;
534        // Child workflows also use plain find-or-create without locking.
535        let (child_id, _saved) = find_or_create_task(
536            &txn,
537            Some(self.task_id),
538            Some(seq),
539            name,
540            "WORKFLOW",
541            input,
542            false,
543            None,
544        )
545        .await?;
546
547        // If child already completed, return a Ctx that will replay
548        // (the caller should check is_completed() or just run steps which will replay)
549        retry_db_write(|| set_status(&txn, child_id, TaskStatus::Running)).await?;
550        txn.commit().await?;
551
552        Ok(Self {
553            db: self.db.clone(),
554            task_id: child_id,
555            sequence: AtomicI32::new(0),
556            executor_id: self.executor_id.clone(),
557        })
558    }
559
560    /// Check if this workflow/child was already completed (for skipping in parent).
561    pub async fn is_completed(&self) -> Result<bool, DurableError> {
562        let status = get_status(&self.db, self.task_id).await?;
563        Ok(status == Some(TaskStatus::Completed))
564    }
565
566    /// Get the saved output if this task is completed.
567    pub async fn get_output<T: DeserializeOwned>(&self) -> Result<Option<T>, DurableError> {
568        match get_output(&self.db, self.task_id).await? {
569            Some(val) => Ok(Some(serde_json::from_value(val)?)),
570            None => Ok(None),
571        }
572    }
573
574    /// Mark this workflow as completed with an output value.
575    pub async fn complete<T: Serialize>(&self, output: &T) -> Result<(), DurableError> {
576        let json = serde_json::to_value(output)?;
577        let db = &self.db;
578        let task_id = self.task_id;
579        retry_db_write(|| complete_task(db, task_id, json.clone())).await
580    }
581
582    /// Run a step with a configurable retry policy.
583    ///
584    /// Unlike `step()`, the closure must implement `Fn` (not `FnOnce`) since
585    /// it may be called multiple times on retry. Retries happen in-process with
586    /// configurable backoff between attempts.
587    ///
588    /// ```ignore
589    /// let result: u32 = ctx
590    ///     .step_with_retry("call_api", RetryPolicy::exponential(3, Duration::from_secs(1)), || async {
591    ///         api.call().await
592    ///     })
593    ///     .await?;
594    /// ```
595    pub async fn step_with_retry<T, F, Fut>(
596        &self,
597        name: &str,
598        policy: RetryPolicy,
599        f: F,
600    ) -> Result<T, DurableError>
601    where
602        T: Serialize + DeserializeOwned,
603        F: Fn() -> Fut,
604        Fut: std::future::Future<Output = Result<T, DurableError>>,
605    {
606        let seq = self.sequence.fetch_add(1, Ordering::SeqCst);
607
608        // Check if workflow is paused or cancelled before executing
609        check_status(&self.db, self.task_id).await?;
610
611        // Find or create — idempotent via UNIQUE(parent_id, name)
612        // Set max_retries from policy when creating.
613        // No locking here — retry logic handles re-execution in-process.
614        let (step_id, saved_output) = find_or_create_task(
615            &self.db,
616            Some(self.task_id),
617            Some(seq),
618            name,
619            "STEP",
620            None,
621            false,
622            Some(policy.max_retries),
623        )
624        .await?;
625
626        // If already completed, replay from saved output
627        if let Some(output) = saved_output {
628            let val: T = serde_json::from_value(output)?;
629            tracing::debug!(step = name, seq, "replaying saved output");
630            return Ok(val);
631        }
632
633        // Get current retry state from DB (for resume across restarts)
634        let (mut retry_count, max_retries) = get_retry_info(&self.db, step_id).await?;
635
636        // Retry loop
637        loop {
638            // Re-check status before each retry attempt
639            check_status(&self.db, self.task_id).await?;
640            set_status(&self.db, step_id, TaskStatus::Running).await?;
641            match f().await {
642                Ok(val) => {
643                    let json = serde_json::to_value(&val)?;
644                    complete_task(&self.db, step_id, json).await?;
645                    tracing::debug!(step = name, seq, retry_count, "step completed");
646                    return Ok(val);
647                }
648                Err(e) => {
649                    if retry_count < max_retries {
650                        // Increment retry count and reset to PENDING
651                        retry_count = increment_retry_count(&self.db, step_id).await?;
652                        tracing::debug!(
653                            step = name,
654                            seq,
655                            retry_count,
656                            max_retries,
657                            "step failed, retrying"
658                        );
659
660                        // Compute backoff duration
661                        let backoff = if policy.initial_backoff.is_zero() {
662                            std::time::Duration::ZERO
663                        } else {
664                            let factor = policy
665                                .backoff_multiplier
666                                .powi((retry_count - 1) as i32)
667                                .max(1.0);
668                            let millis =
669                                (policy.initial_backoff.as_millis() as f64 * factor) as u64;
670                            std::time::Duration::from_millis(millis)
671                        };
672
673                        if !backoff.is_zero() {
674                            tokio::time::sleep(backoff).await;
675                        }
676                    } else {
677                        // Exhausted retries — mark FAILED
678                        fail_task(&self.db, step_id, &e.to_string()).await?;
679                        tracing::debug!(
680                            step = name,
681                            seq,
682                            retry_count,
683                            "step exhausted retries, marked FAILED"
684                        );
685                        return Err(e);
686                    }
687                }
688            }
689        }
690    }
691
692    /// Mark this workflow as failed.
693    pub async fn fail(&self, error: &str) -> Result<(), DurableError> {
694        let db = &self.db;
695        let task_id = self.task_id;
696        retry_db_write(|| fail_task(db, task_id, error)).await
697    }
698
699    /// Set the timeout for this task in milliseconds.
700    ///
701    /// If a task stays RUNNING longer than timeout_ms, it will be eligible
702    /// for recovery by `Executor::recover()`.
703    ///
704    /// If the task is currently RUNNING and has a `started_at`, this also
705    /// computes and stores `deadline_epoch_ms = started_at_epoch_ms + timeout_ms`.
706    pub async fn set_timeout(&self, timeout_ms: i64) -> Result<(), DurableError> {
707        let sql = format!(
708            "UPDATE durable.task \
709             SET timeout_ms = {timeout_ms}, \
710                 deadline_epoch_ms = CASE \
711                     WHEN status = 'RUNNING' AND started_at IS NOT NULL \
712                     THEN EXTRACT(EPOCH FROM started_at) * 1000 + {timeout_ms} \
713                     ELSE deadline_epoch_ms \
714                 END \
715             WHERE id = '{}'",
716            self.task_id
717        );
718        self.db
719            .execute(Statement::from_string(DbBackend::Postgres, sql))
720            .await?;
721        Ok(())
722    }
723
724    /// Start or resume a root workflow with a timeout in milliseconds.
725    ///
726    /// Equivalent to calling `Ctx::start()` followed by `ctx.set_timeout(timeout_ms)`.
727    pub async fn start_with_timeout(
728        db: &DatabaseConnection,
729        name: &str,
730        input: Option<serde_json::Value>,
731        timeout_ms: i64,
732    ) -> Result<Self, DurableError> {
733        let ctx = Self::start(db, name, input).await?;
734        ctx.set_timeout(timeout_ms).await?;
735        Ok(ctx)
736    }
737
738    // ── Workflow control (management API) ─────────────────────────
739
740    /// Pause a workflow by ID. Sets status to PAUSED and recursively
741    /// cascades to all PENDING/RUNNING descendants (children, grandchildren, etc.).
742    ///
743    /// Only workflows in PENDING or RUNNING status can be paused.
744    pub async fn pause(db: &DatabaseConnection, task_id: Uuid) -> Result<(), DurableError> {
745        let model = Task::find_by_id(task_id).one(db).await?;
746        let model =
747            model.ok_or_else(|| DurableError::custom(format!("task {task_id} not found")))?;
748
749        match model.status {
750            TaskStatus::Pending | TaskStatus::Running => {}
751            status => {
752                return Err(DurableError::custom(format!(
753                    "cannot pause task in {status} status"
754                )));
755            }
756        }
757
758        // Pause the task itself and all descendants in one recursive CTE
759        let sql = format!(
760            "WITH RECURSIVE descendants AS ( \
761                 SELECT id FROM durable.task WHERE id = '{task_id}' \
762                 UNION ALL \
763                 SELECT t.id FROM durable.task t \
764                 INNER JOIN descendants d ON t.parent_id = d.id \
765             ) \
766             UPDATE durable.task SET status = 'PAUSED' \
767             WHERE id IN (SELECT id FROM descendants) \
768               AND status IN ('PENDING', 'RUNNING')"
769        );
770        db.execute(Statement::from_string(DbBackend::Postgres, sql))
771            .await?;
772
773        tracing::info!(%task_id, "workflow paused");
774        Ok(())
775    }
776
777    /// Resume a paused workflow by ID. Sets status back to RUNNING and
778    /// recursively cascades to all PAUSED descendants (resetting them to PENDING).
779    pub async fn resume(db: &DatabaseConnection, task_id: Uuid) -> Result<(), DurableError> {
780        let model = Task::find_by_id(task_id).one(db).await?;
781        let model =
782            model.ok_or_else(|| DurableError::custom(format!("task {task_id} not found")))?;
783
784        if model.status != TaskStatus::Paused {
785            return Err(DurableError::custom(format!(
786                "cannot resume task in {} status (must be PAUSED)",
787                model.status
788            )));
789        }
790
791        // Resume the root task back to RUNNING
792        let mut active: TaskActiveModel = model.into();
793        active.status = Set(TaskStatus::Running);
794        active.update(db).await?;
795
796        // Recursively resume all PAUSED descendants back to PENDING
797        let cascade_sql = format!(
798            "WITH RECURSIVE descendants AS ( \
799                 SELECT id FROM durable.task WHERE parent_id = '{task_id}' \
800                 UNION ALL \
801                 SELECT t.id FROM durable.task t \
802                 INNER JOIN descendants d ON t.parent_id = d.id \
803             ) \
804             UPDATE durable.task SET status = 'PENDING' \
805             WHERE id IN (SELECT id FROM descendants) \
806               AND status = 'PAUSED'"
807        );
808        db.execute(Statement::from_string(DbBackend::Postgres, cascade_sql))
809            .await?;
810
811        tracing::info!(%task_id, "workflow resumed");
812        Ok(())
813    }
814
815    /// Cancel a workflow by ID. Sets status to CANCELLED and recursively
816    /// cascades to all non-terminal descendants.
817    ///
818    /// Cancellation is terminal — a cancelled workflow cannot be resumed.
819    pub async fn cancel(db: &DatabaseConnection, task_id: Uuid) -> Result<(), DurableError> {
820        let model = Task::find_by_id(task_id).one(db).await?;
821        let model =
822            model.ok_or_else(|| DurableError::custom(format!("task {task_id} not found")))?;
823
824        match model.status {
825            TaskStatus::Completed | TaskStatus::Failed | TaskStatus::Cancelled => {
826                return Err(DurableError::custom(format!(
827                    "cannot cancel task in {} status",
828                    model.status
829                )));
830            }
831            _ => {}
832        }
833
834        // Cancel the task itself and all non-terminal descendants in one recursive CTE
835        let sql = format!(
836            "WITH RECURSIVE descendants AS ( \
837                 SELECT id FROM durable.task WHERE id = '{task_id}' \
838                 UNION ALL \
839                 SELECT t.id FROM durable.task t \
840                 INNER JOIN descendants d ON t.parent_id = d.id \
841             ) \
842             UPDATE durable.task SET status = 'CANCELLED', completed_at = now() \
843             WHERE id IN (SELECT id FROM descendants) \
844               AND status NOT IN ('COMPLETED', 'FAILED', 'CANCELLED')"
845        );
846        db.execute(Statement::from_string(DbBackend::Postgres, sql))
847            .await?;
848
849        tracing::info!(%task_id, "workflow cancelled");
850        Ok(())
851    }
852
853    // ── Query API ─────────────────────────────────────────────────
854
855    /// List tasks matching the given filter, with sorting and pagination.
856    ///
857    /// ```ignore
858    /// let tasks = Ctx::list(&db, TaskQuery::default().status("RUNNING").limit(10)).await?;
859    /// ```
860    pub async fn list(
861        db: &DatabaseConnection,
862        query: TaskQuery,
863    ) -> Result<Vec<TaskSummary>, DurableError> {
864        let mut select = Task::find();
865
866        // Filters
867        if let Some(status) = &query.status {
868            select = select.filter(TaskColumn::Status.eq(status.to_string()));
869        }
870        if let Some(kind) = &query.kind {
871            select = select.filter(TaskColumn::Kind.eq(kind.as_str()));
872        }
873        if let Some(parent_id) = query.parent_id {
874            select = select.filter(TaskColumn::ParentId.eq(parent_id));
875        }
876        if query.root_only {
877            select = select.filter(TaskColumn::ParentId.is_null());
878        }
879        if let Some(name) = &query.name {
880            select = select.filter(TaskColumn::Name.eq(name.as_str()));
881        }
882        if let Some(queue) = &query.queue_name {
883            select = select.filter(TaskColumn::QueueName.eq(queue.as_str()));
884        }
885
886        // Sorting
887        let (col, order) = match query.sort {
888            TaskSort::CreatedAt(ord) => (TaskColumn::CreatedAt, ord),
889            TaskSort::StartedAt(ord) => (TaskColumn::StartedAt, ord),
890            TaskSort::CompletedAt(ord) => (TaskColumn::CompletedAt, ord),
891            TaskSort::Name(ord) => (TaskColumn::Name, ord),
892            TaskSort::Status(ord) => (TaskColumn::Status, ord),
893        };
894        select = select.order_by(col, order);
895
896        // Pagination
897        if let Some(offset) = query.offset {
898            select = select.offset(offset);
899        }
900        if let Some(limit) = query.limit {
901            select = select.limit(limit);
902        }
903
904        let models = select.all(db).await?;
905
906        Ok(models.into_iter().map(TaskSummary::from).collect())
907    }
908
909    /// Count tasks matching the given filter.
910    pub async fn count(
911        db: &DatabaseConnection,
912        query: TaskQuery,
913    ) -> Result<u64, DurableError> {
914        let mut select = Task::find();
915
916        if let Some(status) = &query.status {
917            select = select.filter(TaskColumn::Status.eq(status.to_string()));
918        }
919        if let Some(kind) = &query.kind {
920            select = select.filter(TaskColumn::Kind.eq(kind.as_str()));
921        }
922        if let Some(parent_id) = query.parent_id {
923            select = select.filter(TaskColumn::ParentId.eq(parent_id));
924        }
925        if query.root_only {
926            select = select.filter(TaskColumn::ParentId.is_null());
927        }
928        if let Some(name) = &query.name {
929            select = select.filter(TaskColumn::Name.eq(name.as_str()));
930        }
931        if let Some(queue) = &query.queue_name {
932            select = select.filter(TaskColumn::QueueName.eq(queue.as_str()));
933        }
934
935        let count = select.count(db).await?;
936        Ok(count)
937    }
938
939    // ── Accessors ────────────────────────────────────────────────
940
941    pub fn db(&self) -> &DatabaseConnection {
942        &self.db
943    }
944
945    pub fn task_id(&self) -> Uuid {
946        self.task_id
947    }
948
949    pub fn next_sequence(&self) -> i32 {
950        self.sequence.fetch_add(1, Ordering::SeqCst)
951    }
952
953    /// Deserialize the stored input for this task.
954    ///
955    /// Returns `Ok(value)` when the task has a non-null `input` column that
956    /// deserializes to `T`. Returns an error if the input is missing or
957    /// cannot be deserialized.
958    ///
959    /// ```ignore
960    /// let args: IngestInput = ctx.input().await?;
961    /// ```
962    pub async fn input<T: DeserializeOwned>(&self) -> Result<T, DurableError> {
963        let row = self
964            .db
965            .query_one(Statement::from_string(
966                DbBackend::Postgres,
967                format!(
968                    "SELECT input FROM durable.task WHERE id = '{}'",
969                    self.task_id
970                ),
971            ))
972            .await?
973            .ok_or_else(|| {
974                DurableError::custom(format!("task {} not found", self.task_id))
975            })?;
976
977        let input_json: Option<serde_json::Value> = row
978            .try_get_by_index(0)
979            .map_err(|e| DurableError::custom(e.to_string()))?;
980
981        let value = input_json.ok_or_else(|| {
982            DurableError::custom(format!("task {} has no input", self.task_id))
983        })?;
984
985        serde_json::from_value(value)
986            .map_err(|e| DurableError::custom(format!("failed to deserialize input: {e}")))
987    }
988}
989
990// ── Internal SQL helpers ─────────────────────────────────────────────
991
992/// Find an existing task by (parent_id, name) or create a new one.
993///
994/// Returns `(task_id, Option<saved_output>)`:
995/// - `saved_output` is `Some(json)` when the task is COMPLETED (replay path).
996/// - `saved_output` is `None` when the task is new or in-progress.
997///
998/// When `lock` is `true` and an existing non-completed task is found, this
999/// function attempts to acquire a `FOR UPDATE SKIP LOCKED` row lock. If
1000/// another worker holds the lock, `DurableError::StepLocked` is returned so
1001/// the caller can skip execution rather than double-firing side effects.
1002///
1003/// When `lock` is `false`, a plain SELECT is used (appropriate for workflow
1004/// and child-workflow creation where concurrent start is safe).
1005///
1006/// When `lock` is `true`, the caller MUST call this within a transaction.
1007/// The lock prevents concurrent creation/claiming of the same step. The
1008/// caller should set the step to RUNNING and commit promptly — the RUNNING
1009/// status itself prevents other executors from re-claiming the step.
1010///
1011/// `max_retries`: if Some, overrides the schema default when creating a new task.
1012#[allow(clippy::too_many_arguments)]
1013async fn find_or_create_task(
1014    db: &impl ConnectionTrait,
1015    parent_id: Option<Uuid>,
1016    sequence: Option<i32>,
1017    name: &str,
1018    kind: &str,
1019    input: Option<serde_json::Value>,
1020    lock: bool,
1021    max_retries: Option<u32>,
1022) -> Result<(Uuid, Option<serde_json::Value>), DurableError> {
1023    let parent_eq = match parent_id {
1024        Some(p) => format!("= '{p}'"),
1025        None => "IS NULL".to_string(),
1026    };
1027    let parent_sql = match parent_id {
1028        Some(p) => format!("'{p}'"),
1029        None => "NULL".to_string(),
1030    };
1031
1032    if lock {
1033        // Locking path (for steps): we need exactly-once execution.
1034        //
1035        // Strategy:
1036        // 1. INSERT the row with ON CONFLICT DO NOTHING — idempotent creation.
1037        //    If another transaction is concurrently inserting the same row,
1038        //    Postgres will block here until that transaction commits or rolls
1039        //    back, ensuring we never see a phantom "not found" for a row being
1040        //    inserted.
1041        // 2. Attempt FOR UPDATE SKIP LOCKED — if we just inserted the row we
1042        //    should get it back; if the row existed and is locked by another
1043        //    worker we get nothing.
1044        // 3. If SKIP LOCKED returns empty, return StepLocked.
1045
1046        let new_id = Uuid::new_v4();
1047        let seq_sql = match sequence {
1048            Some(s) => s.to_string(),
1049            None => "NULL".to_string(),
1050        };
1051        let input_sql = match &input {
1052            Some(v) => format!("'{}'", serde_json::to_string(v)?),
1053            None => "NULL".to_string(),
1054        };
1055
1056        let max_retries_sql = match max_retries {
1057            Some(r) => r.to_string(),
1058            None => "3".to_string(), // schema default
1059        };
1060
1061        // Step 1: insert-or-skip
1062        let insert_sql = format!(
1063            "INSERT INTO durable.task (id, parent_id, sequence, name, kind, status, input, max_retries) \
1064             VALUES ('{new_id}', {parent_sql}, {seq_sql}, '{name}', '{kind}', 'PENDING', {input_sql}, {max_retries_sql}) \
1065             ON CONFLICT (parent_id, sequence) DO NOTHING"
1066        );
1067        db.execute(Statement::from_string(DbBackend::Postgres, insert_sql))
1068            .await?;
1069
1070        // Step 2: lock the row (ours or pre-existing) by (parent_id, sequence)
1071        let lock_sql = format!(
1072            "SELECT id, status::text, output FROM durable.task \
1073             WHERE parent_id {parent_eq} AND sequence = {seq_sql} \
1074             FOR UPDATE SKIP LOCKED"
1075        );
1076        let row = db
1077            .query_one(Statement::from_string(DbBackend::Postgres, lock_sql))
1078            .await?;
1079
1080        if let Some(row) = row {
1081            let id: Uuid = row
1082                .try_get_by_index(0)
1083                .map_err(|e| DurableError::custom(e.to_string()))?;
1084            let status: String = row
1085                .try_get_by_index(1)
1086                .map_err(|e| DurableError::custom(e.to_string()))?;
1087            let output: Option<serde_json::Value> = row.try_get_by_index(2).ok();
1088
1089            if status == TaskStatus::Completed.to_string() {
1090                // Replay path — return saved output
1091                return Ok((id, output));
1092            }
1093            if status == TaskStatus::Running.to_string() {
1094                // Another worker already claimed this step (set RUNNING and committed).
1095                // We got the row lock (no longer held in a long txn) but must not
1096                // double-execute.
1097                return Err(DurableError::StepLocked(name.to_string()));
1098            }
1099            // Task is PENDING — we're the first to claim it.
1100            return Ok((id, None));
1101        }
1102
1103        // Step 3: SKIP LOCKED returned empty — another worker holds the lock
1104        Err(DurableError::StepLocked(name.to_string()))
1105    } else {
1106        // Plain find without locking — safe for workflow-level operations.
1107        // Multiple workers resuming the same workflow is fine; individual
1108        // steps will be locked when executed.
1109        let mut query = Task::find().filter(TaskColumn::Name.eq(name));
1110        query = match parent_id {
1111            Some(p) => query.filter(TaskColumn::ParentId.eq(p)),
1112            None => query.filter(TaskColumn::ParentId.is_null()),
1113        };
1114        // Skip cancelled/failed tasks — a fresh row will be created instead.
1115        // Completed tasks are still returned so child tasks can replay saved output.
1116        let status_exclusions = vec![TaskStatus::Cancelled, TaskStatus::Failed];
1117        let existing = query
1118            .filter(TaskColumn::Status.is_not_in(status_exclusions))
1119            .one(db)
1120            .await?;
1121
1122        if let Some(model) = existing {
1123            if model.status == TaskStatus::Completed {
1124                return Ok((model.id, model.output));
1125            }
1126            return Ok((model.id, None));
1127        }
1128
1129        // Task does not exist — create it
1130        let id = Uuid::new_v4();
1131        let new_task = TaskActiveModel {
1132            id: Set(id),
1133            parent_id: Set(parent_id),
1134            sequence: Set(sequence),
1135            name: Set(name.to_string()),
1136            kind: Set(kind.to_string()),
1137            status: Set(TaskStatus::Pending),
1138            input: Set(input),
1139            max_retries: Set(max_retries.map(|r| r as i32).unwrap_or(3)),
1140            ..Default::default()
1141        };
1142        new_task.insert(db).await?;
1143
1144        Ok((id, None))
1145    }
1146}
1147
1148async fn get_output(
1149    db: &impl ConnectionTrait,
1150    task_id: Uuid,
1151) -> Result<Option<serde_json::Value>, DurableError> {
1152    let model = Task::find_by_id(task_id)
1153        .filter(TaskColumn::Status.eq(TaskStatus::Completed.to_string()))
1154        .one(db)
1155        .await?;
1156
1157    Ok(model.and_then(|m| m.output))
1158}
1159
1160async fn get_status(
1161    db: &impl ConnectionTrait,
1162    task_id: Uuid,
1163) -> Result<Option<TaskStatus>, DurableError> {
1164    let model = Task::find_by_id(task_id).one(db).await?;
1165
1166    Ok(model.map(|m| m.status))
1167}
1168
1169/// Returns (retry_count, max_retries) for a task.
1170async fn get_retry_info(
1171    db: &DatabaseConnection,
1172    task_id: Uuid,
1173) -> Result<(u32, u32), DurableError> {
1174    let model = Task::find_by_id(task_id).one(db).await?;
1175
1176    match model {
1177        Some(m) => Ok((m.retry_count as u32, m.max_retries as u32)),
1178        None => Err(DurableError::custom(format!(
1179            "task {task_id} not found when reading retry info"
1180        ))),
1181    }
1182}
1183
1184/// Increment retry_count and reset status to PENDING. Returns the new retry_count.
1185async fn increment_retry_count(
1186    db: &DatabaseConnection,
1187    task_id: Uuid,
1188) -> Result<u32, DurableError> {
1189    let model = Task::find_by_id(task_id).one(db).await?;
1190
1191    match model {
1192        Some(m) => {
1193            let new_count = m.retry_count + 1;
1194            let mut active: TaskActiveModel = m.into();
1195            active.retry_count = Set(new_count);
1196            active.status = Set(TaskStatus::Pending);
1197            active.error = Set(None);
1198            active.completed_at = Set(None);
1199            active.update(db).await?;
1200            Ok(new_count as u32)
1201        }
1202        None => Err(DurableError::custom(format!(
1203            "task {task_id} not found when incrementing retry count"
1204        ))),
1205    }
1206}
1207
1208// NOTE: set_status uses raw SQL because SeaORM cannot express the CASE expression
1209// for conditional deadline_epoch_ms computation or COALESCE on started_at.
1210async fn set_status(
1211    db: &impl ConnectionTrait,
1212    task_id: Uuid,
1213    status: TaskStatus,
1214) -> Result<(), DurableError> {
1215    let sql = format!(
1216        "UPDATE durable.task \
1217         SET status = '{status}', \
1218             started_at = COALESCE(started_at, now()), \
1219             deadline_epoch_ms = CASE \
1220                 WHEN '{status}' = 'RUNNING' AND timeout_ms IS NOT NULL \
1221                 THEN EXTRACT(EPOCH FROM now()) * 1000 + timeout_ms \
1222                 ELSE deadline_epoch_ms \
1223             END \
1224         WHERE id = '{task_id}'"
1225    );
1226    db.execute(Statement::from_string(DbBackend::Postgres, sql))
1227        .await?;
1228    Ok(())
1229}
1230
1231/// Check if the task is paused or cancelled. Returns an error if so.
1232async fn check_status(db: &DatabaseConnection, task_id: Uuid) -> Result<(), DurableError> {
1233    let status = get_status(db, task_id).await?;
1234    match status {
1235        Some(TaskStatus::Paused) => Err(DurableError::Paused(format!("task {task_id} is paused"))),
1236        Some(TaskStatus::Cancelled) => {
1237            Err(DurableError::Cancelled(format!("task {task_id} is cancelled")))
1238        }
1239        _ => Ok(()),
1240    }
1241}
1242
1243/// Check if the parent task's deadline has passed. Returns `DurableError::Timeout` if so.
1244async fn check_deadline(db: &DatabaseConnection, task_id: Uuid) -> Result<(), DurableError> {
1245    let model = Task::find_by_id(task_id).one(db).await?;
1246
1247    if let Some(m) = model
1248        && let Some(deadline_ms) = m.deadline_epoch_ms
1249    {
1250        let now_ms = std::time::SystemTime::now()
1251            .duration_since(std::time::UNIX_EPOCH)
1252            .map(|d| d.as_millis() as i64)
1253            .unwrap_or(0);
1254        if now_ms > deadline_ms {
1255            return Err(DurableError::Timeout("task deadline exceeded".to_string()));
1256        }
1257    }
1258
1259    Ok(())
1260}
1261
1262async fn complete_task(
1263    db: &impl ConnectionTrait,
1264    task_id: Uuid,
1265    output: serde_json::Value,
1266) -> Result<(), DurableError> {
1267    let model = Task::find_by_id(task_id).one(db).await?;
1268
1269    if let Some(m) = model {
1270        let mut active: TaskActiveModel = m.into();
1271        active.status = Set(TaskStatus::Completed);
1272        active.output = Set(Some(output));
1273        active.completed_at = Set(Some(chrono::Utc::now().into()));
1274        active.update(db).await?;
1275    }
1276    Ok(())
1277}
1278
1279async fn fail_task(
1280    db: &impl ConnectionTrait,
1281    task_id: Uuid,
1282    error: &str,
1283) -> Result<(), DurableError> {
1284    let model = Task::find_by_id(task_id).one(db).await?;
1285
1286    if let Some(m) = model {
1287        let mut active: TaskActiveModel = m.into();
1288        active.status = Set(TaskStatus::Failed);
1289        active.error = Set(Some(error.to_string()));
1290        active.completed_at = Set(Some(chrono::Utc::now().into()));
1291        active.update(db).await?;
1292    }
1293    Ok(())
1294}
1295
1296#[cfg(test)]
1297mod tests {
1298    use super::*;
1299    use std::sync::Arc;
1300    use std::sync::atomic::{AtomicU32, Ordering};
1301
1302    /// test_retry_db_write_succeeds_first_try: a closure that always succeeds
1303    /// should be called exactly once and return Ok.
1304    #[tokio::test]
1305    async fn test_retry_db_write_succeeds_first_try() {
1306        let call_count = Arc::new(AtomicU32::new(0));
1307        let cc = call_count.clone();
1308        let result = retry_db_write(|| {
1309            let c = cc.clone();
1310            async move {
1311                c.fetch_add(1, Ordering::SeqCst);
1312                Ok::<(), DurableError>(())
1313            }
1314        })
1315        .await;
1316        assert!(result.is_ok());
1317        assert_eq!(call_count.load(Ordering::SeqCst), 1);
1318    }
1319
1320    /// test_retry_db_write_succeeds_after_transient_failure: a closure that
1321    /// fails twice then succeeds should return Ok and be called 3 times.
1322    #[tokio::test]
1323    async fn test_retry_db_write_succeeds_after_transient_failure() {
1324        let call_count = Arc::new(AtomicU32::new(0));
1325        let cc = call_count.clone();
1326        let result = retry_db_write(|| {
1327            let c = cc.clone();
1328            async move {
1329                let n = c.fetch_add(1, Ordering::SeqCst);
1330                if n < 2 {
1331                    Err(DurableError::Db(sea_orm::DbErr::Custom(
1332                        "transient".to_string(),
1333                    )))
1334                } else {
1335                    Ok(())
1336                }
1337            }
1338        })
1339        .await;
1340        assert!(result.is_ok());
1341        assert_eq!(call_count.load(Ordering::SeqCst), 3);
1342    }
1343
1344    /// test_retry_db_write_exhausts_retries: a closure that always fails should
1345    /// be called 1 + MAX_CHECKPOINT_RETRIES times total then return an error.
1346    #[tokio::test]
1347    async fn test_retry_db_write_exhausts_retries() {
1348        let call_count = Arc::new(AtomicU32::new(0));
1349        let cc = call_count.clone();
1350        let result = retry_db_write(|| {
1351            let c = cc.clone();
1352            async move {
1353                c.fetch_add(1, Ordering::SeqCst);
1354                Err::<(), DurableError>(DurableError::Db(sea_orm::DbErr::Custom(
1355                    "always fails".to_string(),
1356                )))
1357            }
1358        })
1359        .await;
1360        assert!(result.is_err());
1361        // 1 initial attempt + MAX_CHECKPOINT_RETRIES retry attempts
1362        assert_eq!(
1363            call_count.load(Ordering::SeqCst),
1364            1 + MAX_CHECKPOINT_RETRIES
1365        );
1366    }
1367
1368    /// test_retry_db_write_returns_original_error: when all retries are
1369    /// exhausted the FIRST error is returned, not the last retry error.
1370    #[tokio::test]
1371    async fn test_retry_db_write_returns_original_error() {
1372        let call_count = Arc::new(AtomicU32::new(0));
1373        let cc = call_count.clone();
1374        let result = retry_db_write(|| {
1375            let c = cc.clone();
1376            async move {
1377                let n = c.fetch_add(1, Ordering::SeqCst);
1378                Err::<(), DurableError>(DurableError::Db(sea_orm::DbErr::Custom(format!(
1379                    "error-{}",
1380                    n
1381                ))))
1382            }
1383        })
1384        .await;
1385        let err = result.unwrap_err();
1386        // The message of the first error contains "error-0"
1387        assert!(
1388            err.to_string().contains("error-0"),
1389            "expected first error (error-0), got: {err}"
1390        );
1391    }
1392}