For years, Python code with threads has leaned on a rule nobody wrote down, that only one thread runs at a time. A check and the write that follows it are two steps, but another thread almost never got in between. Free-threaded Python takes that away.
tinyjobs is a job queue I maintain. I made its worker run several event loops in threads on Python 3.14t. The whole suite, 1,706 tests, was green before the audit began. This post is about what was broken anyway. An audit found four races, I added a fifth myself, and one import put the GIL back with a single warning on stderr.
Safe by accident
The bug has one shape, and you have written it.
if key not in cache:
cache[key] = build(key)
return cache[key]
Each line is safe on its own. The three together are not, because another thread can change cache between any two of them.
The GIL never made this correct. It made it rare. A thread keeps the interpreter for five milliseconds before it has to give it up, and these lines take a few microseconds. Without the GIL, two threads run them at the same moment on two cores. A window that was open one time in a thousand is now open every time.
Two threads, one name
tinyjobs keeps a registry of tasks by name. A task that isn't there yet can be resolved on first use, which is how Django's tasks are found.
def get(self, name):
return self._tasks.get(name) or self._resolve(name)
def _resolve(self, name):
for resolver in self._resolvers:
task = resolver(name)
if task is not None:
self.register(task)
return task
Thread A and thread B both ask for the same name, and both find nothing. Both call the resolver, and each gets its own task object, wrapping its own new function. A registers first. B arrives, finds the name bound to a different function, and register does what it was built to do with two functions under one name, and raises TaskAlreadyRegisteredError.
I ran the real Django backend with six request threads enqueueing the same task for the first time. On 3.14t, 129 of 1,195 enqueues failed. With PYTHON_GIL=1, on the same build and the same script, none did.
On the worker side it was worse, though I had to build the case. Django's worker command discovers tasks before it starts, so this only reaches custom resolvers and tasks outside <app>.tasks. I took a worker with four loops, a resolver slowed by two milliseconds to stand in for a first import, and 192 jobs due at the same instant. The error isn't one the worker expects from a lookup, so a job that hit it stayed running until its lease expired. That happened to 20 jobs in one run and 28 in the other.
The fix is one line.
return self._tasks.setdefault(task.name, task)
setdefault checks and writes under the dictionary's own lock. One thread wins, and the other gets the winner's task.
A cache that was empty for a moment
The JSON codec keeps a cache from type to adapter. Registering a new type rebuilds it.
def _rebuild_type_cache(self):
self._by_type = {}
for adapter in reversed(self._adapters):
for adapter_type in adapter.types:
self._by_type[adapter_type] = adapter
The first line publishes an empty dictionary, and the loop fills it while everyone can see it. A reader does the usual two steps, not in and then [...], and they can now land on two different dictionaries. Three threads encoding a datetime while a fourth registered an enum got 45 KeyErrors without the GIL, and none with it.
The fix has two halves. The writer builds the new dictionary in a local variable and assigns it at the end, so nobody sees it half full. The reader takes self._by_type once and works on that one object.
A flag nobody heard
The other two are not the GIL's fault. They come from the threads themselves. The moment a worker has several loops, things get called from the wrong one.
A worker stops when a flag is raised. The flag wraps an asyncio future, and set() resolved it directly.
def set(self):
self._set = True
if self._future is not None and not self._future.done():
self._future.set_result(None)
A future belongs to one event loop. Resolving it from another thread changes its state, but the loop is asleep in select and nobody wakes it. The stop request is there. The loop just doesn't look.
A review of the same branch had already measured what this costs, on a worker pointed at an address that never answers, with a fifteen-second connect timeout, and asked to stop after one second. It stopped after 15.0. On main the same stop took 1.1 seconds, so this was my own doing. The branch had moved the connect onto the worker's own loop, which sleeps until the socket answers. I closed that path.
The audit found the same mistake still reachable from a loop that had just started. Forty starts with a stop aimed at that moment showed nothing, so this one was fixed without being caught in the act. Now set() checks whose future it is, and hands the result to the owner with loop.call_soon_threadsafe.
The fourth race was also found by reading the code, and I never saw it happen. Each loop cleared a shutdown deadline on the shared app as it started, with no lock, so a loop that started late could erase a deadline another had just set. The window is a few instructions wide. I fixed it anyway, and only the first loop clears it now.
The one I added myself
With the GIL off, a profile showed the thread pool for def tasks taking its lock three times per job. I replaced the count of idle threads with a semaphore, as the standard library's pool does. A thread that finishes a job releases a permit, and a submit that gets a permit knows a thread is waiting. Handing a job to a thread went from 63 to 32 microseconds.
A review found the hole. A thread finishes job A, and before it releases its permit, job B is submitted. No permit is free and the pool is at its size, so B just sits in the queue. The thread releases its permit, loops, and takes B itself. Now there is one permit and zero idle threads.
On its own that costs microseconds. It becomes a hang in the one pool that replaces stuck threads. When a job outlives its timeout, that pool is allowed one more thread, but it started the thread only if a job was already waiting. So B runs past its timeout, the queue is empty, and no thread starts.
Job C arrives, takes the stale permit, and trusts it. Nobody is coming. C waits for a thread that is already busy, while the pool was allowed a new one. If every thread is stuck like B's, C never starts, and its own timeout can't save it, because the timeout starts when the job does.
The old code, with its lock, could not do this. The fix keeps the fast path and takes the lock again only at the two places where the pool changes size. A second review found another way to reach the same state, through a thread that fails to start. The third found nothing.
The GIL that came back
One problem was not a race at all. redis-py imports hiredis when it is installed, to parse replies faster. hiredis ships wheels for 3.14t, but it doesn't declare itself safe without the GIL, so the interpreter turns the GIL back on when it loads.
The interpreter says so once, in a RuntimeWarning on stderr at import time, which is easy to lose in a worker's log. After that nothing fails. The worker runs, the tests pass, and every benchmark measures the wrong thing. So the worker now checks at startup.
sysconfig.get_config_var("Py_GIL_DISABLED") and sys._is_gil_enabled()
A free-threaded build with the GIL enabled gets a line in the log, and CI has a test that imports every tinyjobs module and checks the GIL is still off.
Does it hold?
A fix for a race is easy to believe and hard to prove, so each one got a test, and each test had to fail on the old code first. Two of mine didn't. The cache test passed on the old code, and the flag test hung there, where it should have failed. Both were rewritten until the old code gave the right error, which is TaskAlreadyRegisteredError for the registry, KeyError for the cache and, for the flag, the Non-thread-safe operation that asyncio raises in debug mode.
The tests say the fixes hold. Whether the threads are worth having is a separate question, so I also ran the whole thing under load, on a ten-core laptop with two Redis instances.
1 process, 8 loops, Python 3.14t
42,000 async def jobs/s, 97% of what 8 processes do
with the GIL on, the same threads flatten at 27,000
3.14t now runs in CI next to 3.12, 3.13 and 3.14. The full numbers are on the Measured page.
What I can't promise
- An audit finds what it looks for. Two of the four races were reproduced. The other two were found by reading the code and never seen in a run. I have no way to count the ones nobody thought of.
-
Your tasks are in the same position.
deftasks in one worker now run truly in parallel. If two of them share a dictionary, a counter or a client, they have the bugs above. - Your dependencies decide too. One C extension that hasn't declared itself safe turns the GIL back on for the whole process.
That's the whole trick
Read once, write once, and build new state in private before you publish it. Almost every fix here was one of those three, and most were under five lines. Finding them was the work.
tinyjobs is on GitHub and PyPI, and the free-threaded Python page has the setup.
If you have run your own code on a free-threaded build, I'd like to hear what broke first.
Top comments (6)
The setdefault fix covers registration, but not the resolver: both threads still ran
_resolve(name)to completion before either one reached the dict, so anything with a side effect inside a resolver now happens twice instead of once per race. An import is idempotent and the secondregisterthrows, so it stays invisible in the numbers — but a resolver that opens a connection, starts a thread or appends to a metrics counter won't be. I'd either put a per-name lock around the whole lookup, or make the resolver itself the dedupe point (functools.cacheneeds to be hashable per name, which works if the key is just the name).On the import that put the GIL back: is there anything in CI that fails when that happens, or does it stay a stderr warning?
sys._is_gil_enabled()right after the suite starts is one assertion, and it catches the case where a package you added a month ago quietly re-enables it and every timing-based race test you have goes green for the wrong reason.You're right about the first one.
setdefaultdedupes the result, not the call. Both threads still run the resolver, and one of the two tasks is thrown away. The resolvers tinyjobs ships only import a module and wrap a function, so nothing shows, but a custom one with a side effect would do it twice. Today the contract is that a resolver is a pure lookup, and that should be written down. A lock on the miss path is the stronger fix, and it would cost nothing once the name is registered.One note on
functools.cache. It keeps its own state safe, but it doesn't promise a single call. Two threads that miss the same key both run the function, so it has the same window.On the GIL, yes, CI fails. The 3.14t job runs
assert not sys._is_gil_enabled()before the suite starts, and one test imports every tinyjobs module in a subprocess and checks the GIL is still off. That second one is there for exactly your case, a dependency added later that quietly turns it back on.The unwritten rule is the real hazard: code that was only safe because of the GIL, with no test that says so. Which kind of bug showed up first for you?
The check-then-write kind, the shape in the first snippet. In tinyjobs it was the task registry.
Two threads found nothing, both resolved the name, and the second one raised when it tried to register. 129 of 1,195 enqueues failed on 3.14t and none with the GIL on. The fix was
setdefault, which checks and writes in one step.And you're right about the tests. The suite was green the whole time, because nothing in it ran two threads through that path at once.
That's the frustrating part. This is code we all write out of habit, and with the GIL off it no longer gets away with it.
one import turns the GIL back on with a single RuntimeWarning on stderr, and after that nothing fails. the tests pass and every benchmark measures the wrong thing.
Yes, and the silence is the worst part. A crash you notice. Here the only sign was one line at import time, easy to lose in a worker's log. So the worker now checks
sys._is_gil_enabled()at startup, and CI imports every module and fails if the GIL came back.