Repository navigation
fix(worker,queue): job lifecycle hardening from #64 (W2) - #68
Merged
Merged
Conversation
…lock Several replicas starting with auto_migrate (or the CLI while the app starts) used to race: the losers failed on duplicate pg_type / hammerwork_migrations keys. run_migrations now holds a migration lock for the whole run (pg_advisory_lock on PostgreSQL, GET_LOCK on MySQL, keyed by the database), taken on a dedicated connection that also runs every statement, re-reads the applied migrations after acquiring it and releases it on every path. An abandoned run closes the connection, which releases the lock. Recording a migration ignores an existing row. New MigrationRunner::acquire_migration_lock / release_migration_lock with no-op defaults. Tests race 6 runs against a migrated database (with a non-idempotent probe migration) and against a fresh scratch database, on both backends; without the lock all of them fail. Part of #64 (H3). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…caling and harden the worker loop Part of #64: C1, C2, H9, H10, M1, M2, M5, M6, M8, M10, plus the TestQueue failure-policy gap left by #65. - C1: the claim writes lease_expires_at/last_heartbeat_at in the same statement (new DatabaseQueue::dequeue_leased; dequeue uses DEFAULT_LEASE_DURATION), so a reaper with any staleness window never reclaims a live job; older_than only applies to rows claimed without a lease. A zero lease never expires. heartbeat_job takes the run and only extends that run (attempts + started_at). - C2: spawned children are built before the parent completes (SpawnManager::prepare_spawn) and enqueued in the completing transaction (DatabaseQueue::complete_job_run_with_children); a spawn failure fails the run so the parent is retried. - H9: WorkerPool::new() does not autoscale; autoscaling only starts or retires workers of the template's queue. - H10: alerts are checked by the monitoring task (Worker::with_monitoring_interval), never in the dequeue loop; alert HTTP requests time out after 10s and a failed alert is retried after 60s (or the cooldown). - M1: disable_recurring_job holds the pending occurrence; enable_recurring_job reschedules from the next occurrence and revives finished jobs. CLI cron enable/disable use them. - M2: with_max_retries / Worker::new docs match the behaviour. - M5: zero polling_interval / job_timeout are rejected at config load; idle polls wait at least MIN_POLL_INTERVAL; a zero default timeout means none; sub-second durations round-trip through TOML. - M6: the rate limiter refunds the token of a poll that claims no job, and refills with sub-millisecond precision. - M8: no per-poll COUNT(*) for metrics. - M10: the monitoring task is aborted on every exit path (drop guard). - TestQueue: mark_job_dead/mark_job_timed_out apply the workflow failure policy; finish_job_run reports cancelled jobs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Oct 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #64: workstream W2 (job lifecycle). Fixes C1, C2, H3, H9, H10, M1, M2, M5, M6, M8, M10, and closes the gap #65 left in
TestQueue::mark_job_dead/mark_job_timed_out.It is one PR rather than two because the worker loop changes for C1/C2 and for H10/M5/M6/M8/M10 touch the same functions in
src/worker.rs. The migration lock (H3) is a separate commit and can be reviewed on its own.What changed, by finding
C1: the reaper reclaimed running jobs
lease_expires_at = now + leaseandlast_heartbeat_at = started_aton PostgreSQL (inclaim_sql), MySQL (in the claimingUPDATE) andTestQueue.DatabaseQueue::dequeue_leased(queue, weights, lease). Workers pass their own lease.dequeueanddequeue_with_priority_weightsusequeue::DEFAULT_LEASE_DURATION(5 minutes).older_thanis.older_than(thestarted_atage) now applies only to rows without a lease of their own, that is, rows claimed by a pre-upgrade worker. That is the conservative behaviour for legacy rows.job requeue-stalehelp and the docs say so.with_lease_duration(Duration::ZERO)takes a lease that never expires: no heartbeats, and the reaper never reclaims the job. It used to be reclaimed after the pool's fallback window.heartbeat_job(&run, lease)takes the dequeued run and matchesid,status = 'Running',attemptsandstarted_at(±1ms, as infinish_job_run). A stale worker's heartbeat returnsfalseand no longer extends the new run's lease.heartbeat_jobwas added in this unreleased cycle.015_add_job_leases.C2: lost spawned children
SpawnManager::prepare_spawnruns the spawn handler, checks the limit and applies inheritance, before the parent is completed.DatabaseQueue::complete_job_run_with_children(run, children). On PostgreSQL and MySQL it completes the parent and inserts the children in one transaction, guarded by the run. The default implementation enqueues the children first, then completes the parent.SpawnLimitExceeded, a malformed_spawn_configand a child insert error.on_spawn_completeruns after the commit.on_job_completehook no longer fires twice for spawning jobs.execute_spawnis kept for use outside workers.H3: concurrent migrations
run_migrationsholds a migration lock for the whole run:pg_advisory_lock.GET_LOCK('hammerwork_migrations:' + SHA1(DATABASE())). The name is hashed because MySQL lock names are server-wide and at most 64 characters.How the lock is held:
close_on_drop, so an abandoned run releases the lock as well.Other changes:
ON CONFLICT DO NOTHING/INSERT IGNORE.MigrationRunner::acquire_migration_lock/release_migration_lock, with no-op defaults.current_schema().H9: autoscaling
WorkerPool::new()usesAutoscaleConfig::disabled().AutoscaleConfig::default()and the presets are still enabled, so an explicitwith_autoscaling(AutoscaleConfig::default())keeps working.H10: alerts in the dequeue loop
acquire_jobno longer checks alert thresholds or starvation. The monitoring task already did both; its interval is now configurable withWorker::with_monitoring_interval(default 30s).ALERT_HTTP_TIMEOUT).FAILED_ALERT_RETRY_DELAY(60s, or the cooldown if that is shorter) instead of on every check.M1: disable and enable recurring jobs
recurringandnext_run_at.Pendingbut is held. The runnable predicate now requiresrecurring OR cron_schedule IS NULL, in both backends'RUNNABLE_IN_QUEUE_SQLand inTestQueue.Running, reschedules it to the next occurrence after now:Pending, attempts reset. This revives aCompleted,Failed,DeadorTimedOutjob. Occurrences missed while the job was disabled are not run.JobNotFoundfor a missing job, and an error for a job without a cron schedule. This is the same on every backend.cron enable/cron disablenow call these methods instead of flipping the flag with raw SQL.Smaller fixes
with_max_retriesexample now shows it lowering the limit. TheWorker::newdocs drop the "3 maximum retry attempts" claim. The behaviour is unchanged.WorkerConfig::validaterejects a zeropolling_intervaland a zerojob_timeout. It runs infrom_file,from_envandWorkerPool::from_hammerwork_config, consistent with howpurge_interval_secs = 0is already rejected.MIN_POLL_INTERVAL(10ms), andwith_default_timeout(ZERO)means no default timeout."0s". Sub-second durations are now written in milliseconds ("500ms").refund()s it when no job is claimed.get_queue_depthfor metrics is removed. The monitoring task updates the queue depth.mark_job_deadandmark_job_timed_outapply the workflow policy and a fail-fast batch's failure.finish_job_runis overridden, soRecordedOutcome::cancelledis correct.Deadapplies the policy too.Behaviour and API changes to note
DatabaseQueue:dequeue_leased,complete_job_run_with_children;heartbeat_jobsignature: takes&Job, not a job id;RecordedOutcome.spawnedis new.WorkerPool::new()no longer autoscales.polling_intervalorjob_timeoutare rejected.TestQueuecron reschedule semantics (it creates a new job) are unchanged; that is out of scope.Tests
New generic scenarios follow the
backend_tests!pattern and run on PostgreSQL and MySQL (and onTestQueuewhere it applies):tests/worker_robustness_tests.rs(C1)older_than = 1ms. The job runs once.tests/job_spawning_tests.rs(C2)Completedand no child exists.complete_job_run_with_childrenis atomic and guarded by the run.tests/migration_lock_tests.rs(H3)run_migrationswith a non-idempotent probe migration on the migrated database.tests/worker_config_tests.rsOther
tests/queue_api_tests.rs(M1, onTestQueue, PostgreSQL and MySQL): disable holds the pending run, enable resumes it, and a job finished while disabled is revived.src/queue/test.rs;config.rs);refund(rate_limit.rs);alerting.rs);runis dropped, andWorkerPool::new()not autoscaling (worker.rs).Runs, the way CI runs them, against the
hw_lifedatabases (PostgreSQL 5433, MySQL 3307, migrated with the CLI), after rebasing on9db5313:--include-ignored --skip mysql): 1821 passed, 0 failed.--include-ignored mysql, both URLs MySQL): 164 passed, 0 failed.migration_lock_tests,worker_robustness_tests,job_spawning_tests,worker_config_tests) passed 3 more times on both backends.--features postgres,mysql,test,encryption,tracing,streaming,kafka): 524 passed.cargo fmt --all --checkandcargo clippy --workspace --all-targets --all-features --locked -- -D warningsare clean, and so is the CI feature matrix ("",postgres,mysql,postgres,mysql,postgres,encryption,mysql,tracing,postgres,streaming,postgres,webhooks).🤖 Generated with Claude Code