Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(ingestion): read Python __all__ as a bounded visibility signal (#2475)

JikSau-D7883799372e6
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.md
index 774b7ccfd..d4d5bb45f 100644
--- a/docs/layers/DEAD_CODE.md
+++ b/docs/layers/DEAD_CODE.md
@@ -296,10 +296,17 @@ These are the cases where a finding is most likely wrong:
unused-export pass: a symbol defined in a barrel that nobody imports should
still be reported. A symbol re-exported through a barrel to external callers
can therefore surface as an unused export.
-- **Python `__all__` is not read.** The dead-code layer never consults `__all__`,
- so declaring a public API there does not by itself rescue a symbol. The
- rescues that do apply are the `__init__.py` exemption, the dunder-name skip,
- and intra-module reference tracking.
+- **Python `__all__` is read for visibility, never as a rescue.** A literal
+ module-level `__all__` (list, tuple or set of string constants) raises the
+ names it lists to `public`, even underscore-prefixed ones; a name it omits
+ keeps its name-based visibility, because the list is often stale and
+ demoting on absence would hide a genuinely dead export. Membership is capped
+ at the visibility label: it sets no export marker, mints no edge, and
+ suppresses no finding, so declaring a public API there does not by itself
+ rescue a symbol. Lists built at runtime (comprehensions, `+=`,
+ concatenation) are treated as absent. The rescues that do apply are the
+ `__init__.py` exemption, the dunder-name skip, and intra-module reference
+ tracking.
- **Test-only usage reads as usage.** A test file's import produces a real graph
edge, so a symbol only its tests touch is not flagged. That is deliberate, but
it also means repowise will not tell you a symbol is *exclusively* exercised by
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index ae3daea1b..0be479541 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -50,7 +50,7 @@ workspace overlays, MCP responses, and CLI output.
| Signature | Compact declaration text. | `build_signature()` via parser extractors | `def create_app(config: Config) -> FastAPI` |
| Symbol docstring | Human text attached to a symbol, when extractable. | `extract_symbol_docstring()` | `"Create and configure the API app."` |
| Module docstring | File-level docstring. | `extract_module_docstring()` | `"Command-line entry points."` |
-| Visibility | Public/private/protected/internal classification. | Language-specific visibility helpers | `_helper -> private`, `UserService -> public` |
+| Visibility | Public/private/protected/internal classification. A Python name listed in a literal module-level `__all__` reads public even when underscore-prefixed; a name the list omits keeps its name-based visibility. | Language-specific visibility helpers | `_helper -> private`, `UserService -> public` |
| Async flag | Whether a symbol is async. | `_is_async_node()` | `async def fetch() -> is_async=true` |
| Complexity estimate | Symbol complexity field, persisted to symbols. | Parser/model pipeline; defaults to `1` unless language extraction enriches it | `complexity_estimate: 3` |
| Decorators | Decorator/modifier strings captured with a symbol. | `ASTParser._extract_symbols()` | `["@router.get('/users')"]` |
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 40199675b..b02df1da1 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -5,14 +5,16 @@ text alone (the ``visibility_fn`` shape). Some cannot, because the answer
depends on surrounding AST context — C/C++ ``public:`` / ``private:``
access specifier siblings, ``static`` storage class at file scope and
``__declspec(dllexport)`` attributes; the C# and Java no-modifier
-defaults, which differ by enclosing declaration; TS/JS export position; Rust's
-trait items, which may not write a modifier of their own. Each has a
-``refine_*_visibility`` the parser calls after the generic
-``visibility_fn``.
+defaults, which differ by enclosing declaration; TS/JS export position;
+Python's module-level ``__all__``, which can export a name the identifier
+alone would call private; Rust's trait items, which may not write a modifier
+of their own. Each has a ``refine_*_visibility`` the parser calls after the
+generic ``visibility_fn``.
"""
from __future__ import annotations
+import ast
import re
from collections.abc import Callable
from typing import TYPE_CHECKING
@@ -31,6 +33,130 @@ def py_visibility(name: str, _mods: list[str]) -> str:
return "public"
+# ---------------------------------------------------------------------------
+# Python module __all__ visibility refinement
+# ---------------------------------------------------------------------------
+
+# A definition nested under one of these belongs to that scope, not to the
+# module's namespace, so a module-level ``__all__`` does not govern it.
+_PY_MEMBER_ANCESTORS = frozenset(
+ {"class_definition", "function_definition", "async_function_definition", "lambda"}
+)
+
+
+def _py_all_literal(value: ast.expr | None) -> set[str] | None:
+ """The names in a literal ``__all__`` value, or ``None`` when it is not literal.
+
+ List, tuple and set all enumerate statically; every element must be a plain
+ string constant. A comprehension, a concatenation, a call or a name is a
+ list this module assembles at runtime, and reading part of it would be
+ worse than reading none of it.
+ """
+ if not isinstance(value, (ast.List, ast.Tuple, ast.Set)):
+ return None
+ names: set[str] = set()
+ for element in value.elts:
+ if not isinstance(element, ast.Constant) or not isinstance(element.value, str):
+ return None
+ names.add(element.value)
+ return names
+
+
+def _py_all_has_other_binding(tree: ast.Module, accepted: list[ast.Name]) -> bool:
+ """True when ``__all__`` is written or imported anywhere but the literal assignments.
+
+ ``tree.body`` cannot see ``__all__ += [...]``, a binding inside an ``if``
+ or a function, an unpacking target, a ``del``, or ``from x import __all__``.
+ Each of those makes the list something other than the single literal the
+ caller can trust, so the whole signal is dropped rather than half-read.
+ """
+ accepted_ids = {id(node) for node in accepted}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Name) and node.id == "__all__":
+ if isinstance(node.ctx, (ast.Store, ast.Del)) and id(node) not in accepted_ids:
+ return True
+ elif isinstance(node, ast.alias) and node.name == "__all__":
+ return True
+ return False
+
+
+def py_module_all_names(src: str) -> frozenset[str] | None:
+ """Names from a literal module-level ``__all__``, or ``None`` for no signal.
+
+ ``None`` means the module gave no answer this pass may act on: no
+ ``__all__`` at all, one built at runtime (a comprehension, ``+=``, a
+ concatenation, a non-string element), or any shape that leaves the list
+ not statically enumerable — a second assignment, an assignment below module
+ level, a ``del``, an import of the name. A built list is treated as absent
+ rather than half-parsed.
+ """
+ # A module with no ``__all__`` token has no literal to read, and most
+ # modules do not — the parse below is the only cost this pass adds, so the
+ # reject keeps it off every Python file in the tree but the ones that use
+ # the name (the same shape as ``ts_export_aliases``' ``" as "`` guard).
+ if "__all__" not in src:
+ return None
+ try:
+ tree = ast.parse(src)
+ except (SyntaxError, ValueError):
+ return None
+
+ names: set[str] = set()
+ accepted: list[ast.Name] = []
+ assigned = False
+ for stmt in tree.body:
+ targets: list[ast.expr]
+ value: ast.expr | None
+ if isinstance(stmt, ast.Assign):
+ targets, value = stmt.targets, stmt.value
+ elif isinstance(stmt, ast.AnnAssign):
+ targets, value = [stmt.target], stmt.value
+ else:
+ continue
+ for target in targets:
+ if not (isinstance(target, ast.Name) and target.id == "__all__"):
+ continue
+ if assigned:
+ return None # two bindings: the second one wins at runtime
+ literal = _py_all_literal(value)
+ if literal is None:
+ return None
+ names = literal
+ assigned = True
+ accepted.append(target)
+
+ if not assigned or _py_all_has_other_binding(tree, accepted):
+ return None
+ return frozenset(names)
+
+
+def refine_py_visibility(
+ def_node: Node,
+ current_visibility: str,
+ name: str,
+ all_names: frozenset[str] | None,
+) -> str:
+ """Raise a module-level name the module lists in ``__all__`` to ``public``.
+
+ ``py_visibility`` reads the identifier alone, so an underscore-prefixed
+ name that ``__all__`` explicitly exports reads ``private``. Membership is
+ the one thing that changes here, and it is capped at the visibility label:
+ it sets no export marker, mints no edge and suppresses no dead-code
+ finding, so ``__all__`` alone can never mark a symbol reachable. A name
+ the list omits is left exactly as it was — ``__all__`` is often stale, and
+ demoting on absence would move a genuinely dead export into the opt-in
+ internals pass and hide it from the default report.
+ """
+ if all_names is None or name not in all_names:
+ return current_visibility
+ node = def_node.parent
+ while node is not None:
+ if node.type in _PY_MEMBER_ANCESTORS:
+ return current_visibility
+ node = node.parent
+ return "public"
+
+
def ts_visibility(name: str, mods: list[str]) -> str:
mods_lower = [m.lower() for m in mods]
# ``#x`` is an ECMAScript private member: private without any modifier.
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 9e5fbc722..c16357a08 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -64,9 +64,11 @@ from .extractors.bindings.ts_js import (
)
from .extractors.synthetic_symbols import extract_synthetic_symbols
from .extractors.visibility import (
+ py_module_all_names,
refine_cpp_visibility,
refine_csharp_visibility,
refine_java_visibility,
+ refine_py_visibility,
refine_rust_visibility,
refine_ts_visibility,
ts_deferred_export_names,
@@ -863,6 +865,7 @@ def _refine_visibility(
visibility: str,
name: str,
ts_deferred_exports: frozenset[str] | None,
+ py_all_names: frozenset[str] | None,
src: str,
) -> tuple[str, bool]:
"""``(visibility, is_exported_symbol)`` after the language's AST-context rules."""
@@ -885,6 +888,11 @@ def _refine_visibility(
# inline, via ``export { x }`` lists, or ``export default x``.
if language in _TS_JS_LANGUAGES:
return refine_ts_visibility(def_node, visibility, name, ts_deferred_exports), False
+ # Python: a literal ``__all__`` raises the names it lists to public; it
+ # never demotes the ones it omits. GDScript shares ``py_visibility`` but
+ # has no ``__all__``, so the gate is on the language, not the fn.
+ if language == "python":
+ return refine_py_visibility(def_node, visibility, name, py_all_names), False
# Rust: a trait's items may not write ``pub`` of their own, so the
# trait's modifier is the only place their visibility is stated.
if language == "rust":
@@ -1525,13 +1533,25 @@ class ASTParser:
ts_deferred_exports: frozenset[str] | None = None
if language in _TS_JS_LANGUAGES:
ts_deferred_exports = ts_deferred_export_names(src)
+ # Literal module ``__all__`` names, once per file for the Python
+ # refinement. None means no signal (built at runtime or absent).
+ py_all_names: frozenset[str] | None = None
+ if language == "python":
+ py_all_names = py_module_all_names(src)
cpp_exports = (
collect_cpp_export_types(matches, src) if language == "cpp" else CppExportTypes()
)
for capture_dict in matches:
built = self._symbol_from_match(
- capture_dict, config, file_info, src, cpp_exports, ts_deferred_exports, seen
+ capture_dict,
+ config,
+ file_info,
+ src,
+ cpp_exports,
+ ts_deferred_exports,
+ py_all_names,
+ seen,
)
if built is None:
continue
@@ -1564,6 +1584,7 @@ class ASTParser:
src: str,
cpp_exports: CppExportTypes,
ts_deferred_exports: frozenset[str] | None,
+ py_all_names: frozenset[str] | None,
seen: set[tuple[int, str]],
) -> tuple[Symbol, Node] | None:
"""One query match as a symbol and its definition node, or None to drop it.
@@ -1612,6 +1633,7 @@ class ASTParser:
config.visibility_fn(name, modifier_texts),
name,
ts_deferred_exports,
+ py_all_names,
src,
)
diff --git a/tests/unit/ingestion/test_py_visibility_refinement.py b/tests/unit/ingestion/test_py_visibility_refinement.py
new file mode 100644
index 000000000..c5203c0df
--- /dev/null
+++ b/tests/unit/ingestion/test_py_visibility_refinement.py
@@ -0,0 +1,197 @@
+"""Python visibility refinement from a literal module-level ``__all__``.
+
+``py_visibility`` reads the identifier alone, so a name the module excludes
+from ``__all__`` still read as exported and an underscore-prefixed name the
+module explicitly exports still read ``private``. ``refine_py_visibility``
+raises the second case to ``public`` and deliberately leaves the first alone:
+``__all__`` is advisory and often stale, so demoting on absence would move a
+genuinely dead export into the opt-in internals pass and hide it.
+
+The signal is capped at the visibility label. It sets no export marker, mints
+no edge and suppresses no finding, so membership can never, by itself, mark a
+symbol reachable — ``test_python_dead_code_fixes.py`` pins that end to end.
+Only a literal list, tuple or set of string constants counts; anything built
+at runtime is treated as absent rather than half-parsed.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.extractors.visibility import py_module_all_names
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _symbols(src: str, path: str = "src/module.py") -> dict[str, str]:
+ info = FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="python",
+ size_bytes=len(src),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = _PARSER.parse_file(info, src.encode("utf-8"))
+ return {s.name: s.visibility for s in parsed.symbols}
+
+
+# ---------------------------------------------------------------------------
+# Visibility refinement
+# ---------------------------------------------------------------------------
+
+
+def test_listed_top_level_names_stay_public() -> None:
+ src = """
+__all__ = ["foo", "Bar", "CONST_VAL"]
+
+def foo(): pass
+class Bar: pass
+CONST_VAL = 42
+"""
+ vis = _symbols(src)
+ assert vis["foo"] == "public"
+ assert vis["Bar"] == "public"
+ assert vis["CONST_VAL"] == "public"
+
+
+def test_underscore_name_listed_in_all_is_public() -> None:
+ """The one hard effect of the signal: an explicit export wins over the name."""
+ src = """
+__all__ = ["_internal_hook", "foo"]
+
+def _internal_hook(): pass
+def foo(): pass
+def _other(): pass
+"""
+ vis = _symbols(src)
+ assert vis["_internal_hook"] == "public"
+ assert vis["foo"] == "public"
+ assert vis["_other"] == "private"
+
+
+def test_name_absent_from_all_is_not_demoted() -> None:
+ """``__all__`` is advisory: absence never moves a name out of the export pass.
+
+ Demoting ``baz`` to private would hide it from the default report (the
+ uncalled-private pass is opt-in), which is the outcome the issue forbids.
+ """
+ src = """
+__all__ = ["foo"]
+
+def foo(): pass
+def _bar(): pass
+def baz(): pass
+"""
+ vis = _symbols(src)
+ assert vis["foo"] == "public"
+ assert vis["_bar"] == "private"
+ assert vis["baz"] == "public"
+
+
+def test_tuple_and_annotated_literal_forms_are_read() -> None:
+ src = """
+__all__: tuple[str, ...] = ("export_a", "_export_b")
+
+def export_a(): pass
+def _export_b(): pass
+def unexported(): pass
+"""
+ vis = _symbols(src)
+ assert vis["export_a"] == "public"
+ assert vis["_export_b"] == "public"
+ assert vis["unexported"] == "public"
+
+
+def test_members_are_governed_by_their_own_scope() -> None:
+ src = """
+__all__ = ["MyClass", "_module_helper"]
+
+class MyClass:
+ def public_method(self): pass
+ def _private_method(self): pass
+
+ class Inner:
+ def _deep(self): pass
+
+def _module_helper(): pass
+"""
+ vis = _symbols(src)
+ assert vis["MyClass"] == "public"
+ assert vis["_module_helper"] == "public"
+ assert vis["public_method"] == "public"
+ assert vis["_private_method"] == "private"
+ assert vis["Inner"] == "public"
+ assert vis["_deep"] == "private"
+
+
+def test_no_all_keeps_name_based_visibility() -> None:
+ src = """
+def public_fn(): pass
+def _private_fn(): pass
+def __dunder_name__(): pass
+"""
+ vis = _symbols(src)
+ assert vis["public_fn"] == "public"
+ assert vis["_private_fn"] == "private"
+ assert vis["__dunder_name__"] == "public"
+
+
+ "all_source",
+ [
+ # += mutates a list the literal read never saw.
+ '__all__ = ["foo"]\n__all__ += ["_bar"]',
+ # A comprehension is assembled at runtime.
+ '__all__ = [name for name in ("_bar",)]',
+ # Concatenation, a call, a non-string element.
+ '__all__ = ["foo"] + ["_bar"]',
+ '__all__ = list(("_bar",))',
+ '__all__ = ["foo", NAME]',
+ # A second binding and a nested one rewrite the list elsewhere.
+ '__all__ = ["foo"]\n__all__ = ["_bar"]',
+ 'if True:\n __all__ = ["_bar"]',
+ # An unpacking target is a binding this pass cannot enumerate.
+ '__all__, other = ["_bar"], 1',
+ "from other import __all__",
+ ],
+)
+def test_dynamic_all_is_treated_as_absent(all_source: str) -> None:
+ src = f"{all_source}\n\ndef foo(): pass\ndef _bar(): pass\n"
+ vis = _symbols(src)
+ assert vis["_bar"] == "private"
+ assert vis["foo"] == "public"
+
+
+# ---------------------------------------------------------------------------
+# py_module_all_names — the reader behind the refinement
+# ---------------------------------------------------------------------------
+
+
+def test_literal_reader_returns_the_listed_names() -> None:
+ assert py_module_all_names('__all__ = ["a", "_b"]') == frozenset({"a", "_b"})
+ assert py_module_all_names('__all__ = ("a", "_b")') == frozenset({"a", "_b"})
+ assert py_module_all_names('__all__ = {"a", "_b"}') == frozenset({"a", "_b"})
+ assert py_module_all_names('__all__: list[str] = ["a"]') == frozenset({"a"})
+
+
+def test_literal_reader_returns_none_without_a_signal() -> None:
+ # No ``__all__``, a built one, and an empty one are different answers:
+ # only the first two are "no signal", the third is "nothing exported".
+ assert py_module_all_names("def foo(): pass") is None
+ assert py_module_all_names("# see __all__ for the API\ndef foo(): pass") is None
+ assert py_module_all_names('__all__ = ["a"] + ["b"]') is None
+ assert py_module_all_names("__all__: list[str]") is None
+ assert py_module_all_names("__all__ = []") == frozenset()
+
+
+def test_literal_reader_survives_unparseable_source() -> None:
+ assert py_module_all_names("def broken(:\n") is None
diff --git a/tests/unit/ingestion/test_python_dead_code_fixes.py b/tests/unit/ingestion/test_python_dead_code_fixes.py
index 6e7f0cef0..12a13575d 100644
--- a/tests/unit/ingestion/test_python_dead_code_fixes.py
+++ b/tests/unit/ingestion/test_python_dead_code_fixes.py
@@ -363,6 +363,21 @@ def test_name_only_in_all_string_is_not_rescued() -> None:
assert "orphan" in _unused_export_names(graph)
+def test_all_promoted_name_is_not_rescued_by_the_promotion() -> None:
+ """``__all__`` raises a name to public; it does not mark it reachable.
+
+ ``_bar`` is underscore-prefixed, so the literal ``__all__`` is the only
+ reason it reads public, and nothing imports it. If membership were a
+ rescue the name would vanish from the report; the visibility change alone
+ must leave the unused-export finding standing."""
+ sources = {
+ "pkg/__init__.py": "",
+ "pkg/mod.py": ('__all__ = ["_bar"]\n\n\ndef _bar():\n return 1\n'),
+ }
+ graph = _graph_from_sources(sources)
+ assert "_bar" in _unused_export_names(graph)
+
+
def test_dynamic_use_edge_marks_target_file_live() -> None:
"""An incoming ``dynamic_uses`` edge keeps every public export of the
target file out of the unused-export results (analyzer contract that the