Sub topic 14
Migrating and testing existing code
This chapter assumes you know the threading module and concurrent.futures, and that you can read basic lock code. You should also know what the free-threaded build is and how to detect it, from the earlier chapters. Here you will turn that knowledge into a migration plan for a real project, and learn how to test for the bugs the GIL used to hide.
Why migration is mostly about testing
Moving code to a free-threaded build rarely means rewriting it. Most pure-Python code runs unchanged. The risk is that code which was accidentally safe under the GIL becomes unsafe once threads run in parallel. Such code passes its tests and then fails rarely, under load, in production.
So the work has three parts:
- Find out whether your dependencies can run without the GIL.
- Run your existing test suite on the free-threaded build.
- Add tests that try to provoke races, and fix what they find.
Step 1: Audit your dependencies
Every compiled dependency needs a build for the free-threaded ABI. Free-threaded wheels carry a t in their tags, for example cp313t. Pure-Python packages work as they are. Packages with C, C++, Rust or Cython code need a release built for the free-threaded interpreter.
Check three things for each compiled dependency:
- Does the project publish
cp313t(or newer) wheels on PyPI? - Does the extension declare that it can run without the GIL?
- Does the project's issue tracker mention free-threading problems?
The community compatibility tracker at py-free-threading.github.io lists the status of popular packages. It is a good first stop, but your own test is the final check.
What happens when an extension does not declare support
An extension module declares GIL-free support through the Py_mod_gil slot, set to Py_MOD_GIL_NOT_USED. If a module has no such declaration, the interpreter assumes it is unsafe. It then re-enables the GIL for the whole process when the module is imported, and emits a RuntimeWarning. The GIL stays on for the rest of that process.
This is the most common migration surprise. Your program runs on python3.13t, but a single legacy import has silently turned the free-threaded build back into a regular one. Your threads then run one at a time, and you may not notice.
The script below imports each module you name and reports the first one that turns the GIL on.
import importlib
import sys
def find_gil_reenablers(module_names):
if not hasattr(sys, "_is_gil_enabled"):
raise SystemExit("Needs Python 3.13 or newer")
if sys._is_gil_enabled():
raise SystemExit("The GIL is already on before any import")
for name in module_names:
importlib.import_module(name)
if sys._is_gil_enabled():
print(f"Importing {name!r} enabled the GIL")
return name
print("No module re-enabled the GIL")
return None
if __name__ == "__main__":
find_gil_reenablers(sys.argv[1:] or ["json", "sqlite3"])Run it as python3.13t check_imports.py numpy pandas yourpackage. Do not set PYTHON_GIL=1 or -X gil=1 for this check, because that forces the GIL on for every import.
An import can pull in other modules, so the name printed may be a package whose dependency is the real cause. Read the warning text, which names the module that lacks the declaration.
Step 2: Run your existing tests with the GIL forced off
Run your normal suite on the free-threaded build with the GIL explicitly disabled:
PYTHON_GIL=0 python3.13t -m pytestForcing the GIL off is useful because it overrides the automatic re-enabling. If an extension is truly unsafe, you now see crashes or wrong results instead of a quiet fallback. Use this setting in a dedicated test job, not in production, and treat a crash from a legacy extension as a sign it needs an upgrade.
Also add a guard test so continuous integration fails if the GIL turns itself back on:
import sys
import sysconfig
import pytest
@pytest.mark.skipif(
not sysconfig.get_config_var("Py_GIL_DISABLED"),
reason="not a free-threaded build",
)
def test_gil_stays_off():
import yourpackage # replace with your real imports
assert sys._is_gil_enabled() is FalseCompare results across both builds. A test that passes on the standard build and fails on the free-threaded one points to a concurrency assumption, a dependency problem, or a timing-sensitive test.
Step 3: Stress-test shared state
Ordinary tests are single-threaded, so they cannot find data races. A race test needs many threads that hit the same code at the same moment, many times over. A threading.Barrier makes the threads start each round together, which raises the chance of a collision.
The harness below runs a function on several threads in lockstep and collects any exceptions. It then tests a cache with a check-then-act pattern: "if the key is missing, compute it and store it".
import threading
def hammer(func, threads=8, rounds=200):
"""Call func() from many threads at once, round after round."""
barrier = threading.Barrier(threads)
errors = []
def runner():
try:
for _ in range(rounds):
barrier.wait()
func()
except threading.BrokenBarrierError:
pass
except BaseException as exc:
errors.append(exc)
barrier.abort()
workers = [threading.Thread(target=runner) for _ in range(threads)]
for w in workers:
w.start()
for w in workers:
w.join()
if errors:
raise errors[0]
class Cache:
def __init__(self, locked):
self._data = {}
self._lock = threading.Lock() if locked else None
self.compute_calls = [] # list.append is safe across threads
def _compute(self, key):
self.compute_calls.append(key)
return key * 2
def _get(self, key):
if key not in self._data:
self._data[key] = self._compute(key)
return self._data[key]
def get(self, key):
if self._lock is None:
return self._get(key)
with self._lock:
return self._get(key)
def run(locked):
cache = Cache(locked)
round_no = [0] # only read here, written between runs
def work():
cache.get(21)
hammer(work, threads=8, rounds=1)
return len(cache.compute_calls)
if __name__ == "__main__":
for locked in (False, True):
worst = max(run(locked) for _ in range(300))
print(f"locked={locked}: most compute calls for one key = {worst}")With the lock, the key is computed once every time. Without it, several threads can pass the not in check before any of them stores the result, so the count can exceed 1. The dictionary itself never gets corrupted, because individual dict operations are safe on the free-threaded build. The bug is the gap between the check and the store. This is the main category to look for: a sequence of individually safe operations that is not safe as a whole.
A test that finds a race only some of the time is still valuable, so run it many times. A passing run proves little, and a single failure proves a bug.
More tools for finding races
- pytest-run-parallel is a pytest plugin that runs each test on several threads at once. For example,
pytest --parallel-threads=4 --iterations=10. It turns an existing suite into a stress test with little effort. Tests that rely on global state need fixtures that are safe to share. - ThreadSanitizer (TSan) detects data races in C code, including extensions and the interpreter itself. It needs a CPython built with
--with-thread-sanitizer. Use it when you maintain a C extension. - Lower the switch interval with
sys.setswitchinterval(1e-6)on a standard build. This does not simulate true parallelism, but it makes the GIL hand over control more often and can expose some check-then-act bugs before you move to the new build.
Fixing what you find
Apply fixes in this order of preference:
- Remove the sharing. Give each thread its own data with
threading.local(), or pass values through aqueue.Queue. - Make shared data immutable. Tuples, frozen dataclasses and
frozensetcannot be corrupted. - Lock the whole logical operation. Hold the lock across the check and the update, not around each step.
Avoid adding many fine-grained locks. They make deadlocks likely and slow the code down. Keep lock-protected sections short and always take multiple locks in the same order.
Common migration mistakes
| Mistake | Why it hurts | Better approach |
|---|---|---|
| Assuming `x += 1` on shared state is safe | It is a read, an add and a write. Updates are lost when threads interleave | Hold a lock, or keep the counter per thread and combine at the end |
| Trusting a passing single run | Races are timing-dependent and show up rarely | Run stress tests many times, in CI, on every change |
| Not noticing GIL re-enabling | Performance silently drops to GIL levels | Add the `sys._is_gil_enabled()` guard test |
| Locking each step separately | The gap between steps is still a race | Lock the full check-then-act sequence |
| Rolling out without benchmarks | Single-thread code is slower on the free-threaded build, and gains need real parallel work | Measure both builds on your actual workload |
Rolling out gradually
Run both builds side by side for a while. Keep the standard build as the default and run the free-threaded build in CI and on a small share of traffic. Benchmark the real workload on both. If the work is CPU-bound and splits into independent pieces, expect gains. If it is mostly single-threaded, expect no gain, and a possible slowdown.
Exercise
Your service runs on python3.13t, but throughput matches the standard build. PYTHON_GIL is not set. Name one likely cause and one way to confirm it.
Show answer
An imported C extension probably lacks the Py_MOD_GIL_NOT_USED declaration, so the interpreter re-enabled the GIL when it was imported. Confirm it by checking sys._is_gil_enabled() after each import (or by reading the startup RuntimeWarning). The result tells you which module is responsible, and you can then upgrade or replace it.
Exercise
A test calls cache.get(key) from eight threads, and a counter shows _compute ran three times for one key. The dictionary has no corrupted entries. What is the bug, and what is the fix?
Show answer
The bug is a check-then-act race. Several threads see the key as missing before any of them stores a value, so each computes it. The individual dict operations are safe, but the sequence is not. Hold one lock around the whole check, compute and store, as in the locked Cache.