Capture file corrupted ("Invalid record type") when threads that predate the Tracker replace their stack
Is there an existing issue for this?
- I have searched the existing issues
Current Behavior
When tracking starts while other threads are already running (e.g. with memray attach, or memray.Tracker entered mid-program), the capture file can be corrupted. Reading it then either stops early with
Memray ERROR: Invalid record typesilently dropping every record after the corruption, or crashes the reader with a segfault in FrameTree::getTraceIndex (see below).
It's a race, so it needs the right timing: a thread that predates the Tracker must allocate inside a C call that was already in progress when tracking started, and then make its next Python call while other threads are writing to the capture file. The script below exaggerates those conditions to hit it reliably; in a real program it should be rare.
Expected Behavior
The capture file is never corrupted.
Steps To Reproduce
import os, threading, zlib
from memray import FileReader, Tracker
from memray._test import allocate_without_gil_held
DATA = bytes(range(256)) * 20000
def blocked(depth, read_fd, write_fd):
if depth:
return blocked(depth - 1, read_fd, write_fd)
allocate_without_gil_held(write_fd, read_fd) # blocks, then allocates
def noisy(stop):
while not stop.is_set():
zlib.compress(DATA, 1) # allocates without the GIL
for i in range(30):
pipes = [(os.pipe(), os.pipe()) for _ in range(96)]
threads = [threading.Thread(target=blocked, args=(300, go[0], ready[1]))
for ready, go in pipes]
for t in threads: t.start()
for ready, _ in pipes: os.read(ready[0], 1) # all blocked in the C call
stop = threading.Event()
with Tracker(f"out{i}.bin"):
noise = [threading.Thread(target=noisy, args=(stop,)) for _ in range(8)]
for t in noise: t.start()
for _, go in pipes: os.write(go[1], b"x")
for t in threads: t.join()
stop.set()
for t in noise: t.join()
for ready, go in pipes:
for fd in (*ready, *go): os.close(fd)
reader = FileReader(f"out{i}.bin")
n = sum(1 for _ in reader.get_allocation_records())
print(i, n == reader.metadata.total_allocations)(memray._test is only available in a source checkout.)
Results on main (3b79fac), Python 3.14:
- macOS: 6/30 and 12/30 rounds read back fewer records than written, with
Invalid record type. - Linux:
Invalid record typein 6 of 60 rounds (there the corruption tended to land after the last allocation record, so the counts still matched), and in a pytest version of this, a segfault reading the file on the 3rd attempt:
Fatal Python error: Segmentation fault
memray::tracking_api::FrameTree::getTraceIndex(unsigned long, unsigned long) frame_tree.h:42
FileReader.get_allocation_records (generator)Memray Version
main (1.20.0, commit 3b79fac)
Python Version
3.14
Operating System
macOS, Linux
Anything else?
Cause: a thread that predates the Tracker gets a frozen copy of its stack, replaced on its first profile event by PythonStackTracker::handleTraceEvent → populateShadowStack() → clear() → emitPendingPushesAndPops(). If frames of the frozen copy were already emitted, that writes pop records without holding Tracker::s_mutex, while allocation hooks on other threads write under it. install_trace_function() has the same pattern.
Source: bloomberg/memray