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
3 changes: 3 additions & 0 deletions newsfragments/1191.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Trio no longer crashes when an async function is implemented in C or
Cython and then passed directly to `trio.run` or
``nursery.start_soon``.
3 changes: 3 additions & 0 deletions newsfragments/550.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Trio no longer crashes when an async function is implemented in C or
Cython and then passed directly to `trio.run` or
``nursery.start_soon``.
15 changes: 11 additions & 4 deletions trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1348,18 +1348,25 @@ def _return_value_looks_like_wrong_library(value):
else:
context = copy_context()

if not hasattr(coro, "cr_frame"):
# This async function is implemented in C or Cython
async def python_wrapper(orig_coro):
return await orig_coro

coro = python_wrapper(coro)
coro.cr_frame.f_locals.setdefault(
LOCALS_KEY_KI_PROTECTION_ENABLED, system_task
)

task = Task(
coro=coro,
parent_nursery=nursery,
runner=self,
name=name,
context=context,
)
self.tasks.add(task)
coro.cr_frame.f_locals.setdefault(
LOCALS_KEY_KI_PROTECTION_ENABLED, system_task
)

self.tasks.add(task)
if nursery is not None:
nursery._children.add(task)
task._activate_cancel_status(nursery._cancel_status)
Expand Down
38 changes: 38 additions & 0 deletions trio/_core/tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import warnings
from contextlib import contextmanager, ExitStack
from math import inf
from textwrap import dedent

import attr
import outcome
Expand Down Expand Up @@ -2389,3 +2390,40 @@ def abort_fn(_):
task.coro.send(None)

assert abort_fn_called


def test_async_function_implemented_in_C():
# These used to crash because we'd try to mutate the coroutine object's
# cr_frame, but C functions don't have Python frames.

ns = {"_core": _core}
try:
exec(
dedent(
"""
async def agen_fn(record):
assert not _core.currently_ki_protected()
record.append("the generator ran")
yield
"""
),
ns,
)
except SyntaxError:
pytest.skip("Requires Python 3.6+")
else:
agen_fn = ns["agen_fn"]

run_record = []
agen = agen_fn(run_record)
_core.run(agen.__anext__)
assert run_record == ["the generator ran"]

async def main():
start_soon_record = []
agen = agen_fn(start_soon_record)
async with _core.open_nursery() as nursery:
nursery.start_soon(agen.__anext__)
assert start_soon_record == ["the generator ran"]

_core.run(main)