Repository navigation
fix(queue): enforce the job lifecycle state machine (#19 C3/H2/H3/H5/H6/M1–M3) - #29
Merged
Merged
Conversation
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
force-pushed
the
fix/job-state-machine
branch
from
October 8, 2026 09:29
0cc5949 to
d975973
Compare
This was referenced Oct 8, 2026
Closed
Closed
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>
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 #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
DatabaseQueue::finish_job_run(&run, JobOutcome) -> Result<Option<RecordedOutcome>>.Runningthe same run. A run is identified by itsattemptsplus itsstarted_at.started_atis needed because recurring jobs resetattemptson every reschedule.None. The worker then logs a warning and skips its hooks and events.DatabaseQueueimplementations still compile.complete_job,fail_job,retry_job,mark_job_dead,mark_job_timed_out,reschedule_cron_job,retry_dead_job) keep their signatures.JobTransition::allowed_from(table indocs/job-types.md).HammerworkError::InvalidJobTransition. A missing job returnsJobNotFound.complete_job,fail_jobandmark_job_*apply the same dependency, workflow and batch effects as a worker run, but never reschedule cron jobs.SELECT … FOR UPDATEon the job, then check the guard.40001/40P01) are retried.JSON_CONTAINScannot use an index. Dependents, and the jobs failed byFailFast, 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.mysql-integrationscenario binary. A cleanupDELETEwas 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.concurrent_completions_do_not_blocknow guards this case.#19 items
finish_job_runchecks the run (zombie-safe)manual_transitions_are_guarded,zombie_worker_cannot_overwrite_reclaimed_jobmax_attempts.Worker::with_max_retries(n)now only caps it (min), and workers have no cap by default. The last failure always ends the jobDead; workers never leave a jobFailedjob_max_attempts_is_the_retry_limit(5 runs, 1 run, capped at 2)error_messageandfailed_at/timed_out_atstay on the job until the next run, and the fail/timeout hooks still firerecurring_jobs_are_rescheduled_after_terminal_failureTimedOutis terminal only on the last attempttimeouts_retry_until_attempts_are_exhaustedwaiting→satisfied. A terminal failure applies the workflow's policy:FailFastfails the workflow's pending jobs;ContinueOnFailurefails the jobs that depend on the failed one, directly or transitively;Manualleaves them waiting until someone callsretry_dead_job. Workflow counters, status,completed_atandfailed_atare maintained. The reaper'sDeadjobs 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_childFailFastfails the batch's jobs that have not started. Thehammerwork_batchesrow moves toProcessingwhen its first job finishes; its counters, final status,completed_atanderror_summaryare written when the batch finishes. Removed the misleading worker commentbatch_failure_modes_are_enforced; updatedbatch_progress_is_livewith_retry_strategyretry_strategyJSON column, read by every query. ARetryStrategy::Customcannot be stored, so enqueueing one is rejected withInvalidJobPayloadretry_strategy_is_persistedenqueue_batchfieldsenqueue,enqueue_batch,enqueue_workflowand archive restore now share one multi-rowQueryBuilderinsert per backend that stores every fieldenqueue_batch_stores_all_fieldsAlready 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_livealso fails there.Remaining (deferred): M4 (weighted-selection starvation), M6 (DB clock vs app clock), M7 (MySQL
TIMESTAMP2038 limit), and the LOW items: pause not enforced in dequeue queries, N+1 dependency queries,cancel_workflowleaving running jobs alone, cron next run computed from completion time, and theget_queue_depthscan. Also not done: a child enqueued after its parent already completed stayswaiting, because resolution only runs when a parent completes.Public API and behaviour changes
DatabaseQueue::finish_job_run(with a default implementation)queue::lifecycle,JobOutcome,RecordedOutcomeandJobTransition(re-exported at the crate root)HammerworkError::InvalidJobTransition(the enum is not#[non_exhaustive], so exhaustive matches need a new arm)JobNotFound; they used to returnOk.retry_dead_jobalso acceptsTimedOutjobs.with_max_retriesis now a cap, not an override.fail_job/mark_job_deadon a job in aFailFastbatch or workflow fail its siblings.Customretry strategy is an error.retryaction routesDeadjobs toretry_dead_job.018_add_job_retry_strategy) is required, since every job query reads the column.IF NOT EXISTS; MySQL usesinformation_schema-guardedPREPARE/EXECUTE, so both can be re-run.(batch_id, status)index.TestQueuechecks the sameallowed_fromguards in its manual transitions and uses the defaultfinish_job_run.Verification
cargo fmt --all --checkcargo clippy --workspace --all-targets --all-features -- -D warningscargo 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,streamingcargo test --workspace --all-features --lib-- --include-ignored --skip mysql, and-- --include-ignored mysqlwith both URLs set to MySQL🤖 Generated with Claude Code