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
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `WorkerPool::from_config` creates `pool_size` workers and configures autoscaling from `WorkerConfig`
- `WebhookManager::from_config` and `StreamManager::from_config` build managers from the `webhooks` and `streaming` sections
- `ArchiveConfig::archival_policy` / `archival_config`, `RateLimitingConfig::throttle_for`, `WorkerConfig::autoscale_config`, `DatabaseConfig::connection_timeout`
- **🩺 Job leases and stale job recovery** ([#19](https://github.com/CodingAnarchy/hammerwork/issues/19) C2): jobs left `Running` by a crashed or killed worker are no longer stuck forever
- Migration `015_add_job_leases` adds `last_heartbeat_at` and `lease_expires_at` to `hammerwork_jobs` (PostgreSQL and MySQL). Run `cargo hammerwork migration run` before upgrading workers.
- Workers heartbeat running jobs every third of their lease (`Worker::with_lease_duration`, default 5 minutes)
- `DatabaseQueue::heartbeat_job` and `DatabaseQueue::requeue_stale_jobs(older_than)` (returns `StaleJobRecovery`). Expired jobs go back to `Pending`, or to `Dead` when out of attempts. Safe to run concurrently (`FOR UPDATE SKIP LOCKED` plus a `status = 'Running'` guard). Both methods have default implementations, so custom `DatabaseQueue` implementations keep compiling.
- `WorkerPool` runs the reaper every 60 seconds (`with_stale_job_reaper`, `without_stale_job_reaper`)
- CLI: `cargo hammerwork job requeue-stale [--older-than-secs N]`
- `Worker::with_shutdown_grace_period` (default 30 seconds) and `RetryStrategy::validate`

### Changed
- **Breaking:** `RetryStrategy::Custom` now holds an `Arc<dyn Fn(u32) -> Duration + Send + Sync>` (`retry::CustomRetryFn`) instead of a `Box`, so it can be cloned. Code using `RetryStrategy::custom(..)` is unaffected; code constructing the variant directly must switch `Box::new` to `Arc::new`. Two `Custom` strategies now compare equal when they share the same function.
- `WorkerPool::shutdown` now waits until every worker has stopped (bounded by each worker's shutdown grace period) instead of returning as soon as the signal is sent
- **CI**: replaced the disabled `Integration Tests` workflow with `.github/workflows/ci.yml`: rustfmt, clippy (`--all-targets --all-features -D warnings`), unit tests, PostgreSQL 16 and MySQL 8 integration jobs, and a `cargo audit` job. Runs on pushes and pull requests to `master` and on demand (#7).
- `DatabaseConfig::create_tables` is deprecated; tables are created by migrations (`auto_migrate`)
- AWS KMS clients (`aws-kms` feature) now load config with `BehaviorVersion::latest()` instead of the deprecated `v2025_01_17`, matching the Kinesis client. This picks up the SDK's newer defaults, including HTTP(S) proxy settings from the environment.
Expand Down Expand Up @@ -45,6 +54,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- MySQL dequeues and the PostgreSQL weighted dequeue ignored `dependency_status` and could run a job before its dependencies completed.
- MySQL dequeues now use `FOR UPDATE SKIP LOCKED` (MySQL 8.0+), so concurrent workers skip rows being claimed instead of blocking on them.
- MySQL job claims run at READ COMMITTED and retry when InnoDB aborts them as deadlock victims (error 1213), which concurrent workers otherwise hit intermittently.
- **Worker robustness** ([#17](https://github.com/CodingAnarchy/hammerwork/issues/17), [#19](https://github.com/CodingAnarchy/hammerwork/issues/19))
- Errors from completing, failing or retrying a job (and from dequeuing) are logged and followed by an exponential backoff that honours `ThrottleConfig::backoff_on_error`, instead of being discarded with the worker spinning hot (H1)
- A panicking job handler no longer kills the worker: the panic fails the job with `Job handler panicked: <message>` and goes through the normal retry / dead path (H2)
- `WorkerPool` supervises its workers: a worker that dies is logged and restarted instead of the pool returning on the first failure and detaching the rest (H3)
- `WorkerPool::shutdown` is graceful: in-flight jobs finish (up to the grace period) and record their outcome before workers stop, and `shutdown` waits for them. Dropping the pool also shuts it down. Previously shutdown cancelled the running handler and left the job `Running` (C2)
- Huge retry delays no longer panic in `chrono::Duration::from_std(..).unwrap()`; retry delays are clamped to 365 days (H4)
- `RetryStrategy::calculate_delay` no longer panics on overflow (exponential from attempt ~65, Fibonacci ~94, huge linear values) or on a NaN / negative multiplier; it saturates and clamps to `max_delay`. Jitter with an invalid factor no longer panics (H5)
- Cloning a `RetryStrategy::Custom` (e.g. through `Worker::clone` for autoscaling) no longer panics (H6)
- Webhook delivery no longer panics when truncating a response body in the middle of a multi-byte UTF-8 character (H7)
- The autoscaler no longer panics on a zero `evaluation_window`
- **Archiving ([#14](https://github.com/CodingAnarchy/hammerwork/issues/14))**, PostgreSQL and MySQL:
- `archive_jobs` now moves jobs: the archive insert and the delete from `hammerwork_jobs` run in one transaction, and candidates are selected with `FOR UPDATE SKIP LOCKED` so concurrent archivers do not collide. Previously the row stayed in `hammerwork_jobs` with its old status.
- `get_job` falls back to the archive table and returns archived jobs with `JobStatus::Archived` (previously it returned the stale pre-archive row)
Expand Down
8 changes: 8 additions & 0 deletions cargo-hammerwork/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,15 @@ cargo hammerwork job enqueue --queue QUEUE --payload JSON [OPTIONS]
cargo hammerwork job retry <JOB_ID> # Retry a failed job
cargo hammerwork job cancel <JOB_ID> # Cancel a pending job
cargo hammerwork job delete <JOB_ID> # Remove a job
cargo hammerwork job requeue-stale [--older-than-secs N] # Reclaim jobs stuck in Running
```

`job requeue-stale` moves `Running` jobs whose lease has expired (their worker crashed
or was killed) back to `Pending`, or to `Dead` when they have no attempts left. Jobs
that never recorded a lease are reclaimed once they started more than
`--older-than-secs` ago (default 3600). It is safe to run alongside workers, and needs
migration `015_add_job_leases`.

### Worker Management Commands

```bash
Expand Down Expand Up @@ -218,6 +225,7 @@ cargo-hammerwork/
- List jobs with advanced filtering (queue, status, priority, time-based)
- Job enqueueing with priority, delays, timeouts, and retry configuration
- Bulk operations (retry, cancel, purge) with safety confirmations
- Stale job recovery (`requeue-stale`) for jobs orphaned by crashed workers
- Detailed job inspection with full lifecycle tracking

#### Queue Management
Expand Down
98 changes: 98 additions & 0 deletions cargo-hammerwork/src/commands/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,26 @@ pub enum JobCommand {
#[arg(long, help = "Confirm the purge operation")]
confirm: bool,
},
#[command(
about = "Reclaim jobs stuck in Running after a worker crashed",
long_about = "Reclaim jobs left in Running by workers that crashed or were killed.\n\n\
A Running job is stale when its lease (renewed by worker heartbeats) has \
expired, or, if it never recorded a lease, when it started more than \
--older-than-secs ago. Stale jobs with attempts left go back to Pending; \
the rest are marked Dead. Safe to run while workers and other reapers are \
running. Requires migration 015_add_job_leases.\n\n\
Example: cargo hammerwork job requeue-stale --older-than-secs 3600"
)]
RequeueStale {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[arg(
long,
default_value_t = 3600,
help = "For jobs without a lease: reclaim if started more than N seconds ago"
)]
older_than_secs: u64,
},
}

impl JobCommand {
Expand Down Expand Up @@ -180,6 +200,11 @@ impl JobCommand {
)
.await?;
}
JobCommand::RequeueStale {
older_than_secs, ..
} => {
requeue_stale_jobs(pool, *older_than_secs).await?;
}
}
Ok(())
}
Expand All @@ -192,6 +217,7 @@ impl JobCommand {
JobCommand::Retry { database_url, .. } => database_url,
JobCommand::Cancel { database_url, .. } => database_url,
JobCommand::Purge { database_url, .. } => database_url,
JobCommand::RequeueStale { database_url, .. } => database_url,
};

url_option
Expand Down Expand Up @@ -572,6 +598,32 @@ async fn enqueue_job(
Ok(())
}

async fn requeue_stale_jobs(pool: DatabasePool, older_than_secs: u64) -> Result<()> {
let older_than = std::time::Duration::from_secs(older_than_secs);
let recovery = match pool.create_job_queue() {
crate::utils::database::JobQueueWrapper::Postgres(queue) => {
queue.requeue_stale_jobs(older_than).await?
}
crate::utils::database::JobQueueWrapper::MySQL(queue) => {
queue.requeue_stale_jobs(older_than).await?
}
};

for id in &recovery.requeued {
info!("↩️ Requeued stale job {}", id);
}
for id in &recovery.dead {
info!("💀 Marked stale job {} dead (no attempts left)", id);
}
info!(
"✅ Reclaimed {} stale jobs ({} requeued, {} dead)",
recovery.total(),
recovery.requeued.len(),
recovery.dead.len()
);
Ok(())
}

async fn retry_jobs(
pool: DatabasePool,
job_id: Option<String>,
Expand Down Expand Up @@ -786,6 +838,52 @@ async fn purge_jobs(
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;

#[derive(Parser)]
struct TestCli {
#[command(subcommand)]
command: JobCommand,
}

#[test]
fn test_requeue_stale_parses_with_default_threshold() {
let cli = TestCli::try_parse_from(["test", "requeue-stale"]).unwrap();
match cli.command {
JobCommand::RequeueStale {
database_url,
older_than_secs,
} => {
assert!(database_url.is_none());
assert_eq!(older_than_secs, 3600);
}
_ => panic!("expected RequeueStale"),
}

let cli = TestCli::try_parse_from([
"test",
"requeue-stale",
"--older-than-secs",
"120",
"-u",
"postgres://localhost/db",
])
.unwrap();
match cli.command {
JobCommand::RequeueStale {
database_url,
older_than_secs,
} => {
assert_eq!(database_url.as_deref(), Some("postgres://localhost/db"));
assert_eq!(older_than_secs, 120);
}
_ => panic!("expected RequeueStale"),
}

assert!(
TestCli::try_parse_from(["test", "requeue-stale", "--older-than-secs", "-5"]).is_err()
);
}

#[test]
fn test_list_jobs_query_postgres_binds_typed_params() {
Expand Down
5 changes: 5 additions & 0 deletions docs/migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ Migrations are organized chronologically and represent the evolution of Hammerwo
8. **008_add_result_config** - Add result configuration storage fields
9. **009_add_tracing** - Add distributed tracing and correlation fields
10. **010_add_archival** - Add job archival support and archive table
11. **011_add_encryption** - Add encryption fields and key storage
12. **012_optimize_dependencies** - Optimize dependency lookups
13. **013_add_key_audit** - Add encryption key audit table
14. **014_add_queue_pause** - Add queue pause state table
15. **015_add_job_leases** - Add `last_heartbeat_at` and `lease_expires_at` for job leases and stale job recovery

## Running Migrations

Expand Down
70 changes: 70 additions & 0 deletions docs/worker-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,76 @@ pool.start().await?;
pool.shutdown().await?;
```

`start` spawns every worker and a supervisor, then waits until the pool shuts down.
The workers run in their own tasks, so you can drop the `start` future (for example
in a `tokio::select!` on a shutdown signal) and then call `shutdown`:

```rust
tokio::select! {
result = pool.start() => result?,
_ = tokio::signal::ctrl_c() => pool.shutdown().await?,
}
```

Dropping the pool also shuts its workers down gracefully.

### Supervision

If a worker task stops unexpectedly (a bug that panics outside a job handler, for
example), the pool logs it and restarts the worker after one second. A panic inside
a job handler never reaches this point: the worker catches it and fails the job
with the error `Job handler panicked: <message>`, which then goes through the
normal retry / dead-letter path.

Errors in the worker loop itself (the database failing while a job is dequeued or
its outcome recorded) are logged, and the worker backs off exponentially, starting
at the throttle's `backoff_on_error` (or the poll interval, at least 100ms) and
capped at 60 seconds.

### Graceful Shutdown

On `shutdown`, idle workers stop immediately. A worker in the middle of a job stops
polling but lets the job finish and record its outcome, for up to its shutdown grace
period (30 seconds by default). Only then is the handler cancelled. `shutdown`
returns once every worker has stopped.

```rust
let worker = Worker::new(queue.clone(), "reports".to_string(), handler)
.with_shutdown_grace_period(Duration::from_secs(120));
```

### Job Leases and Stale Job Recovery

A worker that crashes, is OOM-killed or loses its pod leaves its job in `Running`.
Hammerwork recovers these jobs with leases (requires migration `015_add_job_leases`):

- While a handler runs, the worker records a heartbeat and extends the job's lease
every third of its lease duration (5 minutes by default). Jobs that finish sooner
never write a heartbeat.
- `DatabaseQueue::requeue_stale_jobs(older_than)` reclaims `Running` jobs whose
lease has expired. Jobs that never recorded a lease (they had not reached their
first heartbeat, or were started by an older Hammerwork version) count as stale
once they started more than `older_than` ago.
- A reclaimed job goes back to `Pending` and runs again immediately. The interrupted
run already counted as an attempt; a job with no attempts left is moved to `Dead`.
- Every `WorkerPool` runs this reaper every 60 seconds, with `older_than` set to the
longest lease of its workers. Several pools or processes can reap at once safely.

```rust
let worker = Worker::new(queue.clone(), "video".to_string(), handler)
.with_lease_duration(Duration::from_secs(60)); // detect crashed workers within ~1 min

let mut pool = WorkerPool::new()
// Reap every 30s; jobs without a lease are stale after 10 minutes
.with_stale_job_reaper(Duration::from_secs(30), Duration::from_secs(600));
// Or turn it off and run `cargo hammerwork job requeue-stale` from a scheduler:
// let mut pool = WorkerPool::new().without_stale_job_reaper();
```

If a lease expires while the handler is still running (for example after a long
stop-the-world pause), the job can be reclaimed and run again elsewhere, so handlers
should be idempotent. The worker logs a warning when it notices it lost a lease.

### Mixed Configuration Pools

```rust
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ pub use job::{Job, JobId, JobStatus, ResultConfig, ResultStorage};
pub use priority::{
JobPriority, PriorityError, PrioritySelectionStrategy, PriorityStats, PriorityWeights,
};
pub use queue::JobQueue;
pub use queue::{JobQueue, StaleJobRecovery};
pub use rate_limit::{RateLimit, RateLimiter, ThrottleConfig};
pub use retry::{JitterType, RetryStrategy, fibonacci};
pub use spawn::{JobSpawnExt, SpawnConfig, SpawnHandler, SpawnManager, SpawnResult};
Expand Down
11 changes: 11 additions & 0 deletions src/migrations/015_add_job_leases.mysql.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- Migration 015: Add job leases for stale job recovery (MySQL)
-- Workers record a heartbeat and extend a lease while a job is Running.
-- A reaper (DatabaseQueue::requeue_stale_jobs) reclaims Running jobs whose
-- lease has expired, e.g. because the worker crashed or was killed.

ALTER TABLE hammerwork_jobs
ADD COLUMN last_heartbeat_at TIMESTAMP(6) NULL DEFAULT NULL,
ADD COLUMN lease_expires_at TIMESTAMP(6) NULL DEFAULT NULL;

-- Index so the reaper only scans Running jobs
CREATE INDEX idx_hammerwork_jobs_status_lease ON hammerwork_jobs (status, lease_expires_at);
15 changes: 15 additions & 0 deletions src/migrations/015_add_job_leases.postgres.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- Migration 015: Add job leases for stale job recovery (PostgreSQL)
-- Workers record a heartbeat and extend a lease while a job is Running.
-- A reaper (DatabaseQueue::requeue_stale_jobs) reclaims Running jobs whose
-- lease has expired, e.g. because the worker crashed or was killed.

ALTER TABLE hammerwork_jobs
ADD COLUMN IF NOT EXISTS last_heartbeat_at TIMESTAMPTZ;

ALTER TABLE hammerwork_jobs
ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ;

-- Partial index so the reaper only scans Running jobs
CREATE INDEX IF NOT EXISTS idx_hammerwork_jobs_running_lease
ON hammerwork_jobs (lease_expires_at, started_at)
WHERE status = 'Running';
15 changes: 15 additions & 0 deletions src/migrations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,5 +405,20 @@ impl<DB: Database> MigrationManager<DB> {
include_str!("014_add_queue_pause.postgres.sql").to_string(),
include_str!("014_add_queue_pause.mysql.sql").to_string(),
);

// Migration 015: Add job leases for stale job recovery
self.register_migration(
Migration {
id: "015_add_job_leases".to_string(),
description: "Add job heartbeat and lease columns for stale job recovery"
.to_string(),
version: 15,
created_at: chrono::DateTime::parse_from_rfc3339("2026-10-08T00:00:00Z")
.unwrap()
.with_timezone(&Utc),
},
include_str!("015_add_job_leases.postgres.sql").to_string(),
include_str!("015_add_job_leases.mysql.sql").to_string(),
);
}
}
Loading
Loading