From f7fdc8b91b42bfbf46dc71b1e683abc07db8c170 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:32:37 +0000 Subject: [PATCH] Report unparsable SQL and pathological nesting instead of raising explain() promises never to raise on malformed input, but two kinds of input escaped it and became bare 500s from every endpoint: - SQL whose string or comment never ends. sqlglot raises TokenError for that, which is a sibling of the ParseError the adapter caught, not a subclass. Half-typed SQL like `SELECT 'abc` hits it. - Deeply nested code. Lowering and analysis recurse over the tree, so a 1,000-term `a + b + ...` chain or a few thousand nested brackets hit the recursion limit, and CPython's own parser reports the same thing as MemoryError. The adapter now catches SqlglotError, and explain() catches RecursionError around the static pass and returns a degraded result with an error diagnostic that says why, the same way a parse failure is reported. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW --- explain_my_code/adapters/python.py | 9 +++- explain_my_code/adapters/sql.py | 8 +-- explain_my_code/core.py | 80 ++++++++++++++++++++++++------ tests/test_api.py | 15 ++++++ tests/test_explain.py | 41 +++++++++++++++ 5 files changed, 135 insertions(+), 18 deletions(-) diff --git a/explain_my_code/adapters/python.py b/explain_my_code/adapters/python.py index 02a287d..eef0e55 100644 --- a/explain_my_code/adapters/python.py +++ b/explain_my_code/adapters/python.py @@ -1041,6 +1041,13 @@ def parse(self, source: str) -> ParseResult: diagnostics.append( Diagnostic(message="Explained the portion above the error.", severity="info") ) + except MemoryError as exc: + # CPython's parser reports a stack overflow on extreme nesting as MemoryError + # (bare on 3.11, "Python source too complex to parse" from 3.12). Input is + # capped at MAX_SOURCE_BYTES, so this is that condition, not a real OOM. It is + # the same as our own passes hitting the recursion limit and is reported the + # same way, by the caller. + raise RecursionError(str(exc) or "parser stack overflowed") from exc lowerer = PythonLowerer(source) root = lowerer.lower(tree) @@ -1066,7 +1073,7 @@ def _parse_longest_prefix(source: str) -> ast.Module | None: for end in range(len(lines) - 1, 0, -1): try: return ast.parse("\n".join(lines[:end])) - except SyntaxError: + except (SyntaxError, MemoryError, RecursionError): continue return None diff --git a/explain_my_code/adapters/sql.py b/explain_my_code/adapters/sql.py index 3d458e4..e66288e 100644 --- a/explain_my_code/adapters/sql.py +++ b/explain_my_code/adapters/sql.py @@ -23,15 +23,17 @@ ) try: + # SqlglotError, not ParseError: an unterminated string or comment fails in the + # tokenizer and raises TokenError, which is a sibling of ParseError. import sqlglot from sqlglot import expressions as exp - from sqlglot.errors import ParseError + from sqlglot.errors import SqlglotError SQLGLOT_AVAILABLE = True except ImportError: # pragma: no cover sqlglot = None # type: ignore[assignment] exp = None # type: ignore[assignment] - ParseError = Exception # type: ignore[assignment,misc] + SqlglotError = Exception # type: ignore[assignment,misc] SQLGLOT_AVAILABLE = False @@ -596,7 +598,7 @@ def parse(self, source: str) -> ParseResult: diagnostics: list[Diagnostic] = [] try: statements = sqlglot.parse(source) - except ParseError as error: + except SqlglotError as error: diagnostics.append(Diagnostic(f"Could not parse SQL: {error}", severity="error")) return ParseResult( root, Language.SQL, source, diagnostics, self.parser_name, degraded=True diff --git a/explain_my_code/core.py b/explain_my_code/core.py index cb3163f..2211525 100644 --- a/explain_my_code/core.py +++ b/explain_my_code/core.py @@ -8,12 +8,23 @@ import re import time +from collections.abc import Callable from dataclasses import dataclass, field +from functools import partial from typing import Any from explain_my_code.adapters.base import get_adapter, load_all, registered_languages from explain_my_code.analysis.pipeline import Analysis, analyze -from explain_my_code.ir import Annotation, Diagnostic, Language, Level, ParseResult +from explain_my_code.ir import ( + Annotation, + Diagnostic, + Kind, + Language, + Level, + Node, + ParseResult, + Span, +) from explain_my_code.narrate.annotate import LineExplanation, annotate, line_view, summarize load_all() @@ -149,19 +160,17 @@ def explain( language = Language(language) timings: dict[str, float] = {} - - started = time.perf_counter() - parsed: ParseResult = get_adapter(language).parse(code) - timings["parse"] = (time.perf_counter() - started) * 1000 - - started = time.perf_counter() - analysis = analyze(parsed) - timings["analyze"] = (time.perf_counter() - started) * 1000 - - started = time.perf_counter() - annotations = annotate(parsed, analysis, level) - summary = summarize(analysis, level) - timings["explain"] = (time.perf_counter() - started) * 1000 + adapter = get_adapter(language) + try: + parsed, analysis, annotations, summary = _static_pass(adapter.parse, code, level, timings) + except RecursionError: + # The lowering and analysis passes recurse over the tree, so pathological + # nesting (a thousand-term `a + b + ...` chain, thousands of nested brackets) + # can exhaust the interpreter's recursion limit. That is reported the way a + # parse failure is, instead of failing the whole request. + timings.clear() + too_deep = partial(_too_deep_to_explain, language=language, parser=adapter.parser_name) + parsed, analysis, annotations, summary = _static_pass(too_deep, code, level, timings) enrichment = None if enrich: @@ -196,6 +205,49 @@ def explain( ) +TOO_DEEP_MESSAGE = ( + "This code is nested too deeply to explain: an expression or block goes hundreds of " + "levels deep (a very long `a + b + c + ...` chain counts). Split it up and try again." +) + + +def _static_pass( + parse: Callable[[str], ParseResult], code: str, level: Level, timings: dict[str, float] +) -> tuple[ParseResult, Analysis, list[Annotation], str]: + started = time.perf_counter() + parsed = parse(code) + timings["parse"] = (time.perf_counter() - started) * 1000 + + started = time.perf_counter() + analysis = analyze(parsed) + timings["analyze"] = (time.perf_counter() - started) * 1000 + + started = time.perf_counter() + annotations = annotate(parsed, analysis, level) + summary = summarize(analysis, level) + timings["explain"] = (time.perf_counter() - started) * 1000 + return parsed, analysis, annotations, summary + + +def _too_deep_to_explain(source: str, *, language: Language, parser: str) -> ParseResult: + """An empty, degraded parse that carries the reason as an error diagnostic.""" + lines = source.splitlines() + root = Node( + kind=Kind.MODULE, + span=Span(1, 0, max(len(lines), 1), 0), + name="module", + meta={"unparsed": True}, + ) + return ParseResult( + root, + language, + source, + [Diagnostic(TOO_DEEP_MESSAGE, severity="error")], + parser, + degraded=True, + ) + + def supported_languages() -> list[dict[str, Any]]: out = [] for language in registered_languages(): diff --git a/tests/test_api.py b/tests/test_api.py index 9358b18..8d7e7f8 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -73,6 +73,21 @@ def test_analyze_returns_metrics_without_prose(): assert body["analysis"]["metrics"]["cyclomatic"] == 1 +@pytest.mark.parametrize( + "payload", + [ + {"code": "SELECT 'never closed", "language": "sql"}, + {"code": "x = " + " + ".join(["a"] * 1_000) + "\n", "language": "python"}, + ], + ids=["sql-token-error", "deep-python"], +) +@pytest.mark.parametrize("path", ["/v1/explain", "/v1/explain/all-levels", "/v1/analyze"]) +def test_hostile_input_gets_a_degraded_answer_not_a_500(path, payload): + response = TestClient(app, raise_server_exceptions=False).post(path, json=payload) + assert response.status_code == 200 + assert any(d["severity"] == "error" for d in response.json()["diagnostics"]) + + def test_detect_endpoint(): body = client.post("/v1/detect", json={"code": "#include \nint main(){}"}).json() assert body["language"] == "cpp" diff --git a/tests/test_explain.py b/tests/test_explain.py index 6fa48a2..f15522a 100644 --- a/tests/test_explain.py +++ b/tests/test_explain.py @@ -158,6 +158,47 @@ def test_syntax_error_is_reported_not_raised(): assert any(d.severity == "error" for d in result.diagnostics) +@pytest.mark.parametrize( + "source", + ["SELECT 'unterminated", 'SELECT "unterminated', "SELECT a FROM t /* unterminated"], + ids=["single-quote", "double-quote", "block-comment"], +) +def test_sql_that_fails_to_tokenize_is_reported_not_raised(source): + """sqlglot raises TokenError, not ParseError, when a string or comment never ends.""" + result = explain(source, language=Language.SQL) + assert result.analysis.degraded + assert any(d.severity == "error" for d in result.diagnostics) + + +DEEP_INPUTS = { + "python-long-chain": (Language.PYTHON, "x = " + " + ".join(["a"] * 1_000) + "\n"), + "python-parser-overflow": (Language.PYTHON, "x = " + "-" * 10_000 + "1\n"), + "javascript-nested-arrays": (Language.JAVASCRIPT, "const x = " + "[" * 3_000 + "]" * 3_000 + ";\n"), + "java-nested-parens": ( + Language.JAVA, "class A { int f() { return " + "(" * 3_000 + "1" + ")" * 3_000 + "; } }\n" + ), + "cpp-nested-parens": (Language.CPP, "int f() { return " + "(" * 3_000 + "1" + ")" * 3_000 + "; }\n"), + "sql-nested-parens": (Language.SQL, "SELECT " + "(" * 500 + "1" + ")" * 500 + ";\n"), +} + + +@pytest.mark.parametrize("language,source", list(DEEP_INPUTS.values()), ids=list(DEEP_INPUTS)) +def test_pathologically_deep_nesting_is_reported_not_raised(language, source): + """These used to escape `explain()` as RecursionError (or MemoryError from CPython's + own parser), which the API turned into a bare 500.""" + result = explain(source, language=language) + assert result.analysis.degraded + assert any("nested too deeply" in d.message for d in result.diagnostics) + assert isinstance(result.summary, str) + assert result.to_dict()["degraded"] is True + + +def test_moderately_deep_code_is_still_explained(): + result = explain("x = " + " + ".join(["a"] * 150) + "\n", language=Language.PYTHON) + assert not result.analysis.degraded + assert result.lines + + def test_supported_languages_are_all_available(): for entry in supported_languages(): assert entry["available"], f"{entry['id']} is not available"