fix(python): stop a stdlib-named loose module from capturing a bare import (#4261)

A non-package directory with a file named like a stdlib module (e.g.
`scripts/logging.py`) wrongly captured a bare `import logging` from a
sibling, binding the import — and member calls like `logging.getLogger()` —
to the local file instead of the stdlib module.

The false binding arose at three independent layers, all now guarded by a
vendored, deterministic `_PYTHON_STDLIB_MODULE_NAMES` frozenset (union of
3.10 and 3.13 `sys.stdlib_module_names`, NOT the host's live set):

- `_resolve_python_module_path`: an absolute import whose top-level name is
  a stdlib module no longer resolves to a loose same-named `.py` file or
  namespace dir. A deliberate package shadow (`logging/__init__.py`) still
  resolves — only loose modules/namespaces are refused.
- `_repoint_python_sibling_imports`: stdlib-named loose siblings are no
  longer indexed as repoint targets.
- build.py #1504 pre-migration stem-alias index: a stdlib-named Python file
  no longer claims the collapsed bare-stem alias ("logging"), which would
  otherwise re-capture the external edge. The directory-scoped alias
  ("scripts_logging") is still registered, so genuine stale-id references to
  the file keep healing.

Adds a stdlib-shadow regression plus a non-stdlib positive control.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
safishamsiandClaude Opus 4.8 committed 2026-10-10 01:24:41 +01:00
1 parent 652020e9db
commit 289aa41284
4 files changed
+151 -4

No files matched your search

+13
View File
@@ -1375,6 +1375,7 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
# the header silently dropping out of the race and leaving the PHP file as
# the lone (wrong) "unambiguous" winner.
from graphify.extractors.base import _file_stem as _fs
from graphify.extractors.resolution import _PYTHON_STDLIB_MODULE_NAMES
_alias_candidates: dict[str, set[str]] = {}
for nid in node_set:
attrs = G.nodes[nid]
@@ -1385,6 +1386,16 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if _is_abs(str(sf)):
continue
new_stem = make_id(_fs(rel))
# A Python module whose bare stem is a stdlib name (e.g. `scripts/logging.py`)
# must not claim the collapsed bare-stem alias ("logging"): that alias would
# capture a genuine external `import logging` / `logging.getLogger()` edge
# and bind it to this same-named local file (#4261). The directory-scoped
# alias form ("scripts_logging") is still registered, so a real stale-id
# reference to this file keeps healing.
is_py_stdlib_stem = (
rel.suffix.lower() in (".py", ".pyi")
and make_id(rel.stem) in _PYTHON_STDLIB_MODULE_NAMES
)
if str(attrs.get("label", "")) == rel.name:
suffix = "" # this node IS the file, whatever its (possibly salted) id
else:
@@ -1394,6 +1405,8 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
for old_stem in _old_file_stems(rel):
if old_stem == new_stem:
continue
if is_py_stdlib_stem and old_stem in _PYTHON_STDLIB_MODULE_NAMES:
continue
alias = old_stem + suffix
_alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
_alias_candidates.setdefault(alias, set()).add(nid)
+10
View File
@@ -147,6 +147,7 @@ from graphify.extractors.resolution import ( # noqa: E402,F401
_resolve_js_module_path,
_resolve_lua_import_target,
_probe_python_module_candidate,
_PYTHON_STDLIB_MODULE_NAMES,
_resolve_python_module_path,
_resolve_python_namespace_dir,
_resolve_tsconfig_alias,
@@ -536,6 +537,10 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
# Sibling package directory inside parent_dir (parent_dir / subpkg / __init__.py)
pkg_dir = p_res.parent
parent_dir = pkg_dir.parent
# A loose package named like a stdlib module (e.g. `logging/`) must not
# capture a bare `import logging`, which means the stdlib module (#4261).
if pkg_dir.name in _PYTHON_STDLIB_MODULE_NAMES:
continue
if not (parent_dir / "__init__.py").is_file() and not (parent_dir / "__init__.pyi").is_file():
mod_key = _make_id(pkg_dir.name)
dir_siblings.setdefault(parent_dir, {}).setdefault(mod_key, set()).add(file_node)
@@ -547,6 +552,11 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
if (d / "__init__.py").is_file() or (d / "__init__.pyi").is_file():
continue
# A loose module named like a stdlib module (e.g. `logging.py`) must not
# capture a bare `import logging`, which means the stdlib module (#4261).
if p_res.stem in _PYTHON_STDLIB_MODULE_NAMES:
continue
mod_key = _make_id(p_res.stem)
dir_siblings.setdefault(d, {}).setdefault(mod_key, set()).add(file_node)
+60 -4
View File
@@ -2429,6 +2429,46 @@ def _infer_scan_root_namespace(root: Path) -> str:
return namespace
# Vendored set of Python standard-library top-level module names (union of the
# 3.10 and 3.13 `sys.stdlib_module_names`). A bare `import logging` almost always
# means the stdlib module, so a loose (non-package) local file named `logging.py`
# must NOT capture that import (#4261). This is a frozen constant, NOT the host's
# live `sys.stdlib_module_names`, so extraction is deterministic across machines
# and interpreter versions regardless of the Python running graphify. A deliberate
# package shadow (`logging/__init__.py`) is still resolved — only loose modules and
# namespace dirs are refused.
_PYTHON_STDLIB_MODULE_NAMES = frozenset({
"abc", "aifc", "annotationlib", "antigravity", "argparse", "array", "ast", "asynchat",
"asyncio", "asyncore", "atexit", "audioop", "base64", "bdb", "binascii", "bisect",
"builtins", "bz2", "cProfile", "calendar", "cgi", "cgitb", "chunk", "cmath", "cmd",
"code", "codecs", "codeop", "collections", "colorsys", "compileall", "compression",
"concurrent", "configparser", "contextlib", "contextvars", "copy", "copyreg", "crypt",
"csv", "ctypes", "curses", "dataclasses", "datetime", "dbm", "decimal", "difflib",
"dis", "doctest", "email", "encodings", "ensurepip", "enum", "errno", "faulthandler",
"fcntl", "filecmp", "fileinput", "fnmatch", "fractions", "ftplib", "functools", "gc",
"genericpath", "getopt", "getpass", "gettext", "glob", "graphlib", "grp", "gzip",
"hashlib", "heapq", "hmac", "html", "http", "idlelib", "imaplib", "imghdr", "imp",
"importlib", "inspect", "io", "ipaddress", "itertools", "json", "keyword", "lib2to3",
"linecache", "locale", "logging", "lzma", "mailbox", "mailcap", "marshal", "math",
"mimetypes", "mmap", "modulefinder", "msilib", "msvcrt", "multiprocessing", "netrc",
"nis", "nntplib", "nt", "ntpath", "nturl2path", "numbers", "opcode", "operator",
"optparse", "os", "ossaudiodev", "pathlib", "pdb", "pickle", "pickletools", "pipes",
"pkgutil", "platform", "plistlib", "poplib", "posix", "posixpath", "pprint", "profile",
"pstats", "pty", "pwd", "py_compile", "pyclbr", "pydoc", "pydoc_data", "pyexpat",
"queue", "quopri", "random", "re", "readline", "reprlib", "resource", "rlcompleter",
"runpy", "sched", "secrets", "select", "selectors", "shelve", "shlex", "shutil",
"signal", "site", "smtpd", "smtplib", "sndhdr", "socket", "socketserver", "spwd",
"sqlite3", "sre_compile", "sre_constants", "sre_parse", "ssl", "stat", "statistics",
"string", "stringprep", "struct", "subprocess", "sunau", "symtable", "sys", "sysconfig",
"syslog", "tabnanny", "tarfile", "telnetlib", "tempfile", "termios", "textwrap", "this",
"threading", "time", "timeit", "tkinter", "token", "tokenize", "tomllib", "trace",
"traceback", "tracemalloc", "tty", "turtle", "turtledemo", "types", "typing",
"unicodedata", "unittest", "urllib", "uu", "uuid", "venv", "warnings", "wave",
"weakref", "webbrowser", "winreg", "winsound", "wsgiref", "xdrlib", "xml", "xmlrpc",
"zipapp", "zipfile", "zipimport", "zlib", "zoneinfo",
})
def _resolve_python_module_path(module_name: str, current_path: Path, root: Path, level: int) -> Path | None:
if level > 0:
base = current_path.parent
@@ -2444,7 +2484,23 @@ def _resolve_python_module_path(module_name: str, current_path: Path, root: Path
# src/pkg/mod.py whether the scan root is the repo or src/ (#2072). Mirrors
# the upward walk already used for Lua (_resolve_lua_import_target, #1075).
rel = module_name.replace(".", "/")
hit = _probe_python_module_candidate(root / rel)
# A bare absolute import whose top-level name is a stdlib module means the
# stdlib module, not a loose same-named local file (e.g. a non-package
# `scripts/logging.py` must not capture `import logging`, #4261). A deliberate
# package shadow (`logging/__init__.py`) is a stronger signal of intent and is
# still resolved; only loose .py modules and namespace dirs are refused.
stdlib_shadow = module_name.split(".", 1)[0] in _PYTHON_STDLIB_MODULE_NAMES
def _accept(candidate: Path | None) -> Path | None:
if (
candidate is not None
and stdlib_shadow
and candidate.name not in ("__init__.py", "__init__.pyi")
):
return None
return candidate
hit = _accept(_probe_python_module_candidate(root / rel))
if hit is not None:
return hit
@@ -2458,11 +2514,11 @@ def _resolve_python_module_path(module_name: str, current_path: Path, root: Path
if ns and (module_name == ns or module_name.startswith(ns + ".")):
stripped = module_name[len(ns) + 1:] if module_name != ns else ""
if stripped:
hit = _probe_python_module_candidate(root / stripped.replace(".", "/"))
hit = _accept(_probe_python_module_candidate(root / stripped.replace(".", "/")))
if hit is not None:
return hit
else:
hit = _probe_python_module_candidate(root)
hit = _accept(_probe_python_module_candidate(root))
if hit is not None:
return hit
@@ -2481,7 +2537,7 @@ def _resolve_python_module_path(module_name: str, current_path: Path, root: Path
# __init__.py) is still probed.
if (anc / "__init__.py").is_file():
continue
cand = _probe_python_module_candidate(anc / rel)
cand = _accept(_probe_python_module_candidate(anc / rel))
if cand is not None:
return cand
return None
@@ -270,3 +270,71 @@ def test_aliased_import_resolves_member_call(tmp_path):
edges = _edge_set(G)
assert ("imports", "scripts_main", "scripts_greeter") in edges
assert ("calls", "scripts_main_run", "scripts_greeter_greet") in edges
def test_bare_stdlib_import_does_not_bind_to_same_stem_sibling(tmp_path):
"""G. Stdlib shadow (#4261):
A loose directory with a sibling named like a stdlib module
(scripts/logging.py) must NOT capture a bare `import logging` from
scripts/service.py — that import means the stdlib `logging`, so the edge
must stay the external bare target, not repoint to scripts_logging.
"""
scripts = tmp_path / "scripts"
scripts.mkdir(parents=True)
(scripts / "logging.py").write_text("def configure():\n return 1\n", encoding="utf-8")
(scripts / "service.py").write_text(
"import logging\n\n"
"def run():\n"
" return logging.getLogger(__name__)\n",
encoding="utf-8",
)
paths = [scripts / "logging.py", scripts / "service.py"]
# Cold cache: the shared content-hash cache can replay an extraction that
# predates the stdlib-shadow guard and mask the fix.
res = extract(
paths, root=tmp_path, parallel=False, cache_root=tmp_path / "graphify-cache"
)
import_edges = [
e for e in res["edges"]
if e.get("source") == "scripts_service" and e.get("relation") == "imports"
]
assert len(import_edges) == 1
assert import_edges[0]["target"] == "logging", (
f"Bare `import logging` was falsely repointed to the sibling stdlib-shadow "
f"file scripts_logging: {import_edges[0]}"
)
# The import and member call must stay unresolved external in the built graph,
# not bound to the same-stem sibling file node (#4261 via the build-side #1504
# pre-migration stem-alias index).
G = build_from_json(res, root=str(tmp_path), directed=True)
edges = _edge_set(G)
assert ("imports", "scripts_service", "scripts_logging") not in edges
assert ("calls", "scripts_service_run", "scripts_logging") not in edges
def test_non_stdlib_sibling_still_repoints_control(tmp_path):
"""H. Positive control for #4261:
The stdlib guard must not over-reach. A sibling whose name is NOT a stdlib
module (scripts/greeter.py) still repoints as before.
"""
scripts = tmp_path / "scripts"
scripts.mkdir(parents=True)
(scripts / "greeter.py").write_text("def greet():\n return 42\n", encoding="utf-8")
(scripts / "service.py").write_text(
"import greeter\n\n"
"def run():\n"
" return greeter.greet()\n",
encoding="utf-8",
)
paths = [scripts / "greeter.py", scripts / "service.py"]
res = extract(
paths, root=tmp_path, parallel=False, cache_root=tmp_path / "graphify-cache"
)
G = build_from_json(res, root=str(tmp_path), directed=True)
edges = _edge_set(G)
assert ("imports", "scripts_service", "scripts_greeter") in edges
assert ("calls", "scripts_service_run", "scripts_greeter_greet") in edges