async-blocking-call (EFF101)¶
Family: Execution Effects (EFF) · Exact · Enabled by default · Severity error (a bug) · No automatic fix
A call in async def that always runs a network, database, subprocess, or sleep call that waits on the event loop; its heuristic reports, a call that can reach a blocking call.
What it does¶
Checks async def functions that reach a blocking call on the event loop, directly or through
synchronous helpers: network I/O (requests, httpx.Client, urllib), host name lookups
(socket.getaddrinfo / gethostbyname / getfqdn; the event loop has loop.getaddrinfo();
getaddrinfo with the AI_NUMERICHOST flag only parses an address and is not reported),
database drivers
(sqlite3, psycopg, pymongo, ...; the fetches of a named, server-side psycopg cursor
conn.cursor("name") too), subprocesses waiting for completion, time.sleep, and
waits on other threads (acquiring a threading lock, Event.wait(), Thread.join(),
queue.Queue.get(), put() on a queue known to be bounded (see below), Future.result(),
concurrent.futures.wait(); a zero timeout or
blocking=False / block=False returns at once and is not reported, also when a helper passes
on its own flag parameter and its caller passes False: close(wait=False) over
shutdown(wait=wait); so does result() / exception() of a concurrent.futures.Future known
to be done: under if f.done(): (also after if not f.done(): return, a while not f.done():
poll, or with and), or once await asyncio.wrap_future(f) has returned, on every path to the
call). A function SQLAlchemy's
AsyncSession.run_sync(fn) / AsyncConnection.run_sync(fn) runs is called on the event loop:
its database I/O through the session or connection it receives is awaited for it, its other
blocking calls are reported. Where an argument decides what a library call does, a literal
one is followed: pd.read_csv("https://...") downloads the file.
put() on a queue.Queue, LifoQueue, or PriorityQueue waits only while the queue is full,
which only a queue its maxsize bounds can be, so it is reported only on a queue known to be
bounded: a positive maxsize (a literal, a module constant, a class constant, or an integer a
constructor parameter receives from every call, such as its default) on some path, and every
path known. heki follows the queue from where it is built into local variables, the attributes
the class family's own bodies and methods store (self.queue = queue.Queue(maxsize=n), or a
queue the class's __init__ receives), module globals, and parameters, whose project callers
decide: a helper's at each call, an async def's by what all of its callers pass. A queue built
without a maxsize (or with zero, a negative one, or None), one from a call or an object heki
cannot see, and one a parameter without project callers receives are not known to be bounded,
and putting on them is not reported.
Reading a @property or functools.cached_property attribute of a project class runs its
getter, so the read counts as a call of the getter (self.client whose getter opens a
connection). A property that also defines a setter or deleter is not followed.
Calling a generator function only creates the generator; its body runs where the generator is
iterated: a for loop or comprehension over it, unpacking it, yield from it, a call that
consumes it (list(...), sorted(...), "".join(...), items.extend(...), ...), a lazy wrapper
iterated there (enumerate(...), zip(...), itertools.islice(...), ...), or a project
function iterating the parameter it is handed. A generator returned by a plain function runs
where its caller iterates it. next(gen) runs the body only up to its first yield, which heki
does not separate from the rest, so it is not followed.
A call whose arguments switch off the callee's branch with the blocking call is not followed
into it: load(name, cache=False) does not reach the request under if cache:. The branches
are the callee's tests of its parameters: truthiness, is None, isinstance with builtin,
io, or os.PathLike classes, and hasattr (which a value's class decides for the methods of
the file protocol: read, write, close, ...), also of a parameter the callee rebinds on
some paths (if buf is None: buf = io.StringIO(), then if isinstance(buf, str): open(buf)
opens a file only for a path argument). The arguments that decide them are constants and the
literal defaults of omitted ones (False, None, 0, "", empty displays), values whose
exact class the caller knows (a display or comprehension, or an io.StringIO / io.BytesIO it
constructs, also held in a variable: fetch(io.BytesIO(data)) does not reach the download
under if not hasattr(src, "read"):; an instance of a subclass does not count), and tests the
caller has already made on the same value: a call made only when isinstance(self._input,
PathLike) is false does not reach the callee's branch for isinstance(self._input, PathLike).
A generator's branches are decided at the call that creates it. Lazy initialization does not
relax this rule: a connection opened once still blocks the event loop that once.
The library calls a helper makes with its own parameter are decided at each call the same way
where the catalog decides them by the argument: nap(0) over time.sleep(seconds),
fetch("data:text/plain,hi") over urllib.request.urlopen(url), and a connection to a database
in memory passed to a helper that queries its sqlite3.Connection parameter (execute, the
cursor it gives, its fetches) do not wait, as the same calls written inline do not; also through
more helpers passing the parameter on, and for an omitted parameter's literal default. Where the
argument selects the wait (nap(5), a connection opened on a file), the call through the helper
waits on every call as the inline call does (see below).
The rule reports the boundary: the call (or property read, or iteration) inside the async def
that leads to the blocking operation, with the call chain as related information. Several
boundaries reaching the same blocking call are shown as one report with a count once more than
ten of them of one certainty are shown (in the editor, per file). Inline suppressions and Ratchet baselines see
every boundary: suppressing the first one leaves the others reported, and a baseline counts each.
It does not report:
- calls offloaded to a thread (
asyncio.to_thread,loop.run_in_executor,anyio.to_thread.run_sync,run_in_threadpool,asgiref'ssync_to_async,asyncer.asyncify, and project wrappers that forward their callable to them; what the offloaded function does besides blocking still counts where it is called, such as its queries in a loop forEFF103; what the offloaded call hands back is what its callable returns, as the call written out: aftercur = await asyncio.to_thread(conn.execute, sql),cur.fetchone()waits on the event loop asconn.execute(sql).fetchone()does, also throughloop.run_in_executor,anyio.to_thread.run_sync, and an executor future'sresult(); the callable may be a bound method, a function, afunctools.partialobject, or a lambda, typed by its body); - functions decorated to run on a thread:
@sync_to_async(also as a factory,@sync_to_async(thread_sensitive=False)),channels'@database_sync_to_async,@asyncify, and any decorator declared withoffloads-blocking-arg = 0.@d def fisf = d(f), so callingfcallsd(f); other decorators (functools.wrapswrappers) are followed; - generators that leave the
async defwithout being iterated there: returned, stored, or handed to a call that is not a consuming one, such asStreamingResponse(rows())oriterate_in_threadpool(rows())(whatever iterates them later, often a thread pool, is not analyzed); asyncAPIs, also where they are not awaited directly (async with,asyncio.gather,asyncio.wait_for):httpx.AsyncClient,aiohttp,redis.asyncio, SQLAlchemy'sAsyncSession, psycopg'sAsyncConnection, pymongo'sAsyncMongoClient, ...;- clients that connect on first use (
redis.Redis(...),pymongo.MongoClient(...), except that amongodb+srv://URI literal is resolved in the constructor unlessconnect=False,pymysql.connect(..., defer_connect=True),sqlalchemy.create_engine(...)) and calls that only build an object (Redis.pipeline(), a lazy DjangoQuerySet.filter(...)): the call that does the I/O is the one reported; - spawning a process without waiting (
subprocess.Popen(...)); - private coroutine functions that only run through a synchronous driver without an event loop
(
.send(None), arun_syncfunction);asyncio.run(...)runs its coroutine on an event loop, where blocking stops the tasks it starts; - CLI commands (
@click.command,@app.command), ASGI lifespan handlers, and tests (as pytest finds them:test_*functions and the functions nested in them,test_*.pyand*_test.pyfiles, and files undertest/ortests/; see the option below).
A report is exact when the call, whenever it returns, has run a call that waits for input or
output on the event loop's thread: a network request, a database operation, a child process, or a
sleep (time.sleep with a length that is not zero). The waiting call is the reported call itself,
or the end of a chain of synchronous functions each of which makes the next call on every path on
which it returns.
Each step of the chain is established, not assumed:
- the call is made on every path on which the function returns, exception edges included: an
exception raised before it (by an earlier statement, an earlier call in the same statement or
withheader, or the call itself when it is a helper) that a handler takes and then returns or goes on is a path without it; - every implementation the call can run is followed, and each one makes the next call: all the
overrides in project subclasses of the receiver's class, every class that inherits a mixin
method calling
self, every member of a union; a receiver typed by a protocol has implementations heki cannot list, and is not followed; a call of a property's value (self.handler()) runs what calling a value of the type the getter declares runs (a protocol is not followed), and a read of the property runs the getter, followed when every class the object may be finds a getter of the project for the name first, also after the class asuper()read is in (a class finding a class attribute, a method, a value stored on the class outside its body, or nothing instead, a base heki does not know before the getter,__getattribute__, or a metaclass heki does not know leaves the read not followed); a decorator other thanstaticmethod,classmethod,property,abstractmethod,override, orfinalmay not run the body, and is not followed, each known by what its name is bound to in the decorated function's module (the builtins,abc,typing, ortyping_extensions: afinalthe project defines or imports from elsewhere is another); a function defined twice is not followed, and neither is a function, class, or method whose name the project binds to another object (assumption R1; a name its module body or class body binds last to one named object on every path is that object): another store or adelof the name in its module (also on a branch, afterglobal, or byglobals()orexec), in its class body, or on its class object; a class or function a function binds underglobalthat the module body does not bind on every path (by calling that function), whose name may be unbound; a store ordelfrom another module, also throughsetattrwith a string literal, and any name of a module thatsetattrstores into under a name heki cannot read; a store of the function's__code__; and, for a method, a store of the name on a class the lookup passes, of__bases__on a class along the MRO, or ofself.__class__in a method; a call of a local bound once to a bound method (run = conn.execute, orgetattr(conn, "execute")without a default) or to afunctools.partialobject runs what calling the method or the function runs; - the waiting call is in the ecosystem catalog, waits on every call (a database call that may be
answered by a session's identity map, a cache, an open connection, or that sends only pending
changes does not), and no argument that may come from the caller can make it return at once
(
time.sleep(delay)withdelaya parameter is not established). Such a call in a helper, whose catalog case depends on the helper's own parameter (time.sleep(seconds),urlopen(url),sqlite3.connect(name)) or that is made on its parameter or on what catalog methods return of it (db.execute(sql).fetchone()ondb: sqlite3.Connection), is decided at each call of the helper by what the call passes there, as the call written inline is, also through more helpers passing the parameter on:nap(5)waits, and so does a connection opened on a file; an argument computed from the caller's own parameter leaves it to the caller's callers. A literal argument, and a module constant bound once to one or computed from such constants (PAUSE = 0,PAUSE = BASE - 2; the module's constants as heki's other facts read them, also after a star import that comes before the binding; also imported from another module by the module or by a function, or read as an attribute of its module,settings.PAUSE, unless a module rebinds it or the importing module binds the name again: aglobalstore ordelin a function, another module-level store, a star import), is evaluated:time.sleep(PAUSE)does not wait. An argument heki cannot evaluate counts as one the call waits on (assumption R6), the URL or name a database connection was opened from included: a statement on a SQLAlchemy engine or another DB-API connection opened from a value heki does not know waits.sqlite3.connectis the one exception, as its in-memory form is common: a SQLite connection waits only when heki establishes that it was opened on a file (a literal or a module constant without an in-memory form, or a path built from such parts and__file__, also a module constant bound to such a path and read in a function or another module, unless another module rebinds it), and any other may be in memory. A local or a module global annotated with the connection's or the cursor's class (cur: sqlite3.Cursor = conn.execute(...)) keeps where it was opened, and so does the result of a function annotated with the class whose everyreturngives a connection opened where the same one is (def connect() -> sqlite3.Connection: return sqlite3.connect(DB_PATH)), as its module's own code shows it. A function without a return annotation, one whose returns open the database in different places, and one returning a connection another module gives it or that another function of its module returns stay open.
Waits on another thread (Thread.join(), Event.wait(), acquiring a lock, Queue.get(),
put() on a bounded queue, Future.result(), Executor.shutdown()) end at once when that
thread has done its part, which is state at run time: their reports are heuristic. So is every
other report the rule finds: a path heki cannot decide, a call it cannot resolve to all its
implementations, a database call that waits only in some state of its session or connection.
What a report states¶
A report states that whenever the reported call returns, the waiting call at the end of the
chain has run on the event loop's thread. A heuristic report states that the async def can
reach the blocking call at the end of the chain: some premise below may be open.
Its premises:
- Every return: each function on the chain has made the next call on every path on which it returns normally, exception edges into handlers included; the last call counts as made also when it raised. Open in a heuristic report: one path that reaches the next call is enough, and a branch heki cannot decide counts as taken; only the branches the caller's arguments switch off, and the cases listed above, are left out.
- Every implementation: each call on the chain has as its targets every implementation it can run (assumptions R1, R2, and R5), each a synchronous function run as written, and each has the fact. Open in a heuristic report: through a method call, one candidate implementation that leads on is enough.
- Waits: the last call waits for the network, a database, a child process, or a sleep on
every call, as the ecosystem catalog describes it (R3), for every argument heki cannot evaluate,
the arguments that opened its connection included (R6; a SQLite connection only when it was
established to be opened on a file). Open in a heuristic report: a wait on another thread
counts as blocking although that thread may have done its part, and a database call that waits
only in some state of its session or connection (
emitsin the catalog) counts as waiting.
Not part of the claim: how long the call waits, and how often the reported call runs.
Why is this bad?¶
A call that waits inside a coroutine stops the whole event loop: every other request, timer, and
task waits until it returns, as in a deadlock while the call lasts. An exact report is therefore
an error, which fails the run.
Example¶
import time
def load() -> bytes:
time.sleep(1)
return b""
async def handler() -> bytes:
return load() # EFF101: always runs `time.sleep`
A heuristic report, where the wait runs on some paths only:
import time
CACHE: dict[str, bytes] = {}
def load(key: str) -> bytes:
if key not in CACHE:
time.sleep(1)
return CACHE.get(key, b"")
async def handler(key: str) -> bytes:
return load(key) # EFF101 (heuristic): can reach `time.sleep`
Use instead:
and await asyncio.to_thread(load, key) for the second.
Known limitations¶
These stay open through a helper: a helper that returns early on a test of its parameter before
the waiting call; a connection opened from a path heki does not establish to name a file (a
parameter, an attribute, configuration); a connection a factory returns, or one a module global
holds that is opened lazily; a parameter without an annotation (nothing is reported); a call
reached more than eight method calls from the parameter; and a commit(), which waits only
with pending changes.
These rebind a name without heki seeing it, so a call through the name still counts as running
its definition: a mock.patch or mock.patch.object target patched outside tests, a store
through sys.modules (sys.modules[__name__] = shim, setattr(sys.modules[__name__], "f", g)),
a setattr on a class object under a name heki cannot read, and an instance's __class__ stored
other than through self in a method of its class (obj.__class__ = Other in a helper).
Fix safety¶
No automatic fix.
Options¶
lint.relax-async-in-tests(defaulttrue): skip test code.[[tool.heki.ecosystem]]declares project functions as blocking (effects), as offload wrappers (offloads-blocking-arg; with0, also an offloading decorator), or as async-safe (async-safe).