Ray5th commited on
Commit
c7724f7
ยท
unverified ยท
2 Parent(s): c16211c1808386

Merge pull request #15 from ray5th/fuzz/solve-proof-corpus

Browse files
app.py CHANGED
@@ -281,7 +281,17 @@ def solve_proof(lean_code: str, model_name: str, max_retries: int):
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()
@@ -293,7 +303,7 @@ def solve_proof(lean_code: str, model_name: str, max_retries: int):
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()
 
281
 
282
  tmp_path = None
283
  try:
284
+ # Lean source frequently contains unicode (โˆ€ โ„• โˆƒ โ†‘ etc.). On platforms
285
+ # where the preferred encoding is not UTF-8 (e.g. POSIX/C locale),
286
+ # opening text mode without an explicit encoding can blow up with
287
+ # UnicodeEncodeError / UnicodeDecodeError. Force UTF-8 on both ends.
288
+ tmp = tempfile.NamedTemporaryFile(
289
+ suffix=".lean",
290
+ mode="w",
291
+ delete=False,
292
+ dir="/tmp",
293
+ encoding="utf-8",
294
+ )
295
  tmp_path = tmp.name
296
  tmp.write(lean_code)
297
  tmp.close()
 
303
  agent = LangGraphAgent(model_name=model_name, max_retries=int(max_retries))
304
  result = agent.solve_file_detailed(tmp_path)
305
 
306
+ with open(tmp_path, encoding="utf-8") as f:
307
  final_code = f.read()
308
 
309
  logs = log_buf.getvalue()
src/langgraph_agent.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  from typing import List, TypedDict
3
 
4
  from langgraph.graph import END, StateGraph
@@ -29,20 +30,41 @@ class ProofState(TypedDict):
29
  # ---------------------------------------------------------------------------
30
 
31
  def _read_file(path: str) -> str:
32
- with open(path, "r") as f:
 
 
 
33
  return f.read()
34
 
35
 
36
  def _write_file(path: str, code: str) -> None:
37
- with open(path, "w") as f:
38
  f.write(code)
39
 
40
 
 
 
 
 
 
 
41
  def _extract_lean_code(text: str) -> str:
42
- if "```lean" in text:
43
- return text.split("```lean")[1].split("```")[0].strip()
 
 
 
 
 
 
 
 
 
 
 
 
44
  if "```" in text:
45
- return text.split("```")[1].split("```")[0].strip()
46
  return text.strip()
47
 
48
 
@@ -57,13 +79,17 @@ def _sanitize_imports(code: str) -> str:
57
  return "import Mathlib\n\n" + "\n".join(non_import_lines).lstrip()
58
 
59
 
60
- _THEOREM_KEYWORDS = ("example", "theorem ", "lemma ", "def ")
 
 
 
 
61
 
62
 
63
  def _count_theorem_blocks(code: str) -> int:
64
  return sum(
65
  1 for line in code.splitlines()
66
- if any(line.strip().startswith(kw) for kw in _THEOREM_KEYWORDS)
67
  )
68
 
69
 
 
1
  import os
2
+ import re
3
  from typing import List, TypedDict
4
 
5
  from langgraph.graph import END, StateGraph
 
30
  # ---------------------------------------------------------------------------
31
 
32
  def _read_file(path: str) -> str:
33
+ # Lean source uses โˆ€ โˆƒ โ„• โ†‘ etc. Force UTF-8 so non-UTF-8 default locales
34
+ # (e.g. C/POSIX inside minimal Docker images) don't corrupt or crash on
35
+ # read.
36
+ with open(path, "r", encoding="utf-8") as f:
37
  return f.read()
38
 
39
 
40
  def _write_file(path: str, code: str) -> None:
41
+ with open(path, "w", encoding="utf-8") as f:
42
  f.write(code)
43
 
44
 
45
+ # Match an opening fence tagged `lean` (or `lean4`, `Lean`, etc.) followed by a
46
+ # newline or whitespace โ€” but NOT something like ```leanish that would
47
+ # accidentally consume the "ish" into the code body.
48
+ _LEAN_FENCE_RE = re.compile(r"```\s*lean[0-9]*\s*\n", re.IGNORECASE)
49
+
50
+
51
  def _extract_lean_code(text: str) -> str:
52
+ """
53
+ Extract the Lean code block from an LLM response.
54
+
55
+ Handles:
56
+ - ```lean\n...\n``` (canonical)
57
+ - ```lean4\n...\n``` (some LLMs)
58
+ - ```Lean\n...\n``` (case variation)
59
+ - ```\n...\n``` (no language tag)
60
+ - plain text without fences (returned as-is)
61
+ """
62
+ m = _LEAN_FENCE_RE.search(text)
63
+ if m:
64
+ rest = text[m.end():]
65
+ return rest.split("```", 1)[0].strip()
66
  if "```" in text:
67
+ return text.split("```", 1)[1].split("```", 1)[0].strip()
68
  return text.strip()
69
 
70
 
 
79
  return "import Mathlib\n\n" + "\n".join(non_import_lines).lstrip()
80
 
81
 
82
+ # A declaration keyword must be followed by whitespace or end-of-line so that
83
+ # `examplelike` (false positive) doesn't match and `theorem\n` (no trailing
84
+ # space) does match. `theorem:` and `theorem(` are not valid Lean syntax
85
+ # (the declaration name must come first), so we don't allow those either.
86
+ _THEOREM_KEYWORD_RE = re.compile(r"^\s*(?:example|theorem|lemma|def)(?:\s|$)")
87
 
88
 
89
  def _count_theorem_blocks(code: str) -> int:
90
  return sum(
91
  1 for line in code.splitlines()
92
+ if _THEOREM_KEYWORD_RE.match(line)
93
  )
94
 
95
 
src/lean_verifier.py CHANGED
@@ -35,14 +35,34 @@ class LeanEnvironment:
35
  def verify_proof(self, lean_code: str) -> Dict[str, Any]:
36
  """
37
  Executes a block of Lean code and verifies if it is a correct proof.
38
-
39
  Args:
40
  lean_code (str): The full Lean 4 code string containing imports, theorem statement, and proof.
41
-
42
  Returns:
43
  dict: A dictionary containing the status, errors (if any), and goals (if open sorries remain).
44
  """
45
- response = self.server.run(Command(cmd=lean_code))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  errors = []
48
  goals = []
 
35
  def verify_proof(self, lean_code: str) -> Dict[str, Any]:
36
  """
37
  Executes a block of Lean code and verifies if it is a correct proof.
38
+
39
  Args:
40
  lean_code (str): The full Lean 4 code string containing imports, theorem statement, and proof.
41
+
42
  Returns:
43
  dict: A dictionary containing the status, errors (if any), and goals (if open sorries remain).
44
  """
45
+ # Guard: empty/whitespace input would crash `Command(cmd=...)` with a
46
+ # pydantic ValidationError (min_length=1). Return a clean failure.
47
+ if not lean_code or not lean_code.strip():
48
+ return {
49
+ "status": "failure",
50
+ "errors": ["empty Lean code: nothing to verify"],
51
+ "goals": [],
52
+ "env": None,
53
+ }
54
+
55
+ # Guard: LeanServer can raise on disconnect / crash / OOM. Surface as a
56
+ # failure result so the agent's retry loop continues instead of dying.
57
+ try:
58
+ response = self.server.run(Command(cmd=lean_code))
59
+ except Exception as exc:
60
+ return {
61
+ "status": "failure",
62
+ "errors": [f"Lean server error: {exc}"],
63
+ "goals": [],
64
+ "env": None,
65
+ }
66
 
67
  errors = []
68
  goals = []
src/lmm_client.py CHANGED
@@ -22,7 +22,14 @@ class LMMClient:
22
  messages=messages,
23
  max_tokens=1024,
24
  )
25
- return response.choices[0].message.content
 
 
 
 
 
 
 
26
 
27
  def generate_proof_steps(self, lean_code: str, goals: List[str], errors: List[str]) -> str:
28
  system_prompt = (
 
22
  messages=messages,
23
  max_tokens=1024,
24
  )
25
+ # Defensive: Groq can return empty `choices` on content filter / quota
26
+ # issues โ€” accessing [0] would IndexError and kill the agent.
27
+ choices = getattr(response, "choices", None) or []
28
+ if not choices:
29
+ return ""
30
+ message = getattr(choices[0], "message", None)
31
+ content = getattr(message, "content", None) if message else None
32
+ return content or ""
33
 
34
  def generate_proof_steps(self, lean_code: str, goals: List[str], errors: List[str]) -> str:
35
  system_prompt = (
src/proof_agent.py CHANGED
@@ -4,7 +4,7 @@ from langgraph_agent import LangGraphAgent
4
  class ProofAgent:
5
  """Thin compatibility wrapper around LangGraphAgent."""
6
 
7
- def __init__(self, model_name: str = "qwen3-vl:4b", max_retries: int = 5):
8
  self._agent = LangGraphAgent(model_name=model_name, max_retries=max_retries)
9
 
10
  def solve_file(self, file_path: str) -> bool:
 
4
  class ProofAgent:
5
  """Thin compatibility wrapper around LangGraphAgent."""
6
 
7
+ def __init__(self, model_name: str = "llama-3.3-70b-versatile", max_retries: int = 5):
8
  self._agent = LangGraphAgent(model_name=model_name, max_retries=max_retries)
9
 
10
  def solve_file(self, file_path: str) -> bool:
tests/test_app_fuzz.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fuzz tests for `app.solve_proof`.
3
+
4
+ These tests exercise a fixed corpus of edge-case inputs against
5
+ `app.solve_proof` and assert:
6
+ * every call returns a (status_html, final_code, logs) 3-tuple,
7
+ * no call crashes (uncaught exceptions),
8
+ * the right status messages are produced for each scenario,
9
+ * the temp file `solve_proof` creates is always cleaned up,
10
+ *even* when the underlying agent raises.
11
+
12
+ We mock `langgraph_agent.LangGraphAgent` BEFORE importing `app` so no Lean,
13
+ LLM, or FAISS infrastructure is needed.
14
+ """
15
+
16
+ import io
17
+ import os
18
+ import sys
19
+ import tempfile
20
+ import threading
21
+ import unittest
22
+ from unittest import mock
23
+
24
+ # Make `app.py` and `src/` importable.
25
+ sys.path.insert(0, ".")
26
+ sys.path.insert(0, "src")
27
+
28
+
29
+ # ----- Mock LangGraphAgent BEFORE importing app -----------------------------
30
+ _fake_lg_module = mock.MagicMock()
31
+
32
+
33
+ class _DummyAgent:
34
+ """Stand-in for LangGraphAgent. Configured per-test via class attributes."""
35
+
36
+ # Per-test knobs.
37
+ # If set, __init__ records (model_name, max_retries) here.
38
+ init_log: list = []
39
+ # If set, solve_file_detailed raises this instance instead of returning.
40
+ raise_exc: BaseException | None = None
41
+ # If set, this dict is returned from solve_file_detailed.
42
+ result: dict = {
43
+ "success": True,
44
+ "solved_at_attempt": 1,
45
+ "total_attempts": 1,
46
+ }
47
+ # Record temp file path the agent was passed, plus the bytes on disk.
48
+ last_path: str | None = None
49
+ last_bytes: bytes | None = None
50
+
51
+ def __init__(self, model_name="x", max_retries=5):
52
+ self.model_name = model_name
53
+ self.max_retries = max_retries
54
+ _DummyAgent.init_log.append((model_name, max_retries))
55
+
56
+ def solve_file_detailed(self, file_path: str) -> dict:
57
+ _DummyAgent.last_path = file_path
58
+ try:
59
+ with open(file_path, "rb") as f:
60
+ _DummyAgent.last_bytes = f.read()
61
+ except OSError:
62
+ _DummyAgent.last_bytes = None
63
+
64
+ if _DummyAgent.raise_exc is not None:
65
+ raise _DummyAgent.raise_exc
66
+ return _DummyAgent.result
67
+
68
+
69
+ _fake_lg_module.LangGraphAgent = _DummyAgent
70
+ sys.modules["langgraph_agent"] = _fake_lg_module
71
+
72
+ # Default to having a key set; individual tests override this.
73
+ os.environ.setdefault("GROQ_API_KEY", "test-key")
74
+
75
+ import app # noqa: E402 (must come after the mock above)
76
+
77
+
78
+ # Sentinels for the fuzz corpus -----------------------------------------------
79
+ EMPTY = ""
80
+ WHITESPACE = " \n\t "
81
+ HUGE = "a" * 100_000
82
+ UNICODE = "theorem foo : โˆ€ n : โ„•, โˆƒ m : โ„•, n + m = m + n := by sorry"
83
+ NO_SORRY = "theorem foo : True := trivial"
84
+
85
+
86
+ def _wrap_namedtemp(captured: list[str], lock: threading.Lock):
87
+ """Return a side_effect for `tempfile.NamedTemporaryFile` that records the
88
+ name of every actual tempfile created so callers can assert cleanup."""
89
+ real_ntf = tempfile.NamedTemporaryFile
90
+
91
+ def factory(*args, **kwargs):
92
+ f = real_ntf(*args, **kwargs)
93
+ with lock:
94
+ captured.append(f.name)
95
+ return f
96
+
97
+ return factory
98
+
99
+
100
+ class SolveProofFuzzTests(unittest.TestCase):
101
+ """Each scenario from the fuzz corpus."""
102
+
103
+ def setUp(self):
104
+ # Reset the dummy agent's class-level knobs.
105
+ _DummyAgent.init_log = []
106
+ _DummyAgent.raise_exc = None
107
+ _DummyAgent.result = {
108
+ "success": True,
109
+ "solved_at_attempt": 1,
110
+ "total_attempts": 1,
111
+ }
112
+ _DummyAgent.last_path = None
113
+ _DummyAgent.last_bytes = None
114
+
115
+ # Make sure GROQ_API_KEY is set unless a test clears it.
116
+ os.environ["GROQ_API_KEY"] = "test-key"
117
+
118
+ self._captured_paths: list[str] = []
119
+ self._capture_lock = threading.Lock()
120
+ self._ntf_patch = mock.patch.object(
121
+ app.tempfile,
122
+ "NamedTemporaryFile",
123
+ side_effect=_wrap_namedtemp(self._captured_paths, self._capture_lock),
124
+ )
125
+ self._ntf_patch.start()
126
+
127
+ def tearDown(self):
128
+ self._ntf_patch.stop()
129
+ # Best-effort: clean up anything the test leaked so /tmp doesn't fill.
130
+ for path in self._captured_paths:
131
+ if os.path.exists(path):
132
+ try:
133
+ os.unlink(path)
134
+ except OSError:
135
+ pass
136
+
137
+ # ------------------------------------------------------------------
138
+ # Helpers
139
+ # ------------------------------------------------------------------
140
+ def _assert_triple(self, ret):
141
+ self.assertIsInstance(ret, tuple, f"return is not tuple: {ret!r}")
142
+ self.assertEqual(len(ret), 3, f"return is not length-3 tuple: {ret!r}")
143
+ status, code, logs = ret
144
+ self.assertIsInstance(status, str)
145
+ self.assertIsInstance(code, str)
146
+ self.assertIsInstance(logs, str)
147
+ return status, code, logs
148
+
149
+ def _assert_temp_cleaned(self):
150
+ """Every tempfile we observed must be gone now."""
151
+ for path in self._captured_paths:
152
+ self.assertFalse(
153
+ os.path.exists(path),
154
+ f"tempfile leaked: {path} still exists",
155
+ )
156
+
157
+ # ------------------------------------------------------------------
158
+ # Empty string -> "No input"
159
+ # ------------------------------------------------------------------
160
+ def test_empty_string_returns_no_input(self):
161
+ ret = app.solve_proof(EMPTY, "llama-3.3-70b-versatile", 1)
162
+ status, code, logs = self._assert_triple(ret)
163
+ self.assertIn("No input", status)
164
+ # No tempfile should have been created at all for empty input.
165
+ self.assertEqual(self._captured_paths, [])
166
+ self.assertEqual(code, "")
167
+ self.assertEqual(logs, "")
168
+
169
+ # ------------------------------------------------------------------
170
+ # Whitespace-only -> "No input"
171
+ # ------------------------------------------------------------------
172
+ def test_whitespace_only_returns_no_input(self):
173
+ ret = app.solve_proof(WHITESPACE, "llama-3.3-70b-versatile", 1)
174
+ status, code, logs = self._assert_triple(ret)
175
+ self.assertIn("No input", status)
176
+ self.assertEqual(self._captured_paths, [])
177
+
178
+ # ------------------------------------------------------------------
179
+ # 100KB string must not OOM/crash.
180
+ # ------------------------------------------------------------------
181
+ def test_huge_input_does_not_crash(self):
182
+ ret = app.solve_proof(HUGE, "llama-3.3-70b-versatile", 1)
183
+ status, code, logs = self._assert_triple(ret)
184
+ # Should pass through to the agent (which returns success).
185
+ self.assertIn("Verified", status)
186
+ # The agent must have seen the full 100k bytes.
187
+ self.assertIsNotNone(_DummyAgent.last_bytes)
188
+ self.assertEqual(len(_DummyAgent.last_bytes), 100_000)
189
+ self._assert_temp_cleaned()
190
+
191
+ # ------------------------------------------------------------------
192
+ # Unicode-heavy: must encode UTF-8 to temp file successfully.
193
+ # ------------------------------------------------------------------
194
+ def test_unicode_heavy_encodes_utf8(self):
195
+ ret = app.solve_proof(UNICODE, "llama-3.3-70b-versatile", 1)
196
+ status, code, logs = self._assert_triple(ret)
197
+ self.assertIn("Verified", status)
198
+
199
+ # The bytes the agent saw must be the UTF-8 encoding of UNICODE.
200
+ self.assertIsNotNone(_DummyAgent.last_bytes)
201
+ self.assertEqual(_DummyAgent.last_bytes, UNICODE.encode("utf-8"))
202
+
203
+ # The `code` returned (read back from disk) must round-trip.
204
+ self.assertEqual(code, UNICODE)
205
+
206
+ self._assert_temp_cleaned()
207
+
208
+ # ------------------------------------------------------------------
209
+ # Unicode-heavy under simulated POSIX/ASCII locale.
210
+ #
211
+ # On systems where `locale.getpreferredencoding()` is ASCII (e.g. some
212
+ # Docker containers, HuggingFace Spaces with PYTHONUTF8=0 + LC_ALL=C),
213
+ # `open(path, "w")` without an explicit encoding will reject characters
214
+ # like โˆ€, โ„•, โˆƒ. The fix is to pass `encoding="utf-8"` explicitly when
215
+ # writing the temp file and reading it back.
216
+ #
217
+ # We force ASCII mode by patching the builtins/tempfile callables that
218
+ # `app.solve_proof` uses, defaulting `encoding="ascii"` whenever the
219
+ # caller didn't specify one. If the implementation forgot to pass
220
+ # encoding="utf-8", the unicode write/read will UnicodeEncode/DecodeError.
221
+ # ------------------------------------------------------------------
222
+ def test_unicode_heavy_under_ascii_locale(self):
223
+ real_open = open
224
+ real_ntf = tempfile.NamedTemporaryFile
225
+
226
+ def ascii_open(*args, **kwargs):
227
+ # In text mode (no "b"), default to ASCII if no encoding given.
228
+ mode = kwargs.get("mode")
229
+ if mode is None and len(args) >= 2:
230
+ mode = args[1]
231
+ if mode is None:
232
+ mode = "r"
233
+ if "b" not in mode and "encoding" not in kwargs:
234
+ kwargs["encoding"] = "ascii"
235
+ return real_open(*args, **kwargs)
236
+
237
+ def ascii_ntf(*args, **kwargs):
238
+ mode = kwargs.get("mode", "w+b")
239
+ if "b" not in mode and "encoding" not in kwargs:
240
+ kwargs["encoding"] = "ascii"
241
+ return real_ntf(*args, **kwargs)
242
+
243
+ with mock.patch.object(app.tempfile, "NamedTemporaryFile",
244
+ side_effect=ascii_ntf), \
245
+ mock.patch("builtins.open", side_effect=ascii_open):
246
+ ret = app.solve_proof(UNICODE, "llama-3.3-70b-versatile", 1)
247
+
248
+ status, code, logs = self._assert_triple(ret)
249
+ # Must NOT crash with a UnicodeError leaking through as "Error:".
250
+ self.assertNotIn(
251
+ "UnicodeEncodeError", status,
252
+ f"solve_proof leaked UnicodeEncodeError under ASCII locale: {status!r}",
253
+ )
254
+ self.assertNotIn(
255
+ "UnicodeDecodeError", status,
256
+ f"solve_proof leaked UnicodeDecodeError under ASCII locale: {status!r}",
257
+ )
258
+ # Must produce a Verified status: the agent didn't fail, the encoding
259
+ # plumbing must transparently use utf-8.
260
+ self.assertIn(
261
+ "Verified", status,
262
+ f"solve_proof returned non-Verified status under ASCII locale: {status!r}",
263
+ )
264
+ self.assertEqual(code, UNICODE)
265
+ self._assert_temp_cleaned()
266
+
267
+ # ------------------------------------------------------------------
268
+ # GROQ_API_KEY unset -> "GROQ_API_KEY missing"
269
+ # ------------------------------------------------------------------
270
+ def test_missing_groq_api_key(self):
271
+ with mock.patch.dict(os.environ, {}, clear=True):
272
+ ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 1)
273
+ status, code, logs = self._assert_triple(ret)
274
+ self.assertIn("GROQ_API_KEY missing", status)
275
+ # No tempfile created -- function short-circuits.
276
+ self.assertEqual(self._captured_paths, [])
277
+ self.assertEqual(code, "")
278
+ self.assertEqual(logs, "")
279
+
280
+ # ------------------------------------------------------------------
281
+ # Agent raises -> "Error:" status; temp file still cleaned up.
282
+ # ------------------------------------------------------------------
283
+ def test_agent_raises_runtime_error(self):
284
+ _DummyAgent.raise_exc = RuntimeError("synthetic blow-up")
285
+ ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 1)
286
+ status, code, logs = self._assert_triple(ret)
287
+ self.assertIn("Error", status)
288
+ self.assertIn("synthetic blow-up", status)
289
+ self.assertEqual(code, "")
290
+ # Most important: temp file must be cleaned up even on exception.
291
+ self.assertEqual(len(self._captured_paths), 1)
292
+ self._assert_temp_cleaned()
293
+
294
+ # ------------------------------------------------------------------
295
+ # Agent reports success -> "Verified" status.
296
+ # ------------------------------------------------------------------
297
+ def test_agent_success(self):
298
+ _DummyAgent.result = {
299
+ "success": True,
300
+ "solved_at_attempt": 2,
301
+ "total_attempts": 3,
302
+ }
303
+ ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 3)
304
+ status, code, logs = self._assert_triple(ret)
305
+ self.assertIn("Verified", status)
306
+ self.assertIn("2", status)
307
+ self.assertIn("3", status)
308
+ self._assert_temp_cleaned()
309
+
310
+ # ------------------------------------------------------------------
311
+ # Agent reports failure -> "No proof found" status.
312
+ # ------------------------------------------------------------------
313
+ def test_agent_failure(self):
314
+ _DummyAgent.result = {
315
+ "success": False,
316
+ "solved_at_attempt": None,
317
+ "total_attempts": 5,
318
+ }
319
+ ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 5)
320
+ status, code, logs = self._assert_triple(ret)
321
+ self.assertIn("No proof found", status)
322
+ self.assertIn("5", status)
323
+ self._assert_temp_cleaned()
324
+
325
+ # ------------------------------------------------------------------
326
+ # Code without `sorry` should still pass through unchanged.
327
+ # ------------------------------------------------------------------
328
+ def test_no_sorry_keyword_passes_through(self):
329
+ ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 1)
330
+ status, code, logs = self._assert_triple(ret)
331
+ self.assertIn("Verified", status)
332
+ self.assertEqual(code, NO_SORRY)
333
+ # Bytes seen by agent must equal the input encoded as utf-8.
334
+ self.assertEqual(_DummyAgent.last_bytes, NO_SORRY.encode("utf-8"))
335
+ self._assert_temp_cleaned()
336
+
337
+ # ------------------------------------------------------------------
338
+ # Sanity: tempfile cleanup verified for every scenario in one place.
339
+ # ------------------------------------------------------------------
340
+ def test_temp_file_always_cleaned_up(self):
341
+ """Run every non-short-circuit scenario and assert no tempfile leaks."""
342
+ scenarios = [
343
+ ("ok", NO_SORRY, None),
344
+ ("huge", HUGE, None),
345
+ ("unicode", UNICODE, None),
346
+ ("raise", NO_SORRY, RuntimeError("boom")),
347
+ ]
348
+ for label, code_in, exc in scenarios:
349
+ _DummyAgent.raise_exc = exc
350
+ with self.subTest(label):
351
+ app.solve_proof(code_in, "llama-3.3-70b-versatile", 1)
352
+ _DummyAgent.raise_exc = None
353
+ self._assert_temp_cleaned()
354
+
355
+
356
+ if __name__ == "__main__":
357
+ unittest.main()
tests/test_concurrent_solve.py CHANGED
@@ -93,6 +93,13 @@ class ConcurrentSolveTests(unittest.TestCase):
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
 
 
93
  _DummyAgent.sleep_seconds = 0.0
94
  _DummyAgent.raise_token = None
95
  _DummyAgent.print_tag = False
96
+ # Per-test patch: `app.solve_proof` does `from langgraph_agent import
97
+ # LangGraphAgent` at import time, so `app.LangGraphAgent` is bound to
98
+ # whichever module-level mock loaded first. Other test files do the
99
+ # same trick and can win the race, so we patch on `app` directly.
100
+ self._lg_patcher = mock.patch.object(app, "LangGraphAgent", _DummyAgent)
101
+ self._lg_patcher.start()
102
+ self.addCleanup(self._lg_patcher.stop)
103
  # Snapshot pre-existing tmp .lean files so we ignore unrelated ones.
104
  self._tmp_before = _scan_tmp_lean()
105
 
tests/test_manual_bug_fixes.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Regression tests for bugs found in a manual code review (no agent involved).
3
+
4
+ Each test locks in a specific fix; if any of these start failing, a previously
5
+ fixed bug has been reintroduced.
6
+ """
7
+
8
+ import importlib
9
+ import os
10
+ import sys
11
+ import tempfile
12
+ import unittest
13
+ from unittest import mock
14
+
15
+ sys.path.insert(0, "src")
16
+
17
+ # Other test files (test_app_fuzz, test_concurrent_solve) install a MagicMock
18
+ # in `sys.modules["langgraph_agent"]`, which would shadow the real module and
19
+ # make our helpers return MagicMocks instead of ints/strings. Evict the cached
20
+ # mock so we get a fresh, real import.
21
+ sys.modules.pop("langgraph_agent", None)
22
+
23
+ # `langgraph_agent` imports lean_verifier + retriever + rag_chain which each
24
+ # pull in heavyweight ML libs. Mock those three modules directly so we can
25
+ # import the helpers without installing langchain-groq / lean-interact.
26
+ for _mod in ("lean_verifier", "retriever", "rag_chain"):
27
+ sys.modules[_mod] = mock.MagicMock()
28
+
29
+ import langgraph_agent
30
+ importlib.reload(langgraph_agent) # ensure regex/keyword changes are picked up
31
+ _count_theorem_blocks = langgraph_agent._count_theorem_blocks
32
+ _extract_lean_code = langgraph_agent._extract_lean_code
33
+ _read_file = langgraph_agent._read_file
34
+ _write_file = langgraph_agent._write_file
35
+
36
+
37
+ class TestCountTheoremBlocksKeywordFix(unittest.TestCase):
38
+ """
39
+ The old `_THEOREM_KEYWORDS = ("example", "theorem ", "lemma ", "def ")`
40
+ tuple had inconsistent trailing spaces:
41
+ - `theorem\nfoo` returned 0 (false negative โ€” `theorem ` requires a space)
42
+ - `examplelike` returned 1 (false positive โ€” `example` has no boundary)
43
+ Fixed by switching to a regex with a proper boundary class.
44
+ """
45
+
46
+ def test_theorem_followed_by_newline_counts(self):
47
+ self.assertEqual(_count_theorem_blocks("theorem\nfoo := rfl"), 1)
48
+
49
+ def test_examplelike_does_not_match(self):
50
+ self.assertEqual(_count_theorem_blocks("examplelike := 5"), 0)
51
+
52
+ def test_indented_theorem_counts(self):
53
+ self.assertEqual(_count_theorem_blocks(" theorem foo : True := trivial"), 1)
54
+
55
+ def test_theorem_with_colon_immediately(self):
56
+ # `theorem:` (no space) should NOT match โ€” only valid Lean syntax counts.
57
+ self.assertEqual(_count_theorem_blocks("theorem:bar"), 0)
58
+
59
+ def test_theorem_with_paren_immediately_does_NOT_count(self):
60
+ # Not valid Lean โ€” declaration name must come before `(`.
61
+ self.assertEqual(_count_theorem_blocks("theorem(x : Nat) : True := trivial"), 0)
62
+
63
+ def test_mixed_keywords_each_count(self):
64
+ code = (
65
+ "example : True := trivial\n"
66
+ "theorem foo : True := trivial\n"
67
+ "lemma bar : True := trivial\n"
68
+ "def baz : Nat := 0\n"
69
+ )
70
+ self.assertEqual(_count_theorem_blocks(code), 4)
71
+
72
+
73
+ class TestExtractLeanCodeFenceVariants(unittest.TestCase):
74
+ """
75
+ `_extract_lean_code` used to do `text.split("```lean")[1]` which would
76
+ leave a `4` at the start when the fence was `\`\`\`lean4` (a common LLM
77
+ output). Now uses a regex that requires the lean tag to be terminated by
78
+ whitespace.
79
+ """
80
+
81
+ def test_lean_fence(self):
82
+ self.assertEqual(
83
+ _extract_lean_code("```lean\nfoo := rfl\n```"),
84
+ "foo := rfl",
85
+ )
86
+
87
+ def test_lean4_fence_does_not_leak_digit(self):
88
+ # Old behavior: returned "4\nfoo := rfl"
89
+ self.assertEqual(
90
+ _extract_lean_code("```lean4\nfoo := rfl\n```"),
91
+ "foo := rfl",
92
+ )
93
+
94
+ def test_uppercase_lean_fence(self):
95
+ self.assertEqual(
96
+ _extract_lean_code("```Lean\nfoo := rfl\n```"),
97
+ "foo := rfl",
98
+ )
99
+
100
+ def test_no_fence_returns_stripped(self):
101
+ self.assertEqual(_extract_lean_code(" foo := rfl "), "foo := rfl")
102
+
103
+ def test_untagged_fence(self):
104
+ self.assertEqual(_extract_lean_code("```\nfoo := rfl\n```"), "foo := rfl")
105
+
106
+ def test_leanish_tag_falls_through_to_untagged(self):
107
+ # `leanish` isn't a recognized Lean fence, so the function should fall
108
+ # through to the untagged-fence branch. That branch returns the raw
109
+ # fenced content as-is (including "leanish" on the first line) โ€” Lean
110
+ # will then reject it as a syntax error and we retry. The important
111
+ # thing is no crash.
112
+ result = _extract_lean_code("```leanish\nfoo\n```")
113
+ self.assertIn("foo", result)
114
+
115
+
116
+ class TestUtf8FileIO(unittest.TestCase):
117
+ """
118
+ `_read_file` / `_write_file` previously used the platform default encoding,
119
+ which is C/ASCII on minimal Docker images and would crash on Lean unicode.
120
+ """
121
+
122
+ def test_round_trip_unicode_lean(self):
123
+ code = "theorem foo : โˆ€ n : โ„•, โˆƒ m, n + m = m + n := by sorry"
124
+ with tempfile.NamedTemporaryFile(suffix=".lean", mode="w",
125
+ delete=False, encoding="utf-8") as f:
126
+ path = f.name
127
+ try:
128
+ _write_file(path, code)
129
+ self.assertEqual(_read_file(path), code)
130
+ finally:
131
+ os.unlink(path)
132
+
133
+
134
+ class TestProofAgentDefaultModel(unittest.TestCase):
135
+ """
136
+ `ProofAgent` used to default to `qwen3-vl:4b` (an Ollama model name) after
137
+ the Groq migration, which would fail at runtime. Now defaults to a real
138
+ Groq model.
139
+ """
140
+
141
+ def test_default_model_is_not_a_stale_ollama_name(self):
142
+ # Inspect the function default directly โ€” avoids needing a working
143
+ # LangGraphAgent mock chain.
144
+ import inspect
145
+ import proof_agent
146
+
147
+ sig = inspect.signature(proof_agent.ProofAgent.__init__)
148
+ default = sig.parameters["model_name"].default
149
+ self.assertNotIn("qwen", default.lower())
150
+ self.assertNotIn(":", default,
151
+ "Default looks like an Ollama 'name:tag' format")
152
+
153
+
154
+ if __name__ == "__main__":
155
+ unittest.main()