Spaces:
Sleeping
Sleeping
Merge pull request #15 from ray5th/fuzz/solve-proof-corpus
Browse filesFiles changed (8)
- app.py+12-2
- src/langgraph_agent.py+33-7
- src/lean_verifier.py+23-3
- src/lmm_client.py+8-1
- src/proof_agent.py+1-1
- tests/test_app_fuzz.pyAdded+357
- tests/test_concurrent_solve.py+7
- tests/test_manual_bug_fixes.pyAdded+155
280 unmodified lines2812822832842852862875 unmodified lines293294295296297298299280 unmodified linestmp_path = Nonetry:tmp = tempfile.NamedTemporaryFile(suffix=".lean", mode="w", delete=False, dir="/tmp")tmp_path = tmp.nametmp.write(lean_code)tmp.close()5 unmodified linesagent = LangGraphAgent(model_name=model_name, max_retries=int(max_retries))result = agent.solve_file_detailed(tmp_path)with open(tmp_path) as f:final_code = f.read()logs = log_buf.getvalue()280 unmodified lines2812822832842852862872882892902912922932942952962975 unmodified lines303304305306307308309280 unmodified linestmp_path = Nonetry:# Lean source frequently contains unicode (โ โ โ โ etc.). On platforms# where the preferred encoding is not UTF-8 (e.g. POSIX/C locale),# opening text mode without an explicit encoding can blow up with# UnicodeEncodeError / UnicodeDecodeError. Force UTF-8 on both ends.tmp = tempfile.NamedTemporaryFile(suffix=".lean",mode="w",delete=False,dir="/tmp",encoding="utf-8",)tmp_path = tmp.nametmp.write(lean_code)tmp.close()5 unmodified linesagent = LangGraphAgent(model_name=model_name, max_retries=int(max_retries))result = agent.solve_file_detailed(tmp_path)with open(tmp_path, encoding="utf-8") as f:final_code = f.read()logs = log_buf.getvalue()
123424 unmodified lines29303132333435363738394041424344454647488 unmodified lines57585960616263646566676869import osfrom typing import List, TypedDictfrom langgraph.graph import END, StateGraph24 unmodified lines# ---------------------------------------------------------------------------def _read_file(path: str) -> str:with open(path, "r") as f:return f.read()def _write_file(path: str, code: str) -> None:with open(path, "w") as f:f.write(code)def _extract_lean_code(text: str) -> str:if "```lean" in text:return text.split("```lean")[1].split("```")[0].strip()if "```" in text:return text.split("```")[1].split("```")[0].strip()return text.strip()8 unmodified linesreturn "import Mathlib\n\n" + "\n".join(non_import_lines).lstrip()_THEOREM_KEYWORDS = ("example", "theorem ", "lemma ", "def ")def _count_theorem_blocks(code: str) -> int:return sum(1 for line in code.splitlines()if any(line.strip().startswith(kw) for kw in _THEOREM_KEYWORDS))1234524 unmodified lines30313233343536373839404142434445464748495051525354555657585960616263646566676869708 unmodified lines7980818283848586878889909192939495import osimport refrom typing import List, TypedDictfrom langgraph.graph import END, StateGraph24 unmodified lines# ---------------------------------------------------------------------------def _read_file(path: str) -> str:# Lean source uses โ โ โ โ etc. Force UTF-8 so non-UTF-8 default locales# (e.g. C/POSIX inside minimal Docker images) don't corrupt or crash on# read.with open(path, "r", encoding="utf-8") as f:return f.read()def _write_file(path: str, code: str) -> None:with open(path, "w", encoding="utf-8") as f:f.write(code)# Match an opening fence tagged `lean` (or `lean4`, `Lean`, etc.) followed by a# newline or whitespace โ but NOT something like ```leanish that would# accidentally consume the "ish" into the code body._LEAN_FENCE_RE = re.compile(r"```\s*lean[0-9]*\s*\n", re.IGNORECASE)def _extract_lean_code(text: str) -> str:"""Extract the Lean code block from an LLM response.Handles:- ```lean\n...\n``` (canonical)- ```lean4\n...\n``` (some LLMs)- ```Lean\n...\n``` (case variation)- ```\n...\n``` (no language tag)- plain text without fences (returned as-is)"""m = _LEAN_FENCE_RE.search(text)if m:rest = text[m.end():]return rest.split("```", 1)[0].strip()if "```" in text:return text.split("```", 1)[1].split("```", 1)[0].strip()return text.strip()8 unmodified linesreturn "import Mathlib\n\n" + "\n".join(non_import_lines).lstrip()# A declaration keyword must be followed by whitespace or end-of-line so that# `examplelike` (false positive) doesn't match and `theorem\n` (no trailing# space) does match. `theorem:` and `theorem(` are not valid Lean syntax# (the declaration name must come first), so we don't allow those either._THEOREM_KEYWORD_RE = re.compile(r"^\s*(?:example|theorem|lemma|def)(?:\s|$)")def _count_theorem_blocks(code: str) -> int:return sum(1 for line in code.splitlines()if _THEOREM_KEYWORD_RE.match(line))
34 unmodified lines353637383940414243444546474834 unmodified linesdef verify_proof(self, lean_code: str) -> Dict[str, Any]:"""Executes a block of Lean code and verifies if it is a correct proof.Args:lean_code (str): The full Lean 4 code string containing imports, theorem statement, and proof.Returns:dict: A dictionary containing the status, errors (if any), and goals (if open sorries remain)."""response = self.server.run(Command(cmd=lean_code))errors = []goals = []34 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676834 unmodified linesdef verify_proof(self, lean_code: str) -> Dict[str, Any]:"""Executes a block of Lean code and verifies if it is a correct proof.Args:lean_code (str): The full Lean 4 code string containing imports, theorem statement, and proof.Returns:dict: A dictionary containing the status, errors (if any), and goals (if open sorries remain)."""# Guard: empty/whitespace input would crash `Command(cmd=...)` with a# pydantic ValidationError (min_length=1). Return a clean failure.if not lean_code or not lean_code.strip():return {"status": "failure","errors": ["empty Lean code: nothing to verify"],"goals": [],"env": None,}# Guard: LeanServer can raise on disconnect / crash / OOM. Surface as a# failure result so the agent's retry loop continues instead of dying.try:response = self.server.run(Command(cmd=lean_code))except Exception as exc:return {"status": "failure","errors": [f"Lean server error: {exc}"],"goals": [],"env": None,}errors = []goals = []
21 unmodified lines2223242526272821 unmodified linesmessages=messages,max_tokens=1024,)return response.choices[0].message.contentdef generate_proof_steps(self, lean_code: str, goals: List[str], errors: List[str]) -> str:system_prompt = (21 unmodified lines222324252627282930313233343521 unmodified linesmessages=messages,max_tokens=1024,)# Defensive: Groq can return empty `choices` on content filter / quota# issues โ accessing [0] would IndexError and kill the agent.choices = getattr(response, "choices", None) or []if not choices:return ""message = getattr(choices[0], "message", None)content = getattr(message, "content", None) if message else Nonereturn content or ""def generate_proof_steps(self, lean_code: str, goals: List[str], errors: List[str]) -> str:system_prompt = (
3 unmodified lines456789103 unmodified linesclass ProofAgent:"""Thin compatibility wrapper around LangGraphAgent."""def __init__(self, model_name: str = "qwen3-vl:4b", max_retries: int = 5):self._agent = LangGraphAgent(model_name=model_name, max_retries=max_retries)def solve_file(self, file_path: str) -> bool:3 unmodified lines456789103 unmodified linesclass ProofAgent:"""Thin compatibility wrapper around LangGraphAgent."""def __init__(self, model_name: str = "llama-3.3-70b-versatile", max_retries: int = 5):self._agent = LangGraphAgent(model_name=model_name, max_retries=max_retries)def solve_file(self, file_path: str) -> bool:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357"""Fuzz tests for `app.solve_proof`.
These tests exercise a fixed corpus of edge-case inputs against`app.solve_proof` and assert: * every call returns a (status_html, final_code, logs) 3-tuple, * no call crashes (uncaught exceptions), * the right status messages are produced for each scenario, * the temp file `solve_proof` creates is always cleaned up, *even* when the underlying agent raises.
We mock `langgraph_agent.LangGraphAgent` BEFORE importing `app` so no Lean,LLM, or FAISS infrastructure is needed."""
import ioimport osimport sysimport tempfileimport threadingimport unittestfrom unittest import mock
# Make `app.py` and `src/` importable.sys.path.insert(0, ".")sys.path.insert(0, "src")
# ----- Mock LangGraphAgent BEFORE importing app -----------------------------_fake_lg_module = mock.MagicMock()
class _DummyAgent: """Stand-in for LangGraphAgent. Configured per-test via class attributes."""
# Per-test knobs. # If set, __init__ records (model_name, max_retries) here. init_log: list = [] # If set, solve_file_detailed raises this instance instead of returning. raise_exc: BaseException | None = None # If set, this dict is returned from solve_file_detailed. result: dict = { "success": True, "solved_at_attempt": 1, "total_attempts": 1, } # Record temp file path the agent was passed, plus the bytes on disk. last_path: str | None = None last_bytes: bytes | None = None
def __init__(self, model_name="x", max_retries=5): self.model_name = model_name self.max_retries = max_retries _DummyAgent.init_log.append((model_name, max_retries))
def solve_file_detailed(self, file_path: str) -> dict: _DummyAgent.last_path = file_path try: with open(file_path, "rb") as f: _DummyAgent.last_bytes = f.read() except OSError: _DummyAgent.last_bytes = None
if _DummyAgent.raise_exc is not None: raise _DummyAgent.raise_exc return _DummyAgent.result
_fake_lg_module.LangGraphAgent = _DummyAgentsys.modules["langgraph_agent"] = _fake_lg_module
# Default to having a key set; individual tests override this.os.environ.setdefault("GROQ_API_KEY", "test-key")
import app # noqa: E402 (must come after the mock above)
# Sentinels for the fuzz corpus -----------------------------------------------EMPTY = ""WHITESPACE = " \n\t "HUGE = "a" * 100_000UNICODE = "theorem foo : โ n : โ, โ m : โ, n + m = m + n := by sorry"NO_SORRY = "theorem foo : True := trivial"
def _wrap_namedtemp(captured: list[str], lock: threading.Lock): """Return a side_effect for `tempfile.NamedTemporaryFile` that records the name of every actual tempfile created so callers can assert cleanup.""" real_ntf = tempfile.NamedTemporaryFile
def factory(*args, **kwargs): f = real_ntf(*args, **kwargs) with lock: captured.append(f.name) return f
return factory
class SolveProofFuzzTests(unittest.TestCase): """Each scenario from the fuzz corpus."""
def setUp(self): # Reset the dummy agent's class-level knobs. _DummyAgent.init_log = [] _DummyAgent.raise_exc = None _DummyAgent.result = { "success": True, "solved_at_attempt": 1, "total_attempts": 1, } _DummyAgent.last_path = None _DummyAgent.last_bytes = None
# Make sure GROQ_API_KEY is set unless a test clears it. os.environ["GROQ_API_KEY"] = "test-key"
self._captured_paths: list[str] = [] self._capture_lock = threading.Lock() self._ntf_patch = mock.patch.object( app.tempfile, "NamedTemporaryFile", side_effect=_wrap_namedtemp(self._captured_paths, self._capture_lock), ) self._ntf_patch.start()
def tearDown(self): self._ntf_patch.stop() # Best-effort: clean up anything the test leaked so /tmp doesn't fill. for path in self._captured_paths: if os.path.exists(path): try: os.unlink(path) except OSError: pass
# ------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------ def _assert_triple(self, ret): self.assertIsInstance(ret, tuple, f"return is not tuple: {ret!r}") self.assertEqual(len(ret), 3, f"return is not length-3 tuple: {ret!r}") status, code, logs = ret self.assertIsInstance(status, str) self.assertIsInstance(code, str) self.assertIsInstance(logs, str) return status, code, logs
def _assert_temp_cleaned(self): """Every tempfile we observed must be gone now.""" for path in self._captured_paths: self.assertFalse( os.path.exists(path), f"tempfile leaked: {path} still exists", )
# ------------------------------------------------------------------ # Empty string -> "No input" # ------------------------------------------------------------------ def test_empty_string_returns_no_input(self): ret = app.solve_proof(EMPTY, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) self.assertIn("No input", status) # No tempfile should have been created at all for empty input. self.assertEqual(self._captured_paths, []) self.assertEqual(code, "") self.assertEqual(logs, "")
# ------------------------------------------------------------------ # Whitespace-only -> "No input" # ------------------------------------------------------------------ def test_whitespace_only_returns_no_input(self): ret = app.solve_proof(WHITESPACE, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) self.assertIn("No input", status) self.assertEqual(self._captured_paths, [])
# ------------------------------------------------------------------ # 100KB string must not OOM/crash. # ------------------------------------------------------------------ def test_huge_input_does_not_crash(self): ret = app.solve_proof(HUGE, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) # Should pass through to the agent (which returns success). self.assertIn("Verified", status) # The agent must have seen the full 100k bytes. self.assertIsNotNone(_DummyAgent.last_bytes) self.assertEqual(len(_DummyAgent.last_bytes), 100_000) self._assert_temp_cleaned()
# ------------------------------------------------------------------ # Unicode-heavy: must encode UTF-8 to temp file successfully. # ------------------------------------------------------------------ def test_unicode_heavy_encodes_utf8(self): ret = app.solve_proof(UNICODE, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) self.assertIn("Verified", status)
# The bytes the agent saw must be the UTF-8 encoding of UNICODE. self.assertIsNotNone(_DummyAgent.last_bytes) self.assertEqual(_DummyAgent.last_bytes, UNICODE.encode("utf-8"))
# The `code` returned (read back from disk) must round-trip. self.assertEqual(code, UNICODE)
self._assert_temp_cleaned()
# ------------------------------------------------------------------ # Unicode-heavy under simulated POSIX/ASCII locale. # # On systems where `locale.getpreferredencoding()` is ASCII (e.g. some # Docker containers, HuggingFace Spaces with PYTHONUTF8=0 + LC_ALL=C), # `open(path, "w")` without an explicit encoding will reject characters # like โ, โ, โ. The fix is to pass `encoding="utf-8"` explicitly when # writing the temp file and reading it back. # # We force ASCII mode by patching the builtins/tempfile callables that # `app.solve_proof` uses, defaulting `encoding="ascii"` whenever the # caller didn't specify one. If the implementation forgot to pass # encoding="utf-8", the unicode write/read will UnicodeEncode/DecodeError. # ------------------------------------------------------------------ def test_unicode_heavy_under_ascii_locale(self): real_open = open real_ntf = tempfile.NamedTemporaryFile
def ascii_open(*args, **kwargs): # In text mode (no "b"), default to ASCII if no encoding given. mode = kwargs.get("mode") if mode is None and len(args) >= 2: mode = args[1] if mode is None: mode = "r" if "b" not in mode and "encoding" not in kwargs: kwargs["encoding"] = "ascii" return real_open(*args, **kwargs)
def ascii_ntf(*args, **kwargs): mode = kwargs.get("mode", "w+b") if "b" not in mode and "encoding" not in kwargs: kwargs["encoding"] = "ascii" return real_ntf(*args, **kwargs)
with mock.patch.object(app.tempfile, "NamedTemporaryFile", side_effect=ascii_ntf), \ mock.patch("builtins.open", side_effect=ascii_open): ret = app.solve_proof(UNICODE, "llama-3.3-70b-versatile", 1)
status, code, logs = self._assert_triple(ret) # Must NOT crash with a UnicodeError leaking through as "Error:". self.assertNotIn( "UnicodeEncodeError", status, f"solve_proof leaked UnicodeEncodeError under ASCII locale: {status!r}", ) self.assertNotIn( "UnicodeDecodeError", status, f"solve_proof leaked UnicodeDecodeError under ASCII locale: {status!r}", ) # Must produce a Verified status: the agent didn't fail, the encoding # plumbing must transparently use utf-8. self.assertIn( "Verified", status, f"solve_proof returned non-Verified status under ASCII locale: {status!r}", ) self.assertEqual(code, UNICODE) self._assert_temp_cleaned()
# ------------------------------------------------------------------ # GROQ_API_KEY unset -> "GROQ_API_KEY missing" # ------------------------------------------------------------------ def test_missing_groq_api_key(self): with mock.patch.dict(os.environ, {}, clear=True): ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) self.assertIn("GROQ_API_KEY missing", status) # No tempfile created -- function short-circuits. self.assertEqual(self._captured_paths, []) self.assertEqual(code, "") self.assertEqual(logs, "")
# ------------------------------------------------------------------ # Agent raises -> "Error:" status; temp file still cleaned up. # ------------------------------------------------------------------ def test_agent_raises_runtime_error(self): _DummyAgent.raise_exc = RuntimeError("synthetic blow-up") ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) self.assertIn("Error", status) self.assertIn("synthetic blow-up", status) self.assertEqual(code, "") # Most important: temp file must be cleaned up even on exception. self.assertEqual(len(self._captured_paths), 1) self._assert_temp_cleaned()
# ------------------------------------------------------------------ # Agent reports success -> "Verified" status. # ------------------------------------------------------------------ def test_agent_success(self): _DummyAgent.result = { "success": True, "solved_at_attempt": 2, "total_attempts": 3, } ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 3) status, code, logs = self._assert_triple(ret) self.assertIn("Verified", status) self.assertIn("2", status) self.assertIn("3", status) self._assert_temp_cleaned()
# ------------------------------------------------------------------ # Agent reports failure -> "No proof found" status. # ------------------------------------------------------------------ def test_agent_failure(self): _DummyAgent.result = { "success": False, "solved_at_attempt": None, "total_attempts": 5, } ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 5) status, code, logs = self._assert_triple(ret) self.assertIn("No proof found", status) self.assertIn("5", status) self._assert_temp_cleaned()
# ------------------------------------------------------------------ # Code without `sorry` should still pass through unchanged. # ------------------------------------------------------------------ def test_no_sorry_keyword_passes_through(self): ret = app.solve_proof(NO_SORRY, "llama-3.3-70b-versatile", 1) status, code, logs = self._assert_triple(ret) self.assertIn("Verified", status) self.assertEqual(code, NO_SORRY) # Bytes seen by agent must equal the input encoded as utf-8. self.assertEqual(_DummyAgent.last_bytes, NO_SORRY.encode("utf-8")) self._assert_temp_cleaned()
# ------------------------------------------------------------------ # Sanity: tempfile cleanup verified for every scenario in one place. # ------------------------------------------------------------------ def test_temp_file_always_cleaned_up(self): """Run every non-short-circuit scenario and assert no tempfile leaks.""" scenarios = [ ("ok", NO_SORRY, None), ("huge", HUGE, None), ("unicode", UNICODE, None), ("raise", NO_SORRY, RuntimeError("boom")), ] for label, code_in, exc in scenarios: _DummyAgent.raise_exc = exc with self.subTest(label): app.solve_proof(code_in, "llama-3.3-70b-versatile", 1) _DummyAgent.raise_exc = None self._assert_temp_cleaned()
if __name__ == "__main__": unittest.main()92 unmodified lines93949596979892 unmodified lines_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()92 unmodified lines9394959697989910010110210310410592 unmodified lines_DummyAgent.sleep_seconds = 0.0_DummyAgent.raise_token = None_DummyAgent.print_tag = False# Per-test patch: `app.solve_proof` does `from langgraph_agent import# LangGraphAgent` at import time, so `app.LangGraphAgent` is bound to# whichever module-level mock loaded first. Other test files do the# same trick and can win the race, so we patch on `app` directly.self._lg_patcher = mock.patch.object(app, "LangGraphAgent", _DummyAgent)self._lg_patcher.start()self.addCleanup(self._lg_patcher.stop)# Snapshot pre-existing tmp .lean files so we ignore unrelated ones.self._tmp_before = _scan_tmp_lean()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Regression tests for bugs found in a manual code review (no agent involved).
Each test locks in a specific fix; if any of these start failing, a previouslyfixed bug has been reintroduced."""
import importlibimport osimport sysimport tempfileimport unittestfrom unittest import mock
sys.path.insert(0, "src")
# Other test files (test_app_fuzz, test_concurrent_solve) install a MagicMock# in `sys.modules["langgraph_agent"]`, which would shadow the real module and# make our helpers return MagicMocks instead of ints/strings. Evict the cached# mock so we get a fresh, real import.sys.modules.pop("langgraph_agent", None)
# `langgraph_agent` imports lean_verifier + retriever + rag_chain which each# pull in heavyweight ML libs. Mock those three modules directly so we can# import the helpers without installing langchain-groq / lean-interact.for _mod in ("lean_verifier", "retriever", "rag_chain"): sys.modules[_mod] = mock.MagicMock()
import langgraph_agentimportlib.reload(langgraph_agent) # ensure regex/keyword changes are picked up_count_theorem_blocks = langgraph_agent._count_theorem_blocks_extract_lean_code = langgraph_agent._extract_lean_code_read_file = langgraph_agent._read_file_write_file = langgraph_agent._write_file
class TestCountTheoremBlocksKeywordFix(unittest.TestCase): """ The old `_THEOREM_KEYWORDS = ("example", "theorem ", "lemma ", "def ")` tuple had inconsistent trailing spaces: - `theorem\nfoo` returned 0 (false negative โ `theorem ` requires a space) - `examplelike` returned 1 (false positive โ `example` has no boundary) Fixed by switching to a regex with a proper boundary class. """
def test_theorem_followed_by_newline_counts(self): self.assertEqual(_count_theorem_blocks("theorem\nfoo := rfl"), 1)
def test_examplelike_does_not_match(self): self.assertEqual(_count_theorem_blocks("examplelike := 5"), 0)
def test_indented_theorem_counts(self): self.assertEqual(_count_theorem_blocks(" theorem foo : True := trivial"), 1)
def test_theorem_with_colon_immediately(self): # `theorem:` (no space) should NOT match โ only valid Lean syntax counts. self.assertEqual(_count_theorem_blocks("theorem:bar"), 0)
def test_theorem_with_paren_immediately_does_NOT_count(self): # Not valid Lean โ declaration name must come before `(`. self.assertEqual(_count_theorem_blocks("theorem(x : Nat) : True := trivial"), 0)
def test_mixed_keywords_each_count(self): code = ( "example : True := trivial\n" "theorem foo : True := trivial\n" "lemma bar : True := trivial\n" "def baz : Nat := 0\n" ) self.assertEqual(_count_theorem_blocks(code), 4)
class TestExtractLeanCodeFenceVariants(unittest.TestCase): """ `_extract_lean_code` used to do `text.split("```lean")[1]` which would leave a `4` at the start when the fence was `\`\`\`lean4` (a common LLM output). Now uses a regex that requires the lean tag to be terminated by whitespace. """
def test_lean_fence(self): self.assertEqual( _extract_lean_code("```lean\nfoo := rfl\n```"), "foo := rfl", )
def test_lean4_fence_does_not_leak_digit(self): # Old behavior: returned "4\nfoo := rfl" self.assertEqual( _extract_lean_code("```lean4\nfoo := rfl\n```"), "foo := rfl", )
def test_uppercase_lean_fence(self): self.assertEqual( _extract_lean_code("```Lean\nfoo := rfl\n```"), "foo := rfl", )
def test_no_fence_returns_stripped(self): self.assertEqual(_extract_lean_code(" foo := rfl "), "foo := rfl")
def test_untagged_fence(self): self.assertEqual(_extract_lean_code("```\nfoo := rfl\n```"), "foo := rfl")
def test_leanish_tag_falls_through_to_untagged(self): # `leanish` isn't a recognized Lean fence, so the function should fall # through to the untagged-fence branch. That branch returns the raw # fenced content as-is (including "leanish" on the first line) โ Lean # will then reject it as a syntax error and we retry. The important # thing is no crash. result = _extract_lean_code("```leanish\nfoo\n```") self.assertIn("foo", result)
class TestUtf8FileIO(unittest.TestCase): """ `_read_file` / `_write_file` previously used the platform default encoding, which is C/ASCII on minimal Docker images and would crash on Lean unicode. """
def test_round_trip_unicode_lean(self): code = "theorem foo : โ n : โ, โ m, n + m = m + n := by sorry" with tempfile.NamedTemporaryFile(suffix=".lean", mode="w", delete=False, encoding="utf-8") as f: path = f.name try: _write_file(path, code) self.assertEqual(_read_file(path), code) finally: os.unlink(path)
class TestProofAgentDefaultModel(unittest.TestCase): """ `ProofAgent` used to default to `qwen3-vl:4b` (an Ollama model name) after the Groq migration, which would fail at runtime. Now defaults to a real Groq model. """
def test_default_model_is_not_a_stale_ollama_name(self): # Inspect the function default directly โ avoids needing a working # LangGraphAgent mock chain. import inspect import proof_agent
sig = inspect.signature(proof_agent.ProofAgent.__init__) default = sig.parameters["model_name"].default self.assertNotIn("qwen", default.lower()) self.assertNotIn(":", default, "Default looks like an Ollama 'name:tag' format")
if __name__ == "__main__": unittest.main()app.py+12-2
src/langgraph_agent.py+33-7
src/lean_verifier.py+23-3
src/lmm_client.py+8-1
src/proof_agent.py+1-1
tests/test_app_fuzz.pyAdded+357
tests/test_concurrent_solve.py+7
tests/test_manual_bug_fixes.pyAdded+155