Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Cancel remaining fields on exceptions #238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 20, 2025
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
40 changes: 33 additions & 7 deletions 40 src/graphql/execution/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

from __future__ import annotations

from asyncio import ensure_future, gather, shield, wait_for
from asyncio import (
CancelledError,
create_task,
ensure_future,
gather,
shield,
wait_for,
)
from contextlib import suppress
from copy import copy
from typing import (
Expand Down Expand Up @@ -459,12 +466,23 @@ async def get_results() -> dict[str, Any]:
field = awaitable_fields[0]
results[field] = await results[field]
else:
results.update(
zip(
awaitable_fields,
await gather(*(results[field] for field in awaitable_fields)),
)
)
tasks = {
create_task(results[field]): field # type: ignore[arg-type]
for field in awaitable_fields
}

try:
awaited_results = await gather(*tasks)
except Exception:
# Cancel unfinished tasks before raising the exception
for task in tasks:
if not task.done():
task.cancel()
await gather(*tasks, return_exceptions=True)
raise

results.update(zip(awaitable_fields, awaited_results))

return results

return get_results()
Expand Down Expand Up @@ -538,6 +556,10 @@ async def await_completed() -> Any:
try:
return await completed
except Exception as raw_error:
# Before Python 3.8 CancelledError inherits Exception and
# so gets caught here.
if isinstance(raw_error, CancelledError):
raise # pragma: no cover
self.handle_field_error(
raw_error,
return_type,
Expand Down Expand Up @@ -745,6 +767,10 @@ async def complete_awaitable_value(
if self.is_awaitable(completed):
completed = await completed
except Exception as raw_error:
# Before Python 3.8 CancelledError inherits Exception and
# so gets caught here.
if isinstance(raw_error, CancelledError):
raise # pragma: no cover
self.handle_field_error(
raw_error, return_type, field_group, path, incremental_data_record
)
Expand Down
40 changes: 40 additions & 0 deletions 40 tests/execution/test_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
GraphQLInt,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
Expand Down Expand Up @@ -193,3 +194,42 @@ async def is_type_of_baz(obj, *_args):
{"foo": [{"foo": "bar", "foobar": 1}, {"foo": "baz", "foobaz": 2}]},
None,
)

@pytest.mark.asyncio
async def cancel_on_exception():
barrier = Barrier(2)
mgorven marked this conversation as resolved.
Show resolved Hide resolved
completed = False

async def succeed(*_args):
nonlocal completed
await barrier.wait()
completed = True # pragma: no cover

async def fail(*_args):
raise RuntimeError("Oops")

schema = GraphQLSchema(
GraphQLObjectType(
"Query",
{
"foo": GraphQLField(GraphQLNonNull(GraphQLBoolean), resolve=fail),
"bar": GraphQLField(GraphQLBoolean, resolve=succeed),
},
)
)

ast = parse("{foo, bar}")

awaitable_result = execute(schema, ast)
assert isinstance(awaitable_result, Awaitable)
result = await asyncio.wait_for(awaitable_result, 1.0)

assert result == (
None,
[{"message": "Oops", "locations": [(1, 2)], "path": ["foo"]}],
)

# Unblock succeed() and check that it does not complete
await barrier.wait()
await asyncio.sleep(0)
assert not completed
Morty Proxy This is a proxified and sanitized view of the page, visit original site.