python / python/cpython

`asyncio.timeout(0)` swallows a prior task cancellation

Abierto
#134,471 8 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-asyncio type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug report

Bug description:

async with asyncio.timeout(0) will catch and process a prior unrelated cancellation of the enclosing task.

import asyncio

async def test(timeout):
    task = asyncio.current_task()
    task.cancel()

    try:
        async with asyncio.timeout(timeout):
            await asyncio.sleep(1)
    except TimeoutError:
        print("timeout caught")
    except asyncio.CancelledError:
        print("CancelledError caught")
        raise

    await asyncio.sleep(2)
    print("not cancelled")

asyncio.run(test(timeout=0))  # prints "timeout caught" and "not_cancelled"

This code prints timeout caught and not_cancelled, which means that asyncio.timeout(0) swallows the preceding task.cancel(), so the task pretty much ignores cancellation and proceeds.

Notably, that doesn't happen with a positive timeout. In the above example, asyncio.run(test(timeout=0.001)) will only print CancelledError caught, which I believe is the correct behavior.
In this case, asyncio.Timeout's internal timeout handler (_on_timeout) never gets to run, so the context manager doesn't interfere at all - it doesn't cancel/uncancel the task and simply passes CancelledError through.

Possible solution

I believe this behavior was unintentedly introduced in #102815, where the logic in __aexit__ was changed to only consider new cancel requests when deciding if it should raise a TimeoutError. That was necessary for Timeout to work correctly if used while handling a CancelledError, but now it can get confused between "internal" and "external" cancellations that happened on the same loop iteration.

I think we could capture task's _must_cancel flag when entering the context manager. If it was set, it means that CancelledError was supposed to be delivered and Timeout shouldn't mess with that attempt.

Draft PR to illustrate the idea: https://github.com/python/cpython/pull/134472

Additional context

I've hit this issue in production with redis-py, which uses asyncio.timeout(0) internally in the connection parser:

# reduced for brevity
from redis.asyncio import Redis

async def test(timeout):
    redis: Redis = await get_redis()
    task = asyncio.current_task()
    task.cancel()
    await redis.set("foo", "bar")
    assert False, "not cancelled"
CPython versions tested on:

3.12, 3.13, CPython main branch, 3.14, 3.11

Operating systems tested on:

macOS

Linked PRs
  • gh-134472

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza con asyncio.Timeout.aexit y su manejador _on_timeout, y después revisa el borrador del PR #134472. Reproduce los ejemplos de timeout cero y timeout positivo; se considera terminado cuando una cancelación previa se propaga como CancelledError, mientras que el manejo de un timeout genuino sigue generando TimeoutError, con cobertura de regresión.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
backend
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.