Skip to content

fix(worker,queue): job lifecycle hardening from #64 (W2) - #68

Merged
CodingAnarchy merged 2 commits into
masterfrom
fix/job-lifecycle
Oct 9, 2026
Merged

CodingAnarchy merged 2 commits into
masterfrom
fix/job-lifecycle

Conversation

@CodingAnarchy

Copy link
Copy Markdown
Owner

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

  • Claim with a lease. The claim statement now writes lease_expires_at = now + lease and last_heartbeat_at = started_at on PostgreSQL (in claim_sql), MySQL (in the claiming UPDATE) and TestQueue.
    • New DatabaseQueue::dequeue_leased(queue, weights, lease). Workers pass their own lease.
    • dequeue and dequeue_with_priority_weights use queue::DEFAULT_LEASE_DURATION (5 minutes).
    • The default trait implementation ignores the lease, so custom backends keep compiling.
  • Reaper. A job whose lease is valid is never reclaimed, whatever older_than is.
    • older_than (the started_at age) 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.
    • The CLI job requeue-stale help and the docs say so.
  • Lease 0. 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. heartbeat_job(&run, lease) takes the dequeued run and matches id, status = 'Running', attempts and started_at (±1ms, as in finish_job_run). A stale worker's heartbeat returns false and no longer extends the new run's lease.
    • This changes the signature from a job id. heartbeat_job was added in this unreleased cycle.
  • Schema. No migration: the columns come from 015_add_job_leases.

C2: lost spawned children

  • SpawnManager::prepare_spawn runs the spawn handler, checks the limit and applies inheritance, before the parent is completed.
  • New 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.
  • Any spawn failure fails the parent's run, so it is retried. That covers a handler error, SpawnLimitExceeded, a malformed _spawn_config and a child insert error.
  • on_spawn_complete runs after the commit.
  • The on_job_complete hook no longer fires twice for spawning jobs.
  • execute_spawn is kept for use outside workers.

H3: concurrent migrations

run_migrations holds a migration lock for the whole run:

  • PostgreSQL: pg_advisory_lock.
  • MySQL: 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:

  • It is taken on a dedicated connection that also runs every statement of the run.
  • The applied migrations are read only after the lock is acquired.
  • It is released on every path, including errors. That connection is close_on_drop, so an abandoned run releases the lock as well.

Other changes:

  • Recording a migration uses ON CONFLICT DO NOTHING / INSERT IGNORE.
  • New trait methods MigrationRunner::acquire_migration_lock / release_migration_lock, with no-op defaults.
  • The PostgreSQL runner checks for the tracking table in current_schema().

H9: autoscaling

  • WorkerPool::new() uses AutoscaleConfig::disabled().
  • AutoscaleConfig::default() and the presets are still enabled, so an explicit with_autoscaling(AutoscaleConfig::default()) keeps working.
  • Autoscaling scales one queue: the template's, or the first worker's. The supervisor only counts, clones and retires workers of that queue, so workers of other queues are never retired.

H10: alerts in the dequeue loop

  • acquire_job no longer checks alert thresholds or starvation. The monitoring task already did both; its interval is now configurable with Worker::with_monitoring_interval (default 30s).
  • The alert HTTP client has a 10s timeout (ALERT_HTTP_TIMEOUT).
  • An alert that reached no target is retried after FAILED_ALERT_RETRY_DELAY (60s, or the cooldown if that is shorter) instead of on every check.

M1: disable and enable recurring jobs

  • Disable clears recurring and next_run_at.
    • A pending occurrence stays Pending but is held. The runnable predicate now requires recurring OR cron_schedule IS NULL, in both backends' RUNNABLE_IN_QUEUE_SQL and in TestQueue.
    • A run in progress finishes and is not rescheduled.
  • Enable, unless the job is Running, reschedules it to the next occurrence after now: Pending, attempts reset. This revives a Completed, Failed, Dead or TimedOut job. Occurrences missed while the job was disabled are not run.
  • Both methods return JobNotFound for a missing job, and an error for a job without a cron schedule. This is the same on every backend.
  • CLI cron enable / cron disable now call these methods instead of flipping the flag with raw SQL.

Smaller fixes

  • M2: the with_max_retries example now shows it lowering the limit. The Worker::new docs drop the "3 maximum retry attempts" claim. The behaviour is unchanged.
  • M5: zero durations.
    • WorkerConfig::validate rejects a zero polling_interval and a zero job_timeout. It runs in from_file, from_env and WorkerPool::from_hammerwork_config, consistent with how purge_interval_secs = 0 is already rejected.
    • Builders cannot fail, so they degrade safely instead: idle polls wait at least MIN_POLL_INTERVAL (10ms), and with_default_timeout(ZERO) means no default timeout.
    • Found along the way: TOML wrote the 500ms default polling interval as "0s". Sub-second durations are now written in milliseconds ("500ms").
  • M6: rate limiter.
    • The worker takes a token before it polls and refund()s it when no job is claimed.
    • The token bucket refills from the elapsed time at full precision.
  • M8: the per-poll get_queue_depth for metrics is removed. The monitoring task updates the queue depth.
  • M10: the monitoring task is held in an abort-on-drop guard, so it stops on return, error, panic or a dropped future.
  • TestQueue (the fix(queue): apply workflow failure policies and terminal fail_job on every backend #65 gap):
    • mark_job_dead and mark_job_timed_out apply the workflow policy and a fail-fast batch's failure.
    • finish_job_run is overridden, so RecordedOutcome::cancelled is correct.
    • A job the reaper marks Dead applies the policy too.

Behaviour and API changes to note

  • DatabaseQueue:
    • new methods with defaults: dequeue_leased, complete_job_run_with_children;
    • heartbeat_job signature: takes &Job, not a job id;
    • RecordedOutcome.spawned is new.
  • WorkerPool::new() no longer autoscales.
  • A spawn failure now fails and retries the parent instead of being logged.
  • A disabled recurring job's pending run is held.
  • Config files or environment variables with a zero polling_interval or job_timeout are rejected.
  • The TestQueue cron 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 on TestQueue where it applies):

tests/worker_robustness_tests.rs (C1)

  • A claimed job, with a 1h lease and with the default lease, survives reapers with windows of 0, 1ms and 1s. A short-lease job is reclaimed.
  • A stale heartbeat cannot extend a new run's lease, and the new run is reclaimed on schedule.
  • A zero lease is never reclaimed.
  • The issue's scenario A end to end: two pools, one with a 1h lease and one reaping every 100ms with older_than = 1ms. The job runs once.
  • The existing reaper tests now simulate legacy, unleased rows explicitly.

tests/job_spawning_tests.rs (C2)

  • Children are enqueued with the completion.
  • A failing spawn handler retries the parent, and the children are spawned exactly once.
  • Injected failure: the third child carries a closure retry strategy, which cannot be stored, so its insert fails inside the transaction. The completion is rolled back: the parent is not Completed and no child exists.
  • At the API level, complete_job_run_with_children is atomic and guarded by the run.

tests/migration_lock_tests.rs (H3)

  • 6 concurrent run_migrations with a non-idempotent probe migration on the migrated database.
  • 6 concurrent full runs on a fresh scratch database.
  • On both backends, every run succeeds. With the lock removed, all four tests fail.

tests/worker_config_tests.rs

  • H9: mixed queues, where only the template queue is scaled down and up.
  • M6: idle and paused polls do not spend the rate limit.
  • H10: a webhook that never answers does not block job processing or shutdown.

Other

  • tests/queue_api_tests.rs (M1, on TestQueue, PostgreSQL and MySQL): disable holds the pending run, enable resumes it, and a job finished while disabled is revived.
  • Unit tests:
    • lease and heartbeat behaviour, and the TestQueue failure policy, in src/queue/test.rs;
    • zero-duration validation and the 500ms round trip (config.rs);
    • sub-millisecond refill and refund (rate_limit.rs);
    • alert timeout and retry delay (alerting.rs);
    • zero poll interval, the monitoring task stopping when run is dropped, and WorkerPool::new() not autoscaling (worker.rs).

Runs, the way CI runs them, against the hw_life databases (PostgreSQL 5433, MySQL 3307, migrated with the CLI), after rebasing on 9db5313:

  • PostgreSQL (--include-ignored --skip mysql): 1821 passed, 0 failed.
  • MySQL (--include-ignored mysql, both URLs MySQL): 164 passed, 0 failed.
  • The new concurrency tests (migration_lock_tests, worker_robustness_tests, job_spawning_tests, worker_config_tests) passed 3 more times on both backends.
  • Doctests (--features postgres,mysql,test,encryption,tracing,streaming,kafka): 524 passed.
  • cargo fmt --all --check and cargo clippy --workspace --all-targets --all-features --locked -- -D warnings are clean, and so is the CI feature matrix ("", postgres, mysql, postgres,mysql, postgres,encryption, mysql,tracing, postgres,streaming, postgres,webhooks).

🤖 Generated with Claude Code

CodingAnarchy and others added 2 commits October 9, 2026 19:30
…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>
@CodingAnarchy
CodingAnarchy merged commit 82d1644 into master Oct 9, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant