From 60d0cd278b3a9fdd1fa5ddef32d671a6cb91db00 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Fri, 9 Oct 2026 18:16:25 -0400 Subject: [PATCH] fix(queue): apply workflow failure policies and terminal fail_job on every backend - PostgreSQL/MySQL fail_job_dependencies now applies the workflow's FailurePolicy (fail_fast / continue_on_failure / manual) and updates the workflow's counters and status, locking the job and workflow like a terminal transition. It used to fail the dependents under every policy. - TestQueue::fail_job is a terminal Failed, as the trait documents, and applies the workflow policy and a fail-fast batch's failure. It used to retry the job or mark it dead. - TestQueue::dequeue counts an attempt; fail_job_dependencies, get_workflow_status and enqueue_workflow (job depends_on) match the database backends. - Document each policy, including Manual, on FailurePolicy and fail_job_dependencies. - New generic tests (TestQueue, PostgreSQL, MySQL) for fail_job and each policy; re-enable the statistics scenario on TestQueue; move TestQueue tests that exercised retry-or-dead to retry_job / mark_job_dead. Closes #59 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + docs/testing.md | 48 ++- docs/workflows.md | 12 +- examples/test_queue_example.rs | 17 +- src/queue/mod.rs | 29 +- src/queue/mysql.rs | 76 ++++- src/queue/postgres.rs | 76 ++++- src/queue/test.rs | 366 ++++++++++++-------- src/workflow.rs | 17 +- tests/queue_api_tests.rs | 4 +- tests/test_queue_tests.rs | 56 ++-- tests/workflow_failure_policy_tests.rs | 440 +++++++++++++++++++++++++ 12 files changed, 890 insertions(+), 257 deletions(-) create mode 100644 tests/workflow_failure_policy_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc1754..4b2922d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - The CLI no longer hangs when the database is unreachable: connecting gives up after 10 seconds with a clear error. Configure with `connect_timeout_secs` in `config.toml`, `cargo hammerwork config set connect_timeout_secs N`, or `HAMMERWORK_CONNECT_TIMEOUT`. +- **Queue failure semantics are the same on every backend** ([#59](https://github.com/CodingAnarchy/hammerwork/issues/59)): + - PostgreSQL/MySQL `fail_job_dependencies` now applies the workflow's `FailurePolicy`, as documented. It used to fail the failed job's dependents under every policy: under `Manual` it failed jobs that should keep waiting, and under `FailFast` it left the workflow's other pending jobs and its status alone. It now locks the job and its workflow like a terminal transition, applies `FailFast` (the workflow's `Pending`/`Retrying` jobs and all dependents fail, workflow `failed`), `ContinueOnFailure` (only the transitive dependents fail) or `Manual` (nothing changes), and updates the workflow's counters and status. + - `TestQueue::fail_job` is a terminal `Failed`, as the trait documents and the database backends implement. It used to increment `attempts` and move the job to `Retrying`, or to `Dead` once attempts ran out. It now also applies the workflow policy and a `FailFast` batch's failure, like the database backends. Code that relied on the old behaviour should do what a worker does: `retry_job` while `attempts < max_attempts`, then `mark_job_dead`. + - `TestQueue::dequeue` counts an attempt (`attempts + 1`) like the database backends, so a `Worker`'s retry/dead decision works the same on it. + - `TestQueue::fail_job_dependencies` applies the policies like the database backends (it failed nothing under `ContinueOnFailure` and ignored jobs outside workflows), `get_workflow_status` derives the status from the policy (a failure under `ContinueOnFailure` or `Manual` no longer makes the workflow `failed` while jobs can still run), and `enqueue_workflow` honours each job's own `depends_on`. + - The `FailurePolicy` and `fail_job_dependencies` docs describe the behaviour of each policy, including `Manual` (dependents wait until the failed job is re-run or the workflow is cancelled). - **CLI and web bugs found by testing every command and endpoint against both databases** ([#44](https://github.com/CodingAnarchy/hammerwork/issues/44)): - CLI `backup restore` bound text into UUID/INT columns on PostgreSQL (it never worked there), dropped timestamps and the error message, and counted skipped duplicates as restored; `--skip-existing` compared a UUID with text. CSV backups now quote fields instead of replacing commas. - CLI `cron` was mostly stubs: `create` wrote text ids/priorities that PostgreSQL rejected and accepted five-field schedules the scheduler cannot run; `list`/`next` printed "coming soon"; `update` did nothing. They are now real (library scheduling, real next-run times, `update` recomputes the next run). `cron create --description` (never stored) was removed. diff --git a/docs/testing.md b/docs/testing.md index 4a140e8..8e64f2e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -390,7 +390,7 @@ async fn test_batch_fail_fast() { // Process first job and fail it let first_job = queue.dequeue("fail_fast_queue").await.unwrap().unwrap(); - queue.fail_job(first_job.id, "Intentional failure".to_string()).await.unwrap(); + queue.fail_job(first_job.id, "Intentional failure").await.unwrap(); // With FailFast, remaining jobs should be automatically failed let batch_status = queue.get_batch_status(batch_id).await.unwrap(); @@ -470,7 +470,7 @@ async fn test_workflow_fail_fast() { // Dequeue any job and fail it let job = queue.dequeue("fail_fast_workflow").await.unwrap().unwrap(); - queue.fail_job(job.id, "Intentional failure for testing".to_string()).await.unwrap(); + queue.fail_job(job.id, "Intentional failure for testing").await.unwrap(); // With FailFast policy, the workflow should be marked as failed let status = queue.get_workflow_status(workflow_id).await.unwrap(); @@ -493,24 +493,22 @@ async fn test_job_retry_logic() { let job_id = queue.enqueue(job).await.unwrap(); - // First attempt - let attempt1 = queue.dequeue("retry_queue").await.unwrap().unwrap(); - assert_eq!(attempt1.attempts, 0); - queue.fail_job(job_id, "First failure".to_string()).await.unwrap(); - - // Second attempt - let attempt2 = queue.dequeue("retry_queue").await.unwrap().unwrap(); - assert_eq!(attempt2.attempts, 1); - queue.fail_job(job_id, "Second failure".to_string()).await.unwrap(); - - // Third attempt - let attempt3 = queue.dequeue("retry_queue").await.unwrap().unwrap(); - assert_eq!(attempt3.attempts, 2); - queue.fail_job(job_id, "Third failure".to_string()).await.unwrap(); - - // Fourth failure should make job dead (no more retries) + // `fail_job` is a terminal failure that is never retried automatically. A + // worker retries a failed run with `retry_job` while the job has attempts left + // (each dequeue counts as one) and marks it dead after the last one. + for attempt in 1..=3 { + let job = queue.dequeue("retry_queue").await.unwrap().unwrap(); + assert_eq!(job.attempts, attempt); + if job.attempts < job.max_attempts { + queue.retry_job(job_id, queue.clock().now()).await.unwrap(); + } else { + queue.mark_job_dead(job_id, "Third failure").await.unwrap(); + } + } + + // No more retries assert!(queue.dequeue("retry_queue").await.unwrap().is_none()); - + // Verify job is dead let final_job = queue.get_job(job_id).await.unwrap().unwrap(); assert_eq!(final_job.status, JobStatus::Dead); @@ -527,14 +525,14 @@ async fn test_dead_job_purging() { let clock = MockClock::new(); let queue = TestQueue::with_clock(clock.clone()); - // Create and fail jobs to make them dead + // Create jobs and mark them dead for i in 0..5 { let job = Job::new("purge_queue".to_string(), json!({"id": i})) .with_max_attempts(1); let job_id = queue.enqueue(job).await.unwrap(); let dequeued = queue.dequeue("purge_queue").await.unwrap().unwrap(); - queue.fail_job(job_id, "Failed for purge test".to_string()).await.unwrap(); + queue.mark_job_dead(dequeued.id, "Failed for purge test").await.unwrap(); } // Advance time to make jobs eligible for purging @@ -765,12 +763,12 @@ async fn test_email_service() { let newsletter_job = queue.dequeue("email_queue").await.unwrap().unwrap(); assert_eq!(newsletter_job.payload["template"], "newsletter"); - // Simulate email sending failure and retry - queue.fail_job(newsletter_job.id, "SMTP server unavailable".to_string()).await.unwrap(); + // Simulate email sending failure and retry it, as a worker would + queue.retry_job(newsletter_job.id, clock.now()).await.unwrap(); - // Job should be available for retry + // Job should be available for retry; each dequeue counts as an attempt let retry_job = queue.dequeue("email_queue").await.unwrap().unwrap(); - assert_eq!(retry_job.attempts, 1); + assert_eq!(retry_job.attempts, 2); queue.complete_job(retry_job.id).await.unwrap(); } ``` diff --git a/docs/workflows.md b/docs/workflows.md index 6f0495e..ec1961e 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -299,8 +299,9 @@ let workflow = JobGroup::new("manual_review_pipeline") ``` With `Manual`, the dependents of the failed job stay `waiting` and the workflow stays -`running`. Re-run the failed job with `queue.retry_dead_job(job_id)`; when it completes, -its dependents become runnable. To give up instead, call `cancel_workflow`. +`running`. Re-run the failed job with `queue.retry_dead_job(job_id)` (a `Dead` job) or +`queue.retry_job(job_id, at)` (a `Failed` or `TimedOut` one); when it completes, its +dependents become runnable. To give up instead, call `cancel_workflow`. With `FailFast`, every job of the workflow that has not started yet is marked `Failed` (jobs already running finish normally). With `ContinueOnFailure`, the jobs that depend @@ -308,6 +309,13 @@ on the failed job, directly or transitively, are marked `Failed` with `dependency_status = failed`; independent jobs keep running. Jobs that use `Job::depends_on` outside a workflow behave like `ContinueOnFailure`. +`queue.fail_job_dependencies(job_id)` applies the same policy explicitly (and updates the +workflow's counters and status), and returns the jobs it failed. On PostgreSQL and +MySQL every terminal transition already applies it, so after one it finds nothing left +to do. `TestQueue` applies the policies the same way, from `fail_job`, from a worker's +`finish_job_run` and from `fail_job_dependencies`; its `mark_job_dead` and +`mark_job_timed_out` only change the job's status. + ## Workflow Management ### Creating and Managing Workflows diff --git a/examples/test_queue_example.rs b/examples/test_queue_example.rs index 038f743..a9fc80f 100644 --- a/examples/test_queue_example.rs +++ b/examples/test_queue_example.rs @@ -506,7 +506,10 @@ async fn error_handling_example() -> Result<(), Box> { println!("\nšŸ”„ Attempt 1:"); match email_handler(job.clone()).await { Err(e) => { - queue.fail_job(job.id, &e.to_string()).await?; + // Like a worker: retry while the job has attempts left. + assert!(job.attempts < job.max_attempts); + let retry_at = clock.now() + Duration::minutes(5); + queue.retry_job(job.id, retry_at).await?; println!(" āŒ Failed: {}", e); let job_state = queue.get_job(job.id).await?.unwrap(); @@ -519,9 +522,6 @@ async fn error_handling_example() -> Result<(), Box> { } } - // Schedule retry - let retry_at = clock.now() + Duration::minutes(5); - queue.retry_job(job_id, retry_at).await?; println!("ā³ Scheduled retry in 5 minutes"); // Advance time and retry @@ -532,7 +532,8 @@ async fn error_handling_example() -> Result<(), Box> { println!("\nšŸ”„ Attempt 2:"); match email_handler(job.clone()).await { Err(e) => { - queue.fail_job(job.id, &e.to_string()).await?; + assert!(job.attempts < job.max_attempts); + queue.retry_job(job.id, clock.now()).await?; println!(" āŒ Failed again: {}", e); let job_state = queue.get_job(job.id).await?.unwrap(); @@ -546,13 +547,13 @@ async fn error_handling_example() -> Result<(), Box> { } // Attempt 3 (final) - queue.retry_job(job_id, clock.now()).await?; - if let Some(job) = queue.dequeue("email_queue").await? { println!("\nšŸ”„ Attempt 3 (final):"); match email_handler(job.clone()).await { Err(e) => { - queue.fail_job(job.id, &e.to_string()).await?; + // The last attempt failed: the job is dead. + assert_eq!(job.attempts, job.max_attempts); + queue.mark_job_dead(job.id, &e.to_string()).await?; println!(" āŒ Failed permanently: {}", e); let job_state = queue.get_job(job.id).await?.unwrap(); diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 96341bc..062568e 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -361,10 +361,31 @@ pub trait DatabaseQueue: Send + Sync { /// have been satisfied (completed successfully). async fn get_ready_jobs(&self, queue_name: &str, limit: u32) -> Result>; - /// Mark job dependencies as failed when a job fails. - /// - /// This propagates failure through the dependency graph according to the - /// workflow's failure policy. + /// Apply the failure of `failed_job_id` to the jobs that can no longer run because + /// of it, according to its workflow's + /// [`FailurePolicy`](crate::workflow::FailurePolicy), and return the jobs that were + /// failed: + /// + /// - `FailFast`: the workflow's other `Pending` and `Retrying` jobs, and every job + /// that (transitively) depends on the failed one, become `Failed`; the workflow + /// becomes `Failed`. Jobs already `Running` finish their run. + /// - `ContinueOnFailure`: only the `Pending` jobs that (transitively) depend on the + /// failed one become `Failed` (their dependency status `failed`); independent + /// branches keep running. The workflow stays `Running` until all its jobs have + /// finished, and then becomes `Failed`. + /// - `Manual`: nothing changes. The dependents keep waiting until an operator + /// re-runs the failed job ([`retry_job`](Self::retry_job), after which its + /// completion releases them) or cancels the workflow + /// ([`cancel_workflow`](Self::cancel_workflow)). The workflow stays `Running`. + /// + /// A job outside any workflow is treated like `ContinueOnFailure`. The workflow's + /// counters and status are updated in the same transaction. + /// + /// Terminal transitions ([`fail_job`](Self::fail_job), + /// [`finish_job_run`](Self::finish_job_run) and, on the database backends, + /// [`mark_job_dead`](Self::mark_job_dead) and + /// [`mark_job_timed_out`](Self::mark_job_timed_out)) already apply the policy, so + /// calling this afterwards changes nothing and returns an empty list. async fn fail_job_dependencies(&self, failed_job_id: JobId) -> Result>; /// Get all jobs in a workflow. diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index ec5e9ba..a366dc7 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -1793,11 +1793,7 @@ impl DatabaseQueue for crate::queue::JobQueue { super::retry_on_conflict(|| async { let mut conn = self.pool.acquire().await?; let mut tx = Self::begin_claim_transaction(&mut conn).await?; - let result = async { - let now = db_now(&mut tx).await?; - Self::fail_dependents(&mut tx, failed_job_id, now).await - } - .await; + let result = Self::fail_job_dependencies_in_tx(&mut tx, failed_job_id).await; super::end_transaction(tx, result).await }) .await @@ -2860,19 +2856,8 @@ impl crate::queue::JobQueue { if status == JobStatus::Completed { recorded.unblocked = Self::resolve_dependents(conn, job.id).await?; } else { - match &workflow { - Some(w) if w.policy == FailurePolicy::Manual => {} - Some(w) if w.policy == FailurePolicy::FailFast => { - recorded.cancelled = - Self::fail_workflow_pending(conn, &w.id, job.id, now).await?; - recorded - .cancelled - .extend(Self::fail_dependents(conn, job.id, now).await?); - } - // ContinueOnFailure, and jobs with dependencies outside any workflow: - // only the jobs that (transitively) depend on this one can no longer run. - _ => recorded.cancelled = Self::fail_dependents(conn, job.id, now).await?, - } + recorded.cancelled = + Self::apply_failure_policy(conn, workflow.as_ref(), job.id, now).await?; } if let Some(workflow) = &workflow { @@ -2885,6 +2870,61 @@ impl crate::queue::JobQueue { Ok(recorded) } + /// Apply the [`FailurePolicy`] of `workflow` (the failed job's locked workflow, if + /// any) to the failure of `failed_job_id`. Returns the jobs that were failed. + /// + /// - `FailFast` fails the workflow's other `Pending` and `Retrying` jobs, then the + /// jobs that (transitively) depend on the failed one; + /// - `ContinueOnFailure`, and jobs with dependencies outside any workflow, fail + /// only the jobs that (transitively) depend on the failed one; + /// - `Manual` leaves the dependents waiting for an operator. + async fn apply_failure_policy( + conn: &mut sqlx::MySqlConnection, + workflow: Option<&LockedWorkflow>, + failed_job_id: JobId, + now: DateTime, + ) -> Result> { + match workflow { + Some(w) if w.policy == FailurePolicy::Manual => Ok(Vec::new()), + Some(w) if w.policy == FailurePolicy::FailFast => { + let mut failed = + Self::fail_workflow_pending(conn, &w.id, failed_job_id, now).await?; + for id in Self::fail_dependents(conn, failed_job_id, now).await? { + if !failed.contains(&id) { + failed.push(id); + } + } + Ok(failed) + } + _ => Self::fail_dependents(conn, failed_job_id, now).await, + } + } + + /// [`DatabaseQueue::fail_job_dependencies`] in one transaction: lock the failed job + /// and its workflow (in the same order as a terminal transition), apply the + /// workflow's failure policy and update the workflow's counters and status. + async fn fail_job_dependencies_in_tx( + conn: &mut sqlx::MySqlConnection, + failed_job_id: JobId, + ) -> Result> { + let workflow_id: Option> = + sqlx::query_scalar("SELECT workflow_id FROM hammerwork_jobs WHERE id = ? FOR UPDATE") + .bind(failed_job_id.to_string()) + .fetch_optional(&mut *conn) + .await?; + let workflow = match workflow_id.flatten() { + Some(id) => Self::lock_workflow(conn, uuid::Uuid::parse_str(&id)?).await?, + None => None, + }; + let now = db_now(conn).await?; + let failed = + Self::apply_failure_policy(conn, workflow.as_ref(), failed_job_id, now).await?; + if let Some(workflow) = &workflow { + Self::refresh_workflow(conn, workflow, now).await?; + } + Ok(failed) + } + /// Put a recurring job back to `Pending` for its next run. A failed run's error and /// failure time stay visible until the next run; a successful run clears them. async fn reschedule_after_run( diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 573de35..1fe7fe5 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -1651,11 +1651,7 @@ impl DatabaseQueue for crate::queue::JobQueue { async fn fail_job_dependencies(&self, failed_job_id: JobId) -> Result> { super::retry_on_conflict(|| async { let mut tx = self.pool.begin().await?; - let result = async { - let now = db_now(&mut tx).await?; - Self::fail_dependents(&mut tx, failed_job_id, now).await - } - .await; + let result = Self::fail_job_dependencies_in_tx(&mut tx, failed_job_id).await; super::end_transaction(tx, result).await }) .await @@ -2642,19 +2638,8 @@ impl crate::queue::JobQueue { if status == JobStatus::Completed { recorded.unblocked = Self::resolve_dependents(conn, job.id).await?; } else { - match &workflow { - Some(w) if w.policy == FailurePolicy::Manual => {} - Some(w) if w.policy == FailurePolicy::FailFast => { - recorded.cancelled = - Self::fail_workflow_pending(conn, w.id, job.id, now).await?; - recorded - .cancelled - .extend(Self::fail_dependents(conn, job.id, now).await?); - } - // ContinueOnFailure, and jobs with dependencies outside any workflow: - // only the jobs that (transitively) depend on this one can no longer run. - _ => recorded.cancelled = Self::fail_dependents(conn, job.id, now).await?, - } + recorded.cancelled = + Self::apply_failure_policy(conn, workflow.as_ref(), job.id, now).await?; } if let Some(workflow) = &workflow { @@ -2667,6 +2652,61 @@ impl crate::queue::JobQueue { Ok(recorded) } + /// Apply the [`FailurePolicy`] of `workflow` (the failed job's locked workflow, if + /// any) to the failure of `failed_job_id`. Returns the jobs that were failed. + /// + /// - `FailFast` fails the workflow's other `Pending` and `Retrying` jobs, then the + /// jobs that (transitively) depend on the failed one; + /// - `ContinueOnFailure`, and jobs with dependencies outside any workflow, fail + /// only the jobs that (transitively) depend on the failed one; + /// - `Manual` leaves the dependents waiting for an operator. + async fn apply_failure_policy( + conn: &mut sqlx::PgConnection, + workflow: Option<&LockedWorkflow>, + failed_job_id: JobId, + now: DateTime, + ) -> Result> { + match workflow { + Some(w) if w.policy == FailurePolicy::Manual => Ok(Vec::new()), + Some(w) if w.policy == FailurePolicy::FailFast => { + let mut failed = + Self::fail_workflow_pending(conn, w.id, failed_job_id, now).await?; + for id in Self::fail_dependents(conn, failed_job_id, now).await? { + if !failed.contains(&id) { + failed.push(id); + } + } + Ok(failed) + } + _ => Self::fail_dependents(conn, failed_job_id, now).await, + } + } + + /// [`DatabaseQueue::fail_job_dependencies`] in one transaction: lock the failed job + /// and its workflow (in the same order as a terminal transition), apply the + /// workflow's failure policy and update the workflow's counters and status. + async fn fail_job_dependencies_in_tx( + conn: &mut sqlx::PgConnection, + failed_job_id: JobId, + ) -> Result> { + let workflow_id: Option> = + sqlx::query_scalar("SELECT workflow_id FROM hammerwork_jobs WHERE id = $1 FOR UPDATE") + .bind(failed_job_id) + .fetch_optional(&mut *conn) + .await?; + let workflow = match workflow_id.flatten() { + Some(id) => Self::lock_workflow(conn, id).await?, + None => None, + }; + let now = db_now(conn).await?; + let failed = + Self::apply_failure_policy(conn, workflow.as_ref(), failed_job_id, now).await?; + if let Some(workflow) = &workflow { + Self::refresh_workflow(conn, workflow, now).await?; + } + Ok(failed) + } + /// Put a recurring job back to `Pending` for its next run. A failed run's error and /// failure time stay visible until the next run; a successful run clears them. async fn reschedule_after_run( diff --git a/src/queue/test.rs b/src/queue/test.rs index 36411ed..f9997fe 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -41,10 +41,12 @@ use crate::{ batch::{BatchId, BatchResult, BatchStatus, JobBatch}, job::{Job, JobId, JobStatus}, priority::{JobPriority, PriorityWeights}, - queue::{DatabaseQueue, PayloadEncryption, QueuePauseInfo}, + queue::{DatabaseQueue, PayloadEncryption, QueuePauseInfo, lifecycle}, rate_limit::ThrottleConfig, stats::{DeadJobSummary, QueueStats}, - workflow::{JobGroup, WorkflowId, WorkflowStatus}, + workflow::{ + DependencyStatus, FailurePolicy, JobGroup, WorkflowId, WorkflowProgress, WorkflowStatus, + }, }; use async_trait::async_trait; use chrono::{DateTime, Utc}; @@ -354,6 +356,147 @@ impl TestStorage { Ok(()) } + /// Mark an unfinished job `Failed` with `error`, as a side effect of another job's + /// failure. A job still waiting on its dependencies records that they failed. + fn fail_as_side_effect(&mut self, job_id: JobId, error: String, now: DateTime) { + if self.update_job_status(job_id, JobStatus::Failed).is_err() { + return; + } + self.leases.remove(&job_id); + if let Some(job) = self.jobs.get_mut(&job_id) { + job.failed_at = Some(now); + job.error_message = Some(error); + if job.dependency_status == DependencyStatus::Waiting { + job.dependency_status = DependencyStatus::Failed; + } + } + } + + /// The workflow `job_id` belongs to: the one its `workflow_id` names, or else the + /// one listing it among its jobs. + fn workflow_of(&self, job_id: JobId) -> Option<&JobGroup> { + self.jobs + .get(&job_id) + .and_then(|job| job.workflow_id) + .and_then(|id| self.workflows.get(&id)) + .or_else(|| { + self.workflows + .values() + .find(|w| w.jobs.iter().any(|j| j.id == job_id)) + }) + } + + /// The jobs that depend directly on `job_id`. + fn direct_dependents(&self, job_id: JobId) -> Vec { + let mut dependents = self.dependents.get(&job_id).cloned().unwrap_or_default(); + for job in self.jobs.values() { + if job.depends_on.contains(&job_id) && !dependents.contains(&job.id) { + dependents.push(job.id); + } + } + dependents + } + + /// Fail every pending job that (transitively) depends on `failed_job_id`. + fn fail_dependents(&mut self, failed_job_id: JobId, now: DateTime) -> Vec { + let mut failed = Vec::new(); + let mut to_check = vec![failed_job_id]; + while let Some(current) = to_check.pop() { + for id in self.direct_dependents(current) { + let pending = self.jobs.get(&id).is_some_and(|job| { + job.status == JobStatus::Pending + && job.dependency_status != DependencyStatus::Failed + }); + if pending && !failed.contains(&id) { + self.fail_as_side_effect( + id, + lifecycle::dependency_failed_message(current), + now, + ); + failed.push(id); + to_check.push(id); + } + } + } + failed + } + + /// Apply the failure policy of `failed_job_id`'s workflow, as the database + /// backends do (see [`FailurePolicy`]): + /// + /// - `FailFast` fails the workflow's other `Pending` and `Retrying` jobs, then + /// every job that (transitively) depends on the failed one; + /// - `ContinueOnFailure`, and jobs outside any workflow, fail only the jobs that + /// (transitively) depend on the failed one; + /// - `Manual` changes nothing: dependents keep waiting. + /// + /// Returns the jobs that were failed. + fn apply_workflow_failure(&mut self, failed_job_id: JobId, now: DateTime) -> Vec { + let workflow = self.workflow_of(failed_job_id).map(|w| { + ( + w.failure_policy.clone(), + w.jobs.iter().map(|j| j.id).collect(), + ) + }); + match workflow { + Some((FailurePolicy::Manual, _)) => Vec::new(), + Some((FailurePolicy::FailFast, job_ids)) => { + let job_ids: Vec = job_ids; + let mut failed = Vec::new(); + for id in job_ids { + let unstarted = self.jobs.get(&id).is_some_and(|job| { + matches!(job.status, JobStatus::Pending | JobStatus::Retrying) + }); + if id != failed_job_id && unstarted { + self.fail_as_side_effect( + id, + lifecycle::workflow_failed_message(failed_job_id), + now, + ); + failed.push(id); + } + } + for id in self.fail_dependents(failed_job_id, now) { + if !failed.contains(&id) { + failed.push(id); + } + } + failed + } + Some((FailurePolicy::ContinueOnFailure, _)) | None => { + self.fail_dependents(failed_job_id, now) + } + } + } + + /// Fail the `Pending` and `Retrying` jobs of a `FailFast` batch after one of its + /// jobs failed. Returns the jobs that were failed. + fn apply_batch_failure(&mut self, failed_job_id: JobId, now: DateTime) -> Vec { + let Some(batch_id) = self.jobs.get(&failed_job_id).and_then(|job| job.batch_id) else { + return Vec::new(); + }; + let fail_fast = self + .batches + .get(&batch_id) + .is_some_and(|batch| batch.failure_mode == crate::batch::PartialFailureMode::FailFast); + if !fail_fast { + return Vec::new(); + } + let job_ids = self.batch_jobs.get(&batch_id).cloned().unwrap_or_default(); + let mut failed = Vec::new(); + for id in job_ids { + let unstarted = self + .jobs + .get(&id) + .is_some_and(|job| matches!(job.status, JobStatus::Pending | JobStatus::Retrying)); + if unstarted { + self.fail_as_side_effect(id, lifecycle::batch_failed_message(failed_job_id), now); + failed.push(id); + } + } + failed + } + /// Get the next job to dequeue based on priority and scheduled time fn get_next_job(&self, queue_name: &str, weights: Option<&PriorityWeights>) -> Option { // Like the database backends, a paused queue hands out no jobs. @@ -530,22 +673,29 @@ impl TestStorage { /// .with_max_attempts(3); /// let job_id = queue.enqueue(job).await?; /// -/// // Dequeue and fail the job -/// let job = queue.dequeue("retry_queue").await?.unwrap(); -/// queue.fail_job(job_id, "Temporary network error").await?; -/// -/// // Job should be in retrying state -/// let retrying_job = queue.get_job(job_id).await?.unwrap(); -/// assert_eq!(retrying_job.status, JobStatus::Retrying); -/// assert_eq!(retrying_job.attempts, 1); -/// -/// // After 3 failures, job becomes dead -/// queue.fail_job(job_id, "Still failing").await?; -/// queue.fail_job(job_id, "Final failure").await?; +/// // Each dequeue counts as an attempt. Like a worker, retry the job while it has +/// // attempts left and mark it dead once they are used up. +/// for attempt in 1..=3 { +/// let job = queue.dequeue("retry_queue").await?.unwrap(); +/// assert_eq!(job.attempts, attempt); +/// if job.attempts < job.max_attempts { +/// queue.retry_job(job_id, queue.clock().now()).await?; +/// } else { +/// queue.mark_job_dead(job_id, "Still failing").await?; +/// } +/// } /// /// let dead_job = queue.get_job(job_id).await?.unwrap(); /// assert_eq!(dead_job.status, JobStatus::Dead); /// assert_eq!(dead_job.attempts, 3); +/// +/// // `fail_job` records a terminal failure that is not retried automatically. +/// let job_id = queue +/// .enqueue(Job::new("retry_queue".to_string(), json!({"data": "other"}))) +/// .await?; +/// queue.dequeue("retry_queue").await?.unwrap(); +/// queue.fail_job(job_id, "Permanent error").await?; +/// assert_eq!(queue.get_job(job_id).await?.unwrap().status, JobStatus::Failed); /// # Ok(()) /// # } /// ``` @@ -868,6 +1018,8 @@ impl DatabaseQueue for TestQueue { let now = storage.clock.now(); if let Some(job) = storage.jobs.get_mut(&job_id) { job.started_at = Some(now); + // Like the database backends, every dequeue counts as an attempt. + job.attempts += 1; return Ok(Some(job.clone())); } } @@ -890,6 +1042,8 @@ impl DatabaseQueue for TestQueue { let now = storage.clock.now(); if let Some(job) = storage.jobs.get_mut(&job_id) { job.started_at = Some(now); + // Like the database backends, every dequeue counts as an attempt. + job.attempts += 1; return Ok(Some(job.clone())); } } @@ -965,69 +1119,18 @@ impl DatabaseQueue for TestQueue { let mut storage = self.storage.write().await; storage.check_transition(job_id, crate::queue::JobTransition::Fail)?; - // First increment attempts + // A terminal failure, as on the database backends: no automatic retry, and + // `attempts` is left alone (it counts dequeues). + storage.update_job_status(job_id, JobStatus::Failed)?; + storage.leases.remove(&job_id); + let now = storage.clock.now(); if let Some(job) = storage.jobs.get_mut(&job_id) { - job.attempts += 1; + job.failed_at = Some(now); job.error_message = Some(error_message.to_string()); - } else { - return Err(HammerworkError::JobNotFound { - id: job_id.to_string(), - }); - } - - // Then check if we should retry - let should_retry = if let Some(job) = storage.jobs.get(&job_id) { - job.attempts < job.max_attempts - } else { - return Err(HammerworkError::JobNotFound { - id: job_id.to_string(), - }); - }; - - let now = storage.clock.now(); - - if should_retry { - storage.update_job_status(job_id, JobStatus::Retrying)?; - } else { - storage.update_job_status(job_id, JobStatus::Dead)?; - if let Some(job) = storage.jobs.get_mut(&job_id) { - job.failed_at = Some(now); - } - - // Check if this job belongs to a workflow with fail-fast policy - let other_job_ids: Vec = storage - .workflows - .values() - .find(|workflow| { - workflow.failure_policy == crate::workflow::FailurePolicy::FailFast - && workflow.jobs.iter().any(|j| j.id == job_id) - }) - .map(|workflow| { - workflow - .jobs - .iter() - .filter(|j| j.id != job_id) - .map(|j| j.id) - .collect() - }) - .unwrap_or_default(); - - // Fail all other pending jobs in the workflow - for other_job_id in other_job_ids { - if let Some(j) = storage.jobs.get(&other_job_id) - && (j.status == JobStatus::Pending || j.status == JobStatus::Retrying) - { - storage - .update_job_status(other_job_id, JobStatus::Failed) - .ok(); - if let Some(j) = storage.jobs.get_mut(&other_job_id) { - j.error_message = Some("Workflow failed (fail-fast policy)".to_string()); - j.failed_at = Some(now); - } - } - } } + storage.apply_workflow_failure(job_id, now); + storage.apply_batch_failure(job_id, now); Ok(()) } @@ -2030,7 +2133,18 @@ impl DatabaseQueue for TestQueue { workflow.created_at = storage.clock.now(); let workflow_id = workflow.id; - // Store dependencies + // Store dependencies: those of the workflow's dependency map and, like the + // database backends, each job's own `depends_on`. + for job in &workflow.jobs { + if !job.depends_on.is_empty() { + let deps = workflow.dependencies.entry(job.id).or_default(); + for dep_id in &job.depends_on { + if !deps.contains(dep_id) { + deps.push(*dep_id); + } + } + } + } for (job_id, deps) in &workflow.dependencies { storage.dependencies.insert(*job_id, deps.clone()); @@ -2084,34 +2198,37 @@ impl DatabaseQueue for TestQueue { let storage = self.storage.read().await; if let Some(mut workflow) = storage.workflows.get(&workflow_id).cloned() { - // Update workflow status based on job statuses - let mut completed = 0; - let mut failed = 0; - + // Workflow counters and status from its jobs, as the database backends + // compute them on every terminal transition. + let mut progress = WorkflowProgress::default(); for job_id in workflow.jobs.iter().map(|j| j.id) { if let Some(job) = storage.jobs.get(&job_id) { match &job.status { - JobStatus::Completed => completed += 1, - JobStatus::Failed | JobStatus::Dead | JobStatus::TimedOut => failed += 1, + JobStatus::Completed => progress.completed += 1, + JobStatus::Failed | JobStatus::Dead | JobStatus::TimedOut => { + progress.failed += 1 + } _ => {} } } } - workflow.completed_jobs = completed; - workflow.failed_jobs = failed; - - // Only update status if it's not already set to a terminal state - if workflow.status != WorkflowStatus::Cancelled { - if failed > 0 { - workflow.status = WorkflowStatus::Failed; - workflow.failed_at = Some(storage.clock.now()); - } else if completed == workflow.total_jobs { - workflow.status = WorkflowStatus::Completed; - workflow.completed_at = Some(storage.clock.now()); - } else { - workflow.status = WorkflowStatus::Running; + workflow.completed_jobs = progress.completed; + workflow.failed_jobs = progress.failed; + workflow.status = progress.status( + workflow.total_jobs, + &workflow.failure_policy, + &workflow.status, + ); + let now = storage.clock.now(); + match workflow.status { + WorkflowStatus::Completed => { + workflow.completed_at.get_or_insert(now); + } + WorkflowStatus::Failed => { + workflow.failed_at.get_or_insert(now); } + _ => {} } Ok(Some(workflow)) @@ -2183,50 +2300,8 @@ impl DatabaseQueue for TestQueue { async fn fail_job_dependencies(&self, failed_job_id: JobId) -> Result> { let mut storage = self.storage.write().await; - let mut failed_jobs = Vec::new(); - - // Get the workflow this job belongs to - let workflow = storage - .workflows - .values() - .find(|w| w.jobs.iter().any(|j| j.id == failed_job_id)) - .cloned(); - - if let Some(workflow) = workflow { - // Check failure policy - match workflow.failure_policy { - crate::workflow::FailurePolicy::ContinueOnFailure => { - // Don't fail dependencies, continue with independent jobs - } - crate::workflow::FailurePolicy::Manual => { - // Don't automatically fail dependencies, wait for manual intervention - } - crate::workflow::FailurePolicy::FailFast => { - // Fail all pending jobs in the workflow - let current_time = storage.clock.now(); - for job in &workflow.jobs { - if let Some(j) = storage.jobs.get(&job.id) - && j.status == JobStatus::Pending - { - storage.update_job_status(job.id, JobStatus::Failed).ok(); - if let Some(j) = storage.jobs.get_mut(&job.id) { - j.error_message = Some("Dependency failed".to_string()); - j.failed_at = Some(current_time); - // As in the database backends: a job still waiting on - // its dependencies records that they failed. - if j.dependency_status == crate::workflow::DependencyStatus::Waiting - { - j.dependency_status = crate::workflow::DependencyStatus::Failed; - } - } - failed_jobs.push(job.id); - } - } - } - } - } - - Ok(failed_jobs) + let now = storage.clock.now(); + Ok(storage.apply_workflow_failure(failed_job_id, now)) } async fn get_workflow_jobs(&self, workflow_id: WorkflowId) -> Result> { @@ -2809,14 +2884,16 @@ mod tests { let job = Job::new("test_queue".to_string(), json!({"test": true})).with_max_attempts(3); let job_id = queue.enqueue(job).await.unwrap(); - // Dequeue and fail the job - let _dequeued = queue.dequeue("test_queue").await.unwrap(); + // Dequeue and fail the job: a terminal failure, not retried automatically. + let dequeued = queue.dequeue("test_queue").await.unwrap().unwrap(); + assert_eq!(dequeued.attempts, 1); queue.fail_job(job_id, "Test error").await.unwrap(); - // Job should be in retrying status let job = queue.get_job(job_id).await.unwrap().unwrap(); - assert_eq!(job.status, JobStatus::Retrying); + assert_eq!(job.status, JobStatus::Failed); assert_eq!(job.attempts, 1); + assert_eq!(job.error_message.as_deref(), Some("Test error")); + assert!(job.failed_at.is_some()); // Retry the job let retry_at = queue.clock().now() + chrono::Duration::minutes(5); @@ -3019,12 +3096,9 @@ mod tests { } } - // Fail one job + // One job runs out of attempts and dies, as a worker would record it. if let Some(job) = queue.dequeue("stats_queue").await.unwrap() { - queue.fail_job(job.id, "Test failure").await.unwrap(); - // Exhaust retries - queue.fail_job(job.id, "Test failure").await.unwrap(); - queue.fail_job(job.id, "Test failure").await.unwrap(); + queue.mark_job_dead(job.id, "Test failure").await.unwrap(); } // Get stats diff --git a/src/workflow.rs b/src/workflow.rs index 81ff3ab..366e738 100644 --- a/src/workflow.rs +++ b/src/workflow.rs @@ -92,14 +92,25 @@ impl WorkflowStatus { } /// Policy for handling failures in workflows. +/// +/// It applies when a job of the workflow fails terminally (`Failed`, `Dead` or +/// `TimedOut`), not when a failed run is retried. See +/// [`DatabaseQueue::fail_job_dependencies`](crate::queue::DatabaseQueue::fail_job_dependencies). #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] pub enum FailurePolicy { - /// Stop the entire workflow when any job fails + /// Stop the entire workflow when any job fails: its `Pending` and `Retrying` jobs + /// (and any job depending on the failed one) become `Failed`, and the workflow + /// `Failed`. Jobs already running finish their run. #[default] FailFast, - /// Continue executing jobs that don't depend on failed jobs + /// Continue executing jobs that don't depend on failed jobs. The jobs that + /// (transitively) depend on a failed job become `Failed`; the workflow becomes + /// `Failed` once all its jobs have finished. ContinueOnFailure, - /// Require manual intervention to decide how to handle failures + /// Require manual intervention to decide how to handle failures. Nothing is failed + /// automatically: the dependents of a failed job keep waiting, and the workflow + /// stays `Running`, until an operator retries the failed job (its completion then + /// releases them) or cancels the workflow. Manual, } diff --git a/tests/queue_api_tests.rs b/tests/queue_api_tests.rs index 918d98f..f2e840d 100644 --- a/tests/queue_api_tests.rs +++ b/tests/queue_api_tests.rs @@ -446,9 +446,6 @@ async fn test_queue() -> Arc { Arc::new(hammerwork::queue::test::TestQueue::new()) } -// `statistics_queries` is not run on `TestQueue`: its `fail_job` retries the job (or -// marks it dead) instead of moving it to the terminal `Failed` status the trait -// documents and the database backends implement. #[cfg(feature = "test")] backend_tests!( test_queue_tests, @@ -456,6 +453,7 @@ backend_tests!( allow(unused_attributes), [ dead_job_management, + statistics_queries, recurring_jobs, throttle_configuration, pause_information, diff --git a/tests/test_queue_tests.rs b/tests/test_queue_tests.rs index ec0e105..b73db07 100644 --- a/tests/test_queue_tests.rs +++ b/tests/test_queue_tests.rs @@ -186,17 +186,20 @@ async fn test_job_retry_mechanism() { let job = Job::new("retry_queue".to_string(), json!({"retry": "test"})).with_max_attempts(3); let job_id = queue.enqueue(job).await.unwrap(); - // First attempt - dequeue and fail - let _dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); - queue.fail_job(job_id, "First failure").await.unwrap(); + // Each dequeue counts as an attempt. Like a worker, retry a failed run while the + // job has attempts left and mark it dead once they are used up. - let job = queue.get_job(job_id).await.unwrap().unwrap(); - assert_eq!(job.status, JobStatus::Retrying); - assert_eq!(job.attempts, 1); + // First attempt - dequeue and fail + let dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); + assert_eq!(dequeued.attempts, 1); + assert!(dequeued.attempts < dequeued.max_attempts); // Schedule retry let retry_at = clock.now() + Duration::minutes(5); queue.retry_job(job_id, retry_at).await.unwrap(); + let job = queue.get_job(job_id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Pending); + assert_eq!(job.attempts, 1); // Job should not be available immediately assert!(queue.dequeue("retry_queue").await.unwrap().is_none()); @@ -207,19 +210,18 @@ async fn test_job_retry_mechanism() { // Second attempt - fail again let dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, job_id); - queue.fail_job(job_id, "Second failure").await.unwrap(); - - let job = queue.get_job(job_id).await.unwrap().unwrap(); - assert_eq!(job.attempts, 2); - - // Third attempt - fail again (should mark as dead) + assert_eq!(dequeued.attempts, 2); queue.retry_job(job_id, clock.now()).await.unwrap(); - queue.dequeue("retry_queue").await.unwrap(); - queue.fail_job(job_id, "Third failure").await.unwrap(); + + // Third attempt - the last one: mark as dead + let dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); + assert_eq!(dequeued.attempts, dequeued.max_attempts); + queue.mark_job_dead(job_id, "Third failure").await.unwrap(); let job = queue.get_job(job_id).await.unwrap().unwrap(); assert_eq!(job.status, JobStatus::Dead); assert_eq!(job.attempts, 3); + assert_eq!(job.error_message.as_deref(), Some("Third failure")); assert!(job.failed_at.is_some()); } @@ -256,10 +258,7 @@ async fn test_batch_operations() { for i in 0..4 { if let Some(job) = queue.dequeue("batch_queue").await.unwrap() { if i == 2 { - // Fail the third job - queue.fail_job(job.id, "Planned failure").await.unwrap(); - // Exhaust retries - queue.fail_job(job.id, "Planned failure").await.unwrap(); + // Fail the third job (a terminal failure) queue.fail_job(job.id, "Planned failure").await.unwrap(); } else { queue.complete_job(job.id).await.unwrap(); @@ -301,13 +300,14 @@ async fn test_batch_fail_fast() { // Fail second job if let Some(job) = queue.dequeue("failfast_queue").await.unwrap() { queue.fail_job(job.id, "Failure").await.unwrap(); - queue.fail_job(job.id, "Failure").await.unwrap(); - queue.fail_job(job.id, "Failure").await.unwrap(); } - // Check batch status - should be failed even though third job is pending + // The batch fails fast: its third job is failed without running. let status = queue.get_batch_status(batch_id).await.unwrap(); assert_eq!(status.status, BatchStatus::Failed); + assert_eq!(status.completed_jobs, 1); + assert_eq!(status.failed_jobs, 2); + assert!(queue.dequeue("failfast_queue").await.unwrap().is_none()); } #[tokio::test] @@ -393,18 +393,16 @@ async fn test_workflow_failure_policies() { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); - // Fail the first job + // Fail the first job (a terminal failure) let dequeued = queue.dequeue("failfast_wf").await.unwrap().unwrap(); queue.fail_job(dequeued.id, "Test failure").await.unwrap(); - queue.fail_job(dequeued.id, "Test failure").await.unwrap(); - queue.fail_job(dequeued.id, "Test failure").await.unwrap(); // Other jobs should have been failed due to fail-fast policy let failed_job_id = dequeued.id; - // Check that the failed job is dead + // Check that the failed job is failed let failed_job_status = queue.get_job(failed_job_id).await.unwrap().unwrap(); - assert_eq!(failed_job_status.status, JobStatus::Dead); + assert_eq!(failed_job_status.status, JobStatus::Failed); // Check that all other jobs are failed for job in [&job1, &job2, &job3] { @@ -682,10 +680,8 @@ async fn test_queue_statistics() { if i < 3 { queue.complete_job(job.id).await.unwrap(); } else { - // Fail the last 2 - queue.fail_job(job.id, "Test failure").await.unwrap(); - queue.fail_job(job.id, "Test failure").await.unwrap(); - queue.fail_job(job.id, "Test failure").await.unwrap(); + // The last 2 run out of attempts and die, as a worker records it + queue.mark_job_dead(job.id, "Test failure").await.unwrap(); } } } diff --git a/tests/workflow_failure_policy_tests.rs b/tests/workflow_failure_policy_tests.rs new file mode 100644 index 0000000..a6f5c52 --- /dev/null +++ b/tests/workflow_failure_policy_tests.rs @@ -0,0 +1,440 @@ +//! How a job's terminal failure is applied, on both backends and on `TestQueue`: +//! `fail_job` is terminal, and a workflow's `FailurePolicy` decides what happens to +//! the other jobs (`fail_job`, a worker's `finish_job_run` and the explicit +//! `fail_job_dependencies` helper all apply it the same way). + +#![cfg(any(feature = "postgres", feature = "mysql", feature = "test"))] + +mod test_utils; + +use chrono::Utc; +use hammerwork::{ + Job, JobId, JobStatus, + queue::{DatabaseQueue, JobOutcome}, + workflow::{FailurePolicy, JobGroup, WorkflowId, WorkflowStatus}, +}; +use serde_json::json; +use std::sync::Arc; + +/// A workflow `a -> b -> c` plus an independent job `x`. Each job has its own queue, +/// so the scenarios dequeue exactly the job they mean. +struct Graph { + workflow: WorkflowId, + queue: String, + a: JobId, + b: JobId, + c: JobId, + x: JobId, +} + +impl Graph { + fn queue_of(&self, step: &str) -> String { + format!("{}_{step}", self.queue) + } + + fn ids(&self) -> [JobId; 4] { + [self.a, self.b, self.c, self.x] + } +} + +async fn enqueue_graph(queue: &Arc, policy: FailurePolicy) -> Graph +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let name = test_utils::unique_queue("failure_policy"); + let job = |step: &str| Job::new(format!("{name}_{step}"), json!({ "step": step })); + let a = job("a"); + let x = job("x"); + let b = job("b").depends_on(&a.id); + let c = job("c").depends_on(&b.id); + let (a_id, b_id, c_id, x_id) = (a.id, b.id, c.id, x.id); + let workflow = queue + .enqueue_workflow( + JobGroup::new(format!("policy-{}", policy.as_str())) + .with_failure_policy(policy) + .add_job(a) + .add_job(x) + .add_job(b) + .add_job(c), + ) + .await + .unwrap(); + Graph { + workflow, + queue: name, + a: a_id, + b: b_id, + c: c_id, + x: x_id, + } +} + +async fn status_of(queue: &Arc, id: JobId) -> JobStatus +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + queue.get_job(id).await.unwrap().expect("job exists").status +} + +async fn workflow_status(queue: &Arc, graph: &Graph) -> WorkflowStatus +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + queue + .get_workflow_status(graph.workflow) + .await + .unwrap() + .expect("workflow exists") + .status +} + +/// Dequeue the job of `step`, asserting it is `expected`. +async fn run(queue: &Arc, graph: &Graph, step: &str, expected: JobId) -> Job +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let job = queue + .dequeue(&graph.queue_of(step)) + .await + .unwrap() + .unwrap_or_else(|| panic!("job {step} is runnable")); + assert_eq!(job.id, expected); + job +} + +/// Whether `step`'s queue has a runnable job. +async fn runnable(queue: &Arc, graph: &Graph, step: &str) -> bool +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + !queue + .get_ready_jobs(&graph.queue_of(step), 10) + .await + .unwrap() + .is_empty() +} + +/// A time that is already due on every backend (`TestQueue`'s mock clock starts at +/// its creation and does not advance on its own). +fn past() -> chrono::DateTime { + Utc::now() - chrono::Duration::hours(1) +} + +fn sorted(mut ids: Vec) -> Vec { + ids.sort(); + ids +} + +async fn cleanup(queue: &Arc, graph: &Graph) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + for id in graph.ids() { + queue.delete_job(id).await.unwrap(); + } +} + +/// How the failure of `a` is recorded. +#[derive(Clone, Copy, Debug)] +enum Trigger { + /// `fail_job`, the manual terminal failure. + FailJob, + /// A worker's last attempt failing: `finish_job_run` with a `Dead` outcome. + WorkerDead, + /// `fail_job_dependencies` called directly, while `a` is still running. + Explicit, +} + +/// Fail `a` with `trigger`. Returns the jobs the queue reports as failed with it, +/// when the trigger reports them. +async fn fail_a(queue: &Arc, graph: &Graph, trigger: Trigger) -> Option> +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let run_a = run(queue, graph, "a", graph.a).await; + match trigger { + Trigger::FailJob => { + queue.fail_job(graph.a, "a failed").await.unwrap(); + assert_eq!(status_of(queue, graph.a).await, JobStatus::Failed); + None + } + Trigger::WorkerDead => { + let outcome = JobOutcome::Dead { + error: "a failed".to_string(), + }; + let recorded = queue + .finish_job_run(&run_a, outcome) + .await + .unwrap() + .expect("the run is current"); + assert_eq!(recorded.status, JobStatus::Dead); + assert_eq!(status_of(queue, graph.a).await, JobStatus::Dead); + Some(recorded.cancelled) + } + Trigger::Explicit => { + let failed = queue.fail_job_dependencies(graph.a).await.unwrap(); + assert_eq!(status_of(queue, graph.a).await, JobStatus::Running); + Some(failed) + } + } +} + +/// `fail_job` is a terminal `Failed`: no automatic retry, `attempts` unchanged, and +/// `retry_job` re-runs it. +async fn fail_job_is_terminal(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("fail_job_terminal"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({})).with_max_attempts(3)) + .await + .unwrap(); + let job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + assert_eq!(job.attempts, 1); + queue.fail_job(id, "permanent").await.unwrap(); + + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Failed); + assert_eq!(job.attempts, 1); + assert_eq!(job.error_message.as_deref(), Some("permanent")); + assert!(job.failed_at.is_some()); + assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!( + queue.fail_job(id, "again").await.is_err(), + "a Failed job cannot fail again" + ); + + queue.retry_job(id, past()).await.unwrap(); + let job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + assert_eq!(job.id, id); + assert_eq!(job.attempts, 2); + queue.delete_job(id).await.unwrap(); +} + +/// `FailFast`: the whole workflow stops. +async fn fail_fast(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + for trigger in [Trigger::FailJob, Trigger::WorkerDead, Trigger::Explicit] { + let graph = enqueue_graph(&queue, FailurePolicy::FailFast).await; + let reported = fail_a(&queue, &graph, trigger).await; + if let Some(reported) = reported { + assert_eq!( + sorted(reported), + sorted(vec![graph.b, graph.c, graph.x]), + "{trigger:?}" + ); + } + for id in [graph.b, graph.c, graph.x] { + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Failed, "{trigger:?}"); + assert!(job.error_message.is_some(), "{trigger:?}"); + } + for step in ["b", "c", "x"] { + assert!(!runnable(&queue, &graph, step).await, "{trigger:?} {step}"); + } + assert_eq!( + workflow_status(&queue, &graph).await, + WorkflowStatus::Failed, + "{trigger:?}" + ); + // Applying the failure again changes nothing. + assert!( + queue + .fail_job_dependencies(graph.a) + .await + .unwrap() + .is_empty(), + "{trigger:?}" + ); + cleanup(&queue, &graph).await; + } +} + +/// `ContinueOnFailure`: the failed job's dependents cannot run, the independent +/// branch continues, and the workflow fails once everything has finished. +async fn continue_on_failure(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + for trigger in [Trigger::FailJob, Trigger::WorkerDead, Trigger::Explicit] { + let graph = enqueue_graph(&queue, FailurePolicy::ContinueOnFailure).await; + let reported = fail_a(&queue, &graph, trigger).await; + if let Some(reported) = reported { + assert_eq!( + sorted(reported), + sorted(vec![graph.b, graph.c]), + "{trigger:?}" + ); + } + for id in [graph.b, graph.c] { + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Failed, "{trigger:?}"); + assert!(job.dependencies_failed(), "{trigger:?}"); + } + assert_eq!(status_of(&queue, graph.x).await, JobStatus::Pending); + assert_eq!( + workflow_status(&queue, &graph).await, + WorkflowStatus::Running, + "{trigger:?}" + ); + + // The independent branch still runs. + run(&queue, &graph, "x", graph.x).await; + if matches!(trigger, Trigger::Explicit) { + // `a` is still running in this scenario; finish it. + queue.fail_job(graph.a, "a failed").await.unwrap(); + } + queue.complete_job(graph.x).await.unwrap(); + assert_eq!(status_of(&queue, graph.x).await, JobStatus::Completed); + assert_eq!( + workflow_status(&queue, &graph).await, + WorkflowStatus::Failed, + "{trigger:?}: every job finished, one failed" + ); + cleanup(&queue, &graph).await; + } +} + +/// `Manual`: nothing is failed automatically. The dependents wait until an operator +/// re-runs the failed job, whose completion releases them. +async fn manual(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + for trigger in [Trigger::FailJob, Trigger::WorkerDead, Trigger::Explicit] { + let graph = enqueue_graph(&queue, FailurePolicy::Manual).await; + let reported = fail_a(&queue, &graph, trigger).await; + if let Some(reported) = reported { + assert!(reported.is_empty(), "{trigger:?}: {reported:?}"); + } + for id in [graph.b, graph.c, graph.x] { + assert_eq!( + status_of(&queue, id).await, + JobStatus::Pending, + "{trigger:?}" + ); + } + for id in [graph.b, graph.c] { + let job = queue.get_job(id).await.unwrap().unwrap(); + assert!(!job.dependencies_failed(), "{trigger:?}"); + } + assert!(!runnable(&queue, &graph, "b").await, "{trigger:?}"); + assert!(runnable(&queue, &graph, "x").await, "{trigger:?}"); + assert_eq!( + workflow_status(&queue, &graph).await, + WorkflowStatus::Running, + "{trigger:?}" + ); + + // The operator re-runs `a`; its completion releases `b`. + match trigger { + Trigger::FailJob => queue.retry_job(graph.a, past()).await.unwrap(), + Trigger::WorkerDead => queue.retry_dead_job(graph.a).await.unwrap(), + // `a` is still running in this scenario. + Trigger::Explicit => {} + } + if !matches!(trigger, Trigger::Explicit) { + run(&queue, &graph, "a", graph.a).await; + } + queue.complete_job(graph.a).await.unwrap(); + queue.resolve_job_dependencies(graph.a).await.unwrap(); + run(&queue, &graph, "b", graph.b).await; + assert_eq!( + workflow_status(&queue, &graph).await, + WorkflowStatus::Running, + "{trigger:?}" + ); + cleanup(&queue, &graph).await; + } +} + +/// Jobs that depend on a failed job outside any workflow can no longer run. +async fn dependents_outside_workflows(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("no_workflow"); + let parent = Job::new(queue_name.clone(), json!({ "step": "parent" })); + let child = Job::new(format!("{queue_name}_child"), json!({})).depends_on(&parent.id); + let (parent_id, child_id) = (parent.id, child.id); + // A one-job group without a policy would still be a workflow; enqueue both jobs + // as plain jobs instead. + queue.enqueue(parent).await.unwrap(); + queue.enqueue(child).await.unwrap(); + + queue.dequeue(&queue_name).await.unwrap().unwrap(); + let failed = queue.fail_job_dependencies(parent_id).await.unwrap(); + assert_eq!(failed, [child_id]); + let child = queue.get_job(child_id).await.unwrap().unwrap(); + assert_eq!(child.status, JobStatus::Failed); + assert!(child.dependencies_failed()); + for id in [parent_id, child_id] { + queue.delete_job(id).await.unwrap(); + } +} + +/// One `#[tokio::test]` per scenario, run against the queue returned by `$setup`. +macro_rules! backend_tests { + ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { + mod $module { + use super::*; + $( + #[tokio::test] + #[$ignore] + async fn $scenario() { + super::$scenario($setup().await).await; + } + )* + } + }; +} + +#[cfg(feature = "postgres")] +backend_tests!( + postgres_tests, + test_utils::setup_postgres_queue, + ignore = "requires PostgreSQL: DATABASE_URL", + [ + fail_job_is_terminal, + fail_fast, + continue_on_failure, + manual, + dependents_outside_workflows, + ] +); + +#[cfg(feature = "mysql")] +backend_tests!( + mysql_tests, + test_utils::setup_mysql_queue, + ignore = "requires MySQL: MYSQL_DATABASE_URL", + [ + fail_job_is_terminal, + fail_fast, + continue_on_failure, + manual, + dependents_outside_workflows, + ] +); + +#[cfg(feature = "test")] +async fn test_queue() -> Arc { + Arc::new(hammerwork::queue::test::TestQueue::new()) +} + +#[cfg(feature = "test")] +backend_tests!( + test_queue_tests, + test_queue, + allow(unused_attributes), + [ + fail_job_is_terminal, + fail_fast, + continue_on_failure, + manual, + dependents_outside_workflows, + ] +);