fix(extract): hash ambiguous Python import placeholders from root-relative data

`_suppress_ambiguous_python_imports` mints a node-less
`ambiguous_python_import_<sha1>` target for an import that more than one
scanned module could satisfy. The hash included the edge's `source_file`
and `source` id as they are at that point in the pipeline, which is
before relativization: `source_file` is still the absolute path and the
importer id is derived from it. The same commit built in two directories
therefore produced different placeholder ids, so `graph.json` was not
reproducible across checkouts and community detection could differ.

Hash the scan-root-relative `source_file` (POSIX form) with the module
name and source location, and drop the path-derived `source` id. These
already identify the import site uniquely, and the existing
`while target in node_ids` guard still prevents a collision with a real
node.

Adds a regression test that builds the same tree in two checkout
directories and asserts identical placeholder edges; it fails without
this change.

Fixes #5044

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit ff047dfea7)
This commit is contained in:
Shaikh Fardin authored and safishamsi committed 2026-11-07 22:31:34 +00:00
1 parent b81d8e51da
commit 444c164cfe
2 files changed
+63 -3

No files matched your search

+29 -3
View File
@@ -370,6 +370,26 @@ def _suppress_ambiguous_python_imports(
except (OSError, RuntimeError):
return False
def _root_relative_source_file(source_file: str) -> str:
"""Scan-root-relative POSIX form of ``source_file`` for id hashing."""
if not source_file:
return ""
path = Path(source_file)
if not path.is_absolute():
return path.as_posix()
try:
return path.relative_to(root).as_posix()
except ValueError:
pass
try:
return path.resolve().relative_to(root).as_posix()
except (OSError, RuntimeError, ValueError):
pass
try:
return os.path.relpath(str(path), str(root)).replace("\\", "/")
except ValueError:
return path.name # different Windows drive: no relative path
kept_edges: list[dict] = []
for edge in edges:
if not isinstance(edge, dict):
@@ -428,10 +448,16 @@ def _suppress_ambiguous_python_imports(
continue
# A raw dotted alias could itself belong to an unrelated real node. Use
# a stable, node-less id so the graph builder drops the unresolved edge
# instead of fabricating a link to that node.
# instead of fabricating a link to that node. The id is hashed only
# from checkout-independent material: at this point source_file and the
# importer's node id still embed the absolute scan root, so the same
# commit built in two directories would mint different ids (#5044).
# The root-relative file, the import's location and the module name
# already identify the import site uniquely.
identity = "\0".join((
str(module_name), str(edge.get("source_file", "")),
str(edge.get("source_location", "")), str(edge.get("source", "")),
str(module_name),
_root_relative_source_file(str(edge.get("source_file", ""))),
str(edge.get("source_location", "")),
))
target = _make_id(f"ambiguous_python_import_{hashlib.sha1(identity.encode()).hexdigest()[:12]}")
while target in node_ids:
@@ -439,3 +439,37 @@ def test_loose_module_directly_under_src_is_not_aliased(tmp_path):
assert _namespace_src_module_parts(("d", "src", "airflow", "sql", "hooks", "sql.py")) == (
"airflow", "sql", "hooks", "sql.py",
)
def test_ambiguous_import_placeholder_id_is_independent_of_checkout_path(tmp_path):
"""#5044: the same tree built in two directories must mint the same
placeholder id for an ambiguous import. The id used to hash the absolute
source path and the absolute-path-derived importer id, so only the checkout
location changed it."""
files = {
"app/main.py": "from helper import f\n\n\ndef run():\n return f()\n",
"one/helper.py": "def f():\n return 1\n",
"two/helper.py": "def f():\n return 2\n",
}
def placeholders(checkout: Path) -> list[tuple[str, str, str]]:
paths = []
for rel, body in files.items():
path = checkout / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
paths.append(path)
result = extract(
paths, cache_root=checkout / "cache", root=checkout, parallel=False
)
return sorted(
(edge["source"], edge["target"], edge.get("source_file", ""))
for edge in result["edges"]
if str(edge.get("target", "")).startswith("ambiguous_python_import_")
)
first = placeholders(tmp_path / "checkout-aaa")
second = placeholders(tmp_path / "nested" / "checkout-bbbbbbbb")
assert first, "the ambiguous `helper` import should keep a placeholder edge"
assert first == second, f"placeholder ids depend on the checkout path: {first} != {second}"