From 3468d85eaffe6bd52456165e0275d1195940e083 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Fri, 9 Oct 2026 23:17:15 -0400 Subject: [PATCH 1/3] feat: claim jobs in batches with dequeue_batch_leased and batch-mode workers Add DatabaseQueue::dequeue_batch / dequeue_batch_leased, which claim up to N runnable jobs in one round trip with the guarantees of a single claim: a lease per job written by the claiming statement, attempts incremented, pause/dependency/disabled-recurring checks, priority order, and no double claims (PostgreSQL: one UPDATE ... WHERE id IN (SELECT ... LIMIT n FOR UPDATE SKIP LOCKED); MySQL: SELECT ... FOR UPDATE SKIP LOCKED LIMIT n + one UPDATE in the READ COMMITTED claim transaction with deadlock retry; TestQueue matches). Weighted priorities pick a level by weight per batch and top up from the others; strict priority fills in strict order. Add DatabaseQueue::release_job_run to hand an unstarted claimed job back to Pending without counting the attempt. Workers in batch mode (with_batch_size, or with_batch_processing_enabled) claim up to batch_size jobs per poll and run them batch_concurrency at a time (default 1). Waiting jobs have their leases renewed by heartbeats, throttle permits are held per claimed job, rate limit tokens are taken per job and refunded when unused, and unstarted jobs are released on shutdown. Both new trait methods have default implementations, so external DatabaseQueue implementors keep compiling. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 36 ++ README.md | 2 +- docs/batch-operations.md | 91 ++- docs/worker-configuration.md | 39 ++ examples/worker_batch_example.rs | 3 +- src/queue/mod.rs | 144 +++++ src/queue/mysql.rs | 161 +++++ src/queue/postgres.rs | 117 ++++ src/queue/test.rs | 184 +++++- src/worker.rs | 609 +++++++++++++++++-- tests/batch_dequeue_tests.rs | 969 ++++++++++++++++++++++++++++++ tests/payload_encryption_tests.rs | 82 +++ 12 files changed, 2383 insertions(+), 54 deletions(-) create mode 100644 tests/batch_dequeue_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 94f16c3..f551597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 they are lost on restart. See [Job Results](docs/job-types.md#job-results). `TestQueue::delete_job` now also deletes the job's result. +### Added + +- **Batch claims.** `DatabaseQueue::dequeue_batch(queue, n)` and + `dequeue_batch_leased(queue, weights, lease, n)` claim up to `n` runnable jobs in one + round trip, with the same guarantees as a single claim: each job's lease is written by + the claiming statement, `attempts` is incremented, paused queues, unfinished + dependencies and disabled recurring jobs are honoured, jobs come back in + `priority DESC, scheduled_at ASC` order, and concurrent claimers never get the same job. + PostgreSQL claims with one `UPDATE ... WHERE id IN (SELECT ... LIMIT n FOR UPDATE SKIP + LOCKED) RETURNING ...`; MySQL with `SELECT ... FOR UPDATE SKIP LOCKED LIMIT n` and one + `UPDATE` in the claim transaction (READ COMMITTED, retried on deadlock); `TestQueue` + matches them. Strict priority fills a batch in strict order; weighted priorities pick a + level by weight per batch, fill from it and top up from other levels. At most + `queue::MAX_DEQUEUE_BATCH_SIZE` (1000) jobs per call. +- **`DatabaseQueue::release_job_run`** hands a claimed job that never ran back to + `Pending`, taking back the claim's attempt, so it can run elsewhere at once. +- **Batch-mode workers.** `Worker::with_batch_size(n)` (or + `with_batch_processing_enabled(true)`, which now claims batches of + `worker::DEFAULT_BATCH_SIZE` = 10) makes a worker claim up to `n` jobs per poll, and + `Worker::with_batch_concurrency(m)` runs up to `m` of them at once (default 1). Each job + is processed exactly as in single-job mode (timeouts, retries, hooks, events, spawning, + result storage, encryption, statistics). Jobs waiting for their turn have their leases + renewed by heartbeats, so the stale job reaper never reclaims them while the worker is + alive. A throttle's `max_concurrent` permit is held per claimed job, and a batch claims + no more jobs than it has rate limit tokens (unused tokens are refunded). On shutdown, + claimed jobs that have not started are released at once. Workers without batch + processing claim one job at a time as before. New getters: `is_batch_processing_enabled`, + `batch_size`, `batch_concurrency`. In a local benchmark, batch claims of 50 were 5-6x + faster than single claims on PostgreSQL and MySQL. + +### Changed + +- `Worker::with_batch_processing_enabled(true)` used to only keep statistics for jobs of a + `JobBatch`; it now also switches the worker to batch claims (batch size 10, one job + running at a time). Leave it off to keep claiming one job per poll. + ## [2.0.0] - 2026-10-09 A hardening release ([#7](https://github.com/CodingAnarchy/hammerwork/issues/7)). It fixes diff --git a/README.md b/README.md index 5c08b90..483661c 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ A high-performance, database-driven job queue for Rust with comprehensive featur - **Job prioritization**: Five priority levels with weighted and strict scheduling algorithms - **Result storage**: Database and in-memory (per-process, bounded) result storage with TTL and automatic cleanup ([Job Results](docs/job-types.md#job-results)) - **Worker autoscaling**: Dynamic worker pool scaling based on queue depth and configurable thresholds -- **Batch operations**: High-performance bulk job enqueuing with optimized worker processing +- **Batch operations**: Bulk job enqueuing in one transaction, and batch claims: workers can claim many jobs per round trip (`Worker::with_batch_size`), each with its own lease - **Cron scheduling**: Full cron expression support with timezone awareness - **Rate limiting**: Token bucket rate limiting with configurable burst limits - **Monitoring**: Prometheus metrics and advanced alerting (enabled by default) diff --git a/docs/batch-operations.md b/docs/batch-operations.md index 5a8201d..2d2dbe7 100644 --- a/docs/batch-operations.md +++ b/docs/batch-operations.md @@ -21,7 +21,7 @@ Batch operations provide: - **Atomic enqueue**: a batch is stored completely or not at all - **Progress tracking**: `get_batch_status` reports pending, completed and failed counts - **Flexible failure handling**: choose what happens when a job of the batch fails -- **Worker statistics**: workers can keep per-batch processing statistics +- **Batch claims**: workers can claim many jobs per round trip and keep per-batch processing statistics A batch holds up to 10,000 jobs, all on the **same queue**. @@ -258,9 +258,12 @@ for (job_id, error) in &result.job_errors { ## Worker Batch Processing -### Enable Batch Processing +### Batch Claims -Enabling batch processing on a worker makes it keep statistics for jobs that belong to a batch: +A worker in batch mode claims up to `batch_size` jobs per poll in one round trip instead +of one job per round trip, then runs them `batch_concurrency` at a time (one at a time by +default). `with_batch_size(n)` enables batch mode; `with_batch_processing_enabled(true)` +alone enables it with the default batch size of 10: ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; @@ -276,15 +279,95 @@ let handler: JobHandler = Arc::new(|job: Job| { }) }); +// Claim up to 50 jobs per poll and run up to 8 of them at once. let worker = Worker::new(queue, "batch_queue".to_string(), handler) - .with_batch_processing_enabled(true) + .with_batch_size(50) + .with_batch_concurrency(8) .with_poll_interval(Duration::from_millis(100)); +assert!(worker.is_batch_processing_enabled()); # Ok(()) # } ``` +Every claimed job gets the same guarantees as a job claimed on its own: + +- **One statement per claim.** PostgreSQL claims the batch with a single + `UPDATE ... WHERE id IN (SELECT ... ORDER BY priority DESC, scheduled_at ASC LIMIT n FOR UPDATE SKIP LOCKED) RETURNING ...`; + MySQL locks the rows with `SELECT ... FOR UPDATE SKIP LOCKED LIMIT n` and claims them + with one `UPDATE` in the same READ COMMITTED transaction (retried on deadlock). + Concurrent workers never claim the same job. +- **Same eligibility.** Paused queues, unfinished dependencies and disabled recurring jobs + are honoured, and each job's `attempts` is incremented. +- **A lease per job, from the claim.** Each job's lease is written by the claiming + statement. While a job waits for its turn in the batch, the worker renews its lease + with heartbeats every third of the lease duration, as it does for running jobs, so the + stale job reaper never reclaims a held job while its worker is alive, however long the + jobs ahead of it take. (Sizing the lease to cover the whole batch would not work: the + worker cannot know how long the jobs ahead will run.) +- **Per-job processing.** Timeouts, retries, hooks, events, spawning, result storage, + encrypted payloads and statistics work exactly as for single jobs. +- **Throttle and rate limit.** With `ThrottleConfig::max_concurrent`, every claimed job + holds a permit until it finishes, so a worker claims no more jobs than there are free + permits. With a rate limit, a batch claims no more jobs than there are tokens, and + tokens for jobs it did not get are handed back. +- **Shutdown.** Claimed jobs that have not started are released back to `Pending` at once + (`DatabaseQueue::release_job_run`, which also takes back the claim's attempt), so other + workers can run them right away. Running jobs get the shutdown grace period. + +#### Priorities + +Without priority weights, or with `PriorityWeights::strict()`, a batch is filled in strict +priority order: highest priority first, then oldest. With weighted priorities, a priority +level is picked by weight (as a single weighted claim picks one) and the batch is filled +with that level's oldest jobs; if the level runs out first, another level is picked by +weight among the remaining ones to fill the rest. Over many batches each level gets +batches in proportion to its weight, and no batch comes back short while other levels +have runnable jobs. + +#### Choosing a batch size + +Batch claims save database round trips, so they help most when jobs are short. A worker +holds the jobs it claimed until it gets to them, so idle workers cannot take them: keep +`batch_size` small relative to the queue depth when jobs are slow, or raise +`batch_concurrency` so held jobs start sooner. In a local benchmark (PostgreSQL 16 and +MySQL 8 on the same machine, no-op handler, 2,000 jobs) claiming in batches of 50 was +about 5-6x faster than claiming one job at a time, and a single batch-mode worker with +batch size 50 and concurrency 10 processed 3-4x more jobs per second than a single-job +worker. Run `HAMMERWORK_BENCH=1 cargo test --all-features --test batch_dequeue_tests -- --include-ignored --nocapture throughput` +to measure your own setup. + +### Claiming Batches Directly + +The queue API claims batches too, for custom consumers: + +```rust,no_run +# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; +# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)] +# async fn doc(queue: std::sync::Arc>, handler: hammerwork::worker::JobHandler, jobs: Vec, worker: hammerwork::Worker, batch_id: hammerwork::BatchId) -> std::result::Result<(), Box> { +use hammerwork::{JobOutcome, queue::DatabaseQueue}; +use std::time::Duration; + +// Up to 20 jobs, strict priority order, each leased for 2 minutes. +let jobs = queue + .dequeue_batch_leased("emails", None, Duration::from_secs(120), 20) + .await?; +for job in jobs { + let run = job.clone(); + let job = queue.decrypt_job(job).await?; // a no-op for unencrypted jobs + // ... run it, renewing its lease with `heartbeat_job` while it runs or waits ... + queue.finish_job_run(&run, JobOutcome::Completed).await?; +} +# Ok(()) +# } +``` + +Jobs you claimed but will not run go back with `queue.release_job_run(&job)`. + ### Access Batch Statistics +Workers with batch processing enabled also keep statistics for jobs that belong to a +`JobBatch`: + ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; # #[allow(unused_variables, unused_mut, dead_code, unreachable_code)] diff --git a/docs/worker-configuration.md b/docs/worker-configuration.md index d2e59bf..f6de346 100644 --- a/docs/worker-configuration.md +++ b/docs/worker-configuration.md @@ -576,6 +576,45 @@ let worker = Worker::new(queue, "high_volume".to_string(), handler) # } ``` +### Batch Claims + +For many short jobs, a worker can claim several jobs per database round trip. With +`with_batch_size(n)` the worker claims up to `n` jobs per poll in one statement and runs +them `with_batch_concurrency(m)` at a time (default 1, so the worker still runs one handler +at a time unless you raise it): + +```rust,no_run +# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; +# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)] +# async fn doc(queue: std::sync::Arc>, handler: hammerwork::worker::JobHandler, payload: serde_json::Value, job: hammerwork::Job) -> std::result::Result<(), Box> { +use hammerwork::{ThrottleConfig, Worker}; +use std::time::Duration; + +let worker = Worker::new(queue, "notifications".to_string(), handler) + .with_batch_size(20) // Claim up to 20 jobs per poll + .with_batch_concurrency(5) // Run up to 5 of them at once + .with_lease_duration(Duration::from_secs(60)) + .with_throttle_config(ThrottleConfig::new().max_concurrent(50)); +assert_eq!(worker.batch_size(), 20); +# Ok(()) +# } +``` + +- Each claimed job holds its own lease from the moment it is claimed. Jobs waiting for + their turn have their leases renewed every third of the lease duration, like running + jobs, so a short lease is safe even for large batches of slow jobs. +- With a throttle, each claimed job holds one `max_concurrent` permit until it finishes: + a worker never claims more jobs than there are free permits. With a rate limit, a batch + claims no more jobs than there are tokens, and unused tokens are handed back. +- On shutdown, jobs that were claimed but not started go straight back to `Pending` (their + attempt is not counted); running jobs get the shutdown grace period. +- Weighted priorities pick one level by weight per batch and fill the batch from it + (topping up from other levels); strict priority fills in strict order. See + [Batch Operations](batch-operations.md#worker-batch-processing). + +A worker holds the jobs it claimed until it gets to them, so other workers cannot take +them meanwhile. Prefer small batches for slow jobs, or raise the batch concurrency. + ### Resource-Intensive Jobs ```rust,no_run diff --git a/examples/worker_batch_example.rs b/examples/worker_batch_example.rs index 9a20d64..74154a6 100644 --- a/examples/worker_batch_example.rs +++ b/examples/worker_batch_example.rs @@ -158,7 +158,8 @@ async fn batch_worker_demo( // Create worker with batch processing enabled let worker = Worker::new(queue.clone(), "batch_processing_queue".to_string(), handler) - .with_batch_processing_enabled(true) // Enable batch processing features + .with_batch_size(10) // Claim up to 10 jobs per poll (enables batch processing) + .with_batch_concurrency(4) // and run up to 4 of them at once .with_poll_interval(Duration::from_millis(100)) .with_max_retries(3) .with_stats_collector(stats_collector.clone()) diff --git a/src/queue/mod.rs b/src/queue/mod.rs index a5b0af7..348d7ed 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -123,6 +123,107 @@ pub trait DatabaseQueue: Send + Sync { } } + /// Claim up to `max_jobs` runnable jobs of `queue_name` at once, highest priority + /// first, then oldest, each with a lease of [`DEFAULT_LEASE_DURATION`]. + /// + /// See [`dequeue_batch_leased`](Self::dequeue_batch_leased). + async fn dequeue_batch(&self, queue_name: &str, max_jobs: usize) -> Result> { + self.dequeue_batch_leased(queue_name, None, DEFAULT_LEASE_DURATION, max_jobs) + .await + } + + /// Claim up to `max_jobs` runnable jobs of `queue_name` at once and hold a lease on + /// each until `now + lease` (by the database clock). + /// + /// Every claimed job is claimed exactly as [`dequeue_leased`](Self::dequeue_leased) + /// claims one: it is `Pending`, due, not waiting on dependencies and not a disabled + /// recurring job's held occurrence; its queue is not paused; its `attempts` is + /// incremented; and its lease is written by the statement that claims it. + /// Concurrent callers never claim the same job (`FOR UPDATE SKIP LOCKED` on the + /// database backends). Returns fewer than `max_jobs` jobs (possibly none) when fewer + /// are runnable, and none for a `max_jobs` of zero. + /// + /// The jobs are returned in claim order: highest priority first, then oldest + /// (`priority DESC, scheduled_at ASC`). Each stays `Running` under its own lease + /// until its outcome is recorded with [`finish_job_run`](Self::finish_job_run) or + /// it is handed back with [`release_job_run`](Self::release_job_run); a caller that + /// holds jobs before running them must keep their leases alive with + /// [`heartbeat_job`](Self::heartbeat_job), or the reaper reclaims them once their + /// lease expires. + /// + /// Priority selection: + /// - without `weights`, or with strict [`PriorityWeights`](crate::priority::PriorityWeights), + /// jobs are claimed in strict priority order: the batch is filled from the highest + /// priority level first, then the next, and so on; + /// - with weighted `weights`, a priority level is picked by weight among the levels + /// that have runnable jobs, exactly as a single weighted claim picks one, and the + /// batch is filled with that level's oldest jobs. If the level has fewer runnable + /// jobs than the batch has room for, another level is picked by weight among the + /// remaining ones to fill the rest, and so on. So over many batches each level gets + /// batches in proportion to its weight, and no batch comes back short while other + /// levels have runnable jobs. + /// + /// Jobs with encrypted payloads come back as a single dequeue returns them (with + /// their stored, encrypted payload); decrypt them with + /// [`JobQueue::decrypt_job`](crate::queue::JobQueue::decrypt_job) before running. + /// + /// The default implementation claims the jobs one at a time with + /// [`dequeue_leased`](Self::dequeue_leased) (so with weights each job picks its own + /// level), for backends that predate batch claims. If a claim fails after some + /// jobs were claimed, it returns those jobs rather than the error, so no claimed + /// job is lost to the caller. + async fn dequeue_batch_leased( + &self, + queue_name: &str, + weights: Option<&crate::priority::PriorityWeights>, + lease: std::time::Duration, + max_jobs: usize, + ) -> Result> { + let mut jobs = Vec::new(); + while jobs.len() < max_jobs { + match self.dequeue_leased(queue_name, weights, lease).await { + Ok(Some(job)) => jobs.push(job), + Ok(None) => break, + Err(error) if jobs.is_empty() => return Err(error), + Err(error) => { + tracing::warn!( + "claiming a job of queue {} failed after {} were claimed: {}", + queue_name, + jobs.len(), + error + ); + break; + } + } + } + Ok(jobs) + } + + /// Hand a claimed job that was never run back to its queue. + /// + /// `run` is the job as returned by a dequeue. If it is still `Running` that run + /// (same `attempts` and `started_at`, as in [`finish_job_run`](Self::finish_job_run)), + /// it goes back to `Pending` as if it had not been claimed: the claim's attempt is + /// taken back, its lease and start time are cleared, and it keeps its + /// `scheduled_at`, so it keeps its place in the queue. Returns `false`, and changes + /// nothing, when the job is no longer `Running` that run. + /// + /// Workers in batch mode ([`Worker::with_batch_size`](crate::worker::Worker::with_batch_size)) + /// call this on shutdown for the claimed jobs they have not started, so those jobs + /// can run elsewhere at once instead of waiting for their leases to expire. + /// + /// The default implementation records a retry due now through + /// [`finish_job_run`](Self::finish_job_run), for backends that predate this method: + /// the job is runnable again at once, but the claim still counts as an attempt. + async fn release_job_run(&self, run: &Job) -> Result { + let outcome = JobOutcome::Retry { + retry_at: Utc::now(), + error: RELEASED_JOB_MESSAGE.to_string(), + timed_out: false, + }; + Ok(self.finish_job_run(run, outcome).await?.is_some()) + } + /// Manually mark a job `Completed`. /// /// Only applies to `Pending`, `Running` or `Retrying` jobs (see @@ -1038,6 +1139,16 @@ impl StaleJobRecovery { pub const STALE_JOB_ERROR_MESSAGE: &str = "Job lease expired while Running; the worker is presumed dead and the job was reclaimed"; +/// Error message recorded on a job handed back by the default +/// [`DatabaseQueue::release_job_run`] (the built-in backends release a job without one). +pub const RELEASED_JOB_MESSAGE: &str = + "Job was claimed but not started; released back to its queue"; + +/// The most jobs one [`DatabaseQueue::dequeue_batch_leased`] call claims on the built-in +/// backends; larger requests are capped at this. Keeps the claim statement (and, on +/// MySQL, its list of ids) bounded. +pub const MAX_DEQUEUE_BATCH_SIZE: usize = 1000; + /// Whether a database error aborted the transaction as a deadlock or serialization /// victim (SQLSTATE `40001` on both backends, `40P01` on PostgreSQL). The transaction /// was rolled back, so it is safe to run again. @@ -1456,6 +1567,18 @@ pub(crate) fn weighted_seed(queue_name: &str, attempt: usize) -> u64 { hasher.finish() } +/// Put claimed jobs in claim order: highest priority first, then oldest (`priority +/// DESC, scheduled_at ASC`), as [`DatabaseQueue::dequeue_batch_leased`] returns them. +#[cfg_attr(not(feature = "postgres"), allow(dead_code))] +pub(crate) fn sort_in_claim_order(jobs: &mut [Job]) { + jobs.sort_by(|a, b| { + b.priority + .as_i32() + .cmp(&a.priority.as_i32()) + .then(a.scheduled_at.cmp(&b.scheduled_at)) + }); +} + /// The lease a claim holds when the caller does not choose one: /// [`DatabaseQueue::dequeue`] and [`DatabaseQueue::dequeue_with_priority_weights`], and /// workers by default @@ -2060,6 +2183,27 @@ impl JobQueue { #[cfg(test)] mod tests { + #[test] + fn sort_in_claim_order_is_priority_then_oldest() { + use crate::priority::JobPriority; + let job = |priority: JobPriority, age_secs: i64| { + let mut job = + Job::new("claim".to_string(), serde_json::json!({})).with_priority(priority); + job.scheduled_at = Utc::now() - chrono::Duration::seconds(age_secs); + job + }; + let mut jobs = vec![ + job(JobPriority::Low, 50), + job(JobPriority::High, 10), + job(JobPriority::High, 30), + job(JobPriority::Critical, 1), + ]; + let expected = vec![jobs[3].id, jobs[2].id, jobs[1].id, jobs[0].id]; + sort_in_claim_order(&mut jobs); + let order: Vec<_> = jobs.iter().map(|job| job.id).collect(); + assert_eq!(order, expected); + } + #[test] fn timeout_db_seconds_rounds_up_saturates_and_drops_zero() { use std::time::Duration; diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index 509a1dc..1ec3e0d 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -688,6 +688,86 @@ impl crate::queue::JobQueue { super::end_transaction(tx, result).await } + /// One attempt at claiming up to `limit` runnable jobs of `queue_name` (of + /// `priority` when given), highest priority and oldest first, like + /// [`claim_attempt`](Self::claim_attempt): one transaction locks the rows with + /// `SELECT ... FOR UPDATE SKIP LOCKED LIMIT n`, so concurrent claimers each get + /// different rows, and one `UPDATE ... WHERE id IN (...)` claims them all with their + /// leases. Returns the jobs in claim order. + async fn claim_batch_attempt( + &self, + queue_name: &str, + priority: Option, + lease: i64, + limit: usize, + ) -> Result> { + let mut conn = self.pool.acquire().await?; + let mut tx = Self::begin_claim_transaction(&mut conn).await?; + let result = async { + let query = format!( + "SELECT {JOB_SELECT_FIELDS}, UTC_TIMESTAMP(6) AS claimed_at \ + FROM hammerwork_jobs j WHERE {RUNNABLE_IN_QUEUE_SQL}{} \ + ORDER BY j.priority DESC, j.scheduled_at ASC LIMIT ? FOR UPDATE SKIP LOCKED", + if priority.is_some() { + " AND j.priority = ?" + } else { + "" + } + ); + let mut select = sqlx::query(&query).bind(queue_name).bind(queue_name); + if let Some(priority) = priority { + select = select.bind(priority.as_i32()); + } + let rows = select.bind(limit as u64).fetch_all(&mut *tx).await?; + let Some(first) = rows.first() else { + return Ok(Vec::new()); + }; + // One claim time for the whole batch, from the database clock. + let started_at: DateTime = first.try_get("claimed_at")?; + // A row that cannot be decoded is not claimed: it stays Pending (its lock is + // released at commit) instead of failing the healthy jobs claimed with it. + let mut jobs = super::decodable_rows( + "claimed jobs", + rows.iter().map(|row| { + let id: String = row.try_get("id").unwrap_or_default(); + let job = JobRow::from_row(row) + .map_err(crate::HammerworkError::from) + .and_then(JobRow::into_job); + (id, job) + }), + ); + if jobs.is_empty() { + return Ok(Vec::new()); + } + + let placeholders = vec!["?"; jobs.len()].join(", "); + let sql = format!( + "UPDATE hammerwork_jobs SET status = ?, started_at = ?, attempts = attempts + 1, \ + last_heartbeat_at = ?, lease_expires_at = LEAST(DATE_ADD(?, INTERVAL ? MICROSECOND), \ + CAST('{TIMESTAMP_MAX_SQL}' AS DATETIME(6))) WHERE id IN ({placeholders})" + ); + let mut update = sqlx::query(&sql) + .bind(JobStatus::Running) + .bind(started_at) + .bind(started_at) + .bind(started_at) + .bind(lease); + for job in &jobs { + update = update.bind(job.id.to_string()); + } + update.execute(&mut *tx).await?; + + for job in &mut jobs { + job.status = JobStatus::Running; + job.attempts += 1; + job.started_at = Some(started_at); + } + Ok(jobs) + } + .await; + super::end_transaction(tx, result).await + } + async fn dequeue_with_priority_weights_inner( &self, queue_name: &str, @@ -806,6 +886,87 @@ impl DatabaseQueue for crate::queue::JobQueue { } } + async fn dequeue_batch_leased( + &self, + queue_name: &str, + weights: Option<&crate::priority::PriorityWeights>, + lease: std::time::Duration, + max_jobs: usize, + ) -> Result> { + let max_jobs = max_jobs.min(super::MAX_DEQUEUE_BATCH_SIZE); + if max_jobs == 0 { + return Ok(Vec::new()); + } + let lease = lease_micros(lease); + let weights = match weights { + Some(weights) if !weights.is_strict() => weights, + // Strict priority: highest priority first, then the oldest jobs. + _ => { + return retry_on_deadlock(|| { + self.claim_batch_attempt(queue_name, None, lease, max_jobs) + }) + .await; + } + }; + + // Which priority levels have a runnable job (see `dequeue_leased`). + let levels: Vec = + sqlx::query_scalar(&super::runnable_priorities_sql(RUNNABLE_IN_QUEUE_SQL)) + .bind(queue_name) + .bind(queue_name) + .fetch_all(&self.pool) + .await?; + let mut candidates: Vec = levels + .into_iter() + .filter_map(|level| i32::try_from(level).ok()) + .filter_map(|level| JobPriority::from_i32(level).ok()) + .collect(); + + // Pick a level by weight and fill the batch with its oldest runnable jobs. If it + // runs out first, pick another of the remaining levels by weight for the rest. + let mut jobs = Vec::with_capacity(max_jobs); + let mut attempt = 0; + while jobs.len() < max_jobs + && let Some(priority) = super::pick_weighted_priority( + &candidates, + weights, + super::weighted_seed(queue_name, attempt), + ) + { + let room = max_jobs - jobs.len(); + let claimed = retry_on_deadlock(|| { + self.claim_batch_attempt(queue_name, Some(priority), lease, room) + }) + .await?; + jobs.extend(claimed); + candidates.retain(|candidate| *candidate != priority); + attempt += 1; + } + Ok(jobs) + } + + async fn release_job_run(&self, run: &Job) -> Result { + // Undo this run's claim only: a job reclaimed and claimed again is left alone. + let started = super::run_started_range(run); + let result = sqlx::query( + "UPDATE hammerwork_jobs SET status = ?, started_at = NULL, \ + attempts = GREATEST(attempts - 1, 0), last_heartbeat_at = NULL, \ + lease_expires_at = NULL WHERE id = ? AND status = ? AND attempts = ? \ + AND (? IS NULL OR (started_at > ? AND started_at < ?))", + ) + .bind(JobStatus::Pending) + .bind(run.id.to_string()) + .bind(JobStatus::Running) + .bind(run.attempts) + .bind(started.map(|(from, _)| from)) + .bind(started.map(|(from, _)| from)) + .bind(started.map(|(_, to)| to)) + .execute(&self.pool) + .await?; + // The status always changes, so "rows changed" is "rows matched" here. + Ok(result.rows_affected() > 0) + } + async fn complete_job(&self, job_id: JobId) -> Result<()> { let transition = JobTransition::Complete; self.transition_job(job_id, Guard::Manual(transition), &Target::Completed, false) diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 0683407..2a6b334 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -661,6 +661,88 @@ impl DatabaseQueue for crate::queue::JobQueue { Ok(None) } + async fn dequeue_batch_leased( + &self, + queue_name: &str, + weights: Option<&crate::priority::PriorityWeights>, + lease: std::time::Duration, + max_jobs: usize, + ) -> Result> { + let max_jobs = max_jobs.min(super::MAX_DEQUEUE_BATCH_SIZE); + if max_jobs == 0 { + return Ok(Vec::new()); + } + let lease = super::lease_interval(lease); + let weights = match weights { + Some(weights) if !weights.is_strict() => weights, + // Strict priority: highest priority first, then the oldest jobs. + _ => { + let rows = sqlx::query_as::<_, JobRow>(&claim_batch_sql(false)) + .bind(queue_name) + .bind(lease) + .bind(max_jobs as i64) + .fetch_all(&self.pool) + .await?; + return Ok(claimed_jobs(rows)); + } + }; + + // Which priority levels have a runnable job (see `dequeue_leased`). + let levels: Vec = + sqlx::query_scalar(&super::runnable_priorities_sql(RUNNABLE_IN_QUEUE_SQL)) + .bind(queue_name) + .fetch_all(&self.pool) + .await?; + let mut candidates: Vec = levels + .into_iter() + .filter_map(|level| JobPriority::from_i32(level).ok()) + .collect(); + + // Pick a level by weight and fill the batch with its oldest runnable jobs. If it + // runs out first, pick another of the remaining levels by weight for the rest. + let mut jobs = Vec::with_capacity(max_jobs); + let mut attempt = 0; + while jobs.len() < max_jobs + && let Some(priority) = super::pick_weighted_priority( + &candidates, + weights, + super::weighted_seed(queue_name, attempt), + ) + { + let rows = sqlx::query_as::<_, JobRow>(&claim_batch_sql(true)) + .bind(queue_name) + .bind(lease) + .bind((max_jobs - jobs.len()) as i64) + .bind(priority.as_i32()) + .fetch_all(&self.pool) + .await?; + jobs.extend(claimed_jobs(rows)); + candidates.retain(|candidate| *candidate != priority); + attempt += 1; + } + Ok(jobs) + } + + async fn release_job_run(&self, run: &Job) -> Result { + // Undo this run's claim only: a job reclaimed and claimed again is left alone. + let started = super::run_started_range(run); + let result = sqlx::query( + "UPDATE hammerwork_jobs SET status = $1, started_at = NULL, \ + attempts = GREATEST(attempts - 1, 0), last_heartbeat_at = NULL, \ + lease_expires_at = NULL WHERE id = $2 AND status = $3 AND attempts = $4 \ + AND ($5::timestamptz IS NULL OR (started_at > $5 AND started_at < $6))", + ) + .bind(JobStatus::Pending) + .bind(run.id) + .bind(JobStatus::Running) + .bind(run.attempts) + .bind(started.map(|(from, _)| from)) + .bind(started.map(|(_, to)| to)) + .execute(&self.pool) + .await?; + Ok(result.rows_affected() > 0) + } + async fn complete_job(&self, job_id: JobId) -> Result<()> { let transition = JobTransition::Complete; self.transition_job(job_id, Guard::Manual(transition), &Target::Completed, false) @@ -2291,6 +2373,41 @@ fn claim_sql(by_priority: bool) -> String { ) } +/// Claims up to `$3` runnable jobs of queue `$1` (of priority `$4` when `by_priority`) +/// in one statement, like [`claim_sql`]: the subquery locks the highest-priority, oldest +/// runnable rows that no other transaction holds (`FOR UPDATE SKIP LOCKED`, so +/// concurrent claimers each get different rows), and the update claims all of them, +/// each with a lease of `$2`. A subquery with `LIMIT` is never flattened into a join, +/// so it runs once. `RETURNING` does not keep the subquery's order; callers sort. +fn claim_batch_sql(by_priority: bool) -> String { + format!( + "UPDATE hammerwork_jobs SET status = 'Running', started_at = now(), \ + attempts = attempts + 1, last_heartbeat_at = now(), lease_expires_at = now() + $2 \ + WHERE id IN (SELECT j.id FROM hammerwork_jobs j WHERE {RUNNABLE_IN_QUEUE_SQL}{} \ + ORDER BY j.priority DESC, j.scheduled_at ASC LIMIT $3 FOR UPDATE SKIP LOCKED) \ + RETURNING {JOB_SELECT_FIELDS}", + if by_priority { + " AND j.priority = $4" + } else { + "" + } + ) +} + +/// The jobs of a batch claim, in claim order. A row that cannot be decoded is skipped +/// and logged rather than failing the batch, which would lose the healthy jobs claimed +/// with it; it stays `Running` until its lease expires, like a single claim that fails +/// to decode. +fn claimed_jobs(rows: Vec) -> Vec { + let mut jobs = super::decodable_rows( + "claimed jobs", + rows.into_iter() + .map(|row| (row.id.to_string(), row.into_job())), + ); + super::sort_in_claim_order(&mut jobs); + jobs +} + /// Insert `jobs`, settling the dependency state of those that depend on jobs that /// already finished (see [`lifecycle::settle_new_dependents`]). /// diff --git a/src/queue/test.rs b/src/queue/test.rs index 1616c84..e6a038a 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -533,22 +533,94 @@ impl TestStorage { } /// Get the next job to dequeue based on priority and scheduled time - fn get_next_job(&self, queue_name: &str, weights: Option<&PriorityWeights>) -> Option { + /// The jobs of `queue_name` that can be dequeued now: pending, due and not a + /// disabled recurring job's held occurrence. None while the queue is paused. + fn eligible_jobs(&self, queue_name: &str) -> Vec<&Job> { // Like the database backends, a paused queue hands out no jobs. if self.paused_queues.contains_key(queue_name) { - return None; + return Vec::new(); } - let queue_jobs = self.queues.get(queue_name)?; - let pending_jobs = queue_jobs.get(&JobStatus::Pending)?; + let Some(pending_jobs) = self + .queues + .get(queue_name) + .and_then(|queue_jobs| queue_jobs.get(&JobStatus::Pending)) + else { + return Vec::new(); + }; let now = self.clock.now(); - let eligible_jobs: Vec<&Job> = pending_jobs + pending_jobs .iter() .filter_map(|id| self.jobs.get(id)) .filter(|job| job.scheduled_at <= now) // A disabled recurring job's pending occurrence is held. .filter(|job| job.recurring || job.cron_schedule.is_none()) - .collect(); + .collect() + } + + /// Up to `max_jobs` jobs to claim at once, in claim order, chosen like the database + /// backends' `dequeue_batch_leased`: in strict priority order, or with weighted + /// `weights` filled from a level picked by weight, then from the other levels. + fn get_next_jobs( + &self, + queue_name: &str, + weights: Option<&PriorityWeights>, + max_jobs: usize, + ) -> Vec { + let mut eligible = self.eligible_jobs(queue_name); + eligible.sort_by_key(|job| { + ( + std::cmp::Reverse(job.priority.as_i32()), + job.scheduled_at, + job.created_at, + ) + }); + let weights = match weights { + Some(weights) if !weights.is_strict() => weights, + _ => { + return eligible + .into_iter() + .take(max_jobs) + .map(|job| job.id) + .collect(); + } + }; + + let mut candidates: Vec = Vec::new(); + for job in &eligible { + if !candidates.contains(&job.priority) { + candidates.push(job.priority); + } + } + let mut claimed = Vec::new(); + let mut attempt: u64 = 0; + while claimed.len() < max_jobs { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + queue_name.hash(&mut hasher); + self.clock.now().timestamp_millis().hash(&mut hasher); + attempt.hash(&mut hasher); + let Some(priority) = + super::pick_weighted_priority(&candidates, weights, hasher.finish()) + else { + break; + }; + let room = max_jobs - claimed.len(); + claimed.extend( + eligible + .iter() + .filter(|job| job.priority == priority) + .take(room) + .map(|job| job.id), + ); + candidates.retain(|candidate| *candidate != priority); + attempt += 1; + } + claimed + } + + fn get_next_job(&self, queue_name: &str, weights: Option<&PriorityWeights>) -> Option { + let eligible_jobs = self.eligible_jobs(queue_name); if eligible_jobs.is_empty() { return None; @@ -1136,6 +1208,52 @@ impl DatabaseQueue for TestQueue { })) } + async fn dequeue_batch_leased( + &self, + queue_name: &str, + weights: Option<&PriorityWeights>, + lease: std::time::Duration, + max_jobs: usize, + ) -> Result> { + // One lock for the whole batch: concurrent callers never see the same job as + // claimable, like `FOR UPDATE SKIP LOCKED` on the database backends. + let mut storage = self.storage.write().await; + let max_jobs = max_jobs.min(super::MAX_DEQUEUE_BATCH_SIZE); + let ids = storage.get_next_jobs(queue_name, weights, max_jobs); + let now = storage.clock.now(); + let mut jobs = Vec::with_capacity(ids.len()); + for job_id in ids { + storage.update_job_status(job_id, JobStatus::Running)?; + storage + .leases + .insert(job_id, (now, lease_expiry(now, lease))); + if let Some(job) = storage.jobs.get_mut(&job_id) { + job.started_at = Some(now); + job.attempts += 1; + jobs.push(job.clone()); + } + } + Ok(jobs) + } + + async fn release_job_run(&self, run: &Job) -> Result { + let mut storage = self.storage.write().await; + // Only the run that was dequeued is released, as on the database backends. + let same_run = storage.jobs.get(&run.id).is_some_and(|job| { + job.status == JobStatus::Running && lifecycle::is_same_run(job, run) + }); + if !same_run { + return Ok(false); + } + storage.update_job_status(run.id, JobStatus::Pending)?; + storage.leases.remove(&run.id); + if let Some(job) = storage.jobs.get_mut(&run.id) { + job.started_at = None; + job.attempts = (job.attempts - 1).max(0); + } + Ok(true) + } + async fn complete_job(&self, job_id: JobId) -> Result<()> { let mut storage = self.storage.write().await; storage.check_transition(job_id, crate::queue::JobTransition::Complete)?; @@ -2836,6 +2954,60 @@ mod tests { use super::*; use serde_json::json; + #[tokio::test] + async fn dequeue_batch_claims_in_order_with_leases() { + let queue = TestQueue::new(); + let low = queue + .enqueue(Job::new("batch".to_string(), json!({})).as_low_priority()) + .await + .unwrap(); + let high = queue + .enqueue(Job::new("batch".to_string(), json!({})).as_high_priority()) + .await + .unwrap(); + let normal = queue + .enqueue(Job::new("batch".to_string(), json!({}))) + .await + .unwrap(); + + let claimed = queue.dequeue_batch("batch", 2).await.unwrap(); + let ids: Vec = claimed.iter().map(|job| job.id).collect(); + assert_eq!(ids, [high, normal]); + assert!(claimed.iter().all(|job| job.attempts == 1)); + assert_eq!(queue.get_job_count("batch", &JobStatus::Running).await, 2); + // Leased: a reaper with any window leaves them alone. + let recovery = queue + .requeue_stale_jobs(std::time::Duration::ZERO) + .await + .unwrap(); + assert!(recovery.is_empty()); + + // Paused queues hand out nothing. + queue.pause_queue("batch", None).await.unwrap(); + assert!(queue.dequeue_batch("batch", 5).await.unwrap().is_empty()); + queue.resume_queue("batch", None).await.unwrap(); + let rest = queue.dequeue_batch("batch", 5).await.unwrap(); + assert_eq!(rest.len(), 1); + assert_eq!(rest[0].id, low); + } + + #[tokio::test] + async fn release_job_run_returns_the_job_unclaimed() { + let queue = TestQueue::new(); + let id = queue + .enqueue(Job::new("release".to_string(), json!({}))) + .await + .unwrap(); + let run = queue.dequeue_batch("release", 1).await.unwrap().remove(0); + assert!(queue.release_job_run(&run).await.unwrap()); + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Pending); + assert_eq!(job.attempts, 0); + assert_eq!(job.started_at, None); + assert!(!queue.release_job_run(&run).await.unwrap()); + assert_eq!(queue.dequeue_batch("release", 1).await.unwrap().len(), 1); + } + #[tokio::test] async fn test_basic_enqueue_dequeue() { let queue = TestQueue::new(); diff --git a/src/worker.rs b/src/worker.rs index 0ddd616..5a0bb39 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -80,6 +80,15 @@ pub const MIN_POLL_INTERVAL: Duration = Duration::from_millis(10); /// Floor on the heartbeat interval derived from the lease duration. const MIN_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(100); +/// Default number of jobs a worker in batch mode claims per poll +/// ([`Worker::with_batch_size`]). +pub const DEFAULT_BATCH_SIZE: usize = 10; + +/// Default number of claimed jobs a worker in batch mode runs at once +/// ([`Worker::with_batch_concurrency`]): one, so batch mode changes how jobs are claimed +/// but not how many handlers a worker runs at a time. +pub const DEFAULT_BATCH_CONCURRENCY: usize = 1; + /// Delay before a [`WorkerPool`] restarts a worker that died unexpectedly. const WORKER_RESTART_DELAY: Duration = Duration::from_secs(1); @@ -159,6 +168,48 @@ enum Acquired { Shutdown, } +/// What a batch-mode worker got from one poll. +enum AcquiredBatch { + Jobs(Vec), + Idle, + Shutdown, +} + +/// A job claimed in a batch, with the throttle permit it holds until it finishes. +struct ClaimedJob { + job: Job, + permit: Option, +} + +/// One job of a batch being processed; resolves to its id and processing outcome. +type BatchRun<'a> = Pin)> + Send + 'a>>; + +/// Wait for the next of `runs` to finish and remove it, or `None` when there are none. +fn next_finished<'r, 'a>( + runs: &'r mut Vec>, +) -> impl Future)>> + Send + 'r { + std::future::poll_fn(move |cx| { + if runs.is_empty() { + return Poll::Ready(None); + } + for index in 0..runs.len() { + if let Poll::Ready(finished) = runs[index].as_mut().poll(cx) { + drop(runs.swap_remove(index)); + return Poll::Ready(Some(finished)); + } + } + Poll::Pending + }) +} + +/// The claimed jobs of a batch that have not started yet, whose leases the worker +/// renews while they wait, and those whose lease was found lost. +#[derive(Default)] +struct HeldJobs { + waiting: Vec, + lost: std::collections::HashSet, +} + /// Whether shutdown was requested (or the shutdown sender was dropped), without waiting. fn shutdown_requested(shutdown_rx: &mut mpsc::Receiver<()>) -> bool { !matches!( @@ -765,8 +816,12 @@ pub struct Worker { alert_manager: Option>, /// Timestamp of the last processed job (for starvation detection) last_job_time: Arc>>, - /// Enable optimized batch job processing + /// Claim jobs in batches (and track statistics of jobs that belong to a `JobBatch`) batch_processing_enabled: bool, + /// Most jobs claimed per poll in batch mode + batch_size: usize, + /// Most claimed jobs run at once in batch mode + batch_concurrency: usize, /// Track batch processing statistics batch_stats: Arc>, /// Job lifecycle event hooks @@ -811,6 +866,8 @@ where // Create new instances for per-worker state last_job_time: Arc::new(std::sync::RwLock::new(Utc::now())), batch_processing_enabled: self.batch_processing_enabled, + batch_size: self.batch_size, + batch_concurrency: self.batch_concurrency, batch_stats: Arc::new(std::sync::RwLock::new(BatchProcessingStats::default())), event_hooks: self.event_hooks.clone(), spawn_manager: self.spawn_manager.clone(), @@ -898,6 +955,8 @@ where alert_manager: None, last_job_time: Arc::new(std::sync::RwLock::new(Utc::now())), batch_processing_enabled: false, + batch_size: DEFAULT_BATCH_SIZE, + batch_concurrency: DEFAULT_BATCH_CONCURRENCY, batch_stats: Arc::new(std::sync::RwLock::new(BatchProcessingStats::default())), event_hooks: JobEventHooks::default(), spawn_manager: None, @@ -974,6 +1033,8 @@ where alert_manager: None, last_job_time: Arc::new(std::sync::RwLock::new(Utc::now())), batch_processing_enabled: false, + batch_size: DEFAULT_BATCH_SIZE, + batch_concurrency: DEFAULT_BATCH_CONCURRENCY, batch_stats: Arc::new(std::sync::RwLock::new(BatchProcessingStats::default())), event_hooks: JobEventHooks::default(), spawn_manager: None, @@ -1442,14 +1503,37 @@ where self } - /// Enable optimized batch job processing. - /// - /// When enabled, the worker will detect when jobs belong to batches and provide - /// enhanced monitoring, statistics, and error handling for batch operations. - /// - /// # Arguments - /// - /// * `enabled` - Whether to enable batch processing optimizations + /// Enable batch processing: claim jobs in batches, and track statistics of jobs that + /// belong to a [`JobBatch`](crate::batch::JobBatch) ([`get_batch_stats`](Self::get_batch_stats)). + /// + /// In batch mode the worker claims up to [`batch_size`](Self::with_batch_size) jobs + /// per poll in one round trip ([`DatabaseQueue::dequeue_batch_leased`]) and runs them + /// [`batch_concurrency`](Self::with_batch_concurrency) at a time, one at a time by + /// default. Every claimed job goes through the same path as a single claim: its own + /// timeout, retries, hooks, events, spawning, result storage and statistics. + /// + /// - **Leases.** Each claimed job holds its own lease from the moment it is claimed. + /// While a job waits for its turn, the worker renews its lease with heartbeats + /// every third of the [lease duration](Self::with_lease_duration), as it does for + /// a running job, so a waiting job is never reclaimed by the stale job reaper + /// while the worker is alive, however long the jobs ahead of it take. If a + /// waiting job's lease is lost anyway (an operator changed it, or heartbeats + /// failed for longer than the lease), the worker skips it. + /// - **Throttle and rate limit.** With a throttle's `max_concurrent`, every claimed + /// job holds one of its permits until it finishes, so the worker never claims more + /// jobs than there are free permits (it waits for at least one). With a rate limit, + /// it claims no more jobs than it can take tokens for and hands back the tokens of + /// jobs it did not get. + /// - **Shutdown.** Claimed jobs that have not started are handed back to the queue + /// at once ([`DatabaseQueue::release_job_run`]), without counting an attempt, so + /// other workers can run them instead of waiting for their leases to expire. Jobs + /// already running get the [shutdown grace period](Self::with_shutdown_grace_period), + /// as in single-job mode. + /// + /// Batch claims cut the database round trips per job; holding jobs a worker has not + /// started yet keeps them from idle workers, so keep batches small relative to the + /// queue when jobs are slow. With batch processing off (the default), the worker + /// claims and runs one job at a time. /// /// # Examples /// @@ -1462,6 +1546,7 @@ where /// # let queue = Arc::new(hammerwork::JobQueue::new(pool)); /// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) })); /// + /// // Claim up to 10 jobs (the default batch size) per poll, run them one at a time. /// let worker = Worker::new(queue, "batch_queue".to_string(), handler) /// .with_batch_processing_enabled(true); /// # Ok(()) @@ -1472,6 +1557,67 @@ where self } + /// Claim up to `size` jobs per poll, and enable batch processing (see + /// [`with_batch_processing_enabled`](Self::with_batch_processing_enabled)). + /// + /// Defaults to [`DEFAULT_BATCH_SIZE`] (10). Values below 1 are raised to 1, and the + /// built-in backends claim at most + /// [`MAX_DEQUEUE_BATCH_SIZE`](crate::queue::MAX_DEQUEUE_BATCH_SIZE) jobs at once. + /// + /// # Examples + /// + #[cfg_attr(feature = "postgres", doc = "```rust,no_run")] + #[cfg_attr(not(feature = "postgres"), doc = "```rust,ignore")] + /// use hammerwork::Worker; + /// # use std::sync::Arc; + /// # async fn example() -> Result<(), Box> { + /// # let pool = sqlx::PgPool::connect("postgresql://localhost/test").await?; + /// # let queue = Arc::new(hammerwork::JobQueue::new(pool)); + /// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) })); + /// + /// // Claim up to 50 jobs per poll and run up to 8 of them at once. + /// let worker = Worker::new(queue, "emails".to_string(), handler) + /// .with_batch_size(50) + /// .with_batch_concurrency(8); + /// assert!(worker.is_batch_processing_enabled()); + /// # Ok(()) + /// # } + /// ``` + pub fn with_batch_size(mut self, size: usize) -> Self { + self.batch_size = size.max(1); + self.batch_processing_enabled = true; + self + } + + /// Run up to `concurrency` of a claimed batch's jobs at once (batch mode only). + /// + /// Defaults to [`DEFAULT_BATCH_CONCURRENCY`] (1: the jobs of a batch run one after + /// another). The jobs run concurrently on the worker's task, so a handler that blocks + /// its thread holds up the others; use `tokio::task::spawn_blocking` for blocking + /// work. Values below 1 are raised to 1. A throttle's `max_concurrent` still applies. + pub fn with_batch_concurrency(mut self, concurrency: usize) -> Self { + self.batch_concurrency = concurrency.max(1); + self + } + + /// Whether batch processing is enabled (see + /// [`with_batch_processing_enabled`](Self::with_batch_processing_enabled)). + pub fn is_batch_processing_enabled(&self) -> bool { + self.batch_processing_enabled + } + + /// The most jobs this worker claims per poll in batch mode. See + /// [`with_batch_size`](Self::with_batch_size). + pub fn batch_size(&self) -> usize { + self.batch_size + } + + /// The most claimed jobs this worker runs at once in batch mode. See + /// [`with_batch_concurrency`](Self::with_batch_concurrency). + pub fn batch_concurrency(&self) -> usize { + self.batch_concurrency + } + /// Set the job lifecycle event hooks for this worker. /// /// Event hooks allow you to register callbacks that will be called at various @@ -1751,32 +1897,53 @@ where info!("Worker shutting down for queue: {}", self.queue_name); break; } - // Held until this iteration's job is done, so at most `max_concurrent` - // workers sharing this throttle dequeue or run jobs at once. - let _permit = match &self.concurrency_limit { - Some(limit) => tokio::select! { - biased; - _ = shutdown_rx.recv() => { + + // Single-job mode: a throttle permit held until this iteration is over. + let _permit; + let (outcome, shutting_down) = if self.batch_processing_enabled { + // Each claimed job holds its own throttle permit (see `acquire_batch`). + match self.acquire_batch(&mut shutdown_rx).await { + Ok(AcquiredBatch::Shutdown) => { info!("Worker shutting down for queue: {}", self.queue_name); break; } - // The semaphore is never closed, so this is always a permit. - permit = Arc::clone(limit).acquire_owned() => permit.ok(), - }, - None => None, - }; - let acquired = self.acquire_job(&mut shutdown_rx).await; - - let (outcome, shutting_down) = match acquired { - Ok(Acquired::Shutdown) => { - info!("Worker shutting down for queue: {}", self.queue_name); - break; + Ok(AcquiredBatch::Jobs(batch)) => { + self.run_batch_until_done(batch, &mut shutdown_rx).await + } + Ok(AcquiredBatch::Idle) => (Ok(()), false), + Err(e) => { + error!("Error dequeuing jobs from queue {}: {}", self.queue_name, e); + (Err(e), false) + } } - Ok(Acquired::Job(job)) => self.run_job_until_done(*job, &mut shutdown_rx).await, - Ok(Acquired::Idle) => (Ok(()), false), - Err(e) => { - error!("Error dequeuing job from queue {}: {}", self.queue_name, e); - (Err(e), false) + } else { + // Held until this iteration's job is done, so at most `max_concurrent` + // workers sharing this throttle dequeue or run jobs at once. + _permit = match &self.concurrency_limit { + Some(limit) => tokio::select! { + biased; + _ = shutdown_rx.recv() => { + info!("Worker shutting down for queue: {}", self.queue_name); + break; + } + // The semaphore is never closed, so this is always a permit. + permit = Arc::clone(limit).acquire_owned() => permit.ok(), + }, + None => None, + }; + let acquired = self.acquire_job(&mut shutdown_rx).await; + + match acquired { + Ok(Acquired::Shutdown) => { + info!("Worker shutting down for queue: {}", self.queue_name); + break; + } + Ok(Acquired::Job(job)) => self.run_job_until_done(*job, &mut shutdown_rx).await, + Ok(Acquired::Idle) => (Ok(()), false), + Err(e) => { + error!("Error dequeuing job from queue {}: {}", self.queue_name, e); + (Err(e), false) + } } }; @@ -1918,29 +2085,314 @@ where /// Claim the next job of this worker's queue, with this worker's lease. async fn claim_job(&self) -> Result> { - // Check if the queue is paused + if self.queue_is_paused().await { + return Ok(None); + } + + self.queue + .dequeue_leased( + &self.queue_name, + self.priority_weights.as_ref(), + self.lease_duration, + ) + .await + } + + /// Whether this worker's queue is paused, so the dequeue can be skipped. A failed + /// check counts as not paused: the dequeue checks the pause itself. + async fn queue_is_paused(&self) -> bool { match self.queue.is_queue_paused(&self.queue_name).await { Ok(true) => { debug!( "Queue '{}' is paused, skipping job dequeue", self.queue_name ); - return Ok(None); + true } - Ok(false) => {} + Ok(false) => false, Err(e) => { - // The dequeue checks the pause itself, so carry on. warn!("Failed to check queue pause status: {}", e); + false } } + } - self.queue - .dequeue_leased( - &self.queue_name, - self.priority_weights.as_ref(), - self.lease_duration, - ) - .await + /// Batch mode: wait for capacity, then claim up to `batch_size` jobs in one call. + /// + /// Each claimed job needs a throttle permit (with `max_concurrent`) and a rate limit + /// token (with a rate limit): the worker waits for the first of each, takes as many + /// more as are free right now, up to the batch size, and claims no more jobs than + /// that. Tokens for jobs it did not get are handed back; permits it did not need are + /// dropped. + async fn acquire_batch(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> Result { + let mut capacity = self.batch_size.max(1); + + let mut permits = Vec::new(); + if let Some(limit) = &self.concurrency_limit { + let first = tokio::select! { + biased; + _ = shutdown_rx.recv() => return Ok(AcquiredBatch::Shutdown), + // The semaphore is never closed, so this is always a permit. + permit = Arc::clone(limit).acquire_owned() => permit.ok(), + }; + permits.extend(first); + while permits.len() < capacity { + match Arc::clone(limit).try_acquire_owned() { + Ok(permit) => permits.push(permit), + Err(_) => break, + } + } + capacity = permits.len(); + if capacity == 0 { + return Ok(self.idle_wait_batch(shutdown_rx).await); + } + } + + let mut tokens = 0; + if let Some(rate_limiter) = &self.rate_limiter { + let permit = tokio::select! { + biased; + _ = shutdown_rx.recv() => return Ok(AcquiredBatch::Shutdown), + permit = rate_limiter.acquire() => permit, + }; + if let Err(e) = permit { + warn!("Rate limiter error: {}", e); + return Ok(self.idle_wait_batch(shutdown_rx).await); + } + tokens = 1; + while tokens < capacity && rate_limiter.try_acquire() { + tokens += 1; + } + capacity = tokens; + } + + let claimed = if self.queue_is_paused().await { + Ok(Vec::new()) + } else { + self.queue + .dequeue_batch_leased( + &self.queue_name, + self.priority_weights.as_ref(), + self.lease_duration, + capacity, + ) + .await + }; + if let Some(rate_limiter) = &self.rate_limiter { + let used = claimed.as_ref().map_or(0, Vec::len); + for _ in used..tokens { + rate_limiter.refund(); + } + } + + let jobs = claimed?; + if jobs.is_empty() { + // No job available (or the queue is paused): wait before polling again. + return Ok(self.idle_wait_batch(shutdown_rx).await); + } + debug!( + "Claimed {} job(s) from queue {}", + jobs.len(), + self.queue_name + ); + let mut permits = permits.into_iter(); + Ok(AcquiredBatch::Jobs( + jobs.into_iter() + .map(|job| ClaimedJob { + job, + permit: permits.next(), + }) + .collect(), + )) + } + + /// [`idle_wait`](Self::idle_wait) for batch mode. + async fn idle_wait_batch(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> AcquiredBatch { + match self.idle_wait(shutdown_rx).await { + Acquired::Shutdown => AcquiredBatch::Shutdown, + _ => AcquiredBatch::Idle, + } + } + + /// Process the jobs of a claimed batch, up to `batch_concurrency` at a time, while + /// renewing the leases of the ones still waiting for their turn. + /// + /// If shutdown is requested meanwhile, the jobs that have not started are released + /// back to the queue at once, and the running ones get up to the shutdown grace + /// period to finish before they are cancelled (as in + /// [`run_job_until_done`](Self::run_job_until_done)). + /// + /// Returns the first error recording a job's outcome (the other jobs are still + /// processed) and whether shutdown was requested. + async fn run_batch_until_done( + &self, + batch: Vec, + shutdown_rx: &mut mpsc::Receiver<()>, + ) -> (Result<()>, bool) { + // The runs whose leases are renewed while they wait: the jobs as claimed (same + // id, attempts and started_at), without their payloads. + let held = std::sync::Mutex::new(HeldJobs { + waiting: batch + .iter() + .map(|claimed| Job { + payload: serde_json::Value::Null, + ..claimed.job.clone() + }) + .collect(), + lost: Default::default(), + }); + let lease_keeper = self.maintain_held_leases(&held); + tokio::pin!(lease_keeper); + + let concurrency = self.batch_concurrency.max(1); + let mut queued: std::collections::VecDeque = batch.into(); + let mut running: Vec> = Vec::new(); + let mut first_error = None; + let mut shutting_down = false; + + loop { + while running.len() < concurrency + && let Some(ClaimedJob { job, permit }) = queued.pop_front() + { + if !Self::start_held(&held, job.id) { + warn!( + "Skipping job {} of a claimed batch: it lost its lease while waiting \ + (it is no longer Running this run)", + job.id + ); + continue; + } + running.push(Box::pin(async move { + // The job's throttle permit is held until it is done. + let _permit = permit; + let job_id = job.id; + (job_id, self.process_job(job).await) + })); + } + + tokio::select! { + biased; + _ = shutdown_rx.recv() => { + shutting_down = true; + break; + } + finished = next_finished(&mut running) => match finished { + Some((job_id, outcome)) => { + if let Err(e) = self.log_process_outcome(job_id, outcome) { + first_error.get_or_insert(e); + } + } + None => break, + }, + () = &mut lease_keeper => {} + } + } + + if shutting_down { + self.release_unstarted(queued.drain(..).map(|claimed| claimed.job)) + .await; + if !running.is_empty() { + info!( + "Shutdown requested while {} job(s) of a batch are running; waiting up to \ + {:?} for them to finish", + running.len(), + self.shutdown_grace_period + ); + let drained = tokio::time::timeout(self.shutdown_grace_period, async { + while let Some((job_id, outcome)) = next_finished(&mut running).await { + if let Err(e) = self.log_process_outcome(job_id, outcome) { + first_error.get_or_insert(e); + } + } + }) + .await; + if drained.is_err() { + warn!( + "{} job(s) of a batch did not finish within the {:?} shutdown grace \ + period and were cancelled; they stay Running until their leases \ + expire and the stale job reaper reclaims them", + running.len(), + self.shutdown_grace_period + ); + } + } + } + + (first_error.map_or(Ok(()), Err), shutting_down) + } + + /// Take `job_id` off the waiting list of a batch as it starts. `false` when its + /// lease was lost while it waited, so it must not run. + fn start_held(held: &std::sync::Mutex, job_id: crate::job::JobId) -> bool { + let mut held = held.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + held.waiting.retain(|run| run.id != job_id); + !held.lost.contains(&job_id) + } + + /// Renew the leases of a batch's jobs that are waiting for their turn, every third + /// of the lease duration (like [`maintain_lease`](Self::maintain_lease) for a running + /// job, which takes over once a job starts). A job whose lease is found lost is + /// marked so it is not run. Never completes. + async fn maintain_held_leases(&self, held: &std::sync::Mutex) { + if self.lease_duration.is_zero() { + return std::future::pending().await; + } + let interval = (self.lease_duration / 3).max(MIN_HEARTBEAT_INTERVAL); + loop { + sleep(interval).await; + let waiting = held + .lock() + .map(|held| held.waiting.clone()) + .unwrap_or_default(); + for run in waiting { + match self.queue.heartbeat_job(&run, self.lease_duration).await { + Ok(true) => debug!("Renewed lease on waiting job {}", run.id), + Ok(false) => { + warn!( + "Lost the lease on job {} while it waited in a claimed batch; it \ + will not be run by this worker", + run.id + ); + let mut held = held.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + held.waiting.retain(|waiting| waiting.id != run.id); + held.lost.insert(run.id); + } + Err(e) => warn!("Failed to renew the lease on waiting job {}: {}", run.id, e), + } + } + } + } + + /// Hand claimed jobs that never started back to the queue + /// ([`DatabaseQueue::release_job_run`]) and refund their rate limit tokens. A job + /// that cannot be released stays `Running` until its lease expires. + async fn release_unstarted(&self, jobs: impl IntoIterator) { + let mut released = 0; + for job in jobs { + match self.queue.release_job_run(&job).await { + Ok(true) => { + released += 1; + if let Some(rate_limiter) = &self.rate_limiter { + rate_limiter.refund(); + } + } + Ok(false) => debug!( + "Job {} was no longer Running this run; nothing to release", + job.id + ), + Err(e) => warn!( + "Failed to release unstarted job {}; it stays Running until its lease \ + expires: {}", + job.id, e + ), + } + } + if released > 0 { + info!( + "Released {} claimed job(s) that had not started back to queue {}", + released, self.queue_name + ); + } } /// Sleep for the poll interval (at least [`MIN_POLL_INTERVAL`]), returning early @@ -4849,4 +5301,77 @@ mod tests { } assert!(started.elapsed() >= MIN_POLL_INTERVAL * 5); } + + #[cfg(feature = "postgres")] + #[tokio::test] + async fn batch_builders_set_size_concurrency_and_mode() { + let worker = lazy_worker("batch"); + assert!(!worker.is_batch_processing_enabled()); + assert_eq!(worker.batch_size(), DEFAULT_BATCH_SIZE); + assert_eq!(worker.batch_concurrency(), DEFAULT_BATCH_CONCURRENCY); + + // The old builder alone enables batch claims of the default size. + let enabled = lazy_worker("batch").with_batch_processing_enabled(true); + assert!(enabled.is_batch_processing_enabled()); + assert_eq!(enabled.batch_size(), DEFAULT_BATCH_SIZE); + + // `with_batch_size` enables batch mode; zero values are raised to one. + let sized = lazy_worker("batch") + .with_batch_size(0) + .with_batch_concurrency(0); + assert!(sized.is_batch_processing_enabled()); + assert_eq!(sized.batch_size(), 1); + assert_eq!(sized.batch_concurrency(), 1); + + let worker = lazy_worker("batch") + .with_batch_size(25) + .with_batch_concurrency(5); + let clone = worker.clone(); + assert_eq!(clone.batch_size(), 25); + assert_eq!(clone.batch_concurrency(), 5); + assert!(clone.is_batch_processing_enabled()); + // Batch mode can still be switched off afterwards. + assert!( + !worker + .with_batch_processing_enabled(false) + .is_batch_processing_enabled() + ); + } + + #[tokio::test] + async fn next_finished_yields_runs_as_they_finish() { + let mut runs: Vec> = Vec::new(); + assert!(next_finished(&mut runs).await.is_none()); + + let ids: Vec = (0..3).map(|_| uuid::Uuid::new_v4()).collect(); + for (index, id) in ids.iter().copied().enumerate() { + // The first-pushed run finishes last. + let delay = Duration::from_millis(60 - 20 * index as u64); + runs.push(Box::pin(async move { + sleep(delay).await; + (id, Ok(())) + })); + } + let mut order = Vec::new(); + while let Some((id, outcome)) = next_finished(&mut runs).await { + assert!(outcome.is_ok()); + order.push(id); + } + assert_eq!(order, [ids[2], ids[1], ids[0]]); + assert!(runs.is_empty()); + } + + #[cfg(feature = "postgres")] + #[test] + fn held_job_with_a_lost_lease_is_not_started() { + let kept = Job::new("held".to_string(), serde_json::json!({})); + let lost = Job::new("held".to_string(), serde_json::json!({})); + let held = std::sync::Mutex::new(HeldJobs { + waiting: vec![kept.clone(), lost.clone()], + lost: std::collections::HashSet::from([lost.id]), + }); + assert!(Worker::::start_held(&held, kept.id)); + assert!(!Worker::::start_held(&held, lost.id)); + assert!(held.lock().unwrap().waiting.is_empty()); + } } diff --git a/tests/batch_dequeue_tests.rs b/tests/batch_dequeue_tests.rs new file mode 100644 index 0000000..ace7df8 --- /dev/null +++ b/tests/batch_dequeue_tests.rs @@ -0,0 +1,969 @@ +//! Batch claims (`DatabaseQueue::dequeue_batch_leased`) and batch-mode workers +//! (`Worker::with_batch_size`). +//! +//! The queue scenarios run against PostgreSQL, MySQL and `TestQueue`, so the in-memory +//! queue is held to the same behaviour; the worker scenarios run against both database +//! backends. Each claimed job must get the same guarantees as a single claim: lease, +//! attempt count, pause/dependency/recurring checks, priority order and exactly-once +//! claiming under concurrency. + +#![cfg(any(feature = "postgres", feature = "mysql", feature = "test"))] + +mod test_utils; + +use chrono::Utc; +use hammerwork::{ + Job, JobId, JobPriority, JobStatus, PriorityWeights, cron::CronSchedule, queue::DatabaseQueue, + workflow::JobGroup, +}; +use serde_json::json; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, + time::Duration, +}; + +/// A job of `queue_name` with `priority`, due `age_secs` seconds ago (so claim order +/// within a priority level is known, on TestQueue's mock clock too). +fn aged_job(queue_name: &str, priority: JobPriority, age_secs: i64) -> Job { + let mut job = + Job::new(queue_name.to_string(), json!({ "age": age_secs })).with_priority(priority); + job.scheduled_at = Utc::now() - chrono::Duration::seconds(age_secs); + job +} + +/// A batch claims up to N jobs, highest priority first then oldest, each `Running` +/// with its attempt counted. +async fn batch_claims_in_priority_order(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("batch_order"); + let specs = [ + (JobPriority::Normal, 50), + (JobPriority::Critical, 10), + (JobPriority::Low, 90), + (JobPriority::Normal, 70), + (JobPriority::High, 20), + (JobPriority::Critical, 30), + ]; + let mut ids = HashMap::new(); + for (priority, age) in specs { + let id = queue + .enqueue(aged_job(&queue_name, priority, age)) + .await + .unwrap(); + ids.insert(id, (priority, age)); + } + + assert!( + queue + .dequeue_batch(&queue_name, 0) + .await + .unwrap() + .is_empty() + ); + + let first = queue.dequeue_batch(&queue_name, 4).await.unwrap(); + let order: Vec<(JobPriority, i64)> = first.iter().map(|job| ids[&job.id]).collect(); + assert_eq!( + order, + [ + (JobPriority::Critical, 30), + (JobPriority::Critical, 10), + (JobPriority::High, 20), + (JobPriority::Normal, 70), + ] + ); + for job in &first { + assert_eq!(job.status, JobStatus::Running); + assert_eq!(job.attempts, 1); + assert!(job.started_at.is_some()); + let stored = queue.get_job(job.id).await.unwrap().unwrap(); + assert_eq!(stored.status, JobStatus::Running); + assert_eq!(stored.attempts, 1); + } + + // The rest, then nothing. + let rest = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let order: Vec<(JobPriority, i64)> = rest.iter().map(|job| ids[&job.id]).collect(); + assert_eq!(order, [(JobPriority::Normal, 50), (JobPriority::Low, 90)]); + assert!( + queue + .dequeue_batch(&queue_name, 10) + .await + .unwrap() + .is_empty() + ); + + // Strict weights claim in the same strict order. + let strict_queue = test_utils::unique_queue("batch_strict"); + for (priority, age) in specs { + queue + .enqueue(aged_job(&strict_queue, priority, age)) + .await + .unwrap(); + } + let strict = queue + .dequeue_batch_leased( + &strict_queue, + Some(&PriorityWeights::strict()), + Duration::from_secs(60), + 3, + ) + .await + .unwrap(); + let priorities: Vec = strict.iter().map(|job| job.priority).collect(); + assert_eq!( + priorities, + [ + JobPriority::Critical, + JobPriority::Critical, + JobPriority::High + ] + ); +} + +/// With weighted priorities a batch is filled from one level picked by weight, then +/// topped up from the other levels when that level runs out. +async fn weighted_batch_fills_from_picked_level(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("batch_weighted"); + for age in 0..5 { + queue + .enqueue(aged_job(&queue_name, JobPriority::High, 100 - age)) + .await + .unwrap(); + queue + .enqueue(aged_job(&queue_name, JobPriority::Low, 200 - age)) + .await + .unwrap(); + } + let weights = PriorityWeights::new(); + let lease = Duration::from_secs(60); + + let first = queue + .dequeue_batch_leased(&queue_name, Some(&weights), lease, 3) + .await + .unwrap(); + assert_eq!(first.len(), 3); + let level = first[0].priority; + assert!( + first.iter().all(|job| job.priority == level), + "a batch smaller than the picked level comes from that level only" + ); + // Oldest first within the level. + assert!( + first + .windows(2) + .all(|pair| pair[0].scheduled_at <= pair[1].scheduled_at) + ); + + // Seven are left (2 of the picked level, 5 of the other): a batch of 7 takes all. + let rest = queue + .dequeue_batch_leased(&queue_name, Some(&weights), lease, 10) + .await + .unwrap(); + assert_eq!(rest.len(), 7); + let all: HashSet = first.iter().chain(&rest).map(|job| job.id).collect(); + assert_eq!(all.len(), 10); +} + +/// Paused queues, unfinished dependencies and disabled recurring jobs hold their jobs, +/// as for single claims. +async fn batch_honours_pause_dependencies_and_recurring(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("batch_holds"); + + // A workflow: `child` waits for `parent`. + let parent = Job::new(queue_name.clone(), json!({ "step": "parent" })); + let child = Job::new(queue_name.clone(), json!({ "step": "child" })).depends_on(&parent.id); + let (parent_id, child_id) = (parent.id, child.id); + queue + .enqueue_workflow(JobGroup::new("batch").add_job(parent).then(child)) + .await + .unwrap(); + + // A disabled recurring job's pending occurrence. + let mut cron_job = Job::new(queue_name.clone(), json!({})) + .with_cron(CronSchedule::new("0 0 * * * *").unwrap()) + .unwrap(); + cron_job.scheduled_at = Utc::now() - chrono::Duration::hours(1); + cron_job.next_run_at = Some(cron_job.scheduled_at); + let held_cron = queue.enqueue(cron_job).await.unwrap(); + queue.disable_recurring_job(held_cron).await.unwrap(); + + let plain = queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + + // Paused: nothing is claimed. + queue.pause_queue(&queue_name, Some("test")).await.unwrap(); + assert!( + queue + .dequeue_batch(&queue_name, 10) + .await + .unwrap() + .is_empty() + ); + queue.resume_queue(&queue_name, Some("test")).await.unwrap(); + + let claimed = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let ids: HashSet = claimed.iter().map(|job| job.id).collect(); + assert_eq!(ids, HashSet::from([parent_id, plain])); + + // Completing the parent releases the child. + let parent_run = claimed.iter().find(|job| job.id == parent_id).unwrap(); + queue + .finish_job_run(parent_run, hammerwork::JobOutcome::Completed) + .await + .unwrap() + .expect("the parent run is recorded"); + let next = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let ids: Vec = next.iter().map(|job| job.id).collect(); + assert_eq!(ids, [child_id]); + assert_eq!( + queue.get_job(held_cron).await.unwrap().unwrap().status, + JobStatus::Pending, + "a disabled recurring job ran" + ); +} + +/// Every job of a batch holds its own lease from the claim: a reaper with any +/// staleness window leaves it alone, and the lease can be renewed per job. +async fn batch_claims_hold_leases(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + // The reaper looks at every queue. + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("batch_leases"); + for _ in 0..3 { + queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + } + let claimed = queue + .dequeue_batch_leased(&queue_name, None, Duration::from_secs(600), 3) + .await + .unwrap(); + assert_eq!(claimed.len(), 3); + + let recovery = queue.requeue_stale_jobs(Duration::ZERO).await.unwrap(); + for job in &claimed { + assert!( + !recovery.requeued.contains(&job.id) && !recovery.dead.contains(&job.id), + "a job claimed in a batch had no lease" + ); + assert!( + queue + .heartbeat_job(job, Duration::from_secs(600)) + .await + .unwrap() + ); + } +} + +/// `release_job_run` hands a claimed job back as if it had not been claimed, once. +async fn release_returns_unstarted_job(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("batch_release"); + for age in [20, 10] { + queue + .enqueue(aged_job(&queue_name, JobPriority::Normal, age)) + .await + .unwrap(); + } + let claimed = queue.dequeue_batch(&queue_name, 2).await.unwrap(); + assert_eq!(claimed.len(), 2); + let released = &claimed[0]; + + assert!(queue.release_job_run(released).await.unwrap()); + let stored = queue.get_job(released.id).await.unwrap().unwrap(); + assert_eq!(stored.status, JobStatus::Pending); + assert_eq!(stored.attempts, 0, "the claim's attempt is taken back"); + assert_eq!(stored.started_at, None); + // Not Running this run any more: nothing to release, and no heartbeat. + assert!(!queue.release_job_run(released).await.unwrap()); + assert!( + !queue + .heartbeat_job(released, Duration::from_secs(60)) + .await + .unwrap() + ); + + // It keeps its place and is claimed again. + tokio::time::sleep(Duration::from_millis(5)).await; + let again = queue.dequeue_batch(&queue_name, 5).await.unwrap(); + let ids: Vec = again.iter().map(|job| job.id).collect(); + assert_eq!(ids, [released.id]); + assert_eq!(again[0].attempts, 1); + // A stale run (the first claim) cannot release the new one. Runs are told apart by + // their start time, which TestQueue's mock clock does not move on its own. + if again[0].started_at != released.started_at { + assert!(!queue.release_job_run(released).await.unwrap()); + assert_eq!( + queue.get_job(released.id).await.unwrap().unwrap().status, + JobStatus::Running + ); + } +} + +/// Several tasks claiming batches (strict and weighted) and single jobs at once never +/// claim the same job twice, and together claim every job. +async fn concurrent_batch_claims_never_double_claim(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + const JOBS: usize = 300; + let queue_name = test_utils::unique_queue("batch_concurrent"); + let priorities = [ + JobPriority::Background, + JobPriority::Low, + JobPriority::Normal, + JobPriority::High, + JobPriority::Critical, + ]; + let jobs: Vec = (0..JOBS) + .map(|i| { + Job::new(queue_name.clone(), json!({ "i": i })) + .with_priority(priorities[i % priorities.len()]) + }) + .collect(); + let expected: HashSet = jobs.iter().map(|job| job.id).collect(); + for job in jobs { + queue.enqueue(job).await.unwrap(); + } + + let mut tasks = Vec::new(); + for task in 0..8usize { + let queue = Arc::clone(&queue); + let queue_name = queue_name.clone(); + tasks.push(tokio::spawn(async move { + let weights = PriorityWeights::new(); + let mut claimed = Vec::new(); + let mut empty_polls = 0; + while empty_polls < 3 { + let batch = match task % 4 { + 0 => queue + .dequeue_leased(&queue_name, None, Duration::from_secs(600)) + .await + .unwrap() + .into_iter() + .collect(), + 1 => queue + .dequeue_batch_leased( + &queue_name, + Some(&weights), + Duration::from_secs(600), + 5 + task, + ) + .await + .unwrap(), + _ => queue + .dequeue_batch_leased(&queue_name, None, Duration::from_secs(600), 7) + .await + .unwrap(), + }; + if batch.is_empty() { + empty_polls += 1; + tokio::time::sleep(Duration::from_millis(5)).await; + } else { + empty_polls = 0; + claimed.extend(batch.into_iter().map(|job: Job| job.id)); + } + } + claimed + })); + } + + let mut seen = HashSet::new(); + let mut total = 0; + for task in tasks { + for id in task.await.unwrap() { + total += 1; + assert!(seen.insert(id), "job {id} was claimed twice"); + } + } + assert_eq!(total, JOBS); + assert_eq!(seen, expected); + for id in expected.iter().take(20) { + assert_eq!(queue.get_job(*id).await.unwrap().unwrap().attempts, 1); + } +} + +/// 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(flavor = "multi_thread", worker_threads = 4)] + #[$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", + [ + batch_claims_in_priority_order, + weighted_batch_fills_from_picked_level, + batch_honours_pause_dependencies_and_recurring, + batch_claims_hold_leases, + release_returns_unstarted_job, + concurrent_batch_claims_never_double_claim, + ] +); + +#[cfg(feature = "mysql")] +backend_tests!( + mysql_tests, + test_utils::setup_mysql_queue, + ignore = "requires MySQL: MYSQL_DATABASE_URL", + [ + batch_claims_in_priority_order, + weighted_batch_fills_from_picked_level, + batch_honours_pause_dependencies_and_recurring, + batch_claims_hold_leases, + release_returns_unstarted_job, + concurrent_batch_claims_never_double_claim, + ] +); + +#[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), + [ + batch_claims_in_priority_order, + weighted_batch_fills_from_picked_level, + batch_honours_pause_dependencies_and_recurring, + batch_claims_hold_leases, + release_returns_unstarted_job, + concurrent_batch_claims_never_double_claim, + ] +); + +/// Worker scenarios: they need a `JobQueue`, so they run on the database backends only. +#[cfg(any(feature = "postgres", feature = "mysql"))] +mod worker { + use super::*; + use hammerwork::{ + HammerworkError, JobQueue, RateLimit, ThrottleConfig, Worker, worker::JobHandler, + }; + use std::{ + sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Instant, + }; + use tokio::sync::mpsc; + + async fn enqueue_jobs( + queue: &Arc>, + queue_name: &str, + count: usize, + ) -> Vec + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + let mut ids = Vec::with_capacity(count); + for i in 0..count { + ids.push( + queue + .enqueue(Job::new(queue_name.to_string(), json!({ "i": i }))) + .await + .unwrap(), + ); + } + ids + } + + /// Wait until `queue_name` has `count` jobs in `status`, or panic after `timeout`. + async fn wait_for_status( + queue: &Arc>, + queue_name: &str, + status: &str, + count: u64, + timeout: Duration, + ) where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + let deadline = Instant::now() + timeout; + loop { + let counts = queue.get_job_counts_by_status(queue_name).await.unwrap(); + let have = counts.get(status).copied().unwrap_or(0); + if have == count { + return; + } + assert!( + Instant::now() < deadline, + "timed out waiting for {count} {status} jobs: {counts:?}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + + /// A handler that counts runs per job id, sleeping `delay` in each. + fn counting_handler(runs: Arc>>, delay: Duration) -> JobHandler { + Arc::new(move |job: Job| { + let runs = Arc::clone(&runs); + Box::pin(async move { + *runs.lock().unwrap().entry(job.id).or_default() += 1; + tokio::time::sleep(delay).await; + Ok::<(), HammerworkError>(()) + }) + }) + } + + /// A pool of batch-mode workers runs every job exactly once. + pub async fn batch_worker_processes_everything_once(queue: Arc>) + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + const JOBS: usize = 150; + let queue_name = test_utils::unique_queue("batch_worker"); + let ids = enqueue_jobs(&queue, &queue_name, JOBS).await; + let runs = Arc::new(Mutex::new(HashMap::new())); + + let mut tasks = Vec::new(); + let mut senders = Vec::new(); + for _ in 0..3 { + let worker = Worker::new( + Arc::clone(&queue), + queue_name.clone(), + counting_handler(Arc::clone(&runs), Duration::from_millis(2)), + ) + .with_poll_interval(Duration::from_millis(20)) + .with_batch_size(8) + .with_batch_concurrency(3); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + senders.push(shutdown_tx); + tasks.push(tokio::spawn(async move { worker.run(shutdown_rx).await })); + } + + wait_for_status( + &queue, + &queue_name, + "Completed", + JOBS as u64, + Duration::from_secs(60), + ) + .await; + let runs = runs.lock().unwrap().clone(); + assert_eq!(runs.len(), JOBS); + assert!(runs.values().all(|count| *count == 1), "a job ran twice"); + assert!(ids.iter().all(|id| runs.contains_key(id))); + for id in ids.iter().take(20) { + assert_eq!(queue.get_job(*id).await.unwrap().unwrap().attempts, 1); + } + + for sender in senders { + sender.send(()).await.unwrap(); + } + for task in tasks { + task.await.unwrap().unwrap(); + } + } + + /// Jobs waiting their turn in a batch keep their leases: with a lease much shorter + /// than the batch takes, a reaper running throughout reclaims none of them. + pub async fn held_jobs_are_not_reaped_while_waiting(queue: Arc>) + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("batch_held"); + let ids = enqueue_jobs(&queue, &queue_name, 4).await; + let runs = Arc::new(Mutex::new(HashMap::new())); + + // Lease 600ms, heartbeat every 200ms; the batch runs ~2.8s one job at a time. + let worker = Worker::new( + Arc::clone(&queue), + queue_name.clone(), + counting_handler(Arc::clone(&runs), Duration::from_millis(700)), + ) + .with_poll_interval(Duration::from_millis(20)) + .with_lease_duration(Duration::from_millis(600)) + .with_batch_size(4) + .with_batch_concurrency(1); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let recovery = queue + .requeue_stale_jobs(Duration::from_secs(3600)) + .await + .unwrap(); + for id in &ids { + assert!( + !recovery.requeued.contains(id) && !recovery.dead.contains(id), + "job {id} was reaped while held by a live batch worker" + ); + } + let counts = queue.get_job_counts_by_status(&queue_name).await.unwrap(); + if counts.get("Completed") == Some(&4) { + break; + } + assert!( + Instant::now() < deadline, + "batch did not finish: {counts:?}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let runs = runs.lock().unwrap().clone(); + assert_eq!(runs.len(), 4); + assert!(runs.values().all(|count| *count == 1)); + for id in &ids { + assert_eq!(queue.get_job(*id).await.unwrap().unwrap().attempts, 1); + } + + shutdown_tx.send(()).await.unwrap(); + worker_task.await.unwrap().unwrap(); + } + + /// On shutdown, the claimed jobs that have not started go straight back to + /// `Pending` (attempt not counted) while the running one finishes. + pub async fn shutdown_releases_unstarted_jobs(queue: Arc>) + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + let queue_name = test_utils::unique_queue("batch_shutdown"); + let ids = enqueue_jobs(&queue, &queue_name, 5).await; + let runs = Arc::new(Mutex::new(HashMap::new())); + + let worker = Worker::new( + Arc::clone(&queue), + queue_name.clone(), + counting_handler(Arc::clone(&runs), Duration::from_millis(800)), + ) + .with_poll_interval(Duration::from_millis(20)) + .with_shutdown_grace_period(Duration::from_secs(10)) + .with_batch_size(5) + .with_batch_concurrency(1); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + // All five are claimed in one batch, and the first starts. + wait_for_status(&queue, &queue_name, "Running", 5, Duration::from_secs(10)).await; + let deadline = Instant::now() + Duration::from_secs(10); + while runs.lock().unwrap().is_empty() { + assert!(Instant::now() < deadline, "no job started"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let requested = Instant::now(); + shutdown_tx.send(()).await.unwrap(); + worker_task.await.unwrap().unwrap(); + assert!(requested.elapsed() < Duration::from_secs(5)); + + let started: Vec = runs.lock().unwrap().keys().copied().collect(); + assert_eq!(started.len(), 1, "only the first job of the batch started"); + for id in &ids { + let job = queue.get_job(*id).await.unwrap().unwrap(); + if started.contains(id) { + assert_eq!(job.status, JobStatus::Completed, "the running job finished"); + } else { + assert_eq!( + job.status, + JobStatus::Pending, + "an unstarted job was not released" + ); + assert_eq!(job.attempts, 0); + assert_eq!(job.started_at, None); + } + } + + // The released jobs run normally afterwards. + let claimed = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + assert_eq!(claimed.len(), 4); + } + + /// A throttle's `max_concurrent` bounds the jobs a batch-mode pool holds (claims or + /// runs) at once, whatever the batch size and concurrency. + pub async fn batch_worker_respects_throttle(queue: Arc>) + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + const JOBS: usize = 12; + let queue_name = test_utils::unique_queue("batch_throttle"); + enqueue_jobs(&queue, &queue_name, JOBS).await; + + let active = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let done = Arc::new(AtomicUsize::new(0)); + let handler: JobHandler = { + let (active, peak, done) = (Arc::clone(&active), Arc::clone(&peak), Arc::clone(&done)); + Arc::new(move |_job: Job| { + let (active, peak, done) = + (Arc::clone(&active), Arc::clone(&peak), Arc::clone(&done)); + Box::pin(async move { + let now = active.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(100)).await; + active.fetch_sub(1, Ordering::SeqCst); + done.fetch_add(1, Ordering::SeqCst); + Ok::<(), HammerworkError>(()) + }) + }) + }; + let template = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(20)) + .with_throttle_config(ThrottleConfig::new().max_concurrent(2)) + .with_batch_size(10) + .with_batch_concurrency(10); + // Two clones share the throttle. + let workers = [template.clone(), template]; + let mut tasks = Vec::new(); + let mut senders = Vec::new(); + for worker in workers { + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + senders.push(shutdown_tx); + tasks.push(tokio::spawn(async move { worker.run(shutdown_rx).await })); + } + + let deadline = Instant::now() + Duration::from_secs(30); + while done.load(Ordering::SeqCst) < JOBS { + let counts = queue.get_job_counts_by_status(&queue_name).await.unwrap(); + let running = counts.get("Running").copied().unwrap_or(0); + assert!( + running <= 2, + "{running} jobs held at once with max_concurrent 2" + ); + assert!(Instant::now() < deadline, "jobs did not finish"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(peak.load(Ordering::SeqCst) <= 2); + wait_for_status( + &queue, + &queue_name, + "Completed", + JOBS as u64, + Duration::from_secs(10), + ) + .await; + + for sender in senders { + sender.send(()).await.unwrap(); + } + for task in tasks { + task.await.unwrap().unwrap(); + } + } + + /// A rate limit caps how many jobs a batch claims: with a burst of 3 and 3 jobs a + /// second, a batch size of 10 claims at most the tokens available. + pub async fn batch_worker_respects_rate_limit(queue: Arc>) + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + const JOBS: usize = 9; + let queue_name = test_utils::unique_queue("batch_rate"); + enqueue_jobs(&queue, &queue_name, JOBS).await; + + let starts = Arc::new(Mutex::new(Vec::new())); + let handler: JobHandler = { + let starts = Arc::clone(&starts); + Arc::new(move |_job: Job| { + let starts = Arc::clone(&starts); + Box::pin(async move { + starts.lock().unwrap().push(Instant::now()); + Ok::<(), HammerworkError>(()) + }) + }) + }; + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(20)) + .with_rate_limit(RateLimit::per_second(3)) + .with_batch_size(10) + .with_batch_concurrency(10); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let began = Instant::now(); + let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + // The first poll can take the 3-token burst only; the queue keeps the rest. + let deadline = Instant::now() + Duration::from_secs(10); + while starts.lock().unwrap().is_empty() { + assert!(Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(5)).await; + } + let counts = queue.get_job_counts_by_status(&queue_name).await.unwrap(); + assert!( + counts.get("Pending").copied().unwrap_or(0) >= (JOBS - 3) as u64, + "a batch claimed more jobs than it had rate limit tokens: {counts:?}" + ); + + wait_for_status( + &queue, + &queue_name, + "Completed", + JOBS as u64, + Duration::from_secs(20), + ) + .await; + // A burst of 3, then one token every 333ms: the k-th job (from 1) cannot start + // before (k - 3) / 3 seconds. + let mut starts = starts.lock().unwrap().clone(); + starts.sort(); + assert_eq!(starts.len(), JOBS); + for (index, start) in starts.iter().enumerate() { + let earliest = Duration::from_millis(333 * (index as u64 + 1).saturating_sub(3)); + let at = start.duration_since(began); + assert!( + at + Duration::from_millis(100) >= earliest, + "job {} started at {at:?}, before its rate limit token ({earliest:?})", + index + 1 + ); + } + + shutdown_tx.send(()).await.unwrap(); + worker_task.await.unwrap().unwrap(); + } + + /// Informative benchmark, not a gate: jobs per second claimed one at a time versus + /// in batches, and processed by a single-job versus a batch-mode worker. Run with + /// `--nocapture` to see the numbers. + pub async fn batch_vs_single_claim_throughput(queue: Arc>) + where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + { + if std::env::var_os("HAMMERWORK_BENCH").is_none() { + eprintln!("set HAMMERWORK_BENCH=1 to run the batch claim benchmark"); + return; + } + const JOBS: usize = 2000; + let backend = std::any::type_name::(); + + // Claims only. + let single_queue = test_utils::unique_queue("bench_single"); + enqueue_jobs(&queue, &single_queue, JOBS).await; + let began = Instant::now(); + let mut claimed = 0; + while queue.dequeue(&single_queue).await.unwrap().is_some() { + claimed += 1; + } + let single = claimed as f64 / began.elapsed().as_secs_f64(); + + let mut batch_rates = Vec::new(); + for size in [10, 50, 100] { + let batch_queue = test_utils::unique_queue("bench_batch"); + enqueue_jobs(&queue, &batch_queue, JOBS).await; + let began = Instant::now(); + let mut claimed = 0; + loop { + let batch = queue.dequeue_batch(&batch_queue, size).await.unwrap(); + if batch.is_empty() { + break; + } + claimed += batch.len(); + } + batch_rates.push((size, claimed as f64 / began.elapsed().as_secs_f64())); + } + eprintln!("[{backend}] claim throughput: single {single:.0} jobs/s"); + for (size, rate) in &batch_rates { + eprintln!( + "[{backend}] claim throughput: batch of {size} {rate:.0} jobs/s ({:.1}x)", + rate / single + ); + } + + // End to end: one worker, no-op handler. + let mut worker_rates = Vec::new(); + for (label, size, concurrency) in [ + ("single-job worker", 0, 1), + ("batch worker (10, sequential)", 10, 1), + ("batch worker (50, concurrency 10)", 50, 10), + ] { + let worker_queue = test_utils::unique_queue("bench_worker"); + enqueue_jobs(&queue, &worker_queue, JOBS).await; + let handler: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); + let mut worker = Worker::new(Arc::clone(&queue), worker_queue.clone(), handler) + .with_poll_interval(Duration::from_millis(10)); + if size > 0 { + worker = worker + .with_batch_size(size) + .with_batch_concurrency(concurrency); + } + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let began = Instant::now(); + let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + wait_for_status( + &queue, + &worker_queue, + "Completed", + JOBS as u64, + Duration::from_secs(600), + ) + .await; + worker_rates.push((label, JOBS as f64 / began.elapsed().as_secs_f64())); + shutdown_tx.send(()).await.unwrap(); + task.await.unwrap().unwrap(); + } + for (label, rate) in &worker_rates { + eprintln!("[{backend}] worker throughput: {label} {rate:.0} jobs/s"); + } + } + + #[cfg(feature = "postgres")] + backend_tests!( + postgres_tests, + test_utils::setup_postgres_queue, + ignore = "requires PostgreSQL: DATABASE_URL", + [ + batch_worker_processes_everything_once, + held_jobs_are_not_reaped_while_waiting, + shutdown_releases_unstarted_jobs, + batch_worker_respects_throttle, + batch_worker_respects_rate_limit, + batch_vs_single_claim_throughput, + ] + ); + + #[cfg(feature = "mysql")] + backend_tests!( + mysql_tests, + test_utils::setup_mysql_queue, + ignore = "requires MySQL: MYSQL_DATABASE_URL", + [ + batch_worker_processes_everything_once, + held_jobs_are_not_reaped_while_waiting, + shutdown_releases_unstarted_jobs, + batch_worker_respects_throttle, + batch_worker_respects_rate_limit, + batch_vs_single_claim_throughput, + ] + ); +} diff --git a/tests/payload_encryption_tests.rs b/tests/payload_encryption_tests.rs index 9e12d90..7770200 100644 --- a/tests/payload_encryption_tests.rs +++ b/tests/payload_encryption_tests.rs @@ -1341,6 +1341,76 @@ where assert!(children.iter().all(|c| c.depends_on == vec![id])); } +/// Jobs claimed in a batch come back in their stored (encrypted) form, like a single +/// dequeue, and a batch-mode worker hands each handler the plaintext. +async fn batch_claims_round_trip(plain: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue = encrypted_queue(&plain, engine("k1", KEY_A).await).await; + let queue_name = test_utils::unique_queue("enc_batch"); + let mut payloads = Vec::new(); + for i in 0..3 { + let payload = json!({ "card": secret("card"), "i": i }); + queue + .enqueue( + Job::new(queue_name.clone(), payload.clone()) + .with_encryption(config("k1")) + .with_retention_policy(long_retention()), + ) + .await + .unwrap(); + payloads.push(payload); + } + + let claimed = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + assert_eq!(claimed.len(), 3); + let mut decrypted = Vec::new(); + for job in claimed { + assert!(job.is_encrypted); + assert_eq!(job.payload, json!({"encrypted": true})); + let run = job.clone(); + decrypted.push(queue.decrypt_job(job).await.unwrap().payload); + // Hand it back for the worker below. + assert!(queue.release_job_run(&run).await.unwrap()); + } + decrypted.sort_by_key(|payload| payload["i"].as_i64()); + assert_eq!(decrypted, payloads); + + let seen = Arc::new(Mutex::new(Vec::new())); + let handler: JobHandler = { + let seen = Arc::clone(&seen); + Arc::new(move |job: Job| { + let seen = Arc::clone(&seen); + Box::pin(async move { + seen.lock().unwrap().push(job.payload.clone()); + Ok(()) + }) + }) + }; + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(50)) + .with_batch_size(5) + .with_batch_concurrency(2); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + let deadline = Instant::now() + Duration::from_secs(15); + while seen.lock().unwrap().len() < 3 { + assert!( + Instant::now() < deadline, + "the batch worker did not run the jobs" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + shutdown_tx.send(()).await.unwrap(); + task.await.unwrap().unwrap(); + + let mut seen = seen.lock().unwrap().clone(); + seen.sort_by_key(|payload| payload["i"].as_i64()); + assert_eq!(seen, payloads, "the handlers see the plaintext"); +} + #[cfg(feature = "postgres")] mod postgres { use super::*; @@ -1351,6 +1421,12 @@ mod postgres { whole_payload_round_trip(test_utils::setup_postgres_queue().await).await; } + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_batch_claims_round_trip() { + batch_claims_round_trip(test_utils::setup_postgres_queue().await).await; + } + #[tokio::test] #[ignore] // Requires database connection async fn test_postgres_pii_fields_round_trip() { @@ -1462,6 +1538,12 @@ mod mysql { whole_payload_round_trip(test_utils::setup_mysql_queue().await).await; } + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_batch_claims_round_trip() { + batch_claims_round_trip(test_utils::setup_mysql_queue().await).await; + } + #[tokio::test] #[ignore] // Requires database connection async fn test_mysql_pii_fields_round_trip() { From 609cdd44324fa13a22f94d01eb2bf712fc885b84 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Fri, 9 Oct 2026 23:36:02 -0400 Subject: [PATCH 2/3] fix(worker): keep batch claiming opt-in via with_batch_size with_batch_processing_enabled(true) only kept batch statistics before 2.1; switching existing workers to claims of 10 would change how a minor release distributes work. Default the batch size to 1, so batch claims start only with with_batch_size(n). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++--------- docs/batch-operations.md | 3 ++- src/worker.rs | 14 ++++++++------ 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f551597..b1c8dad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,9 +40,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `queue::MAX_DEQUEUE_BATCH_SIZE` (1000) jobs per call. - **`DatabaseQueue::release_job_run`** hands a claimed job that never ran back to `Pending`, taking back the claim's attempt, so it can run elsewhere at once. -- **Batch-mode workers.** `Worker::with_batch_size(n)` (or - `with_batch_processing_enabled(true)`, which now claims batches of - `worker::DEFAULT_BATCH_SIZE` = 10) makes a worker claim up to `n` jobs per poll, and +- **Batch-mode workers.** `Worker::with_batch_size(n)` makes a worker claim up to `n` jobs + per poll (`with_batch_processing_enabled(true)` alone keeps `worker::DEFAULT_BATCH_SIZE` + = 1, so existing workers still claim one job at a time), and `Worker::with_batch_concurrency(m)` runs up to `m` of them at once (default 1). Each job is processed exactly as in single-job mode (timeouts, retries, hooks, events, spawning, result storage, encryption, statistics). Jobs waiting for their turn have their leases @@ -54,12 +54,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `batch_size`, `batch_concurrency`. In a local benchmark, batch claims of 50 were 5-6x faster than single claims on PostgreSQL and MySQL. -### Changed - -- `Worker::with_batch_processing_enabled(true)` used to only keep statistics for jobs of a - `JobBatch`; it now also switches the worker to batch claims (batch size 10, one job - running at a time). Leave it off to keep claiming one job per poll. - ## [2.0.0] - 2026-10-09 A hardening release ([#7](https://github.com/CodingAnarchy/hammerwork/issues/7)). It fixes diff --git a/docs/batch-operations.md b/docs/batch-operations.md index 2d2dbe7..c854f78 100644 --- a/docs/batch-operations.md +++ b/docs/batch-operations.md @@ -263,7 +263,8 @@ for (job_id, error) in &result.job_errors { A worker in batch mode claims up to `batch_size` jobs per poll in one round trip instead of one job per round trip, then runs them `batch_concurrency` at a time (one at a time by default). `with_batch_size(n)` enables batch mode; `with_batch_processing_enabled(true)` -alone enables it with the default batch size of 10: +alone keeps the default batch size of 1, so it claims one job per poll as before and only +adds batch statistics: ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; diff --git a/src/worker.rs b/src/worker.rs index 5a0bb39..6695822 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -80,9 +80,10 @@ pub const MIN_POLL_INTERVAL: Duration = Duration::from_millis(10); /// Floor on the heartbeat interval derived from the lease duration. const MIN_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(100); -/// Default number of jobs a worker in batch mode claims per poll -/// ([`Worker::with_batch_size`]). -pub const DEFAULT_BATCH_SIZE: usize = 10; +/// Default number of jobs a worker in batch mode claims per poll: one, so +/// `with_batch_processing_enabled(true)` alone keeps claiming one job at a time (as before +/// 2.1) and only adds batch statistics. Set a larger size with [`Worker::with_batch_size`]. +pub const DEFAULT_BATCH_SIZE: usize = 1; /// Default number of claimed jobs a worker in batch mode runs at once /// ([`Worker::with_batch_concurrency`]): one, so batch mode changes how jobs are claimed @@ -1546,7 +1547,8 @@ where /// # let queue = Arc::new(hammerwork::JobQueue::new(pool)); /// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) })); /// - /// // Claim up to 10 jobs (the default batch size) per poll, run them one at a time. + /// // Keep statistics for job batches; jobs are still claimed one at a time. Use + /// // `with_batch_size` to claim several jobs per poll. /// let worker = Worker::new(queue, "batch_queue".to_string(), handler) /// .with_batch_processing_enabled(true); /// # Ok(()) @@ -1560,7 +1562,7 @@ where /// Claim up to `size` jobs per poll, and enable batch processing (see /// [`with_batch_processing_enabled`](Self::with_batch_processing_enabled)). /// - /// Defaults to [`DEFAULT_BATCH_SIZE`] (10). Values below 1 are raised to 1, and the + /// Defaults to [`DEFAULT_BATCH_SIZE`] (1). Values below 1 are raised to 1, and the /// built-in backends claim at most /// [`MAX_DEQUEUE_BATCH_SIZE`](crate::queue::MAX_DEQUEUE_BATCH_SIZE) jobs at once. /// @@ -5310,7 +5312,7 @@ mod tests { assert_eq!(worker.batch_size(), DEFAULT_BATCH_SIZE); assert_eq!(worker.batch_concurrency(), DEFAULT_BATCH_CONCURRENCY); - // The old builder alone enables batch claims of the default size. + // The old builder alone enables batch mode with the default size of one job. let enabled = lazy_worker("batch").with_batch_processing_enabled(true); assert!(enabled.is_batch_processing_enabled()); assert_eq!(enabled.batch_size(), DEFAULT_BATCH_SIZE); From acaef7dbc2a67daf04fd4b9c2fb825c0b8df069a Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Fri, 9 Oct 2026 23:37:39 -0400 Subject: [PATCH 3/3] docs(changelog): keep batch claims under Unreleased after the 2.0.1 rebase Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1c8dad..64e3c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,23 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [2.0.1] - 2026-10-10 - -### Fixed - -- **In-memory result storage works.** A job configured with `ResultStorage::Memory` had - its result silently discarded: workers only stored `ResultStorage::Database` results. - Workers now store them in an in-memory store owned by the `JobQueue` and shared by its - clones, before the job is marked Completed, and `get_job_result`, `delete_job_result`, - `cleanup_expired_results` and `delete_job` use it. Results expire at their TTL (checked - on read and pruned as results are stored), and the store holds at most 10,000 results - by default (`queue::DEFAULT_MEMORY_RESULT_CAPACITY`), evicting the one that expires - soonest, or the oldest; set the limit with the new - `JobQueue::with_memory_result_capacity`. In-memory results are per process: other - processes, including `cargo hammerwork` and the web dashboard, don't see them, and - they are lost on restart. See [Job Results](docs/job-types.md#job-results). - `TestQueue::delete_job` now also deletes the job's result. - ### Added - **Batch claims.** `DatabaseQueue::dequeue_batch(queue, n)` and @@ -54,6 +37,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `batch_size`, `batch_concurrency`. In a local benchmark, batch claims of 50 were 5-6x faster than single claims on PostgreSQL and MySQL. +## [2.0.1] - 2026-10-10 + +### Fixed + +- **In-memory result storage works.** A job configured with `ResultStorage::Memory` had + its result silently discarded: workers only stored `ResultStorage::Database` results. + Workers now store them in an in-memory store owned by the `JobQueue` and shared by its + clones, before the job is marked Completed, and `get_job_result`, `delete_job_result`, + `cleanup_expired_results` and `delete_job` use it. Results expire at their TTL (checked + on read and pruned as results are stored), and the store holds at most 10,000 results + by default (`queue::DEFAULT_MEMORY_RESULT_CAPACITY`), evicting the one that expires + soonest, or the oldest; set the limit with the new + `JobQueue::with_memory_result_capacity`. In-memory results are per process: other + processes, including `cargo hammerwork` and the web dashboard, don't see them, and + they are lost on restart. See [Job Results](docs/job-types.md#job-results). + `TestQueue::delete_job` now also deletes the job's result. + ## [2.0.0] - 2026-10-09 A hardening release ([#7](https://github.com/CodingAnarchy/hammerwork/issues/7)). It fixes