python-trio / python-trio/trio

More robust CancelScope misnesting prevention

Open
#3,329 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
7.3k
Forks
431
Avg merge
2d 17h
Merged PRs (30d)
6

Description

@agronholm brought this case up on Gitter:

import trio

async def main():
    async def shim(fn, *args):
        fn(*args)

    scope = trio.CancelScope()
    async with trio.open_nursery() as nursery:
        nursery.start_soon(shim, scope.__enter__)

    async with trio.open_nursery() as nursery:
        nursery.start_soon(shim, scope.__exit__, None, None, None)

trio.run(main)

I think we should probably error here. I took a look at the code and I think the issue is that our CancelScope misnesting prevention only works within a single task -- that is, we don't check that there's no CancelScope currently entered at the end of any task. Unfortunately, IIRC that's hard in that situation to raise an exception with a nice stack trace. As a stopgap, we could raise when exiting the nursery if anything gets marked as misnested. (... which would raise later but should catch all of these misnestings?)


I'm making mostly unsubstantiated conjectures here, based on a few minutes of playing around with the code. There's very likely something I missed!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with CancelScope.enter and exit, then trace nursery teardown as used in the reproducer. Run the provided cross-task misnesting example and inspect how scope state is tracked across tasks. Done means this misnesting is detected and raises an error, either at scope exit or nursery exit, with tests covering the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.