unshielded-cleanup-checkpoint (EFF118)¶
Family: Execution Effects (EFF) · Heuristic · Off by default · Severity error (a bug) · No automatic fix
A cleanup (a finally body, an except taking the cancellation, an __aexit__) that awaits a call reaching an AnyIO or Trio cancellation checkpoint with no shield on the way: in a cancelled scope the cleanup stops there.
Heuristic
This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs when select or extend-select names its code or name, and with lint.heuristic = true (--heuristic) also by default and for its prefixes and ALL. It has not been measured yet. See Rule Precision.
What it does¶
Checks for cleanup code that awaits a call reaching an AnyIO or Trio cancellation checkpoint with
no shield on the way. The rule is heuristic: it runs when select or extend-select names it,
and with --heuristic (lint.heuristic = true).
A cleanup is:
- a
finallybody; - an
exceptclause that is the first of itstryto take the cancellation: a bareexcept,BaseException,asyncio.CancelledError,trio.Cancelled,anyio.get_cancelled_exc_class(), or a tuple holding one; a clause after one whose classes heki cannot tell is left out, and so is a clause after one taking the cancellation (except Cancelled: raisefirst); - the body of an
__aexit__method.
A checkpoint is an await of a call the catalog lists as one: anyio.sleep, the to_thread,
to_process, and to_interpreter calls, run_process, open_process, open_file, the
connections, Event.wait, the acquisition of a Lock, Semaphore, CapacityLimiter, or
Condition (also by async with), Condition.wait, a memory object stream's send and
receive, Process.wait, their Trio counterparts, and run_in_threadpool. The call is found
through awaited project calls, with the shortest chain of calls down to it. A lock or semaphore
made with fast_acquire=True takes no checkpoint while nobody holds it and is not counted.
lowlevel.checkpoint() and checkpoint_if_cancelled() count only where something runs after
them: awaited last, they hand the cancellation on to the caller on purpose.
It does not report:
- a checkpoint inside a
withoverCancelScope(shield=True)ormove_on_after(..., shield=True)(and the othermove_on_*andfail_*calls) on every path to it, in the cleanup or in any function on the way, also when the code names the scope by the module that defines it (anyio._core._tasks.CancelScope); a project function whose checkpoints are all shielded reaches none; - a checkpoint inside a cancel scope that may shield: one made with a
shieldargument that is not a constant, one whoseshieldattribute the function sets, or one made elsewhere; - a checkpoint on a branch the call's constant arguments never take (
await self._stop()where the checkpoint is underif force:andforcedefaults toFalse); - a function every call of which runs it shielded: each awaits it inside a shield, or only
creates its coroutine (
await _shielded(self._close()), a task) where heki does not follow it; a function with no call heki finds is reported; - an await of a coroutine stored first (
pending = work(); await pending), anasync for, and a project context manager entering a shielded scope (not followed); - native asyncio awaits (
asyncio.sleep,asyncio.Lock): what cancels them is a task'scancel(), which is delivered once; - test code.
What a report states¶
A report states that when the scope around the cleanup is already cancelled, the await raises the cancellation at the checkpoint, so the statements after it in the cleanup, and the work of the call itself, do not run.
Its premises:
- Cancelled scope: the cleanup runs while an AnyIO or Trio scope around it is cancelled. An
AnyIO cancellation is level-triggered: every checkpoint inside the cancelled scope raises
again until the scope exits. Open: whether the cleanup runs after a cancellation at all (a
finallyalso runs on a normal exit) is not established. - Checkpoint: the call reaches the checkpoint on some path. Open: one path is enough, and a branch decided by state the call does not show is not told apart.
- No shield: no shield is on the path, in the functions on the way or in the calls of the function holding the cleanup. Open: a caller further up and a caller heki does not see (a framework calling an endpoint) may run it shielded.
Why is this bad?¶
A cleanup releases what the code holds: it deletes a temporary resource, stops a process,
closes a connection, or puts a worker back into its pool. Cancellation is the usual reason the
cleanup runs, and an AnyIO or Trio scope cancelled once cancels every checkpoint inside it, so
the first await that checks for cancellation raises again. A shutdown loop that stops each
process inside try: ... except Exception: ends at the first process, because the cancellation
is not an Exception; a pool that pops a stale worker into a call argument and then awaits
neither destroys nor keeps it.
Example¶
import anyio
async def delete_group(name: str) -> None:
await anyio.to_thread.run_sync(delete_container_group, name)
async def run(name: str) -> None:
try:
await watch(name)
finally:
await delete_group(name) # EFF118
log_deleted(name)
Use instead:
Fix safety¶
No automatic fix. A shield keeps the cleanup running while the scope is cancelled: give a
cleanup that can wait for long a deadline too (anyio.move_on_after(10, shield=True)).
Options¶
lint.heuristic = true(or--heuristic) runs the rule by default;--select EFF118runs it alone.[[tool.heki.ecosystem]]entries witheffects = ["checkpoint"]add checkpoints.