Skip to content

exclusive-object-fanout (EFF110)

Family: Execution Effects (EFF) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Opt-in: an object allowing one operation at a time (asyncio.StreamReader, an asyncpg connection, a WebSocket) used by tasks started together (asyncio.gather, a task group).

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 only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.

Experimental

Its precision is measured on a small sample of reports only. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.

What it does

Checks for an object that allows one operation at a time, used by tasks a function starts together. The rule is opt-in: enable it with --extend-select EFF110 or extend-select = ["EFF110"].

An object allows one operation at a time when the catalog flags a method of its class: a second task calling one while another task is inside one raises. heki knows:

  • asyncio.StreamReader: read, readline, readexactly, readuntil, and async for;
  • asyncpg's Connection: execute, fetch, fetchrow, fetchval, ... (asyncpg.connect() types it);
  • websockets connections: recv, recv_streaming, and async for (websockets.connect() types them);
  • aiohttp's ClientWebSocketResponse and web.WebSocketResponse: receive, receive_str, receive_bytes, receive_json, and async for (ClientSession.ws_connect() types it);
  • SQLAlchemy's (and SQLModel's) AsyncSession, only while it holds no connection: see below.

Add your own with one-at-a-time = "always" on a method in [[tool.heki.ecosystem]].

The tasks are started together by:

  • asyncio.gather(...): its coroutines and tasks, also those of a generator expression or a comprehension unpacked into it (*(read(r) for _ in range(n))), each started once per item;
  • asyncio.wait(...) over a display of tasks ({t1, t2}) or of a comprehension;
  • the create_task calls of one asyncio.TaskGroup, and the start_soon calls of one anyio task group (anyio.create_task_group()), each in a loop started once per iteration.

A task is a coroutine a project call creates (read_line(reader), self.read_frame()), asyncio.create_task of one, or a one-at-a-time call itself (reader.readline()). What it uses comes from its function's summary, any number of calls deep, through the arguments it is given by position or by keyword. The rule reports two tasks, or one started several times, using the same object: a parameter or its attribute (self._reader), a global, a closure variable, or a local variable of the function starting them.

An AsyncSession raises only while it holds no connection: before its first operation, and after commit(), rollback(), or close() give the connection back. It is reported only where the fan-out can be its first operation since then: not after an operation on it, its own or through a call, on every path to the fan-out.

It does not report:

  • different objects, such as a process's stdout and stderr, or each task's own reader and writer;
  • uses made while a lock is held, in the task's function or around the call leading to them (async with self._lock: return await self._reader.readline());
  • an object each task gets for itself: the item of the loop or comprehension starting it (*(read(s) for s in streams)), or one the task's function makes (a session per task);
  • a task started again only after the previous one is done (t = asyncio.create_task(...) again after asyncio.wait returns it), and a task appended to a list once, outside a loop (if proc.stdout: tasks.append(read(proc.stdout)));
  • a task whose function may bind the object's name first (self.reader, _ = await asyncio.open_connection(...)): it may use another object;
  • a fan-out no run reaches;
  • objects whose class is not known, tasks heki cannot resolve, and the same object reached under two different names.

What a report states

A report states that two tasks a function starts together, or one it starts for every item, use the same object that allows one operation at a time, so one of them can raise while the other is inside an operation.

Its premises:

  • One at a time: the object is an instance of a class whose method the catalog or the configuration flags, by the value inferred or an annotation (assumptions R2, R3); for an AsyncSession, the fan-out can be its first operation since it was made or gave its connection back. Established for the paths described above.
  • Together: the tasks are started by one asyncio.gather, asyncio.wait, or task group, and run until the fan-out ends. Established.
  • Same object: each task's function names the object the same way, through the arguments of its call, and may not bind that name. Established, as long as no other code binds it while the tasks run.
  • Resolves: each call on the chain is to the function shown (assumption R1). Open through a method call: one candidate implementation that uses the object is enough.
  • Reaches: each task reaches the use outside any lock it holds. Open: one path is enough, and a branch heki cannot decide counts as taken.

Why is this bad?

These objects keep the state of one operation in progress: a stream reader one pending read, a database connection one query, a WebSocket one receive. A second task starting an operation while the first one is inside raises (RuntimeError: readuntil() called while another coroutine is already waiting for incoming data, asyncpg's InterfaceError: cannot perform operation: another operation is in progress, ConcurrencyError in websockets, RuntimeError: Concurrent call to receive() is not allowed in aiohttp, SQLAlchemy's InvalidRequestError for a session provisioning a connection). The failure depends on timing: it shows under load, or when the first operation is slow.

Example

import asyncio


class FrameClient:
    def __init__(self, reader: asyncio.StreamReader) -> None:
        self._reader = reader

    async def read_frame(self) -> bytes:
        return await self._reader.readexactly(4)

    async def read_frames(self, count: int) -> list[bytes]:
        return await asyncio.gather(*(self.read_frame() for _ in range(count)))  # EFF110

Use instead:

    async def read_frames(self, count: int) -> list[bytes]:
        return [await self.read_frame() for _ in range(count)]

Fix safety

No automatic fix.

Options

  • lint.extend-select = ["EFF110"] (or --extend-select EFF110) enables the rule. It is opt-in: selecting the EFF prefix does not enable it.
  • [[tool.heki.ecosystem]] entries with one-at-a-time = "always" add methods; a session-like class takes "when_unbound", and its methods giving the connection back "unbinds".