Spaces:
Sleeping
Fix stdout race in solve_proof under concurrent requests
Browse filescontextlib.redirect_stdout rebinds the process-wide sys.stdout. With
multiple Gradio users invoking solve_proof simultaneously, the most
recent rebinding wins for every running thread, so log output ended
up in the wrong caller's buffer (or got lost when one call exited its
context manager mid-run of another).
Replace it with a single _ThreadLocalStdout proxy installed once on
sys.stdout, plus a per-call _capture_stdout context manager that
pushes/pops a StringIO onto a thread-local stack. Each thread now sees
only its own buffer; other threads (and any non-capturing threads)
continue to write to the original stdout.
Also harden the cleanup path: track tmp_path separately so that if
NamedTemporaryFile itself raises (or anything before tmp is bound),
the finally block doesn't raise NameError trying to unlink an
undefined name; swallow OSError if the file is already gone.
Add tests/test_concurrent_solve.py exercising 10 concurrent
solve_proof calls with a mocked LangGraphAgent: verifies tuple shape,
no input/output cross-contamination, unique tempfile paths, exception
isolation (1 raising call does not affect the other 9), tempfile
cleanup on all paths, and (the regression check) thread-local log
isolation.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Files changed (2)
- app.py+95-6
- tests/test_concurrent_solve.pyAdded+271
1 unmodified line234556781 unmodified line101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596182 unmodified lines2792802812012822832842852862872882892902912072922932092942952112962972982998 unmodified lines3083093103113122263133143153163173181 unmodified lineimport osimport sysimport tempfilefrom contextlib import redirect_stdoutimport threading
import gradio as gr
1 unmodified line
from langgraph_agent import LangGraphAgent
# ---------------------------------------------------------------------------# Thread-safe stdout capture.## The previous implementation wrapped each call in `contextlib.redirect_stdout`,# which rebinds the process-wide `sys.stdout`. Under concurrent solve_proof# invocations (e.g. multiple Gradio users), the most-recent rebinding wins for# every thread, so logs land in the wrong caller's buffer (or get lost when# one call exits its `with` block and restores stdout while another is mid-run).## We replace it with a thread-local proxy installed once on `sys.stdout`. Each# call pushes its own StringIO onto its thread-local stack via# `_capture_stdout()`; prints from other threads continue to land in their own# buffers (or in the real stdout if they haven't installed one).# ---------------------------------------------------------------------------
class _ThreadLocalStdout: """A `sys.stdout` proxy that dispatches writes to a per-thread buffer."""
def __init__(self, real_stdout): self._real = real_stdout self._tls = threading.local()
def _current(self): stack = getattr(self._tls, "stack", None) if stack: return stack[-1] return self._real
# File-like protocol used by `print()`. def write(self, s): return self._current().write(s)
def flush(self): try: return self._current().flush() except Exception: return None
def isatty(self): try: return self._real.isatty() except Exception: return False
def fileno(self): return self._real.fileno()
# Stack management ------------------------------------------------------ def push(self, buf): stack = getattr(self._tls, "stack", None) if stack is None: stack = [] self._tls.stack = stack stack.append(buf)
def pop(self): stack = getattr(self._tls, "stack", None) if stack: stack.pop()
_STDOUT_PROXY = _ThreadLocalStdout(sys.stdout)sys.stdout = _STDOUT_PROXY
class _capture_stdout: """Context manager that captures stdout for the current thread only."""
def __init__(self, buf): self._buf = buf
def __enter__(self): _STDOUT_PROXY.push(self._buf) return self._buf
def __exit__(self, exc_type, exc, tb): _STDOUT_PROXY.pop() return False
GROQ_MODELS = [ "llama-3.3-70b-versatile", "deepseek-r1-distill-llama-70b",182 unmodified lines if not os.environ.get("GROQ_API_KEY"): return _status_html("err", "GROQ_API_KEY missing — add it as a Space secret"), "", ""
tmp = tempfile.NamedTemporaryFile(suffix=".lean", mode="w", delete=False, dir="/tmp") tmp_path = None try: tmp = tempfile.NamedTemporaryFile(suffix=".lean", mode="w", delete=False, dir="/tmp") tmp_path = tmp.name tmp.write(lean_code) tmp.close()
log_buf = io.StringIO() # Thread-local stdout capture so concurrent solve_proof calls don't # share a single rebound sys.stdout. with redirect_stdout(log_buf): with _capture_stdout(log_buf): agent = LangGraphAgent(model_name=model_name, max_retries=int(max_retries)) result = agent.solve_file_detailed(tmp.name) result = agent.solve_file_detailed(tmp_path)
with open(tmp.name) as f: with open(tmp_path) as f: final_code = f.read()
logs = log_buf.getvalue()8 unmodified lines except Exception as exc: return _status_html("err", f"✗ Error: {exc}"), "", "" finally: if tmp_path is not None: try: os.unlink(tmp.name) os.unlink(tmp_path) except OSError: pass
def _status_html(pill: str, message: str) -> str:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Stress tests for app.solve_proof under concurrent invocation.
These tests mock out LangGraphAgent before importing app, so no Lean/LLM/Groqinfrastructure is required. They focus on: * 10 simultaneous solve_proof calls returning distinct, non-cross-contaminated final_code values (one tempfile per call, paths unique) * Tempfile cleanup (no leftover .lean files in /tmp afterwards) * Exception isolation (one failing call must not affect the other 9) * Detecting the stdout-redirection race condition that the original contextlib.redirect_stdout based implementation exhibited."""
import osimport sysimport tempfileimport threadingimport timeimport unittestfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom unittest import mock
# Make `app` and `src/` importable.sys.path.insert(0, ".")sys.path.insert(0, "src")
# IMPORTANT: mock LangGraphAgent BEFORE importing app so app.py never tries to# instantiate the real agent (which would require lean, langchain, faiss, etc.)._fake_lg_module = mock.MagicMock()
class _DummyAgent: """Stand-in for LangGraphAgent. Configured per-test via class attributes."""
# Per-test knobs (mutated by tests before each scenario). sleep_seconds: float = 0.0 # If a thread's lean_code contains this token, the agent raises. raise_token: str | None = None # Optional: tag to print so we can detect cross-thread stdout bleed. print_tag: bool = False
def __init__(self, model_name="x", max_retries=5): self.model_name = model_name self.max_retries = max_retries
def solve_file_detailed(self, file_path: str) -> dict: # Read what app.solve_proof just wrote so we can react per-call. with open(file_path, "r") as f: code = f.read()
if self.print_tag: # Print enough to be racy if stdout is process-global. for _ in range(20): print(f"TAG::{code}")
# Sleep so calls overlap in real wall time. if self.sleep_seconds: time.sleep(self.sleep_seconds)
if self.raise_token and self.raise_token in code: raise RuntimeError(f"injected failure for {self.raise_token}")
return { "success": True, "solved_at_attempt": 1, "total_attempts": 1, }
_fake_lg_module.LangGraphAgent = _DummyAgentsys.modules["langgraph_agent"] = _fake_lg_module
# Pre-set GROQ_API_KEY so solve_proof doesn't short-circuit.os.environ.setdefault("GROQ_API_KEY", "test-key")
import app # noqa: E402 (must come after the mock above)
def _scan_tmp_lean(prefix_dir: str = "/tmp") -> set[str]: """Return absolute paths of all .lean files currently in `prefix_dir`.""" if not os.path.isdir(prefix_dir): return set() return { os.path.join(prefix_dir, f) for f in os.listdir(prefix_dir) if f.endswith(".lean") }
class ConcurrentSolveTests(unittest.TestCase): def setUp(self): # Reset agent state between scenarios. _DummyAgent.sleep_seconds = 0.0 _DummyAgent.raise_token = None _DummyAgent.print_tag = False # Snapshot pre-existing tmp .lean files so we ignore unrelated ones. self._tmp_before = _scan_tmp_lean()
def tearDown(self): # Best-effort cleanup of anything the tests created that survived a bug. leaked = _scan_tmp_lean() - self._tmp_before for path in leaked: try: os.unlink(path) except OSError: pass
# ------------------------------------------------------------------ # 1 + 3: 10 parallel calls, agent sleeps so calls overlap. # ------------------------------------------------------------------ def test_ten_parallel_calls_no_cross_contamination(self): _DummyAgent.sleep_seconds = 0.1 # force overlap
inputs = [f"theorem t_{i} : True := trivial" for i in range(10)]
def run(code): return code, app.solve_proof(code, "llama-3.3-70b-versatile", 1)
with ThreadPoolExecutor(max_workers=10) as ex: futures = [ex.submit(run, code) for code in inputs] results = [f.result() for f in as_completed(futures)]
self.assertEqual(len(results), 10)
for code, triple in results: self.assertIsInstance(triple, tuple, f"{code!r} did not return tuple") self.assertEqual(len(triple), 3, f"{code!r} returned {triple!r}") status_html, final_code, logs = triple # final_code is what the agent wrote/left in the tempfile, which the # mock leaves untouched, so it must equal the input verbatim. self.assertEqual( final_code, code, f"Cross-contamination: expected {code!r} got {final_code!r}", ) self.assertIn("Verified", status_html, f"Unexpected status: {status_html!r}")
# All tempfiles must be cleaned up. leaked = _scan_tmp_lean() - self._tmp_before self.assertEqual(leaked, set(), f"Tempfiles leaked: {leaked!r}")
# ------------------------------------------------------------------ # 2: Tempfile collision check. Patch NamedTemporaryFile to log paths. # ------------------------------------------------------------------ def test_tempfile_paths_unique_under_concurrency(self): _DummyAgent.sleep_seconds = 0.05
seen_paths: list[str] = [] seen_lock = threading.Lock()
real_ntf = tempfile.NamedTemporaryFile
def logging_ntf(*args, **kwargs): f = real_ntf(*args, **kwargs) with seen_lock: seen_paths.append(f.name) return f
with mock.patch.object(app.tempfile, "NamedTemporaryFile", side_effect=logging_ntf): with ThreadPoolExecutor(max_workers=10) as ex: futures = [ ex.submit( app.solve_proof, f"theorem unique_{i} : True := trivial", "llama-3.3-70b-versatile", 1, ) for i in range(10) ] results = [f.result() for f in as_completed(futures)]
self.assertEqual(len(results), 10) self.assertEqual( len(seen_paths), len(set(seen_paths)), f"Tempfile path collision: {seen_paths!r}", )
# ------------------------------------------------------------------ # 4: one call raises, the other 9 still succeed. # ------------------------------------------------------------------ def test_one_raising_call_does_not_break_others(self): _DummyAgent.sleep_seconds = 0.1 _DummyAgent.raise_token = "BOOM_3"
inputs = [] for i in range(10): if i == 3: inputs.append("theorem t_BOOM_3 : True := trivial") else: inputs.append(f"theorem t_{i} : True := trivial")
def run(code): return code, app.solve_proof(code, "llama-3.3-70b-versatile", 1)
with ThreadPoolExecutor(max_workers=10) as ex: futures = [ex.submit(run, code) for code in inputs] results = [f.result() for f in as_completed(futures)]
oks = [] errs = [] for code, triple in results: self.assertIsInstance(triple, tuple) self.assertEqual(len(triple), 3) status_html, final_code, logs = triple if "BOOM_3" in code: errs.append((code, status_html, final_code)) else: oks.append((code, status_html, final_code))
self.assertEqual(len(oks), 9, "Expected 9 successful calls") self.assertEqual(len(errs), 1, "Expected exactly 1 erroring call")
# Erroring call returns the "✗ Error:" status (per app.solve_proof). _, err_status, err_final = errs[0] self.assertIn("Error", err_status) self.assertEqual(err_final, "")
# The 9 successful calls keep their own inputs intact. for code, status, final in oks: self.assertEqual(final, code) self.assertIn("Verified", status)
# No tempfile leaks even on the error path. leaked = _scan_tmp_lean() - self._tmp_before self.assertEqual(leaked, set(), f"Tempfiles leaked: {leaked!r}")
# ------------------------------------------------------------------ # Stdout race: with print() inside the agent, log buffers must NOT # see each other's output. This is the bug redirect_stdout causes. # ------------------------------------------------------------------ def test_stdout_logs_are_not_cross_contaminated(self): _DummyAgent.sleep_seconds = 0.1 _DummyAgent.print_tag = True # agent prints "TAG::<code>" 20 times
inputs = [f"theorem stdoutcheck_{i} : True := trivial" for i in range(10)]
def run(code): return code, app.solve_proof(code, "llama-3.3-70b-versatile", 1)
with ThreadPoolExecutor(max_workers=10) as ex: futures = [ex.submit(run, c) for c in inputs] results = [f.result() for f in as_completed(futures)]
# Each call's `logs` should contain its own TAG line and only its own. offenders = [] for code, triple in results: _, _, logs = triple own_tag = f"TAG::{code}" if own_tag not in logs: offenders.append(("own-tag-missing", code, logs[:200])) continue # No other call's code should leak into this log. for other in inputs: if other == code: continue if f"TAG::{other}" in logs: offenders.append(("other-tag-leaked", code, other)) break
self.assertEqual( offenders, [], "Stdout was cross-contaminated between concurrent solve_proof calls " "(redirect_stdout is process-global, not thread-local). " f"Offenders: {offenders[:5]!r}", )
if __name__ == "__main__": unittest.main()