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
15 changes: 15 additions & 0 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,21 @@ docket worker --tasks tasks:tasks --concurrency 5

Workers automatically handle concurrency (processing multiple tasks simultaneously), retries on failure, and graceful shutdown. By default, a worker processes up to 10 tasks concurrently.

For local development, add `--reload` to restart the worker when Python files
change under the current directory. Run the command from your project root.

```bash
python -m docket worker --tasks tasks:tasks --reload
```

The reloader keeps watching if the worker fails to start, so saving a fix
starts it again. On a file change or shutdown, the reloader gives the worker
five seconds to finish active tasks before forcibly stopping it. This applies
when you press Ctrl+C or send SIGTERM. Interrupted tasks can remain pending in
Redis until they become eligible for redelivery.

The `--reload` and `--until-finished` options are mutually exclusive.

## Basic Error Handling

By default, if a task fails (raises an exception), Docket will log the error and mark the task as failed in its OpenTelemetry traces. The task won't be retried and the worker will move on to the next task.
Expand Down
2 changes: 1 addition & 1 deletion loq.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ max_lines = 1482

[[rules]]
path = "python/src/docket/cli/__init__.py"
max_lines = 994
max_lines = 1007

[[rules]]
path = "python/src/docket/execution.py"
Expand Down
1 change: 1 addition & 0 deletions python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ dependencies = [
"typing_extensions>=4.12.0",
"tzdata>=2025.2; sys_platform == 'win32'",
"uncalled-for>=0.6.0",
"watchfiles>=1.1.1",
]

[project.optional-dependencies]
Expand Down
3 changes: 2 additions & 1 deletion python/src/docket/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .cli import app

app()
if __name__ == "__main__":
app()
54 changes: 33 additions & 21 deletions python/src/docket/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from rich.table import Table

from docket import __version__, tasks
from docket.cli._reload import run_with_reload
from docket.cli._support import (
LogLevel,
LogFormat,
Expand Down Expand Up @@ -248,30 +249,41 @@ def worker(
envvar="DOCKET_WORKER_DEPENDENCIES",
),
] = None,
reload: Annotated[
bool,
typer.Option("--reload", help="Restart on Python file changes"),
] = False,
) -> None:
asyncio.run(
Worker.run(
docket_name=docket_,
url=url,
name=name,
concurrency=concurrency,
message_batch=message_batch,
redelivery_timeout=redelivery_timeout,
reconnection_delay=reconnection_delay,
minimum_check_interval=minimum_check_interval,
scheduling_resolution=scheduling_resolution,
schedule_automatic_tasks=schedule_automatic_tasks,
enable_internal_instrumentation=enable_internal_instrumentation,
parent_task_spans=parent_task_spans,
until_finished=until_finished,
healthcheck_port=healthcheck_port,
metrics_port=metrics_port,
tasks=tasks,
fallback_task=fallback_task,
dependencies=dependencies,
)
if reload and until_finished:
raise typer.BadParameter("--reload cannot be used with --until-finished")

run_worker = partial(
Worker.run,
docket_name=docket_,
url=url,
name=name,
concurrency=concurrency,
message_batch=message_batch,
redelivery_timeout=redelivery_timeout,
reconnection_delay=reconnection_delay,
minimum_check_interval=minimum_check_interval,
scheduling_resolution=scheduling_resolution,
schedule_automatic_tasks=schedule_automatic_tasks,
enable_internal_instrumentation=enable_internal_instrumentation,
parent_task_spans=parent_task_spans,
until_finished=until_finished,
healthcheck_port=healthcheck_port,
metrics_port=metrics_port,
tasks=tasks,
fallback_task=fallback_task,
dependencies=dependencies,
)

if reload:
run_with_reload(run_worker, logging_level, logging_format)
else:
asyncio.run(run_worker())


@app.command(help="Strikes a task or parameters from the docket")
def strike(
Expand Down
35 changes: 35 additions & 0 deletions python/src/docket/cli/_reload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import asyncio
from collections.abc import Callable, Coroutine
from typing import Any

from watchfiles import PythonFilter, run_process

from docket.cli._support import (
LogFormat,
LogLevel,
set_logging_format,
set_logging_level,
)


def _run_worker(
worker: Callable[[], Coroutine[Any, Any, None]],
logging_level: LogLevel,
logging_format: LogFormat,
) -> None:
set_logging_level(logging_level)
set_logging_format(logging_format)
asyncio.run(worker())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bypass stale bytecode before importing reloaded tasks

With --reload, if a task module is edited to the same byte length within the same timestamp second as the bytecode currently in __pycache__ (for example, a fast before→edited rename), Python can accept that timestamp-based .pyc because it validates only the source's integer mtime and size. The watcher fires, but this invocation then imports the old bytecode and no event remains to retry, so users see the old task implementation; test_worker.py:172-177 masks this case by forcing the mtime two seconds forward. Ensure reload children bypass or remove affected bytecode before importing the task collection.

Useful? React with 👍 / 👎.



def run_with_reload(
worker: Callable[[], Coroutine[Any, Any, None]],
logging_level: LogLevel,
logging_format: LogFormat,
) -> None:
run_process(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the worker's graceful drain during reloads

When --reload is used while an in-flight task takes more than five seconds, this call inherits watchfiles' 5-second sigint_timeout and then force-kills the child. Worker._worker_loop intentionally waits for active tasks in worker.py:887-902, so a save or Ctrl+C cuts that drain short, leaves the stream message pending until redelivery, and contradicts the documented CLI graceful-shutdown behavior; expose or configure an adequate drain timeout rather than relying on the reloader default.

AGENTS.md reference: AGENTS.md:L97-L103

Useful? React with 👍 / 👎.

".",
target=_run_worker,
args=(worker, logging_level, logging_format),
watch_filter=PythonFilter(),
)
6 changes: 4 additions & 2 deletions python/src/docket/cli/_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def duration(duration_str: str | timedelta) -> timedelta:
return timedelta(seconds=int(duration_str))


def set_logging_format(format: LogFormat) -> None:
def set_logging_format(format: LogFormat) -> LogFormat:
root_logger = logging.getLogger()
if format == LogFormat.JSON:
from pythonjsonlogger.json import JsonFormatter
Expand All @@ -154,10 +154,12 @@ def set_logging_format(format: LogFormat) -> None:
formatter = logging.Formatter("%(message)s", datefmt="[%X]")
handler.setFormatter(formatter)
root_logger.addHandler(handler)
return format


def set_logging_level(level: LogLevel) -> None:
def set_logging_level(level: LogLevel) -> LogLevel:
logging.getLogger().setLevel(level.value)
return level


def validate_url(url: str) -> str:
Expand Down
112 changes: 112 additions & 0 deletions python/tests/cli/test_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
import os
import signal
import sys
from collections.abc import Callable
from datetime import datetime, timezone
from pathlib import Path

import pytest
import watchfiles

from docket.docket import Docket
from docket.tasks import sleep, trace
Expand Down Expand Up @@ -75,6 +78,115 @@ async def run(**kwargs: object) -> None:
assert passed["message_batch"] == 17


def test_reload_runs_worker_with_cli_options(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from docket.cli import worker
from docket.cli._support import LogFormat, LogLevel

passed: dict[str, object] = {}
formats: list[LogFormat] = []
levels: list[LogLevel] = []

async def record_worker(**kwargs: object) -> None:
passed.update(kwargs)

def simulate_reload(
path: str,
*,
target: Callable[..., None],
args: tuple[object, ...],
watch_filter: watchfiles.PythonFilter,
) -> None:
assert path == "."
assert watch_filter(watchfiles.Change.modified, "tasks.py")
assert not watch_filter(watchfiles.Change.modified, "notes.txt")
target(*args)

monkeypatch.setattr(Worker, "run", record_worker)
monkeypatch.setattr("docket.cli._reload.run_process", simulate_reload)
monkeypatch.setattr("docket.cli._reload.set_logging_format", formats.append)
monkeypatch.setattr("docket.cli._reload.set_logging_level", levels.append)
worker(
reload=True,
tasks=["app.tasks:registry"],
logging_level=LogLevel.WARNING,
logging_format=LogFormat.PLAIN,
concurrency=3,
)

assert passed["tasks"] == ["app.tasks:registry"]
assert passed["concurrency"] == 3
assert passed["until_finished"] is False
assert formats == [LogFormat.PLAIN]
assert levels == [LogLevel.WARNING]


async def test_reload_rejects_until_finished() -> None:
result = await run_cli(
"worker", "--reload", "--until-finished", env={"TERM": "dumb"}
)

assert result.exit_code == 2
assert "--reload cannot be used with --until-finished" in result.output


async def test_reload_imports_updated_tasks(tmp_path: Path) -> None:
module = tmp_path / "dev_tasks.py"
module.write_text("async def before(): pass\ntasks = [before]\n")
proc = await asyncio.create_subprocess_exec(
str(Path(sys.executable).with_name("docket")),
"worker",
"--reload",
"--url",
"memory://",
"--tasks",
"dev_tasks:tasks",
"--logging-format",
"json",
"--no-schedule-automatic-tasks",
cwd=tmp_path,
env={
**os.environ,
"PYTHONPATH": os.pathsep.join([str(tmp_path), os.getenv("PYTHONPATH", "")]),
"WATCHFILES_FORCE_POLLING": "true",
},
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
assert proc.stdout is not None
stdout = proc.stdout
output: list[str] = []

async def wait_for_log(message: str) -> None:
async with asyncio.timeout(8):
while True:
line = await stdout.readline()
assert line, "".join(output)
output.append(line.decode())
if message in output[-1]:
record: dict[str, str] = json.loads(line)
assert record["message"] == message
return

try:
await wait_for_log("* before()")
# Ensure polling sees a new modification time, even during a fast restart.
timestamp = module.stat().st_mtime + 2
replacement = tmp_path / "dev_tasks.tmp"
replacement.write_text("async def edited(): pass\ntasks = [edited]\n")
os.utime(replacement, (timestamp, timestamp))
replacement.replace(module)
await wait_for_log("* edited()")
finally:
proc.send_signal(signal.SIGINT)
remainder, _ = await asyncio.wait_for(proc.communicate(), timeout=8)

logs = "".join(output) + remainder.decode()
assert proc.returncode == 0, logs
assert logs.count("initiating graceful shutdown") == 2, logs


@pytest.mark.skipif(
os.environ.get("REDIS_VERSION") == "memory",
reason="Memory backend doesn't share state across processes",
Expand Down
Loading