Skip to content

lock-reacquired-while-held (EFF109)

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

Opt-in: a non-reentrant lock (threading.Lock, asyncio.Lock) taken again, directly or through a call, while it is held (the thread or task waits for itself).

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 a non-reentrant lock taken again while it is held: by the function holding it, or by a function it calls, any number of calls deep. The rule is opt-in: enable it with --extend-select EFF109 or extend-select = ["EFF109"].

A lock is non-reentrant when the catalog says so: threading.Lock, asyncio.Lock, asyncio.Condition, and multiprocessing.Lock (threading.RLock is reentrant; a threading.Condition uses an RLock unless it is given another lock; a semaphore's class does not say its count). Add your own with non-reentrant-lock = true in [[tool.heki.ecosystem]].

A function holds a lock from a with or async with over it to the end of that statement, and from an acquire() to a release(), on every path. An acquire() counts when it is awaited, or when it blocks without a timeout (lock.acquire(), lock.acquire(True)). The lock is the same object on both sides when both name it the same way, through the calls between them:

  • an attribute of self, or of another parameter (self._lock, passed on as self or as the lock itself);
  • a module global, also imported from another module or read on its module (_LOCK, locks._LOCK);
  • a variable of an enclosing function that a closure it calls captures.

The calls followed are those that run there, on the same thread or task: plain calls, awaited coroutines, property getters, generators iterated there, and functions builtins call there (sorted(xs, key=self._rank)). The rule reports the inner acquisition, or the call that leads to it, with the call chain as related locations.

It does not report:

  • a call that only creates a coroutine or a generator (asyncio.create_task(self.refresh())), a function run on another thread (asyncio.to_thread, loop.run_in_executor, a threading.Thread target), and a callable stored or handed to code heki does not follow;
  • an acquisition a branch switches off for the call's arguments (self._close(notify=False) where only notify leads to the lock);
  • an acquisition behind a test of state the holder changes: an attribute of the lock's owner that the holder, or what it calls, changes (if self._closed: return, if self._in_own_start(): raise, in the acquiring function or in one on the way to it), or a module global the holder sets (if _LIB is not None: return _LIB in a lazy initialization under the lock): such code keeps a flag to know whether it holds the lock, which heki does not evaluate;
  • a lock the code gives back before taking it again, also inside the with that took it (self._lock.release(), then self._lock.acquire());
  • a lock whose name may be bound to another object before it is taken again (self._lock = threading.Lock(), global _LOCK, del self._lock): by the holder, by a function the holder calls first, or by the function taking the lock or one on the way to it; the name then reaches another lock;
  • a lock some function of the module releases without holding it: another thread gives it back as a signal, so taking it again waits for that thread, by design;
  • acquire(blocking=False) and acquire(timeout=...), which return;
  • locks whose class is not known, a lock in a local variable handed to a helper, and the same lock reached under two different names.

What a report states

A report states that a function holding a non-reentrant lock takes the same lock again, itself or through the calls it makes on its thread or task, so the thread or task waits for itself.

Its premises:

  • Non-reentrant: the lock is an instance of a class the catalog or the configuration flags, by the value inferred or an annotation (assumptions R2, R3).
  • Held: a with over it, or an awaited or blocking acquire(), holds it on every path to the inner acquisition, and nothing gives it back or binds its name again on the way. Established.
  • Same object: both sides name the lock the same way, through the arguments of each call, and no function on the way may bind that name. Established, as long as no other thread binds it.
  • Resolves: each call on the chain is to the function shown (assumption R1). Open through a method call: one candidate implementation that takes the lock is enough.
  • Reaches: each function on the chain reaches the next call on its thread or task. Open: one path is enough, and a branch heki cannot decide counts as taken; only the branches the caller's arguments switch off, and those behind a test of state the holder changes, are left out.

Why is this bad?

A thread that takes a threading.Lock it already holds waits for itself forever, and so does an asyncio task taking an asyncio.Lock it holds: the lock never becomes free, and every other thread or task that needs it stops behind it. The retake is usually hidden in a helper that takes the lock for its own callers, called from a method that already holds it, often only on an error path.

Example

import threading


class Registry:
    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._items: dict[str, int] = {}

    def size(self) -> int:
        with self._lock:
            return len(self._items)

    def add(self, key: str) -> int:
        with self._lock:
            self._items[key] = 1
            return self.size()  # EFF109

Use instead:

    def _size_locked(self) -> int:
        return len(self._items)

    def size(self) -> int:
        with self._lock:
            return self._size_locked()

    def add(self, key: str) -> int:
        with self._lock:
            self._items[key] = 1
            return self._size_locked()

Fix safety

No automatic fix.

Options

  • lint.extend-select = ["EFF109"] (or --extend-select EFF109) enables the rule. It is opt-in: selecting the EFF prefix does not enable it.
  • [[tool.heki.ecosystem]] entries with non-reentrant-lock = true add lock classes.