Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 23 additions & 25 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand All @@ -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);
Expand All @@ -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
Expand Down Expand Up @@ -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();
}
```
Expand Down
12 changes: 10 additions & 2 deletions docs/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,15 +299,23 @@ 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
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
Expand Down
17 changes: 9 additions & 8 deletions examples/test_queue_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,10 @@ async fn error_handling_example() -> Result<(), Box<dyn std::error::Error>> {
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();
Expand All @@ -519,9 +522,6 @@ async fn error_handling_example() -> Result<(), Box<dyn std::error::Error>> {
}
}

// 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
Expand All @@ -532,7 +532,8 @@ async fn error_handling_example() -> Result<(), Box<dyn std::error::Error>> {
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();
Expand All @@ -546,13 +547,13 @@ async fn error_handling_example() -> Result<(), Box<dyn std::error::Error>> {
}

// 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();
Expand Down
29 changes: 25 additions & 4 deletions src/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<Job>>;

/// 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<Vec<JobId>>;

/// Get all jobs in a workflow.
Expand Down
76 changes: 58 additions & 18 deletions src/queue/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1793,11 +1793,7 @@ impl DatabaseQueue for crate::queue::JobQueue<MySql> {
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
Expand Down Expand Up @@ -2860,19 +2856,8 @@ impl crate::queue::JobQueue<MySql> {
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 {
Expand All @@ -2885,6 +2870,61 @@ impl crate::queue::JobQueue<MySql> {
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<Utc>,
) -> Result<Vec<JobId>> {
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<Vec<JobId>> {
let workflow_id: Option<Option<String>> =
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(
Expand Down
Loading
Loading