Skip to content

refactor: behaviour-preserving simplification pass (2.1.x) - #95

Merged
CodingAnarchy merged 8 commits into
masterfrom
refactor/simplify-2.1.x
Oct 11, 2026
Merged

CodingAnarchy merged 8 commits into
masterfrom
refactor/simplify-2.1.x

Conversation

@CodingAnarchy

Copy link
Copy Markdown
Owner

A behaviour-preserving cleanup for a 2.1.x patch release. It removes duplication that built up across the parallel 2.x PRs and changes no public API. Each commit covers one area, so the PR reads best commit by commit (git show --color-moved helps with the moves).

Net: −1,245 lines (+4,686 / −5,931 across 43 files; about 2,300 lines on each side are moves between files).

Queue backends (src/queue): net −224

  • queue/row.rs (new): the backend-independent parts of decoding a hammerwork_jobs row, which both JobRow::into_job copies now use:
    • the column lists;
    • status, result storage and dependency status;
    • the encryption columns (EncryptionRow). Each backend used to carry about 230 identical lines of this.
  • lifecycle.rs:
    • A TransitionStore trait holds the dialect-specific statements (lock job, write target, lock and refresh workflow, resolve and fail dependents, batch outcome).
    • transition_in_tx, after_terminal, apply_failure_policy and fail_job_dependencies are now one generic implementation instead of one per backend.
    • manual_transition and finish_run replace the five manual-transition wrappers in each backend.
    • MySQL's "next run must fit in a TIMESTAMP" filter is now the trait hook can_schedule_at.
  • Conflict retry: MySQL's retry_on_deadlock was a copy of retry_on_conflict, with the same five attempts and 5ms·n backoff. Its SQLSTATE 40001 check is the MySQL half of is_transaction_conflict, so the claim path now uses retry_on_conflict.
  • queue/backend.rs (new): the pub(crate) helpers that only the SQL backends use move out of queue/mod.rs. They are re-exported, so call sites are unchanged. One module-level dead_code allowance replaces 26 per-item cfg_attr lines, and lifecycle.rs gets the same treatment, replacing 18.
  • Hot path: insert_jobs binds job fields by reference instead of cloning the payload, strings and encoded columns of every enqueued job.
  • fill_weighted_batch from fix: batch-mode pause, weighted batch claim loss, undecodable rows in the reaper and MySQL claims #93 stays shared, now in backend.rs.

Worker (src/worker.rs): net +47, mostly module headers and imports

  • Heartbeats: maintain_lease and maintain_held_leases share every_heartbeat, which owns the interval, the zero-lease case and the never-completing tail.

  • Acquisition: Acquired<T> serves both the single-job and batch paths, replacing AcquiredBatch and idle_wait_batch.

  • Events: job_event builds the six JobEvents, and announce_retry is the retry hook plus event that failed and timed-out runs share.

  • Pool maintenance: the reaper, the encrypted-job purge and the result cleanup spawn through spawn_queue_task, a thin wrapper over the existing spawn_periodic. Archival keeps its own setup because it builds a JobArchiver first.

  • Module split: worker.rs (5.8k lines) is split into:

    • worker/hooks.rs
    • worker/autoscale.rs
    • worker/pool.rs (WorkerPool, its supervisor and maintenance tasks)

    Each module carries its own unit tests. Worker stays in worker.rs, and hammerwork::worker::* paths are re-exported unchanged. Code is moved, not changed.

CLI (cargo-hammerwork): net −308

  • Config::resolve_database_url replaces 14 copies of the --database-url/config fallback. The error is the same: "Database URL is required".
  • with_queue! replaces 27 Postgres/MySQL matches whose arms made the same JobQueue call. This includes archive.rs, which built JobQueue::new by hand.
  • fetch_rows! plus IdText replace the per-backend row loops whose arms differed only in how the id column decodes. Sites: job list, queue stats, monitor dashboard, audit log, backup/export job data.
  • Batch CSV export without payload drops the payload column from the shared csv_fields instead of rebuilding the JobData and re-splitting the CSV row. Output is identical, and the splitter stays as a test helper so its assertion remains.
  • status_name delegates to JobStatus::as_str.

Web (hammerwork-web): net −69

  • overview_handler was a line-for-line copy of generate_overview_from_stats and now calls it.
  • The archive handlers hand-expanded try_api!; they now use the macro.
  • Two handlers re-implemented JobPriority's Display; they now use it.

Tests: net −691

  • backend_tests! (five copies) and test_queue() (three) move to test_utils.
  • scenario_tests! replaces 118 one-line wrappers of the form test_<backend>_x() { x(setup().await).await } across eight files.
  • Shared helpers: wait_for_job (four copies), eventually (three) and idle_worker (two) now live in test_utils.
  • Test names and module paths are unchanged, so the CI --skip mysql / mysql filters select the same tests. I checked the --list output against the pre-change run: 417 integration tests, none missing and none added.
  • One deliberate difference: the two pool test files' eventually now polls every 25ms and checks once more at the deadline, as worker_config_tests already did. No assertion was removed.

Dead code

  • calculate_job_level's unused _current_level.
  • A no-op allow(dead_code) on the public JobQueue::pool.
  • test_utils::skip_known_bug, which had no callers.
  • A stale "new method" comment.

Behaviour notes for review

  • MySQL JobRow::into_job error precedence: it now decodes pii_fields before the encryption columns. A row that is invalid in both places reports the pii_fields error instead of the encryption one. Valid rows are unaffected, because the strict list decode already failed whenever the old lenient fallback could have differed.

Verification

Run locally against PostgreSQL 16 and MySQL 8, the way ci.yml runs them:

Check Command Result
PostgreSQL suite cargo test --workspace --all-features -- --include-ignored --skip mysql 1957 passed, 0 failed
MySQL suite cargo test --workspace --all-features -- --include-ignored mysql (both URLs on MySQL) 198 passed, 0 failed
Doctests, default features cargo test -p hammerwork --doc 186 passed
Doctests, extra features --features postgres,mysql,test,encryption,tracing,streaming,kafka 538 passed
Formatting cargo fmt --all --check clean
Lints cargo clippy --workspace --all-targets --all-features --locked -- -D warnings clean
Feature combinations clippy -p hammerwork --lib --tests --no-default-features for all 8 matrix entries clean
MSRV cargo +1.91.1 check --workspace --all-features --all-targets --locked clean
Coverage cargo llvm-cov, both suites merged, CI ignore regex 95.87% lines, 94.69% regions (floor 90%)

🤖 Generated with Claude Code

CodingAnarchy and others added 8 commits October 11, 2026 01:03
… backends

The PostgreSQL and MySQL backends each carried a copy of the backend-independent
parts of reading a job row and of a lifecycle transition.

- queue/row.rs: the job column lists, status/result-storage/dependency-status
  decoding and the encryption column decoding (EncryptionRow), used by both
  JobRow::into_job implementations.
- lifecycle.rs: a TransitionStore trait for the dialect-specific statements, and
  one generic transition_in_tx / after_terminal / apply_failure_policy /
  fail_job_dependencies plus manual_transition and finish_run, replacing the
  per-backend copies and the five manual-transition wrappers in each backend.
- lifecycle.rs: one module-level dead_code allowance instead of 18 per-item
  cfg_attr lines.

No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dule, bind by reference

- MySQL's retry_on_deadlock was a copy of retry_on_conflict (same attempts and
  backoff; its SQLSTATE 40001 check is the MySQL half of is_transaction_conflict).
  The claim path now uses retry_on_conflict.
- The pub(crate) helpers in queue/mod.rs used only by the SQL backends move to
  queue/backend.rs (re-exported, so call sites are unchanged), with one
  module-level dead_code allowance replacing 26 per-item cfg_attr lines.
- insert_jobs binds the job's fields by reference instead of cloning the payload,
  strings and encoded columns of every enqueued job.

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

- Config::resolve_database_url replaces fourteen copies of the
  --database-url / config fallback (same "Database URL is required" error).
- with_queue! replaces the Postgres/MySQL matches whose arms made the same
  JobQueue call (27 sites, including archive.rs building JobQueue::new by hand).
- fetch_rows! and IdText replace per-backend row loops whose arms differed only
  in how the id column decodes (job list, queue stats, monitor dashboard, audit
  log, backup/export job data).
- batch export without payload drops the payload column from csv_fields instead
  of rebuilding the JobData and re-splitting the CSV row (same output).
- status_name delegates to JobStatus::as_str.

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

- overview_handler re-implemented generate_overview_from_stats line for line;
  it now calls it.
- archive handlers spelled out try_api! by hand.
- Two handlers matched JobPriority to the names its Display impl already prints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- backend_tests! (five copies) and test_queue() (three) move to test_utils;
  the batch dequeue tests pass their multi-threaded test attribute.
- scenario_tests! replaces 118 hand-written one-line wrappers
  (test_<backend>_x calls x(setup().await)) in eight files. Test names and
  module paths are unchanged, so the CI --skip mysql / mysql filters select the
  same tests (checked against the --list output).
- wait_for_job (four copies), eventually (three) and idle_worker (two) are
  shared. The pool tests' eventually now polls every 25ms and checks once more
  at the deadline, like the worker config tests' copy.

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

- maintain_lease and maintain_held_leases share every_heartbeat (the
  interval, the zero-lease case and the never-completing tail); maintain_lease
  recomputed the interval held_renewal_interval already gives.
- Acquired<T> serves the single-job and batch paths (AcquiredBatch and
  idle_wait_batch removed).
- job_event builds the six JobEvents, and announce_retry is the retry hook and
  event shared by failed and timed-out runs.
- The stale job reaper, encrypted job purge and result cleanup spawn through
  spawn_queue_task (spawn_periodic on the first worker's queue).
- Lock reads use map/unwrap_or_default instead of if-let/else.

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

worker.rs (5.8k lines) keeps Worker; worker/hooks.rs holds the job event hooks,
worker/autoscale.rs the autoscaling configuration, metrics and decision, and
worker/pool.rs WorkerPool with its supervisor and maintenance tasks. Each
module carries its own unit tests. The public paths (hammerwork::worker::
WorkerPool, AutoscaleConfig, JobEventHooks, ...) are re-exported unchanged.
Code is moved, not changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- calculate_job_level threaded an unused _current_level through its recursion.
- JobQueue::pool is public, so its allow(dead_code) did nothing.
- test_utils::skip_known_bug had no callers.
- A comment in the web queue API called get_priority_stats "new".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CodingAnarchy
CodingAnarchy merged commit fe8f8a0 into master Oct 11, 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