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(perf): stop advising to move I/O out of locks that exist for it (#2911)
Raghav Chamadiyad13e0c9286cb
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py b/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.pyindex 7f0fbcbff..a9f41324f 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py@@ -23,6 +23,7 @@ from __future__ import annotationsfrom ..complexity import PerfHitfrom ..models import Severity+from ..perf.actionability import LOCK_SERIALIZED_BOUNDARIESfrom .base import BiomarkerResult, FileContext_KIND = "blocking_io_under_lock"@@ -36,6 +37,13 @@ _BOUNDARY_PHRASING: dict[str, str] = {}+def _advice(boundary: str, move: str) -> str:+ """*move*, unless the lock most likely exists to serialize this very I/O."""+ if boundary in LOCK_SERIALIZED_BOUNDARIES:+ return "every thread that needs the lock waits for it"+ return move++class BlockingIoUnderLockDetector:name = _KINDcategory = "performance"@@ -57,10 +65,11 @@ class BlockingIoUnderLockDetector:line_start=hit.line,line_end=hit.line,details={"boundary_kind": hit.detail, "cross_function": False},- reason=(- f"{phrasing} runs while a lock is held; move the I/O "- "outside the critical section to avoid serializing "- "every thread on the round-trip"+ reason=f"{phrasing} runs while a lock is held; "+ + _advice(+ hit.detail,+ "move the I/O outside the critical section to avoid "+ "serializing every thread on the round-trip",),))@@ -82,10 +91,8 @@ class BlockingIoUnderLockDetector:"path": list(hit.path),"resolution_basis": hit.resolution_basis,},- reason=(- f"{phrasing} is reached while a lock is held, through "- f"{chain}; move the I/O outside the critical section"- ),+ reason=f"{phrasing} is reached while a lock is held, through {chain}; "+ + _advice(hit.detail, "move the I/O outside the critical section"),)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 5941043fa..124fa9fd6 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@@ -19,6 +19,7 @@ registered.from __future__ import annotations+import refrom dataclasses import replacefrom typing import TYPE_CHECKING@@ -94,6 +95,73 @@ _HOT_PATH_SINK_KINDS = frozenset({"subprocess", "filesystem"})# (``synchronized(repo.find(id)){…}``) runs BEFORE the lock is taken._LOCK_BODY_KINDS = frozenset({"block", "statement_block", "compound_statement", "do_block"})+# A whole condition that is one null test, and the name it tests: ``x == null``,+# ``this.x.get() == null``, ``o.x is null`` (the last segment, ``.get()`` stripped).+_NULL_GUARD = re.compile(+ r"(?:[A-Za-z_]\w*\.)*([A-Za-z_]\w*)(?:\.get\(\))?"+ r"\s*(?:===?\s*(?:null|nil|None)|is\s+null)"+)+_IF_KINDS = frozenset({"if_statement", "if_expression"})+# ``x = ...`` / ``x ??= ...`` / ``x.set(...)``: the held body stores the guarded name.+_ASSIGNS = r"\b{}\s*(?:=(?!=)|\?\?=|\.set\(|\.compareAndSet\()"+++def _null_guarded_name(node: Node | None) -> str | None:+ """The name *node* tests when it is exactly ``if (x == null) {...}``, with no ``else``."""+ if node is None or node.type not in _IF_KINDS or node.child_by_field_name("alternative"):+ return None+ cond = node.child_by_field_name("condition")+ text = (cond.text if cond is not None else b"").decode("utf-8", "replace")+ guard = _NULL_GUARD.fullmatch(text.strip("() \t\r\n"))+ return guard.group(1) if guard is not None else None+++def _sole_statement(body: Node) -> Node | None:+ """The one statement a held body runs, ignoring comments and a trailing ``return``."""+ stmts = [c for c in body.children if c.is_named and "comment" not in c.type]+ if len(stmts) == 2 and stmts[1].type == "return_statement":+ stmts = stmts[:1]+ return stmts[0] if len(stmts) == 1 else None+++def _is_coalescing_assignment(stmt: Node | None) -> bool:+ """``x ??= Load();``: assigns only when ``x`` is still null."""+ if stmt is None or stmt.type != "expression_statement":+ return False+ return b"??=" in (stmt.text or b"")+++def _enclosing_statement(lock: Node) -> Node | None:+ """The statement around *lock*, looking through the block it sits in."""+ outer = lock.parent+ if outer is not None and outer.type in _LOCK_BODY_KINDS:+ outer = outer.parent+ return outer+++def _is_memoizing_lock(lock: Node) -> bool:+ """The lock only makes a one-time initialisation thread-safe.++ The held body assigns the name a null guard tests, where the guard either+ wraps the lock (``if (x == null) { synchronized (m) { x = ... } }``) or is+ the whole held body (double-checked locking); or the whole body is+ ``x ??= Load()``. A trailing ``return`` is allowed. The I/O then runs once,+ and moving it out of the lock would run it more than once, so such a lock+ is not a ``blocking_io_under_lock`` region.+ """+ body = next((c for c in lock.children if c.type in _LOCK_BODY_KINDS), None)+ if body is None:+ return False+ only = _sole_statement(body)+ if _is_coalescing_assignment(only):+ return True+ held = (body.text or b"").decode("utf-8", "replace")+ for guard in (only, _enclosing_statement(lock)):+ name = _null_guarded_name(guard)+ if name and re.search(_ASSIGNS.format(re.escape(name)), held):+ return True+ return False+def _perf_func_name(node: Node) -> str | None:if node.type == "function_body":@@ -613,7 +681,9 @@ def _collect_perf_hits(# Only its BLOCK body runs with the lock held — a sink in the lock-object# expression (``synchronized(repo.find(id)){…}``) runs before the lock is# taken — so ``lock_depth`` is raised per-child, for the body block only.- entering_lock = do_lock_io and dialect.is_lock_scope(node)+ entering_lock = (+ do_lock_io and dialect.is_lock_scope(node) and not _is_memoizing_lock(node)+ )if is_loop:# The outermost loop in a nest fixes ``outer_iter``; deeper loopsdiff --git a/packages/core/src/repowise/core/analysis/health/perf/actionability.py b/packages/core/src/repowise/core/analysis/health/perf/actionability.pyindex 9f89ea5d7..8aea1229a 100644--- a/packages/core/src/repowise/core/analysis/health/perf/actionability.py+++ b/packages/core/src/repowise/core/analysis/health/perf/actionability.py@@ -42,6 +42,11 @@ BATCHABLE_BOUNDARIES = frozenset({"db", "network"})# Fanning out N awaits here spends a pool, rate limit or statement timeout.CONCURRENCY_SENSITIVE_BOUNDARIES = frozenset({"db", "network"})+# I/O a lock usually exists to serialize: a file-backed store or log writes+# under its lock, and a launcher spawns its process once under it. Moving that+# I/O out of the lock reintroduces the race the lock prevents.+LOCK_SERIALIZED_BOUNDARIES = frozenset({"filesystem", "subprocess"})+@dataclass(frozen=True, slots=True)class PerformanceFix:@@ -252,6 +257,8 @@ def assess_fix(("batch_api_contract", "result_equivalence"),)if marker == "blocking_io_under_lock":+ if boundary in LOCK_SERIALIZED_BOUNDARIES:+ return FixAssessment(None, ("io_not_guarded_by_lock",), refusal="lock_serializes_io")owners = {path[0] for detail in details if (path := detail.get("path")) and isinstance(path, list)}@@ -308,6 +315,7 @@ def actionability(__all__ = ["BATCHABLE_BOUNDARIES","BATCHABLE_MARKERS",+ "LOCK_SERIALIZED_BOUNDARIES","Actionability","ActionabilityState","FixAssessment",diff --git a/tests/unit/health/test_perf_opportunities.py b/tests/unit/health/test_perf_opportunities.pyindex af5bfc035..cf1a56185 100644--- a/tests/unit/health/test_perf_opportunities.py+++ b/tests/unit/health/test_perf_opportunities.py@@ -228,6 +228,27 @@ def test_distinct_lock_owners_behind_one_helper_do_not_claim_one_lock_fix():assert opportunity.prerequisites == ("single_lock_owner",)[email protected]("boundary", ["filesystem", "subprocess"])+def test_lock_that_serializes_local_io_gets_no_move_it_out_plan(boundary):+ """A file store's save or a once-only launch under its lock: the lock is the point."""+ opportunity = build_performance_opportunities(+ [+ _finding(+ "store.py",+ 3,+ marker="blocking_io_under_lock",+ boundary=boundary,+ call_path=("store.py::save", "store.py::write_file"),+ )+ ]+ )[0]++ assert opportunity.fix is None+ assert opportunity.actionability_state == "investigate"+ assert opportunity.prerequisites == ("io_not_guarded_by_lock",)+ assert performance_fix_suggestions([opportunity]) == []++def test_performance_fix_plan_carries_closed_strategy_and_true_totals():opportunity = build_performance_opportunities([diff --git a/tests/unit/health/test_perf_phase7b.py b/tests/unit/health/test_perf_phase7b.pyindex 0a405b5c8..5f0bc51c9 100644--- a/tests/unit/health/test_perf_phase7b.py+++ b/tests/unit/health/test_perf_phase7b.py@@ -131,6 +131,42 @@ _LOCK_IO_CASES = [[],"a sink in the lock-OBJECT expression runs before the lock is held",),+ (+ "java",+ "class A{ Object m(Object g, javax.persistence.EntityManager em){"+ " synchronized(g){ if (cache == null) { cache = em.getResultList(); } } return cache; } }",+ [],+ "double-checked lazy init: the I/O runs once, the lock is the memo",+ ),+ (+ "java",+ "class A{ Object m(javax.persistence.EntityManager em){"+ " if (ref.get() == null) { synchronized(ref){ ref.set(em.getResultList()); } }"+ " return ref.get(); } }",+ [],+ "a null guard around the lock that the held body fills is lazy init",+ ),+ (+ "csharp",+ "class A{ object M(AppDbContext ctx){ lock(gate){ _cached ??= ctx.SaveChanges(); "+ "return _cached; } } }",+ [],+ "a ??= memo as the whole held body is lazy init",+ ),+ (+ "java",+ "class A{ void m(Object g, javax.persistence.EntityManager em){"+ " synchronized(g){ if (q == null) { q = new X(); } else { em.getResultList(); } } } }",+ [("blocking_io_under_lock", "db")],+ "a null check with an else branch is a state machine, not a memo",+ ),+ (+ "java",+ "class A{ void m(Object g, javax.persistence.EntityManager em){"+ " synchronized(g){ if (q == null || stale) { q = em.getResultList(); } } } }",+ [("blocking_io_under_lock", "db")],+ "a guard that is not a pure null test can rerun, so the lock still counts",+ ),]@@ -416,6 +452,16 @@ def test_blocking_io_under_lock_renders_cross_function_path():assert "holder -> writer" in finding.reason+def test_blocking_io_under_lock_does_not_advise_moving_file_io_out():+ hits = [+ PerfHit("blocking_io_under_lock", 3, "save", "filesystem"),+ PerfHit("blocking_io_under_lock", 4, "save", "db"),+ ]+ file_io, db = BlockingIoUnderLockDetector().detect(_ctx(hits))+ assert "move the I/O" not in file_io.reason+ assert "move the I/O" in db.reason++def test_new_markers_score_performance_not_defect():ctx = _ctx([PerfHit(k, i + 1, "f", "") for i, k in enumerate(_NEW_KINDS)])results = detect_all(ctx)