An automatic `Perpetual` interrupted by a second SIGTERM waits for `redelivery_timeout` before it runs again

Đang mở
#511 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
59/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python, redis

Hướng nghiên cứu

Start with the reproduction in tests/test_interrupted_automatic_perpetual.py and run it using the memory backend. Then read Worker._execute, process_completed_tasks(), automatic perpetual scheduling in worker.py, and perpetual_is_live() in src/docket/dependencies/_perpetual.py. Done means an interrupted automatic perpetual runs promptly after the next worker starts, with the regression test passing on both memory and Redis backends.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

bug python

Since #505, a second SIGTERM or SIGINT during the drain leaves the interrupted task pending for redelivery, so it runs again instead of being lost (#497). For an automatic Perpetual, the runs hash still holds state: running after the worker exits. The next worker's startup seeding skips the task, and so does the reseed loop every 60 seconds. The task runs again only when the redelivery sweep claims its message after redelivery_timeout, which is 5 minutes by default.

In 0.25.2, the worker marked the interrupted run cancelled, and the next worker's startup seeding ran it again at once. asyncio.run() teardown takes the same path as the second SIGTERM, for example after a task calls sys.exit(). A variant of the test below that cancels both tasks together, the way asyncio.run() does, fails the same way on main.

Steps to reproduce

This test fails on main. It interrupts the task during the drain, the way a second SIGTERM does.

"""An automatic perpetual that a worker shutdown interrupts, and the next worker."""

from __future__ import annotations

import asyncio
from datetime import timedelta
from typing import Any, cast

import pytest

from docket import Docket, Perpetual, Worker
from tests._key_leak_checker import KeyCountChecker
from tests.conftest import wait_until


async def test_next_worker_restarts_an_interrupted_automatic_perpetual(
    docket: Docket,
    caplog: pytest.LogCaptureFixture,
    key_leak_checker: KeyCountChecker,
):
    """A second SIGTERM during the drain interrupts the running perpetual.  The
    next worker to start should run it again at once, well before the
    redelivery timeout."""
    runners: list[asyncio.Task[Any]] = []
    release = asyncio.Event()

    async def perpetual_task(
        perpetual: Perpetual = Perpetual(every=timedelta(seconds=30), automatic=True),
    ) -> None:
        runners.append(cast(asyncio.Task[Any], asyncio.current_task()))
        await release.wait()

    docket.register(perpetual_task)

    # The interrupted run's message stays pending for redelivery, so its runs
    # and progress hashes have no TTL.
    key_leak_checker.add_exemption(docket.runs_key("perpetual_task"))
    key_leak_checker.add_exemption(docket.key("progress:perpetual_task"))

    async with Worker(
        docket,
        minimum_check_interval=timedelta(milliseconds=5),
        scheduling_resolution=timedelta(milliseconds=5),
    ) as worker_a:
        run_a = asyncio.create_task(worker_a.run_forever())
        await wait_until(lambda: len(runners) == 1, description="the first run")

        # The first SIGTERM cancels the worker's task, and the worker drains.
        run_a.cancel()
        await wait_until(
            lambda: "Shutdown requested, finishing" in caplog.text,
            description="the drain",
        )

        # The second SIGTERM cancels the task that the worker is draining.
        runners[0].cancel()
        await asyncio.gather(run_a, return_exceptions=True)

    release.set()

    async with Worker(
        docket,
        redelivery_timeout=timedelta(seconds=30),
        minimum_check_interval=timedelta(milliseconds=5),
        scheduling_resolution=timedelta(milliseconds=5),
    ) as worker_b:
        run_b = asyncio.create_task(worker_b.run_forever())
        await wait_until(
            lambda: len(runners) == 2,
            timeout=2.0,
            description="a second run within 2s of the next worker's start",
        )
        run_b.cancel()
        await asyncio.gather(run_b, return_exceptions=True)

    await docket.cancel("perpetual_task")

Save it as tests/test_interrupted_automatic_perpetual.py and run it on the memory backend:

REDIS_VERSION=memory uv run pytest tests/test_interrupted_automatic_perpetual.py -n 0 --no-cov

Without REDIS_VERSION=memory, the test runs against Redis 8.0 in Docker. It fails the same way on both:

E       AssertionError: a second run within 2s of the next worker's start never became truthy within 2.0s

The same test passes on 0.25.2, on both backends. There the worker logs the interrupted run as cancelled, and the next worker runs the task at once:

INFO     docket.worker:worker.py:1073 ↪ [     3ms] perpetual_task(){perpetual_task}
INFO     docket.worker:worker.py:872 Shutdown requested, finishing 1 active tasks...
INFO     docket.worker:worker.py:1194 ✗ [    18ms] perpetual_task(){perpetual_task} (cancelled)
...
INFO     docket.worker:worker.py:1073 ↪ [     2ms] perpetual_task(){perpetual_task}

On main, after worker A exits, the runs hash holds state: running, and the message is pending for worker A's consumer. With redelivery_timeout=3s on worker B, the second run started 3.3 seconds (Redis 8.0) and 3.7 seconds (memory) after worker B started.

I also checked it end to end with docket worker against Redis 8.0.5. The task was an automatic Perpetual with every=timedelta(seconds=1) that sleeps for 3 seconds, and both workers had --redelivery-timeout 10s. Worker A got two SIGTERMs 0.3 seconds apart while the task ran, and worker B started right after worker A exited:

  • On main, worker B ran the task 9.8, 10.3, and 10.8 seconds after it started (3 of 3 runs).
  • On 0.25.2, worker B ran the task 0.3 seconds after it started (3 of 3 runs).
Why it happens

During a shutdown, when something other than docket.cancel() cancels a running task, Worker._execute re-raises the CancelledError:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/worker.py#L1218-L1229

process_completed_tasks() then writes nothing for that task. The runs hash keeps the running state that _claim wrote, and the message stays pending:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/worker.py#L737-L750

_schedule_all_automatic_perpetual_tasks() skips a task when perpetual_is_live() returns True, and perpetual_is_live() returns True for a running state. The reseed loop calls the same method:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/worker.py#L1036-L1047

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/dependencies/_perpetual.py#L29-L38

Without that check, docket.add() would still refuse the key, because the _schedule script returns EXISTS for a key whose state is running:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/_execution_scripts.py#L164-L172

A worker killed with SIGKILL leaves the same runs hash and pending message. After a SIGKILL in the same end-to-end setup, worker B ran the task 10.8 to 12.3 seconds after it started. That held on both main and 0.25.2 (2 of 2 runs each).

Environment
  • Commit 7e844b1 on main (pydocket 0.25.3.dev14), and 0.25.2
  • Python 3.14.7 on Linux, redis-py 8.1.0. On main, the test also fails on Python 3.10.19.
  • Backends: the memory backend, and Redis 8.0.5 in Docker
  • On main, the test failed in 10 of 10 runs on each backend. On 0.25.2, it passed in 10 of 10.
  • The test passes at 5e059e5 (#504), the commit before #505.

Filed by Claude Opus 5.5 on behalf of @chrisguidry.

Ngôn ngữ chính
Python
Star
148
Fork
12
Merge trung bình
15 giờ 49 phút
Pull request đã merge (30 ngày)
45

Chuẩn bị môi trường

  • Có Dockerfile hoặc tệp Docker Compose
  • Không có mẫu pull request
  • Không có hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của chrisguidry/docket

Tất cả issue của chrisguidry/docket

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.