Skip to content

Commit b6b9d67

Browse files
committed
ASYNC100 now treats start_soon() as a cancel point
1 parent b842265 commit b6b9d67

File tree

13 files changed

+261
-29
lines changed

13 files changed

+261
-29
lines changed

docs/changelog.rst

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,13 @@ Changelog
44

55
`CalVer, YY.month.patch <https://calver.org/>`_
66

7+
24.11.4
8+
=======
9+
- :ref:`ASYNC100 <async100>` once again ignores :func:`trio.open_nursery` and :func:`anyio.create_task_group`, but now treats calls to ``.start_soon()`` as introducing a :ref:`cancel point <cancel_point>`.
10+
711
24.11.3
812
=======
9-
- Revert :ref:`ASYNC100 <async100>` ignoring :func:`trio.open_nursery` and :func:`anyio.create_task_group` due to it not viewing `start_soon()` as introducing a :ref:`cancel point <cancel_point>`.
13+
- Revert :ref:`ASYNC100 <async100>` ignoring :func:`trio.open_nursery` and :func:`anyio.create_task_group` due to it not viewing ``.start_soon()`` as introducing a :ref:`cancel point <cancel_point>`.
1014

1115
24.11.2
1216
=======

docs/rules.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ _`ASYNC100` : cancel-scope-no-checkpoint
1313
A :ref:`timeout_context` does not contain any :ref:`checkpoints <checkpoint>`.
1414
This makes it pointless, as the timeout can only be triggered by a checkpoint.
1515
This check also treats ``yield`` as a checkpoint, since checkpoints can happen in the caller we yield to.
16+
:func:`trio.open_nursery` and :func:`anyio.create_task_group` are excluded, as they are :ref:`schedule points <schedule_point>` but not :ref:`cancel points <cancel_point>` (unless they contain calls to :meth:`trio.Nursery.start_soon`/:meth:`anyio.abc.TaskGroup.start_soon`).
1617
See :ref:`ASYNC912 <async912>` which will in addition guarantee checkpoints on every code path.
1718

1819
_`ASYNC101` : yield-in-cancel-scope

flake8_async/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838

3939

4040
# CalVer: YY.month.patch, e.g. first release of July 2022 == "22.7.1"
41-
__version__ = "24.11.3"
41+
__version__ = "24.11.4"
4242

4343

4444
# taken from https://github.com/Zac-HD/shed

flake8_async/visitors/flake8asyncvisitor.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,7 @@ def set_state(self, attrs: dict[str, Any], copy: bool = False):
134134
def save_state(self, node: ast.AST, *attrs: str, copy: bool = False):
135135
state = self.get_state(*attrs, copy=copy)
136136
if node in self.outer:
137-
# not currently used, and not gonna bother adding dedicated test
138-
# visitors atm
139-
self.outer[node].update(state) # pragma: no cover
137+
self.outer[node].update(state)
140138
else:
141139
self.outer[node] = state
142140

flake8_async/visitors/visitor91x.py

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
flatten_preserving_comments,
2626
fnmatch_qualified_name_cst,
2727
func_has_decorator,
28+
identifier_to_string,
2829
iter_guaranteed_once_cst,
2930
with_has_call,
3031
)
@@ -285,6 +286,7 @@ def __init__(self, *args: Any, **kwargs: Any):
285286
# ASYNC100
286287
self.has_checkpoint_stack: list[bool] = []
287288
self.node_dict: dict[cst.With, list[AttributeCall]] = {}
289+
self.taskgroups: list[str] = []
288290

289291
# --exception-suppress-context-manager
290292
self.suppress_imported_as: list[str] = []
@@ -299,13 +301,28 @@ def should_autofix(self, node: cst.CSTNode, code: str | None = None) -> bool:
299301
and self.library != ("asyncio",)
300302
)
301303

304+
def checkpoint_cancel_point(self) -> None:
305+
self.has_checkpoint_stack = [True] * len(self.has_checkpoint_stack)
306+
# don't need to look for any .start_soon() calls
307+
self.taskgroups.clear()
308+
302309
def checkpoint(self) -> None:
303310
self.uncheckpointed_statements = set()
304-
self.has_checkpoint_stack = [True] * len(self.has_checkpoint_stack)
311+
self.checkpoint_cancel_point()
305312

306313
def checkpoint_statement(self) -> cst.SimpleStatementLine:
307314
return checkpoint_statement(self.library[0])
308315

316+
def visit_Call(self, node: cst.Call) -> None:
317+
# [Nursery/TaskGroup].start_soon introduces a cancel point
318+
if (
319+
isinstance(node.func, cst.Attribute)
320+
and isinstance(node.func.value, cst.Name)
321+
and node.func.attr.value == "start_soon"
322+
and node.func.value.value in self.taskgroups
323+
):
324+
self.checkpoint_cancel_point()
325+
309326
def visit_ImportFrom(self, node: cst.ImportFrom) -> None:
310327
# Semi-crude approach to handle `from contextlib import suppress`.
311328
# It does not handle the identifier being overridden, or assigned
@@ -341,9 +358,12 @@ def visit_FunctionDef(self, node: cst.FunctionDef) -> bool:
341358
"safe_decorator",
342359
"async_function",
343360
"uncheckpointed_statements",
361+
# comp_unknown does not need to be saved
344362
"loop_state",
345363
"try_state",
346364
"has_checkpoint_stack",
365+
# node_dict is cleaned up and don't need to be saved
366+
"taskgroups",
347367
"suppress_imported_as",
348368
copy=True,
349369
)
@@ -491,12 +511,42 @@ def _is_exception_suppressing_context_manager(self, node: cst.With) -> bool:
491511
is not None
492512
)
493513

514+
def _checkpoint_with(self, node: cst.With, entry: bool):
515+
"""Conditionally checkpoints entry/exit of With.
516+
517+
If the `with` only contains calls to open_nursery/create_task_group, it's a
518+
schedule point but not a cancellation point, so we treat it as a checkpoint
519+
for async91x but not for async100.
520+
521+
Saves the name of the taskgroup/nursery if entry is set
522+
"""
523+
if getattr(node, "asynchronous", None):
524+
for item in node.items:
525+
if isinstance(item.item, cst.Call) and identifier_to_string(
526+
item.item.func
527+
) in (
528+
"trio.open_nursery",
529+
"anyio.create_task_group",
530+
):
531+
# save the nursery/taskgroup to see if it has a `.start_soon`
532+
if (
533+
entry
534+
and item.asname is not None
535+
and isinstance(item.asname.name, cst.Name)
536+
):
537+
self.taskgroups.append(item.asname.name.value)
538+
else:
539+
self.checkpoint()
540+
break
541+
else:
542+
self.uncheckpointed_statements = set()
543+
494544
# Async context managers can reasonably checkpoint on either or both of entry and
495545
# exit. Given that we can't tell which, we assume "both" to avoid raising a
496546
# missing-checkpoint warning when there might in fact be one (i.e. a false alarm).
497547
def visit_With_body(self, node: cst.With):
498-
if getattr(node, "asynchronous", None):
499-
self.checkpoint()
548+
self.save_state(node, "taskgroups", copy=True)
549+
self._checkpoint_with(node, entry=True)
500550

501551
# if this might suppress exceptions, we cannot treat anything inside it as
502552
# checkpointing.
@@ -548,15 +598,16 @@ def leave_With(self, original_node: cst.With, updated_node: cst.With):
548598
for res in self.node_dict[original_node]:
549599
self.error(res.node, error_code="ASYNC912")
550600

601+
self.node_dict.pop(original_node, None)
602+
551603
# if exception-suppressing, restore all uncheckpointed statements from
552604
# before the `with`.
553605
if self._is_exception_suppressing_context_manager(original_node):
554606
prev_checkpoints = self.uncheckpointed_statements
555607
self.restore_state(original_node)
556608
self.uncheckpointed_statements.update(prev_checkpoints)
557609

558-
if getattr(original_node, "asynchronous", None):
559-
self.checkpoint()
610+
self._checkpoint_with(original_node, entry=False)
560611
return updated_node
561612

562613
# error if no checkpoint since earlier yield or function entry
@@ -569,7 +620,7 @@ def leave_Yield(
569620

570621
# Treat as a checkpoint for ASYNC100, since the context we yield to
571622
# may checkpoint.
572-
self.has_checkpoint_stack = [True] * len(self.has_checkpoint_stack)
623+
self.checkpoint_cancel_point()
573624

574625
if self.check_function_exit(original_node) and self.should_autofix(
575626
original_node

tests/autofix_files/async100.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,12 +132,6 @@ async def fn(timeout):
132132
await trio.sleep(1)
133133

134134

135-
async def nursery_no_cancel_point():
136-
with trio.CancelScope(): # should error, but reverted PR
137-
async with anyio.create_task_group():
138-
...
139-
140-
141135
async def dont_crash_on_non_name_or_attr_call():
142136
async with contextlib.asynccontextmanager(agen_fn)():
143137
...
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# AUTOFIX
2+
# BASE_LIBRARY anyio
3+
# NOTRIO # trio.create_task_group doesn't exist
4+
# ASYNCIO_NO_ERROR
5+
import anyio
6+
7+
8+
async def bar() -> None: ...
9+
10+
11+
async def anyio_cancelscope():
12+
# error: 9, "anyio", "CancelScope"
13+
...
14+
15+
16+
# see async100_trio for more comprehensive tests
17+
async def nursery_no_cancel_point():
18+
# error: 9, "anyio", "CancelScope"
19+
async with anyio.create_task_group():
20+
...
21+
22+
23+
async def nursery_with_start_soon():
24+
with anyio.CancelScope():
25+
async with anyio.create_task_group() as tg:
26+
tg.start_soon(bar)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
+++
3+
@@ x,15 x,15 @@
4+
5+
6+
async def anyio_cancelscope():
7+
- with anyio.CancelScope(): # error: 9, "anyio", "CancelScope"
8+
- ...
9+
+ # error: 9, "anyio", "CancelScope"
10+
+ ...
11+
12+
13+
# see async100_trio for more comprehensive tests
14+
async def nursery_no_cancel_point():
15+
- with anyio.CancelScope(): # error: 9, "anyio", "CancelScope"
16+
- async with anyio.create_task_group():
17+
- ...
18+
+ # error: 9, "anyio", "CancelScope"
19+
+ async with anyio.create_task_group():
20+
+ ...
21+
22+
23+
async def nursery_with_start_soon():
Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,51 @@
11
# AUTOFIX
22
# ASYNCIO_NO_ERROR # asyncio.open_nursery doesn't exist
3-
# ANYIO_NO_ERROR # anyio.open_nursery doesn't exist
3+
# NOANYIO # anyio.open_nursery doesn't exist
44
import trio
55

66

77
async def nursery_no_cancel_point():
8-
with trio.CancelScope(): # should error, but reverted PR
9-
async with trio.open_nursery():
10-
...
8+
# error: 9, "trio", "CancelScope"
9+
async with trio.open_nursery():
10+
...
11+
12+
13+
# but it is a cancel point if the nursery contains a call to start_soon()
14+
15+
16+
async def nursery_start_soon():
17+
with trio.CancelScope():
18+
async with trio.open_nursery() as n:
19+
n.start_soon(trio.sleep, 0)
20+
21+
22+
async def nursery_start_soon_misnested():
23+
async with trio.open_nursery() as n:
24+
with trio.CancelScope():
25+
n.start_soon(trio.sleep, 0)
26+
27+
28+
async def nested_scope():
29+
with trio.CancelScope():
30+
with trio.CancelScope():
31+
async with trio.open_nursery() as n:
32+
n.start_soon(trio.sleep, 0)
33+
34+
35+
async def nested_nursery():
36+
with trio.CancelScope():
37+
async with trio.open_nursery() as n:
38+
async with trio.open_nursery() as n2:
39+
n2.start_soon(trio.sleep, 0)
40+
41+
42+
async def nested_function_call():
43+
44+
# error: 9, "trio", "CancelScope"
45+
async with trio.open_nursery() as n:
46+
47+
def foo():
48+
n.start_soon(trio.sleep, 0)
49+
50+
# a false alarm in case we call foo()... but we can't check if they do
51+
foo()
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
+++
3+
@@ x,9 x,9 @@
4+
5+
6+
async def nursery_no_cancel_point():
7+
- with trio.CancelScope(): # error: 9, "trio", "CancelScope"
8+
- async with trio.open_nursery():
9+
- ...
10+
+ # error: 9, "trio", "CancelScope"
11+
+ async with trio.open_nursery():
12+
+ ...
13+
14+
15+
# but it is a cancel point if the nursery contains a call to start_soon()
16+
@@ x,11 x,11 @@
17+
18+
async def nested_function_call():
19+
20+
- with trio.CancelScope(): # error: 9, "trio", "CancelScope"
21+
- async with trio.open_nursery() as n:
22+
+ # error: 9, "trio", "CancelScope"
23+
+ async with trio.open_nursery() as n:
24+
25+
- def foo():
26+
- n.start_soon(trio.sleep, 0)
27+
+ def foo():
28+
+ n.start_soon(trio.sleep, 0)
29+
30+
- # a false alarm in case we call foo()... but we can't check if they do
31+
- foo()
32+
+ # a false alarm in case we call foo()... but we can't check if they do
33+
+ foo()

0 commit comments

Comments
 (0)