Skip to content

Commit 3d0a545

Browse files
GoldloliSvilen-Stefanovclaude
authored
fix: keep unchanged subclasses in the merged class hierarchy (#705)
* fix: keep unchanged subclasses in the merged class hierarchy An incremental run re-LSPs only the changed files, so HierarchyBuilder fills superclasses for its own classes only. A changed class's fresh entry carries an empty subclasses list, and merge_results let that empty list replace the cached one that listed the unchanged subclasses. Rebuild subclasses from the merged superclasses, which every run does compute for its own classes. Signed-off-by: Goldloli <39011904+Goldloli@users.noreply.github.com> * test: make the stale-link case depend on the rebuild The fresh entry for pkg.Base already replaced the cached subclasses with an empty list, so the test passed without the rebuild. Leave pkg.Base only in the cached half and merge an empty fresh hierarchy: the plain dict merge keeps the stale link, the rebuild drops it. Signed-off-by: Goldloli <39011904+Goldloli@users.noreply.github.com> * fix: keep lookup-only bases and live subclasses through the merge Three follow-ups to the reverse-link rebuild: - HierarchyBuilder dropped a superclass that was not in this run's own hierarchy. A warm start registers unchanged files as lookup-only declarations, so an edited child lost its link to a cached base. Record the superclass on the child; only the base's own reverse link needs the base to be present. - _filter_to_live_files dropped hierarchy entries but left the reverse links pointing at them, so a deleted child survived in its base's subclasses. Prune those links with the same live set. - Trim the helper docstring to the one-line summary plus a short why, per AGENTS.md. Signed-off-by: Goldloli <39011904+Goldloli@users.noreply.github.com> * fix: only class-like live nodes keep a hierarchy entry A class edited into a function of the same name keeps its qualified name, so the live-node test restored it as a subclass and the stale reverse link survived the merge. Ask the node's declaration kind instead. Caches written before this change keep the old reverse links, so bump the tag version to force a rebuild of the affected baselines. * perf: rebuild subclass lists without scanning siblings Each child is visited once, in sorted order, so a repeat can only come from the child naming the same base twice. Deduplicating the child's own bases replaces the `child not in children` scan, which made a base with k direct subclasses cost O(k^2) on every warm start (20k children: 1.7 s, now 0.02 s). Output and order are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Signed-off-by: Goldloli <39011904+Goldloli@users.noreply.github.com> Co-authored-by: Svilen Stefanov <svilen.ks@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent eca6bcb commit 3d0a545

5 files changed

Lines changed: 209 additions & 9 deletions

File tree

‎static_analyzer/analysis_cache.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,10 @@
7979
# v16: compiler-identity metadata is explicit; other languages retain their existing name resolution.
8080
# v17: Dart accessors and tear-offs contribute edges; incremental package dependencies follow the live graph.
8181
# v18: named TypeScript and JavaScript arrows are function nodes; cached nodes preserve the resolver kind.
82+
# v19: a class hierarchy records a base that only a lookup resolved, so an incremental merge can rebuild
83+
# its reverse links without the base's file; caches written before it may name a stale child.
8284
# Older pickles are treated as cache misses and re-run.
83-
_TAG_VERSION = "v18"
85+
_TAG_VERSION = "v19"
8486

8587

8688
class StaticAnalysisCache:
@@ -452,7 +454,7 @@ def merge_results(
452454
merged_diagnostics.update(new_diagnostics)
453455

454456
merged_call_graph = cached_result.call_graph.union(new.call_graph)
455-
merged_class_hierarchies = {**cached_result.class_hierarchies, **new.class_hierarchies}
457+
merged_class_hierarchies = _rederive_subclasses({**cached_result.class_hierarchies, **new.class_hierarchies})
456458
# A warm-start re-LSPs only changed files, so a changed subclass whose superclass lives in
457459
# an unchanged file emits no INHERITS edge during conversion (the superclass wasn't in that
458460
# partial graph). Re-derive INHERITS from the merged hierarchy against the merged node set so
@@ -471,6 +473,24 @@ def merge_results(
471473
return merged
472474

473475

476+
def _rederive_subclasses(class_hierarchies: dict[str, Any]) -> dict[str, Any]:
477+
"""Rebuild every ``subclasses`` list from the merged ``superclasses`` lists.
478+
479+
Why: each run fills ``superclasses`` only for the classes it rebuilds, so a changed class's
480+
fresh empty ``subclasses`` list would replace the cached one naming its unchanged children.
481+
"""
482+
subclasses: dict[str, list[str]] = {class_name: [] for class_name in class_hierarchies}
483+
for child in sorted(class_hierarchies):
484+
# Each child is visited once, so deduplicating its own bases keeps every list free of repeats
485+
# without scanning the siblings already collected.
486+
for superclass in dict.fromkeys(class_hierarchies[child].get("superclasses") or []):
487+
if superclass in subclasses:
488+
subclasses[superclass].append(child)
489+
return {
490+
class_name: {**info, "subclasses": subclasses[class_name]} for class_name, info in class_hierarchies.items()
491+
}
492+
493+
474494
def _rederive_inherits_edges(call_graph: CallGraph, class_hierarchies: dict[str, Any]) -> None:
475495
"""Add any missing INHERITS edge from the merged hierarchy, endpoints permitting.
476496

‎static_analyzer/engine/hierarchy_builder.py‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,14 @@ def build(self) -> dict[str, dict]:
9595
supertypes = self._lsp.type_hierarchy_supertypes(item)
9696
for st in supertypes:
9797
super_name = self._resolve_type_hierarchy_item(st)
98-
if super_name and super_name in hierarchy:
99-
if super_name not in hierarchy[sym.qualified_name]["superclasses"]:
100-
hierarchy[sym.qualified_name]["superclasses"].append(super_name)
101-
if sym.qualified_name not in hierarchy[super_name]["subclasses"]:
102-
hierarchy[super_name]["subclasses"].append(sym.qualified_name)
98+
if not super_name:
99+
continue
100+
# A lookup-only base is not in this run's hierarchy, but the child's link to it is
101+
# still what a later merge rebuilds the reverse links from.
102+
if super_name not in hierarchy[sym.qualified_name]["superclasses"]:
103+
hierarchy[sym.qualified_name]["superclasses"].append(super_name)
104+
if super_name in hierarchy and sym.qualified_name not in hierarchy[super_name]["subclasses"]:
105+
hierarchy[super_name]["subclasses"].append(sym.qualified_name)
103106
except MethodNotFoundError:
104107
pass
105108
except Exception as e:

‎static_analyzer/incremental_orchestrator.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from static_analyzer.engine.call_graph_builder import CallGraphBuilder, build_package_dependencies
2424
from static_analyzer.engine.language_adapter import LanguageAdapter
2525
from static_analyzer.engine.lsp_client import LSPClient
26+
from static_analyzer.engine.lsp_constants import CLASS_LIKE_KINDS
2627
from static_analyzer.engine.models import CallSite, SymbolInfo
2728
from static_analyzer.engine.result_converter import convert_to_codeboarding_format
2829
from static_analyzer.engine.source_inspector import SourceInspector
@@ -277,11 +278,21 @@ def _filter_to_live_files(merged_analysis: AnalysisData) -> AnalysisData:
277278
# Hierarchy entries are keyed by class qname and carry no file_path, so filter by whether the
278279
# class still exists as a live call-graph node (already filtered above) — the old
279280
# ``info.get("file_path")`` check was always None and dropped every hierarchy, which then
280-
# starved the warm-start INHERITS re-derivation of its source on the next run.
281-
live_class_names = set(merged_analysis.call_graph.nodes.keys())
281+
# starved the warm-start INHERITS re-derivation of its source on the next run. A live node is
282+
# not enough on its own: a class replaced by a function of the same name keeps the qname, so
283+
# only class-like nodes can still own a hierarchy entry.
284+
live_class_names = {
285+
name for name, node in merged_analysis.call_graph.nodes.items() if node.declaration_kind in CLASS_LIKE_KINDS
286+
}
282287
merged_analysis.class_hierarchies = {
283288
name: info for name, info in merged_analysis.class_hierarchies.items() if name in live_class_names
284289
}
290+
# The reverse links were derived before this filter, so a subclass that just died still sits in
291+
# its base's list; drop it here or the stored hierarchy names a class that no longer exists.
292+
merged_analysis.class_hierarchies = {
293+
name: {**info, "subclasses": [child for child in info.get("subclasses", []) if child in live_class_names]}
294+
for name, info in merged_analysis.class_hierarchies.items()
295+
}
285296

286297
return merged_analysis
287298

‎tests/static_analyzer/test_analysis_cache_inmem.py‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from static_analyzer.graph_definitions import GraphIndex, potential_calls, implemented_by
2020
from static_analyzer.incremental_orchestrator import (
2121
_declarations,
22+
_filter_to_live_files,
2223
_restore_inbound_edges_via_definitions,
2324
update_cfg_for_changed_files,
2425
)
@@ -191,6 +192,63 @@ def test_diagnostics_merge_with_new_winning(self) -> None:
191192

192193
self.assertEqual(merged.diagnostics, {"a.py": ["old-a"], "b.py": ["new-b"]})
193194

195+
def test_changed_superclass_keeps_unchanged_subclasses(self) -> None:
196+
# ``Child extends Base`` lives in the unchanged child.py; only ``Base`` is re-LSPed, so
197+
# its fresh entry carries no subclasses. The merge must not drop the cached reverse link.
198+
cached = _result(
199+
CallGraph(language="python"),
200+
source_files=["base.py", "child.py"],
201+
class_hierarchies={
202+
"pkg.Base": {"file_path": "base.py", "superclasses": [], "subclasses": ["pkg.Child"]},
203+
"pkg.Child": {"file_path": "child.py", "superclasses": ["pkg.Base"], "subclasses": []},
204+
},
205+
)
206+
new = _result(
207+
CallGraph(language="python"),
208+
source_files=["base.py"],
209+
class_hierarchies={
210+
"pkg.Base": {"file_path": "base.py", "superclasses": [], "subclasses": []},
211+
},
212+
)
213+
214+
merged = merge_results(_analysis_data(cached), new)
215+
216+
self.assertEqual(merged.class_hierarchies["pkg.Base"]["subclasses"], ["pkg.Child"])
217+
self.assertEqual(merged.class_hierarchies["pkg.Child"]["superclasses"], ["pkg.Base"])
218+
219+
def test_subclasses_derived_from_superclasses_ignore_stale_links(self) -> None:
220+
# A stale reverse link to a class that no longer declares this base must not survive:
221+
# ``subclasses`` is rebuilt from the superclasses the merged hierarchy actually holds.
222+
# The fresh half carries no hierarchy, so nothing overwrites the cached entry — only the
223+
# rebuild can drop the stale link.
224+
cached = _result(
225+
CallGraph(language="python"),
226+
source_files=["base.py"],
227+
class_hierarchies={
228+
"pkg.Base": {"file_path": "base.py", "superclasses": [], "subclasses": ["pkg.Stale"]},
229+
},
230+
)
231+
new = _result(CallGraph(language="python"), source_files=["other.py"])
232+
233+
merged = merge_results(_analysis_data(cached), new)
234+
235+
self.assertEqual(merged.class_hierarchies["pkg.Base"]["subclasses"], [])
236+
237+
def test_a_base_named_twice_lists_its_child_once(self) -> None:
238+
cached = _result(
239+
CallGraph(language="python"),
240+
source_files=["base.py", "child.py"],
241+
class_hierarchies={
242+
"pkg.Base": {"superclasses": [], "subclasses": []},
243+
"pkg.Child": {"superclasses": ["pkg.Base", "pkg.Base"], "subclasses": []},
244+
},
245+
)
246+
new = _result(CallGraph(language="python"), source_files=["other.py"])
247+
248+
merged = merge_results(_analysis_data(cached), new)
249+
250+
self.assertEqual(merged.class_hierarchies["pkg.Base"]["subclasses"], ["pkg.Child"])
251+
194252

195253
class TestWarmStartDeletion(unittest.TestCase):
196254
def test_deleted_changed_file_is_removed_from_cached_cfg(self) -> None:
@@ -231,6 +289,93 @@ def test_deleted_changed_file_is_removed_from_cached_cfg(self) -> None:
231289
self.assertIn("b.bar", updated["call_graph"].nodes)
232290
self.assertEqual([str(path) for path in updated["source_files"]], [str(live_file)])
233291

292+
def test_a_deleted_subclass_is_dropped_from_its_base_reverse_links(self) -> None:
293+
# The changed base kept a reverse link to a child whose file is gone; the merged hierarchy
294+
# derives it before the live-file filter runs, so the filter has to drop it as well.
295+
with tempfile.TemporaryDirectory() as temp_dir:
296+
project_path = Path(temp_dir)
297+
base_file = project_path / "base.py"
298+
base_file.write_text("class Base:\n pass\n", encoding="utf-8")
299+
300+
cg = CallGraph(language="python")
301+
cg.add_node(
302+
Node(
303+
fully_qualified_name="pkg.Base",
304+
node_type=NodeType.CLASS,
305+
file_path=str(base_file),
306+
line_start=1,
307+
line_end=2,
308+
)
309+
)
310+
cached = _result(
311+
cg,
312+
source_files=[str(base_file)],
313+
class_hierarchies={
314+
"pkg.Base": {"superclasses": [], "subclasses": ["pkg.Child"]},
315+
},
316+
)
317+
cached["class_hierarchies"]["pkg.Child"] = {"superclasses": ["pkg.Base"], "subclasses": []}
318+
cached["source_files"] = [base_file, project_path / "child.py"]
319+
320+
adapter = MagicMock()
321+
adapter.file_extensions = [".py"]
322+
adapter.language = "python"
323+
engine_client = MagicMock()
324+
engine_client.get_collected_diagnostics.return_value = {}
325+
ignore_manager = MagicMock()
326+
ignore_manager.should_ignore.return_value = False
327+
328+
updated = update_cfg_for_changed_files(
329+
cached,
330+
{project_path / "child.py"},
331+
adapter,
332+
project_path,
333+
project_path,
334+
engine_client,
335+
ignore_manager,
336+
)
337+
338+
self.assertNotIn("pkg.Child", updated["class_hierarchies"])
339+
self.assertEqual(updated["class_hierarchies"]["pkg.Base"]["subclasses"], [])
340+
341+
def test_a_class_name_reused_by_a_function_leaves_the_base_reverse_links(self) -> None:
342+
# ``Child`` edited from ``class Child(Base)`` into ``def Child(...)`` keeps its qname, so a
343+
# live-node test that ignores kinds would keep the cached entry and restore the stale link.
344+
with tempfile.TemporaryDirectory() as temp_dir:
345+
project_path = Path(temp_dir)
346+
base_file = project_path / "base.py"
347+
base_file.write_text("class Base:\n pass\n", encoding="utf-8")
348+
child_file = project_path / "child.py"
349+
child_file.write_text("def Child():\n pass\n", encoding="utf-8")
350+
351+
cg = CallGraph(language="python")
352+
cg.add_node(
353+
Node(
354+
fully_qualified_name="pkg.Base",
355+
node_type=NodeType.CLASS,
356+
file_path=str(base_file),
357+
line_start=1,
358+
line_end=2,
359+
)
360+
)
361+
# The edited file now declares a function under the class's old qualified name.
362+
cg.add_node(_node("pkg.Child", str(child_file)))
363+
merged = AnalysisData.from_dict(
364+
_result(
365+
cg,
366+
source_files=[str(base_file), str(child_file)],
367+
class_hierarchies={
368+
"pkg.Base": {"superclasses": [], "subclasses": ["pkg.Child"]},
369+
"pkg.Child": {"superclasses": ["pkg.Base"], "subclasses": []},
370+
},
371+
)
372+
)
373+
374+
live = _filter_to_live_files(merged)
375+
376+
self.assertNotIn("pkg.Child", live.class_hierarchies)
377+
self.assertEqual(live.class_hierarchies["pkg.Base"]["subclasses"], [])
378+
234379

235380
def _declared(index: GraphIndex, definition: dict) -> Node | None:
236381
location = definition_location(definition)

‎tests/static_analyzer/test_hierarchy_builder.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,27 @@ def test_infers_php_extends(self):
236236

237237
assert "mod.Base" in hierarchy["mod.Child"]["superclasses"]
238238

239+
def test_a_lookup_only_base_is_kept_on_the_child(self):
240+
"""A warm-start rebuilds only some files: the base arrives as a cached declaration, not as a class here."""
241+
adapter = _make_adapter()
242+
base = _sym("Base", "mod.Base", NodeType.CLASS, start_line=0)
243+
child = _sym("Child", "mod.Child", NodeType.CLASS, start_line=5)
244+
st = _setup_symbol_table(adapter, [child])
245+
st.register_known([base])
246+
247+
lsp = MagicMock()
248+
lsp.type_hierarchy_prepare.side_effect = lambda fp, line, char: [
249+
{"name": "stub", "uri": fp.as_uri() if hasattr(fp, "as_uri") else MOD_PATH.as_uri()}
250+
]
251+
lsp.type_hierarchy_supertypes.side_effect = lambda item: [
252+
{"name": "Base", "uri": MOD_PATH.as_uri(), "selectionRange": {"start": {"line": 0}}}
253+
]
254+
255+
hierarchy = HierarchyBuilder(lsp, st, SourceInspector(), adapter).build()
256+
257+
assert hierarchy["mod.Child"]["superclasses"] == ["mod.Base"]
258+
assert "mod.Base" not in hierarchy
259+
239260
def test_a_base_outside_the_engine_is_kept_for_the_merge(self):
240261
"""A class extending another project's: no candidate here, but the name is what the merge links."""
241262
adapter = _make_adapter()

0 commit comments

Comments
 (0)