record stalls or hangs processes with many native threads (torch on many-core CPUs): Process::lock() ptrace-stops every OS thread on every sample
Summary
When sampling a Python process that has a large native thread pool
(e.g. PyTorch on a many-core machine), py-spy record intermittently slows
the target by 5–15× and, at higher sampling rates, freezes it completely.
Reproduction
A trivial torch program is enough to trigger it deterministically at 200 Hz:
# repro.py
import torch
x = torch.randn(512, 512)
y = x @ x
print("done", float(y.sum()))py-spy record -r 200 --format speedscope -o out.json -- python3 repro.pyOn a 192-core machine, import torch spins up ~159 threads (96 OpenMP plus CUDA runtime/other). Measured wall times:
| command | wall time |
|---|---|
bare python3 repro.py |
~1.5 s |
-r 20 |
~2 s |
| default 100 Hz | 7.6–23.8 s (intermittent) |
-r 200 |
hangs (>30 s, 4/4 runs) |
--nonblocking |
1.54 s |
Root cause
remoteprocess::Process::lock() ptrace-stops every OS thread of the
target on every sample (SEIZE + INTERRUPT + waitpid + DETACH per
thread). With ~159 threads a single sample costs ~8–9 ms:
- at 100 Hz (10 ms interval) the target is frozen ~85% of the time, so a 1.5 s workload stretches to 7–24 s depending on where samples land relative to torch's lazy thread spawn (hence the intermittency);
- at 200 Hz (5 ms interval) the freeze exceeds the interval, so the process never makes progress and its lazy init is stretched indefinitely — a deterministic hang.
--nonblocking (which skips the lock) finishes in 1.54 s, confirming the
lock is the entire cost. --gil is still slow because it also goes through
Process::lock(). The ~150 OpenMP/CUDA worker threads have no
PyThreadState and are never read by py-spy, yet they are all stopped on
every sample.
Proposed fix
Only ptrace-stop the Python threads (those with a PyThreadState), not the whole native thread pool. python_spy.rs already keeps the python→OS thread-id mapping in python_thread_ids, so the change:
pre-scans the PyThreadState list (a lock-free, racy read used only to decide what to lock): if every Python thread is already mapped, lock only those OS threads; otherwise (first sample, or a freshly spawned Python thread) fall back to Process::lock() so the mapping can be resolved; makes the native-stack merge non-fatal when a thread's OS id can't be resolved — the thread keeps its Python-only frames instead of failing the whole sample with failed to get os threadid. After the fix: -r 200 → ~2 s, default 100 Hz → ~1.9 s, and a real --native torch benchmark → ~8 s with 0 sampling errors.
Environment
py-spy 0.4.2 Linux 5.15, 192-core Hygon machine torch (default torch.get_num_threads() = 96)
> (set -x ; cat /etc/os-release ; python3 -VV ; py-spy -VV ; nvidia-smi ; lscpu )
+ cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04 (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
+ python3 -VV
Python 3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]
+ py-spy -VV
py-spy 0.4.2
+ nvidia-smi
Sun Sep 20 16:22:51 2026
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 580.65.06 Driver Version: 580.65.06 CUDA Version: 13.0 |
+-----------------------------------------+------------------------+----------------------+
| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|=========================================+========================+======================|
| 0 NVIDIA H100 PCIe Off | 00000000:E1:00.0 Off | 0 |
| N/A 44C P0 84W / 350W | 0MiB / 81559MiB | 2% Default |
| | | Disabled |
+-----------------------------------------+------------------------+----------------------+
+-----------------------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=========================================================================================|
| No running processes found |
+-----------------------------------------------------------------------------------------+
+ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 48 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 192
On-line CPU(s) list: 0-191
Vendor ID: HygonGenuine
Model name: Hygon C86-4G (OPN:7492H)
CPU family: 24
Model: 7
Thread(s) per core: 2
Core(s) per socket: 96
Socket(s): 1
Stepping: 0
Frequency boost: enabled
CPU max MHz: 2600.0000
CPU min MHz: 1400.0000
BogoMIPS: 5200.03
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid amd_dcm aperfmperf rapl pni pclmulqdq mo
nitor ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat
_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase tsc_adjust bmi1 avx2 smep bmi2 cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_oc
cup_llc cqm_mbm_total cqm_mbm_local avx_vnni avx512_bf16 clzero irperf xsaveerptr wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl avx512vbmi
umip avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq overflow_recov succor smca avx512_vp2intersect sme sev sev_es
Virtualization features:
Virtualization: AMD-V
Caches (sum of all):
L1d: 3 MiB (96 instances)
L1i: 3 MiB (96 instances)
L2: 48 MiB (96 instances)
L3: 192 MiB (12 instances)
NUMA:
NUMA node(s): 6
NUMA node0 CPU(s): 0-15,96-111
NUMA node1 CPU(s): 16-31,112-127
NUMA node2 CPU(s): 32-47,128-143
NUMA node3 CPU(s): 48-63,144-159
NUMA node4 CPU(s): 64-79,160-175
NUMA node5 CPU(s): 80-95,176-191
Vulnerabilities:
Itlb multihit: Not affected
L1tf: Not affected
Mds: Not affected
Meltdown: Not affected
Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Spectre v2: Mitigation; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling
Srbds: Not affected
Tsx async abort: Not affectedSource: benfred/py-spy