diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7fc20b0..95a23c2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,11 +33,39 @@ jobs: CODACY_PROJECT_TOKEN: ${{ secrets.CODACY_PROJECT_TOKEN }} run: bash <(curl -Ls https://coverage.codacy.com/get.sh) report -r coverage.xml + smoke-test: + name: Smoke test Python code + runs-on: ubuntu-latest + services: + redis: + image: docker.io/redis:8 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 6379:6379 + steps: + - uses: actions/checkout@v5 + - uses: ./.github/actions/preparation + - name: Smoke test + run: uv run python tests/smoke_test_rq.py + - name: Test greeting example + working-directory: examples/greeting + run: | + set -o pipefail + ./example + ./worker --burst 2>&1 | tee "$RUNNER_TEMP/worker.log" + # the completion job only runs once every task has succeeded + grep -q "Successfully completed tasktronaut.backend.Backend.perform_complete" "$RUNNER_TEMP/worker.log" + build: name: Test Python package build runs-on: ubuntu-latest needs: - test + - smoke-test services: redis: image: docker.io/redis:8 diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c1b200..9d78d7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Security +## [0.5.0](https://github.com/virtualstaticvoid/tasktronaut/compare/v0.4.0...v0.5.0) - 2026-11-17 + +### Added + +* `tasktronaut.backends.rq.RqQueue` queue class, and `JobScopedReadyJobRegistryMixin` for custom queue classes + (e.g. `django-rq`'s `DjangoRQ`), which hand off ready dependent jobs via `JobScopedReadyJobRegistry` + +### Fixed + +* steps of a process could wait up to ten minutes (until RQ worker maintenance) before being enqueued, because + RQ 3.0 aborts the hand-off of a ready dependent job whenever any other worker concurrently readies or enqueues + a dependent job on the same queue; workers should use `RqQueue` (e.g. `rq worker --queue-class + tasktronaut.backends.rq.RqQueue`) as their queue class + ## [0.4.0](https://github.com/virtualstaticvoid/tasktronaut/compare/v0.3.0...v0.4.0) - 2026-11-16 ### Added diff --git a/Taskfile.yml b/Taskfile.yml index 2cb1dcf..f13fd05 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -76,7 +76,9 @@ tasks: cmds: - uv version --bump minor - uv sync - - git add pyproject.toml uv.lock + - sed -i -E 's/(tasktronaut(\[[a-z,]+\])?==)[0-9][0-9.]*/\1{{.NEXT}}/' docs/source/getting-started.rst + - grep -q '=={{.NEXT}}' docs/source/getting-started.rst + - git add pyproject.toml uv.lock docs/source/getting-started.rst - git commit -m "bump version" release: @@ -84,12 +86,18 @@ tasks: preconditions: - sh: git diff-index --quiet HEAD -- msg: "ERROR: Uncommitted files found." + - sh: gh auth status --active + msg: "ERROR: GitHub CLI not logged in. Run `gh auth login` first." vars: GIT_SHA: sh: git rev-parse --short HEAD VERSION: sh: uv version --short - prompt: Create a release for version {{.VERSION}} [{{.GIT_SHA}}]? + GH_USER: + sh: gh api user --jq .login 2>/dev/null || true + prompt: + - Create a release for version {{.VERSION}} [{{.GIT_SHA}}]? + - Create the GitHub release as user '{{.GH_USER}}'? cmds: - | prev=$(git describe --abbrev=0 --tags HEAD) diff --git a/docs/source/getting-started.rst b/docs/source/getting-started.rst index ddb4ea8..4face05 100644 --- a/docs/source/getting-started.rst +++ b/docs/source/getting-started.rst @@ -29,7 +29,7 @@ For a specific version: .. code-block:: bash - pip install tasktronaut[rq]==0.4.0 + pip install tasktronaut[rq]==0.5.0 Installing with Optional Dependencies ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -65,6 +65,31 @@ Verify the installation was successful by importing Tasktronaut in a Python shel If you see the version number without errors, you're ready to go! +Configuring RQ Workers +~~~~~~~~~~~~~~~~~~~~~~ + +When executing processes with RQ, use :class:`tasktronaut.backends.rq.RqQueue` as the +queue class of your workers, so that each step of a process is enqueued as soon as the +steps it depends on have finished, even when many workers are busy: + +.. code-block:: bash + + rq worker --queue-class tasktronaut.backends.rq.RqQueue + +With ``django-rq``, mix :class:`tasktronaut.backends.rq.JobScopedReadyJobRegistryMixin` +into the queue class and configure it with the ``QUEUE_CLASS`` setting: + +.. code-block:: python + + from django_rq.queues import DjangoRQ + from tasktronaut.backends.rq import JobScopedReadyJobRegistryMixin + + class ApplicationQueue(JobScopedReadyJobRegistryMixin, DjangoRQ): + pass + + # settings.py + RQ = {"QUEUE_CLASS": "myapp.queues.ApplicationQueue"} + Your First Process ------------------ diff --git a/examples/__init__.py b/examples/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/examples/greeting/main.py b/examples/greeting/main.py index 02919b1..9b7128f 100755 --- a/examples/greeting/main.py +++ b/examples/greeting/main.py @@ -1,13 +1,12 @@ import redis -import rq from greeting_process import GreetingProcess -from tasktronaut.backends.rq import RqBackend +from tasktronaut.backends.rq import RqBackend, RqQueue def main(): connection = redis.Redis() - queue = rq.Queue(connection=connection) + queue = RqQueue(connection=connection) backend = RqBackend(queue=queue) process = GreetingProcess.build(name="Chris") diff --git a/examples/greeting/worker b/examples/greeting/worker index 87fc6a0..b7c2baf 100755 --- a/examples/greeting/worker +++ b/examples/greeting/worker @@ -1,3 +1,3 @@ #!/bin/bash set -e -uv run rq worker high default low +uv run rq worker --queue-class tasktronaut.backends.rq.RqQueue "$@" high default low diff --git a/pyproject.toml b/pyproject.toml index 6c53567..ac96bcd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "tasktronaut" -version = "0.4.0" +version = "0.5.0" description = "A simple task orchestration library for running complex processes or workflows in Python." readme = "README.md" requires-python = ">=3.10" @@ -51,6 +51,7 @@ dagster = [ "dagster>=1.12.0", ] test = [ + "fakeredis>=2.40.0", "pytest>=8.4.2", "pytest-cov>=7.0.0", ] diff --git a/src/tasktronaut/backends/rq.py b/src/tasktronaut/backends/rq.py index 5044fe4..95fcd1f 100644 --- a/src/tasktronaut/backends/rq.py +++ b/src/tasktronaut/backends/rq.py @@ -5,15 +5,158 @@ using the RQ (Redis Queue) job queue library. It enables asynchronous execution of Tasktronaut processes with support for job dependencies and Redis-backed job persistence. + +Workers executing Tasktronaut processes should use :class:`RqQueue` (or a queue class +including :class:`JobScopedReadyJobRegistryMixin`) as their queue class, so that the +jobs of a process are enqueued as soon as the jobs they depend on have finished. For +example, ``rq worker --queue-class tasktronaut.backends.rq.RqQueue``. """ +import logging from typing import Any, Dict, List, Optional, Union, cast import rq +from redis.exceptions import WatchError +from rq.job import JobStatus +from rq.registry import ReadyJobRegistry +from rq.utils import as_text from ..backend import Backend, Job from ..types import Description +logger = logging.getLogger(__name__) + + +class JobScopedReadyJobRegistry(ReadyJobRegistry): + """ + Ready job registry whose claim of a job only conflicts with changes to that job. + + RQ 3.0 claims each ready dependent job in an optimistic transaction which watches + the queue's shared ready job registry as well as the job. Every worker writes to + that registry when readying or enqueueing any dependent job, so concurrent + hand-offs of unrelated jobs abort each other, and the aborted job waits for worker + maintenance, which can be up to ten minutes later. Meanwhile, the subsequent steps + of the process sit in the deferred job registry. + + Watching only the job keeps the guarantee against enqueueing a job twice: every + successful claim, and every deletion or cancellation of a job, writes the job's + hash in its transaction, so a competing change to the same job still aborts the + claim. + """ + + def enqueue_jobs(self, job_ids: List[str]) -> List[rq.job.Job]: + """ + Move ready jobs from the registry onto the queue. + + Mirrors RQ 3.0's :meth:`rq.registry.ReadyJobRegistry.enqueue_jobs` except for + the keys it watches; re-check it against RQ's implementation when upgrading + RQ. A job whose claim conflicts with a concurrent change to that job is + skipped and left for :meth:`cleanup`. + + :param job_ids: Ids of the jobs to enqueue, in enqueue order + :type job_ids: List[str] + :return: The jobs that were enqueued + :rtype: List[rq.job.Job] + """ + if not job_ids: + return [] + + queue = rq.Queue( + name=self.name, + connection=self.connection, + job_class=self.job_class, + serializer=self.serializer, + ) + fetched = self.job_class.fetch_many( + job_ids, connection=self.connection, serializer=self.serializer + ) + + enqueued: List[rq.job.Job] = [] + for job_id, job in zip(job_ids, fetched): + if job is None: + self.connection.zrem(self.key, job_id) + continue + if job.get_status(refresh=False) != JobStatus.READY_TO_ENQUEUE: + self.connection.zrem(self.key, job_id) + continue + try: + with self.connection.pipeline() as pipe: + # NOTE: RQ also watches `self.key`, the shared registry + pipe.watch(job.key) + + if pipe.zscore(self.key, job.id) is None: + pipe.unwatch() + continue + + status = cast( + Optional[Union[bytes, str]], pipe.hget(job.key, "status") + ) + if ( + not status + or JobStatus(as_text(status)) != JobStatus.READY_TO_ENQUEUE + ): + pipe.multi() + self.remove(job, pipeline=pipe) + pipe.execute() + continue + + pipe.multi() + self.remove(job, pipeline=pipe) + # pylint: disable=protected-access + if job.has_rate_limit: + queue._enqueue_rate_limited_job(job, pipeline=pipe) + else: + queue._enqueue_job( + job, + pipeline=pipe, + at_front=job.should_enqueue_at_front(), + ) + pipe.execute() + except WatchError: + logger.info( + "Ready job %s changed while enqueueing; skipping for now", job_id + ) + continue + except Exception: # pylint: disable=broad-exception-caught + logger.exception( + "Failed to enqueue ready job %s; leaving in ReadyJobRegistry", + job_id, + ) + continue + enqueued.append(job) + return enqueued + + +class JobScopedReadyJobRegistryMixin: # pylint: disable=too-few-public-methods + """ + Queue mixin which hands off ready dependent jobs via the job-scoped registry. + + A worker enqueues the dependents of a finished job through the + ``ready_job_registry`` of its queue class, so mix this into the queue class + workers are configured with. For example, with ``django-rq``:: + + class ApplicationQueue(JobScopedReadyJobRegistryMixin, DjangoRQ): + pass + + RQ = {"QUEUE_CLASS": "myapp.queues.ApplicationQueue"} + """ + + @property + def ready_job_registry(self) -> JobScopedReadyJobRegistry: + queue = cast(rq.Queue, self) + return JobScopedReadyJobRegistry( + queue=queue, job_class=queue.job_class, serializer=queue.serializer + ) + + +class RqQueue(JobScopedReadyJobRegistryMixin, rq.Queue): + """ + RQ queue which hands off ready dependent jobs via :class:`JobScopedReadyJobRegistry`. + + Use it as the queue class of workers executing Tasktronaut processes, e.g. + ``rq worker --queue-class tasktronaut.backends.rq.RqQueue``. + """ + # pylint: disable=too-many-arguments,too-many-positional-arguments class RqBackend(Backend): diff --git a/tests/backends/test_rq_queue.py b/tests/backends/test_rq_queue.py new file mode 100644 index 0000000..66ba93e --- /dev/null +++ b/tests/backends/test_rq_queue.py @@ -0,0 +1,154 @@ +import unittest +import uuid +from unittest import mock + +import fakeredis +import rq +from redis.client import Pipeline +from rq.job import JobStatus + +from tasktronaut.backends.rq import JobScopedReadyJobRegistry, RqQueue + + +def succeed() -> None: + return None + + +class RedisTestCase(unittest.TestCase): + def setUp(self): + self.connection = fakeredis.FakeStrictRedis() + self.queue_name = f"test-{uuid.uuid4().hex}" + self.queue = rq.Queue(self.queue_name, connection=self.connection) + + def tearDown(self): + self.connection.flushall() + + def enqueue_job_and_dependent(self): + job = self.queue.enqueue(succeed) + dependent = self.queue.enqueue(succeed, depends_on=job) + return job, dependent + + def patch_execute(self, before_execute): + """Run `before_execute` once, ahead of the first watched transaction it accepts.""" + execute = Pipeline.execute + called = [] + + def side_effect(pipeline, *args, **kwargs): + if pipeline.watching and not called and before_execute(): + called.append(True) + return execute(pipeline, *args, **kwargs) + + return ( + mock.patch.object( + Pipeline, "execute", autospec=True, side_effect=side_effect + ), + called, + ) + + def write_ready_registry(self, key: str) -> bool: + # another worker readies and enqueues a dependent of its own + self.connection.zadd(key, {"concurrent-writer": 0}) + self.connection.zrem(key, "concurrent-writer") + return True + + +class JobScopedReadyJobRegistryTestCase(RedisTestCase): + """A ready job's claim must only conflict with changes to that job.""" + + def make_dependent_ready(self): + job, dependent = self.enqueue_job_and_dependent() + job.set_status(JobStatus.FINISHED) + self.queue.move_dependents_to_ready(job) + return dependent + + def test_enqueues_ready_job_when_ready_registry_changes_concurrently(self): + dependent = self.make_dependent_ready() + registry = JobScopedReadyJobRegistry(queue=self.queue) + + patcher, called = self.patch_execute( + lambda: self.write_ready_registry(registry.key) + ) + with patcher: + enqueued = registry.enqueue_jobs([dependent.id]) + + self.assertTrue(called) + self.assertEqual([j.id for j in enqueued], [dependent.id]) + self.assertNotIn(dependent, registry) + self.assertEqual(dependent.get_status(), JobStatus.QUEUED) + self.assertEqual(self.queue.get_job_ids().count(dependent.id), 1) + + def test_does_not_enqueue_ready_job_claimed_concurrently(self): + dependent = self.make_dependent_ready() + registry = JobScopedReadyJobRegistry(queue=self.queue) + + def claim_concurrently(): + # worker maintenance claims and enqueues the same job + self.queue.ready_job_registry.cleanup() + return True + + patcher, called = self.patch_execute(claim_concurrently) + with patcher: + enqueued = registry.enqueue_jobs([dependent.id]) + + self.assertTrue(called) + self.assertEqual(enqueued, []) + self.assertEqual(dependent.get_status(), JobStatus.QUEUED) + self.assertEqual(self.queue.get_job_ids().count(dependent.id), 1) + + def test_enqueue_jobs_without_job_ids(self): + registry = JobScopedReadyJobRegistry(queue=self.queue) + self.assertEqual(registry.enqueue_jobs([]), []) + + def test_drops_missing_job(self): + registry = JobScopedReadyJobRegistry(queue=self.queue) + self.connection.zadd(registry.key, {"missing": 0}) + + self.assertEqual(registry.enqueue_jobs(["missing"]), []) + self.assertIsNone(self.connection.zscore(registry.key, "missing")) + + def test_skips_ready_job_not_in_registry(self): + dependent = self.make_dependent_ready() + registry = JobScopedReadyJobRegistry(queue=self.queue) + self.connection.zrem(registry.key, dependent.id) + + self.assertEqual(registry.enqueue_jobs([dependent.id]), []) + self.assertEqual(dependent.get_status(), JobStatus.READY_TO_ENQUEUE) + self.assertNotIn(dependent.id, self.queue.get_job_ids()) + + def test_drops_job_no_longer_ready(self): + dependent = self.make_dependent_ready() + dependent.set_status(JobStatus.CANCELED) + registry = JobScopedReadyJobRegistry(queue=self.queue) + + self.assertEqual(registry.enqueue_jobs([dependent.id]), []) + self.assertNotIn(dependent, registry) + self.assertNotIn(dependent.id, self.queue.get_job_ids()) + + +class RqQueueTestCase(RedisTestCase): + """A dependent must be enqueued once its dependency succeeds, despite contention.""" + + def test_ready_job_registry(self): + queue = RqQueue(self.queue_name, connection=self.connection) + self.assertIsInstance(queue.ready_job_registry, JobScopedReadyJobRegistry) + + def test_dependent_is_enqueued_when_ready_registry_changes_concurrently(self): + _, dependent = self.enqueue_job_and_dependent() + queue = RqQueue(self.queue_name, connection=self.connection) + key = queue.ready_job_registry.key + + def is_enqueueing_ready_dependent(): + if self.connection.zscore(key, dependent.id) is None: + return False + return self.write_ready_registry(key) + + worker = rq.SimpleWorker( + [queue], connection=self.connection, queue_class=RqQueue + ) + patcher, called = self.patch_execute(is_enqueueing_ready_dependent) + with patcher: + worker.work(burst=True) + + self.assertTrue(called) + self.assertNotIn(dependent, queue.ready_job_registry) + self.assertEqual(dependent.get_status(), JobStatus.FINISHED) diff --git a/tests/smoke_test_rq.py b/tests/smoke_test_rq.py index f509fa6..2cf63f8 100644 --- a/tests/smoke_test_rq.py +++ b/tests/smoke_test_rq.py @@ -6,7 +6,7 @@ import rq import tasktronaut as tq -from tasktronaut.backends.rq import RqBackend +from tasktronaut.backends.rq import RqBackend, RqQueue from tasktronaut.utils import to_kwargs LOG_FILE = "smoke_test_rq.log" @@ -48,13 +48,13 @@ def define_process(self, builder: tq.Builder): def main(): connection = redis.Redis() - queue = rq.Queue(connection=connection) + queue = RqQueue(connection=connection) backend = RqBackend(queue=queue) process = SimpleDefinition.build(a="foo") job: rq.job.Job = process.enqueue(backend) - worker = rq.SimpleWorker([queue]) + worker = rq.SimpleWorker([queue], queue_class=RqQueue) # blocking call, until all jobs are finished # if no jobs, will return immediately diff --git a/uv.lock b/uv.lock index a3cad2c..212c677 100644 --- a/uv.lock +++ b/uv.lock @@ -472,6 +472,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674, upload-time = "2025-05-10T17:42:49.33Z" }, ] +[[package]] +name = "fakeredis" +version = "2.40.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "redis" }, + { name = "sortedcontainers" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/d0/8cbd1339c2a606a0ceda74e1a181248d372bb2c66bc6cf9d954871839ff9/fakeredis-2.40.0.tar.gz", hash = "sha256:16eb05a3e97c37a033c73d1da7e885eb2aa47ba7604cc377144339efa2780a02", size = 332674, upload-time = "2026-10-14T12:46:01.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/e4/6919d3653d72c53d1fb22c97ceb6fa3664cad302994e90ee52279f7eb394/fakeredis-2.40.0-py3-none-any.whl", hash = "sha256:b155ef2442134372eb1cc5664cf5638ccbe0a6dde9d1942153708e2782f315c9", size = 204148, upload-time = "2026-10-14T12:46:00.014Z" }, +] + [[package]] name = "filelock" version = "3.20.0" @@ -1369,6 +1383,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c8/78/3565d011c61f5a43488987ee32b6f3f656e7f107ac2782dd57bdd7d91d9a/snowballstemmer-3.0.1-py3-none-any.whl", hash = "sha256:6cd7b3897da8d6c9ffb968a6781fa6532dce9c3618a4b127d920dab764a19064", size = 103274, upload-time = "2025-05-09T16:34:50.371Z" }, ] +[[package]] +name = "sortedcontainers" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, +] + [[package]] name = "sphinx" version = "8.1.3" @@ -1622,7 +1645,7 @@ wheels = [ [[package]] name = "tasktronaut" -version = "0.4.0" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "pydantic" }, @@ -1645,6 +1668,7 @@ dagster = [ dev = [ { name = "dagster" }, { name = "django-rq" }, + { name = "fakeredis" }, { name = "mypy" }, { name = "pylint" }, { name = "pytest" }, @@ -1675,6 +1699,7 @@ rq = [ { name = "rq" }, ] test = [ + { name = "fakeredis" }, { name = "pytest" }, { name = "pytest-cov" }, ] @@ -1696,6 +1721,7 @@ dagster = [{ name = "dagster", specifier = ">=1.12.0" }] dev = [ { name = "dagster", specifier = ">=1.12.0" }, { name = "django-rq", specifier = ">=4.2.0" }, + { name = "fakeredis", specifier = ">=2.40.0" }, { name = "mypy", specifier = ">=1.18.2" }, { name = "pylint", specifier = ">=4.0.2" }, { name = "pytest", specifier = ">=8.4.2" }, @@ -1720,6 +1746,7 @@ rq = [ { name = "rq", specifier = ">=3.0.0" }, ] test = [ + { name = "fakeredis", specifier = ">=2.40.0" }, { name = "pytest", specifier = ">=8.4.2" }, { name = "pytest-cov", specifier = ">=7.0.0" }, ]