p4r5kpftnp-cmd Claude Opus 4.7 commited on
Commit
ecb47f3
·
1 Parent(s): 8d1d708

Fix stdout race in solve_proof under concurrent requests

Browse files

contextlib.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) hide show
  1. app.py +95 -6
  2. tests/test_concurrent_solve.py +271 -0
app.py CHANGED
@@ -2,7 +2,7 @@ import io
2
  import os
3
  import sys
4
  import tempfile
5
- from contextlib import redirect_stdout
6
 
7
  import gradio as gr
8
 
@@ -10,6 +10,87 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
10
 
11
  from langgraph_agent import LangGraphAgent
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  GROQ_MODELS = [
14
  "llama-3.3-70b-versatile",
15
  "deepseek-r1-distill-llama-70b",
@@ -198,17 +279,21 @@ def solve_proof(lean_code: str, model_name: str, max_retries: int):
198
  if not os.environ.get("GROQ_API_KEY"):
199
  return _status_html("err", "GROQ_API_KEY missing — add it as a Space secret"), "", ""
200
 
201
- tmp = tempfile.NamedTemporaryFile(suffix=".lean", mode="w", delete=False, dir="/tmp")
202
  try:
 
 
203
  tmp.write(lean_code)
204
  tmp.close()
205
 
206
  log_buf = io.StringIO()
207
- with redirect_stdout(log_buf):
 
 
208
  agent = LangGraphAgent(model_name=model_name, max_retries=int(max_retries))
209
- result = agent.solve_file_detailed(tmp.name)
210
 
211
- with open(tmp.name) as f:
212
  final_code = f.read()
213
 
214
  logs = log_buf.getvalue()
@@ -223,7 +308,11 @@ def solve_proof(lean_code: str, model_name: str, max_retries: int):
223
  except Exception as exc:
224
  return _status_html("err", f"✗ Error: {exc}"), "", ""
225
  finally:
226
- os.unlink(tmp.name)
 
 
 
 
227
 
228
 
229
  def _status_html(pill: str, message: str) -> str:
 
2
  import os
3
  import sys
4
  import tempfile
5
+ import threading
6
 
7
  import gradio as gr
8
 
 
10
 
11
  from langgraph_agent import LangGraphAgent
12
 
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Thread-safe stdout capture.
16
+ #
17
+ # The previous implementation wrapped each call in `contextlib.redirect_stdout`,
18
+ # which rebinds the process-wide `sys.stdout`. Under concurrent solve_proof
19
+ # invocations (e.g. multiple Gradio users), the most-recent rebinding wins for
20
+ # every thread, so logs land in the wrong caller's buffer (or get lost when
21
+ # one call exits its `with` block and restores stdout while another is mid-run).
22
+ #
23
+ # We replace it with a thread-local proxy installed once on `sys.stdout`. Each
24
+ # call pushes its own StringIO onto its thread-local stack via
25
+ # `_capture_stdout()`; prints from other threads continue to land in their own
26
+ # buffers (or in the real stdout if they haven't installed one).
27
+ # ---------------------------------------------------------------------------
28
+
29
+ class _ThreadLocalStdout:
30
+ """A `sys.stdout` proxy that dispatches writes to a per-thread buffer."""
31
+
32
+ def __init__(self, real_stdout):
33
+ self._real = real_stdout
34
+ self._tls = threading.local()
35
+
36
+ def _current(self):
37
+ stack = getattr(self._tls, "stack", None)
38
+ if stack:
39
+ return stack[-1]
40
+ return self._real
41
+
42
+ # File-like protocol used by `print()`.
43
+ def write(self, s):
44
+ return self._current().write(s)
45
+
46
+ def flush(self):
47
+ try:
48
+ return self._current().flush()
49
+ except Exception:
50
+ return None
51
+
52
+ def isatty(self):
53
+ try:
54
+ return self._real.isatty()
55
+ except Exception:
56
+ return False
57
+
58
+ def fileno(self):
59
+ return self._real.fileno()
60
+
61
+ # Stack management ------------------------------------------------------
62
+ def push(self, buf):
63
+ stack = getattr(self._tls, "stack", None)
64
+ if stack is None:
65
+ stack = []
66
+ self._tls.stack = stack
67
+ stack.append(buf)
68
+
69
+ def pop(self):
70
+ stack = getattr(self._tls, "stack", None)
71
+ if stack:
72
+ stack.pop()
73
+
74
+
75
+ _STDOUT_PROXY = _ThreadLocalStdout(sys.stdout)
76
+ sys.stdout = _STDOUT_PROXY
77
+
78
+
79
+ class _capture_stdout:
80
+ """Context manager that captures stdout for the current thread only."""
81
+
82
+ def __init__(self, buf):
83
+ self._buf = buf
84
+
85
+ def __enter__(self):
86
+ _STDOUT_PROXY.push(self._buf)
87
+ return self._buf
88
+
89
+ def __exit__(self, exc_type, exc, tb):
90
+ _STDOUT_PROXY.pop()
91
+ return False
92
+
93
+
94
  GROQ_MODELS = [
95
  "llama-3.3-70b-versatile",
96
  "deepseek-r1-distill-llama-70b",
 
279
  if not os.environ.get("GROQ_API_KEY"):
280
  return _status_html("err", "GROQ_API_KEY missing — add it as a Space secret"), "", ""
281
 
282
+ tmp_path = None
283
  try:
284
+ tmp = tempfile.NamedTemporaryFile(suffix=".lean", mode="w", delete=False, dir="/tmp")
285
+ tmp_path = tmp.name
286
  tmp.write(lean_code)
287
  tmp.close()
288
 
289
  log_buf = io.StringIO()
290
+ # Thread-local stdout capture so concurrent solve_proof calls don't
291
+ # share a single rebound sys.stdout.
292
+ with _capture_stdout(log_buf):
293
  agent = LangGraphAgent(model_name=model_name, max_retries=int(max_retries))
294
+ result = agent.solve_file_detailed(tmp_path)
295
 
296
+ with open(tmp_path) as f:
297
  final_code = f.read()
298
 
299
  logs = log_buf.getvalue()
 
308
  except Exception as exc:
309
  return _status_html("err", f"✗ Error: {exc}"), "", ""
310
  finally:
311
+ if tmp_path is not None:
312
+ try:
313
+ os.unlink(tmp_path)
314
+ except OSError:
315
+ pass
316
 
317
 
318
  def _status_html(pill: str, message: str) -> str:
tests/test_concurrent_solve.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stress tests for app.solve_proof under concurrent invocation.
3
+
4
+ These tests mock out LangGraphAgent before importing app, so no Lean/LLM/Groq
5
+ infrastructure is required. They focus on:
6
+ * 10 simultaneous solve_proof calls returning distinct, non-cross-contaminated
7
+ final_code values (one tempfile per call, paths unique)
8
+ * Tempfile cleanup (no leftover .lean files in /tmp afterwards)
9
+ * Exception isolation (one failing call must not affect the other 9)
10
+ * Detecting the stdout-redirection race condition that the original
11
+ contextlib.redirect_stdout based implementation exhibited.
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ import tempfile
17
+ import threading
18
+ import time
19
+ import unittest
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from unittest import mock
22
+
23
+ # Make `app` and `src/` importable.
24
+ sys.path.insert(0, ".")
25
+ sys.path.insert(0, "src")
26
+
27
+ # IMPORTANT: mock LangGraphAgent BEFORE importing app so app.py never tries to
28
+ # instantiate the real agent (which would require lean, langchain, faiss, etc.).
29
+ _fake_lg_module = mock.MagicMock()
30
+
31
+
32
+ class _DummyAgent:
33
+ """Stand-in for LangGraphAgent. Configured per-test via class attributes."""
34
+
35
+ # Per-test knobs (mutated by tests before each scenario).
36
+ sleep_seconds: float = 0.0
37
+ # If a thread's lean_code contains this token, the agent raises.
38
+ raise_token: str | None = None
39
+ # Optional: tag to print so we can detect cross-thread stdout bleed.
40
+ print_tag: bool = False
41
+
42
+ def __init__(self, model_name="x", max_retries=5):
43
+ self.model_name = model_name
44
+ self.max_retries = max_retries
45
+
46
+ def solve_file_detailed(self, file_path: str) -> dict:
47
+ # Read what app.solve_proof just wrote so we can react per-call.
48
+ with open(file_path, "r") as f:
49
+ code = f.read()
50
+
51
+ if self.print_tag:
52
+ # Print enough to be racy if stdout is process-global.
53
+ for _ in range(20):
54
+ print(f"TAG::{code}")
55
+
56
+ # Sleep so calls overlap in real wall time.
57
+ if self.sleep_seconds:
58
+ time.sleep(self.sleep_seconds)
59
+
60
+ if self.raise_token and self.raise_token in code:
61
+ raise RuntimeError(f"injected failure for {self.raise_token}")
62
+
63
+ return {
64
+ "success": True,
65
+ "solved_at_attempt": 1,
66
+ "total_attempts": 1,
67
+ }
68
+
69
+
70
+ _fake_lg_module.LangGraphAgent = _DummyAgent
71
+ sys.modules["langgraph_agent"] = _fake_lg_module
72
+
73
+ # Pre-set GROQ_API_KEY so solve_proof doesn't short-circuit.
74
+ os.environ.setdefault("GROQ_API_KEY", "test-key")
75
+
76
+ import app # noqa: E402 (must come after the mock above)
77
+
78
+
79
+ def _scan_tmp_lean(prefix_dir: str = "/tmp") -> set[str]:
80
+ """Return absolute paths of all .lean files currently in `prefix_dir`."""
81
+ if not os.path.isdir(prefix_dir):
82
+ return set()
83
+ return {
84
+ os.path.join(prefix_dir, f)
85
+ for f in os.listdir(prefix_dir)
86
+ if f.endswith(".lean")
87
+ }
88
+
89
+
90
+ class ConcurrentSolveTests(unittest.TestCase):
91
+ def setUp(self):
92
+ # Reset agent state between scenarios.
93
+ _DummyAgent.sleep_seconds = 0.0
94
+ _DummyAgent.raise_token = None
95
+ _DummyAgent.print_tag = False
96
+ # Snapshot pre-existing tmp .lean files so we ignore unrelated ones.
97
+ self._tmp_before = _scan_tmp_lean()
98
+
99
+ def tearDown(self):
100
+ # Best-effort cleanup of anything the tests created that survived a bug.
101
+ leaked = _scan_tmp_lean() - self._tmp_before
102
+ for path in leaked:
103
+ try:
104
+ os.unlink(path)
105
+ except OSError:
106
+ pass
107
+
108
+ # ------------------------------------------------------------------
109
+ # 1 + 3: 10 parallel calls, agent sleeps so calls overlap.
110
+ # ------------------------------------------------------------------
111
+ def test_ten_parallel_calls_no_cross_contamination(self):
112
+ _DummyAgent.sleep_seconds = 0.1 # force overlap
113
+
114
+ inputs = [f"theorem t_{i} : True := trivial" for i in range(10)]
115
+
116
+ def run(code):
117
+ return code, app.solve_proof(code, "llama-3.3-70b-versatile", 1)
118
+
119
+ with ThreadPoolExecutor(max_workers=10) as ex:
120
+ futures = [ex.submit(run, code) for code in inputs]
121
+ results = [f.result() for f in as_completed(futures)]
122
+
123
+ self.assertEqual(len(results), 10)
124
+
125
+ for code, triple in results:
126
+ self.assertIsInstance(triple, tuple, f"{code!r} did not return tuple")
127
+ self.assertEqual(len(triple), 3, f"{code!r} returned {triple!r}")
128
+ status_html, final_code, logs = triple
129
+ # final_code is what the agent wrote/left in the tempfile, which the
130
+ # mock leaves untouched, so it must equal the input verbatim.
131
+ self.assertEqual(
132
+ final_code,
133
+ code,
134
+ f"Cross-contamination: expected {code!r} got {final_code!r}",
135
+ )
136
+ self.assertIn("Verified", status_html, f"Unexpected status: {status_html!r}")
137
+
138
+ # All tempfiles must be cleaned up.
139
+ leaked = _scan_tmp_lean() - self._tmp_before
140
+ self.assertEqual(leaked, set(), f"Tempfiles leaked: {leaked!r}")
141
+
142
+ # ------------------------------------------------------------------
143
+ # 2: Tempfile collision check. Patch NamedTemporaryFile to log paths.
144
+ # ------------------------------------------------------------------
145
+ def test_tempfile_paths_unique_under_concurrency(self):
146
+ _DummyAgent.sleep_seconds = 0.05
147
+
148
+ seen_paths: list[str] = []
149
+ seen_lock = threading.Lock()
150
+
151
+ real_ntf = tempfile.NamedTemporaryFile
152
+
153
+ def logging_ntf(*args, **kwargs):
154
+ f = real_ntf(*args, **kwargs)
155
+ with seen_lock:
156
+ seen_paths.append(f.name)
157
+ return f
158
+
159
+ with mock.patch.object(app.tempfile, "NamedTemporaryFile", side_effect=logging_ntf):
160
+ with ThreadPoolExecutor(max_workers=10) as ex:
161
+ futures = [
162
+ ex.submit(
163
+ app.solve_proof,
164
+ f"theorem unique_{i} : True := trivial",
165
+ "llama-3.3-70b-versatile",
166
+ 1,
167
+ )
168
+ for i in range(10)
169
+ ]
170
+ results = [f.result() for f in as_completed(futures)]
171
+
172
+ self.assertEqual(len(results), 10)
173
+ self.assertEqual(
174
+ len(seen_paths),
175
+ len(set(seen_paths)),
176
+ f"Tempfile path collision: {seen_paths!r}",
177
+ )
178
+
179
+ # ------------------------------------------------------------------
180
+ # 4: one call raises, the other 9 still succeed.
181
+ # ------------------------------------------------------------------
182
+ def test_one_raising_call_does_not_break_others(self):
183
+ _DummyAgent.sleep_seconds = 0.1
184
+ _DummyAgent.raise_token = "BOOM_3"
185
+
186
+ inputs = []
187
+ for i in range(10):
188
+ if i == 3:
189
+ inputs.append("theorem t_BOOM_3 : True := trivial")
190
+ else:
191
+ inputs.append(f"theorem t_{i} : True := trivial")
192
+
193
+ def run(code):
194
+ return code, app.solve_proof(code, "llama-3.3-70b-versatile", 1)
195
+
196
+ with ThreadPoolExecutor(max_workers=10) as ex:
197
+ futures = [ex.submit(run, code) for code in inputs]
198
+ results = [f.result() for f in as_completed(futures)]
199
+
200
+ oks = []
201
+ errs = []
202
+ for code, triple in results:
203
+ self.assertIsInstance(triple, tuple)
204
+ self.assertEqual(len(triple), 3)
205
+ status_html, final_code, logs = triple
206
+ if "BOOM_3" in code:
207
+ errs.append((code, status_html, final_code))
208
+ else:
209
+ oks.append((code, status_html, final_code))
210
+
211
+ self.assertEqual(len(oks), 9, "Expected 9 successful calls")
212
+ self.assertEqual(len(errs), 1, "Expected exactly 1 erroring call")
213
+
214
+ # Erroring call returns the "✗ Error:" status (per app.solve_proof).
215
+ _, err_status, err_final = errs[0]
216
+ self.assertIn("Error", err_status)
217
+ self.assertEqual(err_final, "")
218
+
219
+ # The 9 successful calls keep their own inputs intact.
220
+ for code, status, final in oks:
221
+ self.assertEqual(final, code)
222
+ self.assertIn("Verified", status)
223
+
224
+ # No tempfile leaks even on the error path.
225
+ leaked = _scan_tmp_lean() - self._tmp_before
226
+ self.assertEqual(leaked, set(), f"Tempfiles leaked: {leaked!r}")
227
+
228
+ # ------------------------------------------------------------------
229
+ # Stdout race: with print() inside the agent, log buffers must NOT
230
+ # see each other's output. This is the bug redirect_stdout causes.
231
+ # ------------------------------------------------------------------
232
+ def test_stdout_logs_are_not_cross_contaminated(self):
233
+ _DummyAgent.sleep_seconds = 0.1
234
+ _DummyAgent.print_tag = True # agent prints "TAG::<code>" 20 times
235
+
236
+ inputs = [f"theorem stdoutcheck_{i} : True := trivial" for i in range(10)]
237
+
238
+ def run(code):
239
+ return code, app.solve_proof(code, "llama-3.3-70b-versatile", 1)
240
+
241
+ with ThreadPoolExecutor(max_workers=10) as ex:
242
+ futures = [ex.submit(run, c) for c in inputs]
243
+ results = [f.result() for f in as_completed(futures)]
244
+
245
+ # Each call's `logs` should contain its own TAG line and only its own.
246
+ offenders = []
247
+ for code, triple in results:
248
+ _, _, logs = triple
249
+ own_tag = f"TAG::{code}"
250
+ if own_tag not in logs:
251
+ offenders.append(("own-tag-missing", code, logs[:200]))
252
+ continue
253
+ # No other call's code should leak into this log.
254
+ for other in inputs:
255
+ if other == code:
256
+ continue
257
+ if f"TAG::{other}" in logs:
258
+ offenders.append(("other-tag-leaked", code, other))
259
+ break
260
+
261
+ self.assertEqual(
262
+ offenders,
263
+ [],
264
+ "Stdout was cross-contaminated between concurrent solve_proof calls "
265
+ "(redirect_stdout is process-global, not thread-local). "
266
+ f"Offenders: {offenders[:5]!r}",
267
+ )
268
+
269
+
270
+ if __name__ == "__main__":
271
+ unittest.main()