Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,28 @@ 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:
desc: Create a release
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)
Expand Down
27 changes: 26 additions & 1 deletion docs/source/getting-started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down Expand Up @@ -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
------------------
Expand Down
Empty file removed examples/__init__.py
Empty file.
5 changes: 2 additions & 3 deletions examples/greeting/main.py
Original file line number Diff line number Diff line change
@@ -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")
Expand Down
2 changes: 1 addition & 1 deletion examples/greeting/worker
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -51,6 +51,7 @@ dagster = [
"dagster>=1.12.0",
]
test = [
"fakeredis>=2.40.0",
"pytest>=8.4.2",
"pytest-cov>=7.0.0",
]
Expand Down
143 changes: 143 additions & 0 deletions src/tasktronaut/backends/rq.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading