From 0aa1fbf1813f3e9bf9e14293f8b64124d69e628a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 07:01:57 +0000 Subject: [PATCH] Parse once in /v1/explain/all-levels The endpoint's docstring says parsing and analysis are level-independent, which is the reason it exists, but it called explain() once per level and so parsed and analysed the snippet three times. It is the endpoint the web UI calls on every run. Re-running the whole pipeline also gave each level its own node ids. The response's `analysis` came from the ELI5 pass, so BEGINNER and DEVELOPER lines carried node ids that matched nothing in it. Explanation.at_level() re-narrates an existing parse and analysis for another audience, and the endpoint uses it for the other two levels. The response is unchanged apart from the now-consistent node ids, and it is ~30% faster on the web sample and 2x on a 195KB file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW --- explain_my_code/api/main.py | 18 ++++++++++-------- explain_my_code/core.py | 34 ++++++++++++++++++++++++++++++++++ tests/test_api.py | 22 ++++++++++++++++++++++ tests/test_explain.py | 11 +++++++++++ 4 files changed, 77 insertions(+), 8 deletions(-) diff --git a/explain_my_code/api/main.py b/explain_my_code/api/main.py index d68a57d..f2edcd2 100644 --- a/explain_my_code/api/main.py +++ b/explain_my_code/api/main.py @@ -129,17 +129,19 @@ def explain_all_levels(payload: ExplainRequest) -> Any: """All three levels in one call. The parse and analysis passes are the expensive part and are level-independent, so - the client can switch levels instantly instead of paying a round trip per level. + they run once and only the narration is repeated per level. The client can switch + levels instantly instead of paying a round trip per level. """ + first = explain( + payload.code, + language=payload.language, + level=Level.ELI5, + filename=payload.filename, + enrich=False, + ) out: dict[str, Any] = {} for level in Level: - result = explain( - payload.code, - language=payload.language, - level=level, - filename=payload.filename, - enrich=False, - ) + result = first if level is first.level else first.at_level(level) out[level.value] = { "summary": result.summary, "lines": [line.to_dict() for line in result.lines], diff --git a/explain_my_code/core.py b/explain_my_code/core.py index cb3163f..87cef58 100644 --- a/explain_my_code/core.py +++ b/explain_my_code/core.py @@ -116,6 +116,40 @@ def to_dict(self, *, include_ir: bool = False) -> dict[str, Any]: out["ir"] = self.analysis.root.to_dict() return out + def at_level(self, level: Level | str) -> Explanation: + """The same parse and analysis, narrated for another audience. + + Parsing and analysis do not depend on the level, so this only re-runs the + narration, and node ids in the result match this explanation's `analysis`. + LLM enrichment is level-specific and is not carried over. + """ + level = Level(level) + started = time.perf_counter() + parsed = ParseResult( + self.analysis.root, + self.language, + self.source, + self.diagnostics, + self.analysis.parser, + self.analysis.degraded, + ) + annotations = annotate(parsed, self.analysis, level) + summary = summarize(self.analysis, level) + lines = line_view(annotations, level) + elapsed = (time.perf_counter() - started) * 1000 + return Explanation( + language=self.language, + level=level, + source=self.source, + summary=summary, + lines=lines, + annotations=annotations, + analysis=self.analysis, + diagnostics=self.diagnostics, + detection_confidence=self.detection_confidence, + timings_ms={"explain": elapsed, "total": elapsed}, + ) + class SourceTooLarge(ValueError): pass diff --git a/tests/test_api.py b/tests/test_api.py index 9358b18..0a47139 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -60,6 +60,28 @@ def test_all_levels_returns_all_three(): assert body["eli5"]["summary"] != body["developer"]["summary"] +def test_all_levels_parses_once(monkeypatch): + from explain_my_code.adapters.base import get_adapter + from explain_my_code.ir import Language + + adapter = get_adapter(Language.PYTHON) + calls = [] + real_parse = adapter.parse + monkeypatch.setattr(adapter, "parse", lambda code: calls.append(code) or real_parse(code)) + client.post("/v1/explain/all-levels", json={"code": PY, "language": "python"}) + assert len(calls) == 1 + + +def test_all_levels_node_ids_match_the_shared_analysis(): + """Every level's lines must point at the nodes `analysis` describes. Parsing once per + level gave each level its own ids, so only ELI5's matched.""" + body = client.post("/v1/explain/all-levels", json={"code": PY}).json() + function_id = body["analysis"]["functions"][0]["nodeId"] + for level in ("eli5", "beginner", "developer"): + definition = next(line for line in body[level]["lines"] if line["line"] == 1) + assert definition["nodeId"] == function_id, level + + def test_include_ir_is_opt_in(): without = client.post("/v1/explain", json={"code": PY}).json() with_ir = client.post("/v1/explain", json={"code": PY, "includeIr": True}).json() diff --git a/tests/test_explain.py b/tests/test_explain.py index 6fa48a2..85c4f8c 100644 --- a/tests/test_explain.py +++ b/tests/test_explain.py @@ -27,6 +27,17 @@ def test_all_three_levels_produce_different_prose(): assert texts[Level.ELI5] != texts[Level.BEGINNER] != texts[Level.DEVELOPER] +@pytest.mark.parametrize("level", list(Level), ids=lambda level: level.value) +def test_at_level_matches_a_fresh_explanation(level): + fresh = explain(SAMPLE, level=level) + reused = explain(SAMPLE, level=Level.ELI5).at_level(level) + assert reused.level is level + assert reused.summary == fresh.summary + assert [(line.line, line.text, line.kind) for line in reused.lines] == [ + (line.line, line.text, line.kind) for line in fresh.lines + ] + + def test_eli5_avoids_jargon(): jargon = ("cyclomatic", "asymptotic", "invariant", "idempotent", "polymorphism") result = explain(SAMPLE, level=Level.ELI5)