Repository navigation
Description
In the free-threaded build, QSBR lets threads read some objects' internal storage (list item arrays, dict keys and values, set tables) without taking a lock. This has a clear performance win, but it can lead to higher peak RSS.
Freed memory is only reclaimed once every attached thread has passed a quiescent state. A thread inside a long-running C call that stays attached (does not release the thread state) reports none until the call returns, so memory freed by all the other threads remains allocated in the meantime.
In this reproduction, two worker threads each append to and clear a list created by the main thread (growing a list created by another thread frees the old array through QSBR), while a third thread runs one large sorted(), which is implemented in C:
Sorted was just one example, see the table at the end for other stdlib functions implemented in C show similar behaviour depending on the blocking time.
import resource, sys, threading
def peak_rss_mb():
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
return r / 2**20 if sys.platform == "darwin" else r / 2**10
words = [f"{i * 2654435761 % 10**9:09d}" for i in range(2_000_000)]
lists = [[], []] # created by the main thread
done = threading.Event()
def sorter():
sorted(words) # one long C call
done.set()
def worker(out):
while not done.is_set():
for _ in range(1_000_000):
out.append(None)
out.clear()
before = peak_rss_mb()
threads = [threading.Thread(target=worker, args=(l,)) for l in lists]
threads.append(threading.Thread(target=sorter))
for t in threads:
t.start()
for t in threads:
t.join()
print(sys.version)
print(f"peak RSS {before:,.0f} MB -> {peak_rss_mb():,.0f} MB")
| build | GIL | peak RSS before | peak RSS after (runs 1 / 2 / 3) |
|---|---|---|---|
| default build | on | 153 MB | 214 / 222 / 237 MB |
| free-threaded | off | 200 MB | 2,717 / 2,749 / 2,880 MB |
As we can see we can see on free threading we see a large spike in RSS which is due to the large sort call. This can be applied to other blocking C calls.
One approach for reducing the impact is to report regular QSBR state with _Py_qsbr_quiescent_state() during the blocking C call where safe to do so, such as where we only hold strong references
In sort specially we could call in merge_at or some similar location and we can see this has a significant peak RSS saving. This did not seem to have any noticeable performance penalty. a similar approach could be done for other internal C functions that risk blocking for a significant period.
| build | GIL | peak RSS before | peak RSS after (runs 1 / 2 / 3) |
|---|---|---|---|
| default build | on | 153 MB | 214 / 222 / 237 MB |
| free-threaded | off | 200 MB | 2,717 / 2,749 / 2,880 MB |
free-threaded + quiescent point in merge_at |
off | 200 MB | 623 / 677 / 594 MB |
Note other examples of peak RSS growing (replacing the sort with X)
| blocker (one call) | time | extra peak RSS |
|---|---|---|
-1 in big_list |
0.34 s | +3.4 GB |
7 ** 1_500_000 |
0.22 s | +2.2 GB |
sum(big_list) |
0.30 s | +2.9 GB |
pickle.dumps (2M dicts) |
1.11 s | +11 GB |
pickle.loads (2M dicts) |
0.76 s | +4.8 GB |
json.dumps (2M dicts) |
0.99 s | +10.5 GB |
The downside of this approach is that each long-running C function needs to be fixed explicitly. I have yet to check whether there is a suitable location in each of the examples above, and it does not address third-party C extensions.
I'm also exploring what it would look like to report a quiescent state in PyErr_CheckSignals(), which the C API docs say long-running C code should call regularly, and also handle GC so should be at a safe quiescent point.
Note that sorted() in the original example does not call it, though.
Activity
picnixz commentedon Nov 27, 2026
@NekoAsakura In general, improving performances count as a feature not a bug unless it's a recent regression.
picnixz commentedon Dec 1, 2026
cc @nascheme and @eendebakpt (I don't think there is anything actionable for now)
mehdipanjwani7-glitch commentedon Dec 2, 2026
dpdani commentedon Dec 2, 2026
Another approach could be adding a quiescence report inside
PyErr_CheckSignals, and call that from a sensible location in the sorting routine, or anywhere else it's needed. (I seemerge_atalready has an error return value so it might be appropriate.) This has the advantage that C extensions are already expected to call this function with some frequency if they are inside some long running operation. In fact, callingsorted(...)and pressing ctrl-c is already quite useless: it raises after the sorting ends.I think it should be safe, in the sense that extensions and CPython internals alike should already be in a state where they only have strong references when they call this function. Though, this may be a requirement that can be explicitly added to the docs.
EDIT: I see now you were already proposing this, sorry.
nascheme commentedon Dec 3, 2026
The
PyErr_CheckSignalsidea sounds good to me. Building up reference cycle trash is conceptually quite similar to building up memory inside QSBR deferrals.johng commentedon Dec 3, 2026
thanks @nascheme, do you think we should also update
sort(and possibly others) to callPyErr_CheckSignalsin appropriate places as part of a long running C call as part of a related fix or is there a chance that could cause a regression?dpdani commentedon Dec 3, 2026
Blanket changes across the codebase are generally discouraged, but adding
PyErr_CheckSignalsin a single place to showcase the impact would be useful, I think.johng commentedon Dec 3, 2026
My question was more do we combine this change with adding
PyErr_CheckSignalsto this specific example withsort(with the QSBR integration)? Just updatingPyErr_CheckSignalswill help C apis that already integrate it but not the case here.I feel adding
PyErr_CheckSignalsto sort could have considerations so wondering if it should be a spinoff PR/issue?dpdani commentedon Dec 3, 2026
They can also be two separate PRs for the same issue. That would probably be best so that they can be reverted individually if need be.