unlocked-write-of-guarded-state (EFF117)¶
Family: Execution Effects (EFF) · Heuristic · Off by default · Severity error (a bug) · No automatic fix
State that another writer changes holding a thread lock (threading.Lock, RLock, Condition, Semaphore), changed here holding none, where a thread heki resolves can run one of the writes: an update can be lost.
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 shared state that one function changes while it holds a thread lock and another
changes holding none, where a thread heki resolves can run one of the two writes. The rule is
heuristic: it runs when select or extend-select names it, and with --heuristic
(lint.heuristic = true).
A thread lock is a value whose class the catalog flags sync-lock-or-tx: threading.Lock,
threading.RLock, threading.Condition, threading.Semaphore, and
threading.BoundedSemaphore. A function holds one:
- from a
withover it to the end of that statement, and from anacquire()(with or without a timeout) to arelease(), on every path; - after a call of a helper that returns holding it (
def _acquire(self): self._lock.acquire()), a lock ofselfwhen the call passes the caller's ownself; - before a
release()that comes on every path from there: code that gives back a lock it did not take itself took it through a helper or was called holding it; - in a function every call of which is made holding a lock, up to two calls above it: a
generator expression made, or a lambda called (
sorted(xs, key=lambda x: self._rank(x))), insidewith self._lock:runs holding the lock, and so does a private method only such code calls, until it gives that lock back with arelease().
The shared state is an attribute of the instance a method runs on (self.count), a module
global (global _cache), or an attribute of a class or module (Registry.items), assigned or
deleted, or changed in place where heki knows it holds a builtin container: an item store or
delete (self.failures[key] = n) or a method of the container's class that changes it
(self.pending.append(item)). Attributes of a threading.local are not shared.
The threads heki resolves are the project functions handed to threading.Thread(target=...),
threading.Timer, asyncio.to_thread, loop.run_in_executor, the submit and map of a
thread pool (or of an executor of unknown kind), anyio.to_thread.run_sync,
trio.to_thread.run_sync, and run_in_threadpool, and the run method of a
threading.Thread subclass, with every function they reach over project calls. A coroutine
function or a generator function handed to a thread is no entry (the thread only creates the
object), nor is a function loop.run_in_executor hands to a process pool. A function a thread
runs is not taken for one that only construction runs, even when a constructor calls it too.
The rule reports the first such write of each state in a function, with a write made holding the lock in another function as a related location.
It does not report:
- a write in a constructor (
__init__,__new__,__post_init__,__init_subclass__), in anos.register_at_fork(after_in_child=...)handler, or in a function only those call (up to two calls above): the object or the child process is not shared yet; nor does a write there make the state one a lock guards; - a write in test code;
- state no writer changes holding a lock, and a write where heki finds any thread lock held, whether or not it is the one the other writer holds;
- a method call heki cannot tie to a builtin container (
self.client.add(...)).
What a report states¶
A report states that two writes of the same state can run at once on two threads, one holding a lock and one holding none, so the lock does not keep them apart and one can lose the other's update.
Its premises:
- Same state: both writes reach the same attribute of the same instance, or the same global (assumption R1 for the methods). Open: two instances of the class are not told apart, and the methods of a base class and its subclasses write the same attribute.
- Guarded: the other writer holds the lock at its write. Open: a timed
acquire()that failed is not told apart from one that succeeded. - Not held: no thread lock is held at the write in the function, through the helpers it
calls, or in its callers up to two calls above. Open: a caller further up, a caller heki does
not see (a public method called from outside the project), a helper taking the lock through
another helper, and a project context manager taking it in
__enter__may hold one. - Shared: the write runs after the object or the state is shared. Open: a function that runs before any thread starts, or only on one thread, is not told apart.
- Threaded: a thread entry heki resolves reaches one of the two writes. Open: one path is enough, and that two threads touch the same instance at once is not established.
An exact tier, with the same lock object on both sides, every caller known (a private method or a module-private function), and every thread entry and helper followed, is future work.
Why is this bad?¶
A lock only keeps apart the code that takes it. A write made without it can run in the middle
of a locked update: a counter incremented under the lock and reset without it loses the reset or
the increments, an invalidation (cache["mtime"] = 0) made without the lock is lost when a
locked rebuild stores the old value back, and a dictionary changed without the lock while a
locked reader iterates it raises RuntimeError: dictionary changed size during iteration. Under
free-threaded CPython, single operations that the GIL kept whole can interleave too.
Example¶
import threading
class Stats:
def __init__(self) -> None:
self._lock = threading.Lock()
self.received = 0
def start(self) -> None:
threading.Thread(target=self._read).start()
def _read(self) -> None:
with self._lock:
self.received += 1
def reset(self) -> None:
self.received = 0 # EFF117
Use instead:
Fix safety¶
No automatic fix.
Options¶
lint.heuristic = true(or--heuristic) runs the rule by default;--select EFF117runs it alone.[[tool.heki.ecosystem]]entries withsync-lock-or-tx = trueadd lock classes.