`get_result()` on a replacement returns `None` when the run it replaced finishes

Aperta
#495 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
52/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python, redis

Direzione di ricerca

Start by running the supplied test in tests/test_results_retrieval.py on the memory backend. Then read the state-event publishing in src/docket/execution.py and src/docket/_execution_scripts.py, along with the referenced get_result() and _terminal sections. Done means a replacement's get_result() waits for and returns its own result despite the older run finishing first, without hanging when execution_ttl=0.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug python

If you replace a task while its current run is still going, get_result() on the replacement returns None as soon as the older run finishes. It doesn't wait for the replacement to run. The replacement still runs later and stores its result, but by then get_result() has already returned.

Steps to reproduce

Add this test to tests/test_results_retrieval.py on main. That file already imports asyncio, datetime, timedelta, Docket, and Worker.

from typing import Callable

from tests.test_get_result_cancellation import wait_for_subscriber


async def test_get_result_on_a_replacement_waits_for_the_replacement(
    docket: Docket, worker: Worker, now: Callable[[], datetime]
):
    """Every run under one key publishes its state on the same channel, so the
    older run's finish reaches a waiter on the replacement.  That waiter has
    to keep waiting until the replacement finishes."""
    older_run_started = asyncio.Event()
    finish_older_run = asyncio.Event()

    async def older_run() -> str:
        older_run_started.set()
        await finish_older_run.wait()
        return "older"

    async def replacement() -> str:
        return "replacement"

    await docket.add(older_run, key="the-key")()
    worker_task = asyncio.create_task(worker.run_until_finished())
    await asyncio.wait_for(older_run_started.wait(), timeout=5)

    execution = await docket.replace(
        replacement, when=now() + timedelta(seconds=1), key="the-key"
    )()
    waiter = asyncio.create_task(execution.get_result(timeout=timedelta(seconds=5)))
    await wait_for_subscriber(docket, "the-key")

    finish_older_run.set()

    assert await waiter == "replacement"
    await asyncio.wait_for(worker_task, timeout=5)

Run it on the memory backend, or drop REDIS_VERSION=memory to run it against the suite's Redis 8.0 container:

REDIS_VERSION=memory uv run pytest "tests/test_results_retrieval.py::test_get_result_on_a_replacement_waits_for_the_replacement" -n 0 --no-cov

It fails right away, well before the replacement's start time:

>       assert await waiter == "replacement"
E       AssertionError: assert None == 'replacement'
What I expected

get_result() on the replacement keeps waiting through the older run's finish. It returns "replacement" when the replacement runs, about a second later.

Why it happens

Every run under a key publishes its state on one channel, {docket}:state:{key}, and nothing in an event identifies the run that published it.

  • When the older run finishes, the runs hash already has the replacement's newer generation. So _terminal takes its supersession branch and leaves the runs hash alone. It still publishes the older run's completed event, on purpose, so waiters don't hang (_execution_scripts.py L354-L357). That payload has no generation in it (execution.py L706-L714).
  • get_result() stops at the first terminal event it receives, calls sync(), and breaks out of the loop (execution.py L831-L838). The sync reads the replacement's record, which still says scheduled with no result_key, so get_result() returns None.

I confirmed this with an event trace in a throwaway copy of the test. The waiter received the older run's completed event within 30 ms of the start and returned None with the replacement still scheduled. The replacement ran and published its own completed about a second later. As a check, I changed the loop locally to keep waiting when the synced state isn't terminal, and the test passed. That change isn't a fix, though: with execution_ttl=0 the finish deletes the runs hash, so the loop would never exit.

Closed PR #486 described this bug and fixed it by adding each run's generation to its state events, but that part isn't on main. A fix like that also needs generation set on the executions that add() and replace() return. In my trace, the replacement's execution reported generation 0 while the runs hash had 2.

I think a Perpetual that reschedules itself can hit this too, since its run publishes completed after the reschedule has bumped the generation. I only tested replace(), though.

Environment
  • Commit 9d3db18 on main
  • Python 3.14.7, plus Python 3.10.21 in the repo's Docker test runner at CPU_LIMIT=0.2
  • Memory backend: failed 25 of 25 runs, and 15 of 15 throttled
  • Redis 8.0 (the suite's Docker container): failed 25 of 25 runs, and 15 of 15 throttled

Filed by Claude Opus 5.5 on behalf of @chrisguidry.

Lingua principale
Python
Stelle
148
Fork
12
Merge medio
15h 49m
PR unite (30g)
45

Preparare l'ambiente

  • Include un Dockerfile o un file Docker Compose
  • Nessun modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di chrisguidry/docket

Tutte le issue di chrisguidry/docket

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.