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
11 changes: 11 additions & 0 deletions src/graphql/execution/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from asyncio import (
FIRST_COMPLETED,
CancelledError,
ensure_future,
gather,
get_running_loop,
Expand Down Expand Up @@ -1214,6 +1215,11 @@ async def with_abort_signal(self, awaitable: Awaitable[T]) -> T:
abort = ensure_future(abort_signal.wait())
try:
await wait({task, abort}, return_when=FIRST_COMPLETED)
except CancelledError:
task.cancel()
with suppress(BaseException):
await task
raise
finally:
if not abort.done():
abort.cancel()
Expand Down Expand Up @@ -1261,6 +1267,11 @@ async def with_aborted_execution_error(self, awaitable: Awaitable[T]) -> T:
abort = ensure_future(abort_signal.wait()) # type: ignore[union-attr]
try:
await wait({task, abort}, return_when=FIRST_COMPLETED)
except CancelledError:
task.cancel()
with suppress(BaseException):
await task
raise
finally:
if not abort.done():
abort.cancel()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from asyncio import FIRST_COMPLETED, ensure_future, wait
from asyncio import FIRST_COMPLETED, CancelledError, ensure_future, gather, wait
from typing import TYPE_CHECKING, Any, Protocol, cast

from ...error import GraphQLError, located_error
Expand Down Expand Up @@ -183,6 +183,11 @@ async def _subscribe(
abort = ensure_future(abort_signal.wait())
try:
await wait({next_batch, abort}, return_when=FIRST_COMPLETED)
except CancelledError:
next_batch.cancel()
abort.cancel()
await gather(next_batch, abort, return_exceptions=True)
raise
finally:
if not abort.done():
abort.cancel()
Expand Down
3 changes: 3 additions & 0 deletions src/graphql/execution/incremental/work_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,10 @@ def _cancel_task(
cancel_awaitables: list[Awaitable[Any]],
) -> None:
"""Cancel a task with the streams produced by it."""
pending_future = task.computation.pending_future
abort_result = task.computation.abort(reason)
if pending_future is not None:
cancel_awaitables.append(pending_future)
if is_awaitable(abort_result):
cancel_awaitables.append(abort_result)
task_node = self._task_nodes.get(task)
Expand Down
109 changes: 108 additions & 1 deletion tests/execution/test_cancellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@

from __future__ import annotations

from asyncio import Event, Future, ensure_future, sleep
import asyncio
from asyncio import (
CancelledError,
Event,
Future,
current_task,
ensure_future,
gather,
get_running_loop,
sleep,
wait_for,
)
from collections.abc import AsyncIterator, Awaitable
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -1251,6 +1262,102 @@ async def aclose(self):
assert return_called is True


@pytest.mark.parametrize("operation", ["query", "subscription"])
async def test_cancels_pending_work_when_the_consumer_task_is_cancelled(operation):
controller = AbortController()
started = Event()
finished = Event()
pending_task: Future | None = None

async def pending(_info=None):
nonlocal pending_task
pending_task = current_task()
started.set()
try:
await Future()
finally:
finished.set()

async def events():
yield {"foo": await pending()}

if operation == "query":
result = execute(
schema,
parse("{ blocker }"),
root_value={"blocker": pending},
abort_signal=controller.signal,
)
assert is_awaitable(result)
else:
stream = subscribe(
schema,
parse("subscription { foo }"),
root_value={"foo": events()},
abort_signal=controller.signal,
)
assert isinstance(stream, AsyncIterator)
result = anext(stream)
consumer = ensure_future(result)
try:
await wait_for(started.wait(), 1)
consumer.cancel()
with pytest.raises(CancelledError):
await consumer
assert finished.is_set()
assert not controller.signal.aborted
finally:
consumer.cancel()
if pending_task is not None:
pending_task.cancel()
await gather(consumer, pending_task, return_exceptions=True)
else: # pragma: no cover - only reached if starting the resolver fails
await gather(consumer, return_exceptions=True)


@pytest.mark.parametrize("enable_early_execution", [False, True])
async def test_settles_incremental_work_when_the_consumer_times_out(
enable_early_execution,
):
controller = AbortController()
started = Event()
finished = Event()
errors = []
loop = get_running_loop()
previous_handler = loop.get_exception_handler()
loop.set_exception_handler(lambda _loop, context: errors.append(context))

async def blocker(_info):
started.set()
try:
await Future()
finally:
await sleep(0)
finished.set()

result = experimental_execute_incrementally(
schema,
parse("{ ... @defer { blocker } }"),
root_value={"blocker": blocker},
abort_signal=controller.signal,
enable_early_execution=enable_early_execution,
)
assert isinstance(result, ExperimentalIncrementalExecutionResults)
consumer = ensure_future(anext(result.subsequent_results))
try:
await wait_for(started.wait(), 1)
with pytest.raises(asyncio.TimeoutError):
await wait_for(consumer, 0.01)
assert finished.is_set()
assert not errors
assert not controller.signal.aborted
finally:
consumer.cancel()
await gather(consumer, return_exceptions=True)
await result.subsequent_results.aclose()
loop.set_exception_handler(previous_handler)


def describe_abort_reason_traceback():
def does_not_extend_the_traceback_of_the_default_reason():
abort_controller = AbortController()
Expand Down
Loading