Skip to content

Commit 9b474bc

Browse files
committed
Fix race condition in result queue handling by using timeout-based get()
The previous implementation checked result_queue.empty() before calling get(), which introduces a classic race condition: the queue may become non-empty immediately after the check, resulting in missed results or misleading errors. This patch replaces the empty() check with result_queue.get(timeout=1.0), allowing the parent process to robustly wait for results with a bounded delay. Also switches from ctx.SimpleQueue() to ctx.Queue() for compatibility with timeout-based get(), which SimpleQueue does not support on Python ≤3.12. Note: The race condition was discovered by Gemini 2.5
1 parent 5977b9d commit 9b474bc

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

cuda_bindings/cuda/bindings/_path_finder/run_python_code_safely.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import multiprocessing
2+
import queue # for Empty
23
import subprocess # nosec B404
34
import sys
45
import traceback
@@ -41,7 +42,7 @@ def __call__(self):
4142
def run_python_code_safely(python_code, *, timeout=None):
4243
"""Run Python code in a spawned subprocess, capturing stdout/stderr/output."""
4344
ctx = multiprocessing.get_context("spawn")
44-
result_queue = ctx.SimpleQueue()
45+
result_queue = ctx.Queue()
4546
process = ctx.Process(target=Worker(python_code, result_queue))
4647
process.start()
4748

@@ -57,15 +58,16 @@ def run_python_code_safely(python_code, *, timeout=None):
5758
stderr=f"Process timed out after {timeout} seconds and was terminated.",
5859
)
5960

60-
if result_queue.empty():
61+
try:
62+
returncode, stdout, stderr = result_queue.get(timeout=1.0)
63+
except (queue.Empty, EOFError):
6164
return subprocess.CompletedProcess(
6265
args=[sys.executable, "-c", python_code],
6366
returncode=-999,
6467
stdout="",
65-
stderr="Process exited without returning results.",
68+
stderr="Process exited or crashed before returning results.",
6669
)
6770

68-
returncode, stdout, stderr = result_queue.get()
6971
return subprocess.CompletedProcess(
7072
args=[sys.executable, "-c", python_code],
7173
returncode=returncode,

0 commit comments

Comments
 (0)