Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): let a keyed loop call clear key_unused for its line (#3539)
Cestercian07ebe6ac50c1
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.pyindex be9742acc..1f34cdc18 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py@@ -429,6 +429,45 @@ def _key_unused(hit: PerfHit) -> bool:return hit.loop is not None and hit.loop.key_unused+def _without_unused_key(facts: LoopFacts | None) -> LoopFacts | None:+ """Clear ``key_unused``; drop the line when that leaves the default facts.++ ``loop_facts`` returns ``None`` for an all-default ``LoopFacts``. A keyed+ call whose own facts are that default still has to clear a key-free sibling+ on the same line, and the line must not keep a default record afterwards.+ """+ if facts is None:+ return None+ if facts.key_unused:+ facts = replace(facts, key_unused=False)+ return None if facts == LoopFacts() else facts+++def _call_line_facts(+ prev: LoopFacts | None,+ facts: LoopFacts | None,+ *,+ this_keyed: bool,+ line_keyed: bool,+) -> LoopFacts | None:+ """One ``LoopFacts`` per call line. Key-free only when every call on it is.++ The same-line sink dedupe keeps the hit the loop key reaches. Here that+ rule applies to helper calls: a keyed call (``_loop_key_feeds``) clears+ ``key_unused`` whichever call is visited first. When the keyed call's own+ facts are all default, the clear is applied to the facts already stored+ for the line.+ """+ if this_keyed and facts is not None:+ return facts+ if line_keyed:+ # A keyed call already stored non-default facts with the key in use.+ if not this_keyed and prev is not None and not prev.key_unused:+ return prev+ return _without_unused_key(facts if facts is not None else prev)+ return facts if facts is not None else prev++def _overrides(dialect: BasePerfDialect, hook: str) -> bool:return getattr(type(dialect), hook) is not getattr(BasePerfDialectClass, hook)@@ -619,6 +658,10 @@ def _collect_perf_hits(] = {}# func_start -> {call_line: facts} for the loop-call targets above.call_facts: dict[int, dict[int, LoopFacts]] = {}+ # func_start -> call lines where some helper call is fed by the loop key.+ # A keyed call can have all-default facts (``loop_facts`` returns None) and+ # still has to clear ``key_unused`` written by a key-free call on the line.+ keyed_lines: dict[int, set[int]] = {}# func_start -> {call_line: loop header line} for the same targets.call_loop_lines: dict[int, dict[int, int]] = {}# ``(first_line, last_line, name)`` of each lambda with no named function@@ -884,8 +927,29 @@ def _collect_perf_hits(if loop_line:call_loop_lines.setdefault(next_start, {})[line] = loop_linefacts = loop_facts(call_node, sink=False, per_call=True)- if facts is not None:- call_facts.setdefault(next_start, {})[line] = facts+ # Same innermost loop ``loop_facts`` just read. A+ # keyed call clears ``key_unused`` for the whole+ # line, even when its own facts are all default.+ loops = _enclosing_loops(+ call_node, dialect, loop_kinds, fn_kinds, do_block_loop+ )+ this_keyed = bool(loops) and _loop_key_feeds(call_node, loops[0])+ if this_keyed:+ keyed_lines.setdefault(next_start, set()).add(line)+ merged = _call_line_facts(+ call_facts.get(next_start, {}).get(line),+ facts,+ this_keyed=this_keyed,+ line_keyed=line in keyed_lines.get(next_start, ()),+ )+ bucket = call_facts.get(next_start)+ if merged is None:+ if bucket is not None:+ bucket.pop(line, None)+ elif bucket is None:+ call_facts[next_start] = {line: merged}+ else:+ bucket[line] = mergedif do_lock_io and lock_depth >= 1 and method:# A non-sink call under a held lock: a candidate entry for the# cross-function ``blocking_io_under_lock`` reachability pass.diff --git a/tests/unit/health/test_perf_crossfn.py b/tests/unit/health/test_perf_crossfn.pyindex 6ea76a3ce..d71809cbd 100644--- a/tests/unit/health/test_perf_crossfn.py+++ b/tests/unit/health/test_perf_crossfn.py@@ -556,6 +556,30 @@ def test_crossfn_hit_carries_the_owning_loops_magnitude(tmp_path):assert finding.details["loop_magnitude"] == "grows_with_data"+def test_crossfn_keyed_call_is_not_key_unused_beside_a_key_free_call(tmp_path):+ """``load(i)`` reaches ``requests.get`` and ``ping`` does not. Sharing the+ loop line must not mark the keyed hit ``loop_key_unused`` in either order."""+ source = (+ "import requests\n"+ "def load(i):\n"+ " return requests.get(i)\n"+ "def ping():\n"+ " return 1\n"+ "def run(ids):\n"+ " for i in ids:\n"+ " {body}\n"+ )+ for name, body in (+ ("keyed-first", "load(i); ping()"),+ ("key-free-first", "ping(); load(i)"),+ ):+ walked, graph = _build(tmp_path / name, {"client.py": source.format(body=body)})+ hits = [h for hs in collect_crossfn_io_in_loop(walked, graph).values() for h in hs]+ (hit,) = [h for h in hits if h.path[-1].endswith("::load")]+ assert "loop_key_unused" not in hit.loop_facts()+ assert hit.loop_facts()["loop_iterates"] == "parameter"++def test_crossfn_hit_carries_the_owning_loops_chunking(tmp_path):"""A caller that already walks its rows a batch at a time is not told to batch."""source = _SCHEDULER.replace(diff --git a/tests/unit/health/test_perf_loop_key.py b/tests/unit/health/test_perf_loop_key.pyindex 3e4c706c4..a11154b7a 100644--- a/tests/unit/health/test_perf_loop_key.py+++ b/tests/unit/health/test_perf_loop_key.py@@ -83,3 +83,36 @@ def test_a_keyed_loop_keeps_the_advisory_batch_plan():(opportunity,) = build_performance_opportunities([_finding(3)])assert opportunity.fix is not Noneassert opportunity.fix.strategy == "batch_or_prefetch_io"+++ ("body", "key_unused"),+ [+ ("load(i); ping()", False),+ ("ping(); load(i)", False),+ ("ping(); pong()", True),+ ],+)+def test_a_line_is_key_free_only_when_every_helper_call_on_it_is(body, key_unused):+ """Two helpers on one loop line share one ``LoopFacts``. A keyed call clears+ ``key_unused`` in either order; a line of only key-free calls keeps it."""+ src = (+ "import requests\n"+ "def load(i):\n"+ " return requests.get(i)\n"+ "def ping():\n"+ " return 1\n"+ "def pong():\n"+ " return 2\n"+ "def run(ids):\n"+ " for i in ids:\n"+ f" {body}\n"+ )+ run = {f.function: f for f in walk_file("t.py", "python", src.encode()).perf_fn_facts}["run"]+ (call_line,) = {line for _name, line in run.loop_call_targets}+ stored = dict(run.loop_call_facts).get(call_line)+ assert stored is not None+ assert stored.key_unused is key_unused+ assert stored.chunked is False+ assert stored.magnitude == "unknown"+ assert stored.iterates == "parameter"