Skip to content

Added task handle support to start() and start_soon() - #1153

Merged
agronholm merged 27 commits into
masterfrom
taskhandle-in-start
Jun 13, 2026
Merged

agronholm merged 27 commits into
masterfrom
taskhandle-in-start

Conversation

@agronholm

Copy link
Copy Markdown
Owner

NOTE Erasing or replacing the contents of this template will result in your pull
request being summarily closed without consideration!

Changes

Adds TaskHandle support to TaskGroup.start_soon() and TaskGroup.start() as per the group consensus.
The latter method has a feature flag for this to preserve backwards compatibility.

Checklist

If this is a user-facing code change, like a bugfix or a new feature, please ensure that
you've fulfilled the following conditions (where applicable):

  • You've added tests (in tests/) which would fail without your patch
  • You've updated the documentation (in docs/), in case of behavior changes or new
    features
  • You've added a new changelog entry (in docs/versionhistory.rst).

If this is a trivial change, like a typo fix or a code reformatting, then you can ignore
these instructions.

Updating the changelog

If there are no entries after the last release, use **UNRELEASED** as the version.
If, say, your patch fixes issue #123, the entry should look like this:

- Fix big bad boo-boo in task groups
  (`#123 <https://github.com/agronholm/anyio/issues/123>`_; PR by @yourgithubaccount)

If there's no issue linked, just link to your pull request instead by updating the
changelog after you've created the PR.

Comment thread src/anyio/_backends/_trio.py Resolved
Co-authored-by: David Brochart <david.brochart@gmail.com>
@agronholm

Copy link
Copy Markdown
Owner Author

This PR doesn't include changes to BlockingPortal. Perhaps it should?

@agronholm

Copy link
Copy Markdown
Owner Author

This PR doesn't include changes to BlockingPortal. Perhaps it should?

OTOH, nothing is breaking so it could be left to a follow-up. It will need a new TaskHandle variant designed for use outside of the event loop thread.

@agronholm
agronholm requested a review from gschaffner May 24, 2026 15:03
Comment thread src/anyio/_backends/_asyncio.py Resolved
Comment thread src/anyio/abc/_tasks.py Resolved
Comment thread src/anyio/abc/_tasks.py Resolved
Comment thread tests/test_taskgroups.py Resolved
Comment thread src/anyio/_backends/_trio.py Resolved
Comment thread src/anyio/_core/_tasks.py Resolved
Comment thread src/anyio/_backends/_asyncio.py Resolved
Comment thread src/anyio/abc/_tasks.py Resolved
Comment thread src/anyio/_core/_tasks.py Resolved
Comment thread src/anyio/_core/_tasks.py Resolved
Comment thread src/anyio/_core/_tasks.py Resolved
@agronholm

agronholm commented May 30, 2026 •

Copy link
Copy Markdown
Owner Author

@gschaffner Can we continue the Awaitable vs Coroutine type annotation discussion here? I find it difficult to jump between the various comment sections. I did some digging and memory refreshing, and found the following about Trio:

  • Trio supports arbitrary awaitables in start_soon()
  • Non-coroutine return values are wrapped in a nested python_wrapper() coroutine function
  • Task.coro points to said wrapper in those cases

As for asyncio:

  • Asyncio supports asend objects in create_task()
  • Asyncio does not support arbitrary awaitables in create_task()
  • However, ensure_future() supports arbitrary awaitables

AnyIO, on master:

  • create_task() supports neither arbitrary awaitables or asend objects
  • start_soon() does not work with asend objects

AnyIO, on this branch:

  • Both create_task() and start_soon() work with asend objects
  • Neither create_task() or start_soon() work with arbitrary awaitables

Given all this, I think it would be reasonable for us to support asend objects but not arbitrary awaitables, yes? That would strike a good compatibility balance between asyncio and Trio. As such, the annotations should remain as Coroutine, not Awaitable. I think the previous change from Coroutine to Awaitable was misguided, given the lack of run-time support.

@gschaffner

Copy link
Copy Markdown
Collaborator

That sounds good to me.

@agronholm

Copy link
Copy Markdown
Owner Author

Ok, so let's see where this leaves us. IIRC, you still had some comments left to be addressed:

  • The start_value type parameter: my choice is to reuse the same class and use Never as the default start value type parameter. Does it make sense to do this work before mypy can support it?
  • Adding __slots__ to CancelScope and Event: I'm trying to add slots to CancelScope at least; there's a test relying on monkey patching which is causing some trouble but I'm working on it.
  • Cancel scope/exception message asymmetry for start(return_handle=False): I'm fine with using the same route for that as return_handle=True.

Was there anything else?

@gschaffner

gschaffner commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

The start_value type parameter: my choice is to reuse the same class and use Never as the default start value type parameter. Does it make sense to do this work before mypy can support it?

Yes, I think so. Currently, for the line value = await tg.start(taskfunc, return_handle=False), IDEs show the hint value: Any, showing the user that the returned value is not being typechecked.

Similarly, for the handle = await tg.start(taskfunc, return_handle=True) case: if we make TaskHandle generic in StartT_co now, users' IDEs will show handle: TaskHandle[int, Any] instead of just showing handle: TaskHandle[int]. It is useful to not hide the temporary Any from users. Making the temporary Any more visible would help to prevent users from being surprised by the API being partially untypechecked.

Was there anything else?

Not much, just a few minor follow-up questions:

  • Should we add a changelog entry for the Awaitable -> Coroutine typing change? (There was a similar entry added in 538b739 / 6ba4245.)

  • The annotations for from_thread.run/AsyncBackend.run_async_from_thread and anyio.run were changed from Coroutine to Awaitable in 538b739 and 9f97cd7, but they don't support Awaitable at runtime (on Trio). Since we changed TaskGroup back to Coroutine, should they also be changed back to Coroutine?

    (Note: BlockingPortal's method annotations were changed to Awaitable in those commits too, but they do actually support Awaitable at runtime.)

  • Do you want to add a regression test for asend support (when the user uses type: ignore)? (There's a test in Added task handle support to start() and start_soon() #1153 (comment).) If starting tasks from asend is intended to be officially supported (is it?), a regression test may be useful since IIUC asend support has accidentally regressed in the past.

  • The minor call_for_coroutine exception string question in Added task handle support to start() and start_soon() #1153 (comment).

@agronholm

Copy link
Copy Markdown
Owner Author

@gschaffner I think I've addressed your feedback now. LMK if I missed something.

@gschaffner

gschaffner commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Nice catch of the start problem, and elegant fix. Last few comments:

  • It looks like there is not any regression test that covers the

    | ExceptionGroup: Exceptions from Trio nursery (2 sub-exceptions)
    +-+---------------- 1 ----------------
        | Traceback (most recent call last):
        |   File "/home/ganden/vc/anyio/src/anyio/_backends/_trio.py", line 254, in run_coro_with_task_status
        |     handle = TaskHandle(coro, name)
        |   File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 262, in __init__
        |     coro.close()
        |     ^^^^^^^^^^
        | AttributeError: 'NoneType' object has no attribute 'close'
        +---------------- 2 ----------------
        | Traceback (most recent call last):
        |   File "/home/ganden/vc/anyio/tests/test_taskgroups.py", line 371, in test_start_exception_delivery
        |     await tg.start(task_fn, return_handle=return_handle)  # type: ignore[arg-type]
        |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        |   File "/home/ganden/vc/anyio/src/anyio/_backends/_trio.py", line 260, in start
        |     handle._start_value = await self._nursery.start(
        |     ^^^^^^
        | UnboundLocalError: cannot access local variable 'handle' where it is not associated with a value
        +------------------------------------
    

    errors that we were seeing (outside of the test suite) prior to the start fix (4605bcf).

    (I.e.: If I revert the src changes in 4605bcf (but keep the tests changes), none of the current tests trigger either of those errors.)

    Consider adding a regression test that, without the start fix, fails with those errors:

    diff --git a/tests/test_taskgroups.py b/tests/test_taskgroups.py
    index e6d0f857..580dfc57 100644
    --- a/tests/test_taskgroups.py
    +++ b/tests/test_taskgroups.py
    @@ -360,13 +360,14 @@ async def test_cancel_with_nested_task_groups() -> None:
        assert len(outer_cancel_spy.call_args_list) < 10
    
    
    -async def test_start_exception_delivery() -> None:
    +@pytest.mark.parametrize("return_handle", [False, True])
    +async def test_start_exception_delivery(return_handle: bool) -> None:
        def task_fn(*, task_status: TaskStatus[str] = TASK_STATUS_IGNORED) -> None:
            task_status.started("hello")
    
        async with anyio.create_task_group() as tg:
            with pytest.raises(TypeError, match="is not a coroutine object"):
    -            await tg.start(task_fn)  # type: ignore[arg-type]
    +            await tg.start(task_fn, return_handle=return_handle)  # type: ignore[call-overload]
    
    
    async def test_start_cancel_after_error() -> None:
  • I still think that we should consider adding __slots__ to Event too, but it's definitely not a blocker for this PR.

    Note: Upstream Trio Event is slotted, upstream asyncio Event isn't.

  • Regarding exception strings (previously: Added task handle support to start() and start_soon() #1153 (comment)): start still has different strings on asyncio and on Trio. Can we give the same message on both backends? On asyncio we have the nice call_for_coroutine error message for users, but on Trio the message is a bit harder for users to understand/debug:

    tests/test_taskgroups.py::test_start_exception_delivery[asyncio] - TypeError('Expected tests.test_taskgroups.test_start_exception_delivery.<locals>.task_fn() to return a coroutine, but the return value (None) is not a coroutine object') [single exception in ExceptionGroup]
    tests/test_taskgroups.py::test_start_exception_delivery[trio] - TypeError('None is not a coroutine object') [single exception in ExceptionGroup]
    

Those couple comments should (hopefully) be my final round of feedback for this PR. Everything else looks good to me!

@gschaffner

gschaffner commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Oop—one more follow-up. Regarding

The annotations for from_thread.run/AsyncBackend.run_async_from_thread and anyio.run were changed from Coroutine to Awaitable in 538b739 and 9f97cd7, but they don't support Awaitable at runtime (on Trio). Since we changed TaskGroup back to Coroutine, should they also be changed back to Coroutine?

(Note: BlockingPortal's method annotations were changed to Awaitable in those commits too, but they do actually support Awaitable at runtime.)

You changed from_thread.run/AsyncBackend.run_async_from_thread to Coroutine (ef4a724), but did not change anyio.run/AsyncBackend.run to Coroutine. Was leaving anyio.run/AsyncBackend.run using Awaitable intentional?

@agronholm

Copy link
Copy Markdown
Owner Author

You changed from_thread.run/AsyncBackend.run_async_from_thread to Coroutine (ef4a724), but did not change anyio.run/AsyncBackend.run to Coroutine. Was leaving anyio.run/AsyncBackend.run using Awaitable intentional?

No, I had planned to change that too, depending on the outcome of these discussions, but then it slipped my mind. Will fix.

@agronholm

Copy link
Copy Markdown
Owner Author

You changed from_thread.run/AsyncBackend.run_async_from_thread to Coroutine (ef4a724), but did not change anyio.run/AsyncBackend.run to Coroutine. Was leaving anyio.run/AsyncBackend.run using Awaitable intentional?

No, I had planned to change that too, depending on the outcome of these discussions, but then it slipped my mind. Will fix.

Oh, but that hit a snag as this test specifically tests for Awaitable support. And on Python 3.14+, asyncio.run() also supports arbitrary awaitables.

@agronholm

Copy link
Copy Markdown
Owner Author

You changed from_thread.run/AsyncBackend.run_async_from_thread to Coroutine (ef4a724), but did not change anyio.run/AsyncBackend.run to Coroutine. Was leaving anyio.run/AsyncBackend.run using Awaitable intentional?

No, I had planned to change that too, depending on the outcome of these discussions, but then it slipped my mind. Will fix.

Oh, but that hit a snag as this test specifically tests for Awaitable support. And on Python 3.14+, asyncio.run() also supports arbitrary awaitables.

I checked, and anyio.run() supports arbitrary awaitables on asyncio, but not on Trio. Not sure what we should do about this. But I'll leave the annotations as Awaitable for now.

@agronholm

Copy link
Copy Markdown
Owner Author

I added __slots__ to a lot of classes (including Event) via a separate commit. That also adds the missing __weakref__ entry to CancelScope.

@agronholm

Copy link
Copy Markdown
Owner Author

I removed the coro check in TaskHandle, as there was no code path remaining that would have tripped that check.

@agronholm
agronholm requested a review from gschaffner June 11, 2026 22:19
@agronholm

Copy link
Copy Markdown
Owner Author

This time I think I covered everything!

@agronholm agronholm added this to the 4.14 milestone Jun 13, 2026

@gschaffner gschaffner left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You changed from_thread.run/AsyncBackend.run_async_from_thread to Coroutine (ef4a724), but did not change anyio.run/AsyncBackend.run to Coroutine. Was leaving anyio.run/AsyncBackend.run using Awaitable intentional?

No, I had planned to change that too, depending on the outcome of these discussions, but then it slipped my mind. Will fix.

Oh, but that hit a snag as this test specifically tests for Awaitable support. And on Python 3.14+, asyncio.run() also supports arbitrary awaitables.

I checked, and anyio.run() supports arbitrary awaitables on asyncio, but not on Trio. Not sure what we should do about this. But I'll leave the annotations as Awaitable for now.

Hm, I forgot about that that test. I suppose some options would be:

It would be nice to resolve anyio.run's Awaitable situation in the same release (and combined changelog entry) as the other handful of APIs that have been changed back to Coroutine. I think that it isn't a blocker for this PR, however.

LGTM!

@agronholm
agronholm merged commit ebdc950 into master Jun 13, 2026
19 checks passed
@agronholm
agronholm deleted the taskhandle-in-start branch June 13, 2026 22:38
@agronholm

Copy link
Copy Markdown
Owner Author

Thanks for sticking with me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants