Skip to content

fix(queue): enforce the job lifecycle state machine (#19 C3/H2/H3/H5/H6/M1–M3) - #29

Merged
CodingAnarchy merged 5 commits into
masterfrom
fix/job-state-machine
Oct 8, 2026
Merged

CodingAnarchy merged 5 commits into
masterfrom
fix/job-state-machine

Conversation

@CodingAnarchy

@CodingAnarchy CodingAnarchy commented Oct 8, 2026 •

Copy link
Copy Markdown
Owner

Part of #19

Job status changes are now guarded, and a worker's run is recorded in one transaction together with its side effects: dependency resolution, the workflow's failure policy, the batch's failure mode, and cron rescheduling. This fixes every non-deferred #19 item except those already merged in #20 and #21.

Design

  • Run outcomes. Workers record each run through the new DatabaseQueue::finish_job_run(&run, JobOutcome) -> Result<Option<RecordedOutcome>>.
    • The outcome applies only while the job is still Running the same run. A run is identified by its attempts plus its started_at. started_at is needed because recurring jobs reset attempts on every reschedule.
    • If the reaper reclaimed the job, an operator changed it, or a newer attempt is running, the call writes nothing and returns None. The worker then logs a warning and skips its hooks and events.
    • The method has a default (non-transactional) implementation, so custom DatabaseQueue implementations still compile.
  • Manual transitions (complete_job, fail_job, retry_job, mark_job_dead, mark_job_timed_out, reschedule_cron_job, retry_dead_job) keep their signatures.
    • Each one applies only from the statuses in JobTransition::allowed_from (table in docs/job-types.md).
    • A rejected transition returns the new HammerworkError::InvalidJobTransition. A missing job returns JobNotFound.
    • complete_job, fail_job and mark_job_* apply the same dependency, workflow and batch effects as a worker run, but never reschedule cron jobs.
  • Transactions. Both backends do the work in one transaction:
    1. SELECT … FOR UPDATE on the job, then check the guard.
    2. Write the new status.
    3. Apply the effects. The workflow row is locked before dependents, dependents are locked in id order, and the batch row is locked last.
    • MySQL runs this at READ COMMITTED, like the dequeue.
    • Deadlock and serialization victims (SQLSTATE 40001/40P01) are retried.
  • Lock scope. On MySQL, JSON_CONTAINS cannot use an index. Dependents, and the jobs failed by FailFast, are therefore found with a non-locking read and then locked by primary key in id order, so a completion never locks or waits on unrelated job rows.
  • Explicit transaction ends. Every lifecycle transaction (transitions, dependency resolution, the reaper, and MySQL's guarded updates) commits or rolls back explicitly. It never relies on the rollback a dropped transaction queues on its connection. The MySQL reaper runs at READ COMMITTED.
    • Context: the first CI run of this PR failed in the mysql-integration scenario binary. A cleanup DELETE was blocked for 30s, and then a newly enqueued job could not be dequeued, which is consistent with a pooled connection left holding locks. It did not reproduce locally, even on a fresh database.
    • Both changes went in as follow-up commits. CI has passed twice since, and concurrent_completions_do_not_block now guards this case.
  • Dependency race. When two parents complete at once, each transaction locks the shared child before counting completed parents. The second one therefore sees the first one's commit. A test runs this race 20 times per backend.

#19 items

Item Fix Test (fails on the previous master)
H2 transition guards Guarded manual transitions; finish_job_run checks the run (zombie-safe) manual_transitions_are_guarded, zombie_worker_cannot_overwrite_reclaimed_job
H3 retry limit The limit is the job's max_attempts. Worker::with_max_retries(n) now only caps it (min), and workers have no cap by default. The last failure always ends the job Dead; workers never leave a job Failed job_max_attempts_is_the_retry_limit (5 runs, 1 run, capped at 2)
H5 recurring jobs A dead or timed-out run of a recurring job reschedules it for the next occurrence, with attempts reset. The failed run's error_message and failed_at/timed_out_at stay on the job until the next run, and the fail/timeout hooks still fire recurring_jobs_are_rescheduled_after_terminal_failure
M1 timeouts A timeout counts as a failed attempt and is retried while attempts remain. TimedOut is terminal only on the last attempt timeouts_retry_until_attempts_are_exhausted
C3 dependencies/workflows Completion moves dependents waiting → satisfied. A terminal failure applies the workflow's policy: FailFast fails the workflow's pending jobs; ContinueOnFailure fails the jobs that depend on the failed one, directly or transitively; Manual leaves them waiting until someone calls retry_dead_job. Workflow counters, status, completed_at and failed_at are maintained. The reaper's Dead jobs get the same effects. The PostgreSQL lookup now uses the GIN index (@>) workflows_complete_end_to_end (2-step, 3-step and fan-in, 3 real workers), workflow_failure_policies, concurrent_parent_completions_release_child
H6 batches On the first terminal failure, FailFast fails the batch's jobs that have not started. The hammerwork_batches row moves to Processing when its first job finishes; its counters, final status, completed_at and error_summary are written when the batch finishes. Removed the misleading worker comment batch_failure_modes_are_enforced; updated batch_progress_is_live
M2 with_retry_strategy Migration 018 adds a retry_strategy JSON column, read by every query. A RetryStrategy::Custom cannot be stored, so enqueueing one is rejected with InvalidJobPayload retry_strategy_is_persisted
M3 enqueue_batch fields enqueue, enqueue_batch, enqueue_workflow and archive restore now share one multi-row QueryBuilder insert per backend that stores every field enqueue_batch_stores_all_fields

Already fixed: C1, H1, H4 and M5 in #20; C2 in #21.

To check the tests fail without this change, I ran them against the library from the previous master (bcd2e5b), changing only the assertions that use the new API. All 11 scenarios failed on both PostgreSQL and MySQL. batch_progress_is_live also fails there.

Remaining (deferred): M4 (weighted-selection starvation), M6 (DB clock vs app clock), M7 (MySQL TIMESTAMP 2038 limit), and the LOW items: pause not enforced in dequeue queries, N+1 dependency queries, cancel_workflow leaving running jobs alone, cron next run computed from completion time, and the get_queue_depth scan. Also not done: a child enqueued after its parent already completed stays waiting, because resolution only runs when a parent completes.

Public API and behaviour changes

  • Added:
    • DatabaseQueue::finish_job_run (with a default implementation)
    • queue::lifecycle, JobOutcome, RecordedOutcome and JobTransition (re-exported at the crate root)
    • HammerworkError::InvalidJobTransition (the enum is not #[non_exhaustive], so exhaustive matches need a new arm)
  • Behaviour:
    • Manual transitions reject invalid source statuses. Calls on missing jobs now return JobNotFound; they used to return Ok.
    • retry_dead_job also accepts TimedOut jobs.
    • with_max_retries is now a cap, not an override.
    • Timeouts are retried.
    • fail_job/mark_job_dead on a job in a FailFast batch or workflow fail its siblings.
    • Enqueueing a Custom retry strategy is an error.
    • hammerwork-web's retry action routes Dead jobs to retry_dead_job.
  • Migration 018 (018_add_job_retry_strategy) is required, since every job query reads the column.
    • PostgreSQL uses IF NOT EXISTS; MySQL uses information_schema-guarded PREPARE/EXECUTE, so both can be re-run.
    • It also adds a (batch_id, status) index.
  • TestQueue checks the same allowed_from guards in its manual transitions and uses the default finish_job_run.

Verification

  • cargo fmt --all --check
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • cargo clippy -p hammerwork --lib --tests --no-default-features --features <f> for every CI feature combination: none, postgres, mysql, postgres,mysql, postgres,encryption, mysql,tracing, postgres,streaming
  • cargo test --workspace --all-features --lib
  • Full suites in both CI styles against local PostgreSQL 16 and MySQL 8: -- --include-ignored --skip mysql, and -- --include-ignored mysql with both URLs set to MySQL
  • The new lifecycle tests, run 3 more times on both backends

🤖 Generated with Claude Code

CodingAnarchy and others added 5 commits October 8, 2026 05:29
Guard every status transition, record worker runs atomically with their
side effects, and make dependencies, workflow policies, batch failure
modes, recurring jobs, timeouts and retry limits behave as documented.

- H2: manual transitions only apply from JobTransition::allowed_from and
  return InvalidJobTransition/JobNotFound otherwise. Workers record runs
  with the new DatabaseQueue::finish_job_run, which only applies while
  the job is still Running the same run (attempts + started_at), so a
  zombie worker cannot overwrite a reclaimed job.
- C3: completion resolves dependents (locked first, READ COMMITTED);
  terminal failures apply the workflow FailurePolicy; workflow counters
  and status are kept up to date, in the same transaction. The reaper
  applies the same effects to jobs it marks Dead.
- H3: the job's max_attempts is the retry limit; with_max_retries only
  caps it. Workers no longer leave jobs in a terminal Failed state.
- H5: recurring jobs are rescheduled after a dead or timed-out run too.
- H6: FailFast batches fail their pending jobs on the first terminal
  failure; the hammerwork_batches row is finalized when the batch ends.
- M1: timed-out runs are retried while attempts remain.
- M2/M3: migration 018 adds retry_strategy; enqueue, enqueue_batch,
  enqueue_workflow and archive restore share one insert storing every
  field.

Part of #19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Integration tests for #19 C3, H2, H3, H5, H6, M1, M2 and M3, run against
PostgreSQL and MySQL. All of them fail on the previous master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ure handling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…icitly

On MySQL, JSON_CONTAINS lookups cannot use an index, so a locking read of
dependents scanned (and locked or waited on) unrelated job rows, including
rows held by concurrent completions. Find candidates with a non-locking
read and lock only those rows by primary key, in id order.

Every lifecycle transaction (transitions, dependency resolution, the
reaper and MySQL's guarded updates) now commits or rolls back explicitly,
so an error can never return a connection to the pool with an open
transaction. The MySQL reaper runs at READ COMMITTED like the dequeue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CodingAnarchy
CodingAnarchy force-pushed the fix/job-state-machine branch from 0cc5949 to d975973 Compare October 8, 2026 09:29
@CodingAnarchy
CodingAnarchy merged commit 8e74662 into master Oct 8, 2026
13 checks passed
CodingAnarchy added a commit that referenced this pull request Oct 8, 2026
)

- Compile-check docs/job-types.md and fix its examples: fragments get a
  hidden prelude; Job::with_delay is a constructor; Job::with_cron takes a
  CronSchedule (with_cron_schedule is a constructor); handlers are typed
  JobHandler and return HammerworkError::Processing; retry comments match
  the max_attempts/with_max_retries semantics from #29.
- Add Job::with_scheduled_at, which the README and guides already used.
- The README TestQueue example was wrapped in cfg(feature = "test"),
  which doctests don't see, so it never compiled; drop the wrapper and
  gate the README/guide includes (one cfg'd module) on the features
  their examples use.
- cargo test --doc with default features failed: the guide includes
  (#49) and 23 API examples needed the postgres feature. Gate those
  examples' fences with cfg_attr(feature = "postgres") and add a CI step
  running doctests with default features.

Part of #48.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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