Bind the package digest to the installed wheel, not source-tree egg-info

A non-editable install from a checkout leaves an untracked, gitignored
obliteratus.egg-info in the source root. The llama-tp gate and its TP
workers run with the checkout on sys.path, so importlib.metadata also
discovered that egg-info. installed_package_set_digest() enumerates every
visible distribution, so the stale build artifact broke the live package
identity (LMS_DEPENDENCY_DRIFT) before any hardware evidence was written.

model_identity now locates exactly one .dist-info for obliteratus under
the active prefix's purelib/platlib, requires its RECORD to own the
package that PathFinder finds there, and fails closed otherwise (no
wheel, egg-only, duplicate or disagreeing installs, ownership mismatch).
A setuptools source-tree obliteratus.egg-info outside the site dirs is
excluded from the inventory only after that wheel is found. All other
metadata/RECORD and duplicate checks are unchanged; a clean install keeps
the same digest.

run_conditional_gate.py refuses llama-tp-local-gpu up front (not_run,
exit 2, actionable message) when the checkout root holds an
obliteratus.egg-info, before any probe or GPU time; --allow-missing does
not bypass it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Joseph MaglyandClaude Opus 5.5 committed 2026-10-22 21:22:41 -04:00
1 parent 3d178f3379
commit 9129e765d1
4 files changed
+341 -5

No files matched your search

+96 -3
View File
@@ -3,13 +3,16 @@
from __future__ import annotations
import hashlib
import importlib.machinery
import importlib.metadata
import importlib.util
import os
import re
import stat
import sys
import sysconfig
from collections.abc import Iterable, Mapping, Sequence
from itertools import islice
from pathlib import Path
from typing import Any
@@ -71,10 +74,100 @@ def _bounded_text_digest(value: object, name: str) -> str:
return hashlib.sha256(payload).hexdigest()
def installed_package_set_digest(distributions: Iterable[Any] | None = None) -> str:
"""Digest every installed distribution's exact metadata and wheel RECORD."""
def _metadata_path(distribution: Any) -> Path:
# PathDistribution has no public metadata-directory accessor. Refuse other
# providers rather than guessing which installation their metadata describes.
path = getattr(distribution, "_path", None)
if (
not isinstance(distribution, importlib.metadata.PathDistribution)
or not isinstance(path, Path)
):
raise ContractError("obliteratus distribution metadata must be on the local filesystem")
return path.absolute()
source = importlib.metadata.distributions() if distributions is None else distributions
def _installed_obliteratus_distribution() -> tuple[Any, Path, tuple[Path, ...]]:
"""Locate the active prefix's wheel and its RECORD-owned installed package.
Do not use distribution(name): a cwd/PYTHONPATH entry ahead of site-packages
makes the default metadata finder discover build-time egg-info first.
"""
prefix = Path(sys.prefix).resolve()
sites = tuple(dict.fromkeys(
Path(sysconfig.get_path(key)).resolve() for key in ("purelib", "platlib")
))
if any(site == prefix or not site.is_relative_to(prefix) for site in sites):
raise ContractError("obliteratus installation paths must be under sys.prefix")
paths = [str(site) for site in sites]
candidates = list(islice(importlib.metadata.distributions(name="obliteratus", path=paths), 2))
if len(candidates) != 1:
raise ContractError(
"expected exactly one installed obliteratus wheel under sys.prefix; "
"install with --no-editable in the active environment; source-tree egg-info "
"is not an installed distribution and duplicate installations are ambiguous"
)
distribution = candidates[0]
metadata_path = _metadata_path(distribution)
if (
metadata_path.suffix != ".dist-info"
or metadata_path.parent not in sites
or metadata_path.resolve() != metadata_path
or _distribution_name(distribution.metadata["Name"]) != "obliteratus"
):
raise ContractError(
"obliteratus requires an installed .dist-info wheel, not source-tree egg-info"
)
specification = importlib.machinery.PathFinder.find_spec("obliteratus", paths)
origin = None if specification is None else specification.origin
package_file = metadata_path.parent / "obliteratus" / "__init__.py"
_bounded_text_digest(distribution.read_text("RECORD"), "RECORD")
if (
origin != str(package_file)
or not package_file.is_file()
or package_file.resolve() != package_file
or not any(
str(entry) == "obliteratus/__init__.py"
and Path(distribution.locate_file(entry)).absolute() == package_file
for entry in distribution.files or ()
)
):
raise ContractError("installed obliteratus wheel RECORD does not own the installed package")
return distribution, metadata_path, sites
def _installed_package_distributions() -> Iterable[Any]:
try:
yield from _package_distributions_with_installed_obliteratus()
except (KeyError, TypeError, UnicodeError, OSError):
raise ContractError("installed distribution metadata is unavailable") from None
def _package_distributions_with_installed_obliteratus() -> Iterable[Any]:
installed, installed_path, sites = _installed_obliteratus_distribution()
seen = False
for index, distribution in enumerate(importlib.metadata.distributions()):
if index >= MAX_DISTRIBUTIONS:
raise ContractError("installed distribution set exceeds its count bound")
if _distribution_name(distribution.metadata["Name"]) != "obliteratus":
yield distribution
continue
path = _metadata_path(distribution).resolve()
if path == installed_path:
seen = True
yield installed
elif path.name == "obliteratus.egg-info" and path.parent not in sites:
# Setuptools' source-tree build artifact is never installed metadata.
continue
else:
raise ContractError("visible obliteratus distributions disagree with the installed wheel")
if not seen:
yield installed
def installed_package_set_digest(distributions: Iterable[Any] | None = None) -> str:
"""Digest exact metadata/RECORDs, binding obliteratus to the active prefix's wheel."""
source = _installed_package_distributions() if distributions is None else distributions
records: list[dict[str, str]] = []
names: set[str] = set()
for index, distribution in enumerate(source):
+13
View File
@@ -194,6 +194,19 @@ def main() -> int:
report = args.evidence_dir / f"{args.gate}.json"
junit = args.evidence_dir / f"{args.gate}.xml"
if args.gate == "llama-tp-local-gpu":
artifact = Path(__file__).resolve().parents[1] / "obliteratus.egg-info"
if artifact.exists() or artifact.is_symlink():
message = (
f"Stale build metadata at {artifact}: source-root egg-info can shadow "
"installed distribution metadata in the qualification processes. "
"Remove this build artifact after the non-editable install, then rerun "
"llama-tp-local-gpu."
)
write_report(report, args.gate, "not_run", reason=message)
print(message, file=sys.stderr)
return 2
missing = missing_prerequisites(args.gate)
if missing:
message = "Missing prerequisites: " + ", ".join(missing)
+67
View File
@@ -460,6 +460,73 @@ def test_remote_prerequisites_are_actionable(monkeypatch):
assert run_conditional_gate.missing_prerequisites("remote-execution") == []
@pytest.mark.parametrize("allow_missing", [False, True])
@pytest.mark.parametrize("artifact_kind", ["directory", "file", "dangling-symlink"])
def test_llama_gate_rejects_source_metadata_before_probes(
tmp_path, monkeypatch, capsys, allow_missing, artifact_kind,
):
checkout = tmp_path / "checkout"
checkout.mkdir()
artifact = checkout / "obliteratus.egg-info"
if artifact_kind == "directory":
artifact.mkdir()
elif artifact_kind == "file":
artifact.write_text("stale metadata", encoding="utf-8")
else:
artifact.symlink_to(checkout / "missing")
monkeypatch.setattr(
run_conditional_gate, "__file__", str(checkout / "scripts" / "run_conditional_gate.py"),
)
monkeypatch.chdir(tmp_path) # Guard the checkout even when cwd is elsewhere.
evidence = tmp_path / "evidence"
monkeypatch.setattr(run_conditional_gate.sys, "argv", [
"run_conditional_gate", "llama-tp-local-gpu", "--evidence-dir", str(evidence),
*(["--allow-missing"] if allow_missing else []),
])
monkeypatch.setattr(conditional_gate_metadata, "_git_output", lambda *args: None)
monkeypatch.setattr(
run_conditional_gate, "missing_prerequisites",
lambda _gate: pytest.fail("stale metadata must be detected before hardware probes"),
)
monkeypatch.setattr(
run_conditional_gate.subprocess, "run",
lambda *_args, **_kwargs: pytest.fail("stale metadata must not launch pytest"),
)
assert run_conditional_gate.main() == 2
report = json.loads((evidence / "llama-tp-local-gpu.json").read_text())
assert report["status"] == "not_run"
assert str(artifact) in report["reason"]
assert "Remove this build artifact after the non-editable install" in report["reason"]
assert "Stale build metadata" in capsys.readouterr().err
assert not (evidence / "llama-tp-local-gpu.xml").exists()
def test_llama_gate_clean_checkout_still_launches_qualification(tmp_path, monkeypatch):
monkeypatch.setattr(
run_conditional_gate, "__file__", str(tmp_path / "scripts" / "run_conditional_gate.py"),
)
monkeypatch.setattr(run_conditional_gate.sys, "argv", [
"run_conditional_gate", "llama-tp-local-gpu", "--evidence-dir", str(tmp_path),
])
monkeypatch.setattr(run_conditional_gate, "missing_prerequisites", lambda _gate: [])
monkeypatch.setattr(conditional_gate_metadata, "_git_output", lambda *args: None)
commands = []
def run(command, *, check):
commands.append(command)
(tmp_path / "llama-tp-local-gpu.xml").write_text(
'<testsuite tests="1" failures="0" errors="0" skipped="0"/>', encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(run_conditional_gate.subprocess, "run", run)
assert run_conditional_gate.main() == 0
assert commands[0][:4] == [
sys.executable, "-m", "pytest", run_conditional_gate.GATES["llama-tp-local-gpu"],
]
assert json.loads((tmp_path / "llama-tp-local-gpu.json").read_text())["status"] == "passed"
def test_summary_rejects_selected_failure_and_marks_unselected_stale():
policy = {
"gates": [
+165 -2
View File
@@ -50,6 +50,169 @@ def _distribution(name: str, *, record: str = "module.py,sha256=abc,3\n") -> _Di
)
def _wheel(site: Path, name: str = "obliteratus", version: str = "1.2.3"):
metadata = site / f"{name}-{version}.dist-info"
metadata.mkdir(parents=True)
package = site / name / "__init__.py"
package.parent.mkdir(exist_ok=True)
package.write_text(f"__version__ = {version!r}\n", encoding="utf-8")
(metadata / "METADATA").write_text(
f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding="utf-8",
)
(metadata / "RECORD").write_text(
f"{name}/__init__.py,,\n{metadata.name}/METADATA,,\n{metadata.name}/RECORD,,\n",
encoding="utf-8",
)
return identity_module.importlib.metadata.Distribution.at(metadata)
@pytest.fixture
def installed_environment(tmp_path, monkeypatch):
prefix = tmp_path / "environment"
site = prefix / "lib" / "site-packages"
site.mkdir(parents=True)
monkeypatch.setattr(identity_module.sys, "prefix", str(prefix))
monkeypatch.setattr(identity_module.sysconfig, "get_path", lambda _key: str(site))
# Real PathDistribution discovery, isolated from the test host's packages.
monkeypatch.setattr(identity_module.sys, "path", [str(site)])
return site
@pytest.mark.parametrize("source_entry", ["absolute", "cwd"])
def test_source_egg_info_cannot_shadow_installed_identity(
tmp_path, monkeypatch, installed_environment, source_entry,
):
site = installed_environment
installed = _wheel(site)
dependency = _wheel(site, "dependency")
expected = installed_package_set_digest([installed, dependency])
assert installed_package_set_digest() == expected
source = tmp_path / "checkout"
egg = source / "obliteratus.egg-info"
egg.mkdir(parents=True)
(egg / "PKG-INFO").write_text("Name: obliteratus\nVersion: 0.0.0\n", encoding="utf-8")
(egg / "SOURCES.txt").write_text("obliteratus/__init__.py\n", encoding="utf-8")
source_package = source / "obliteratus"
source_package.mkdir()
(source_package / "__init__.py").write_text("__version__ = '0.0.0'\n", encoding="utf-8")
monkeypatch.chdir(source)
identity_module.sys.path.insert(0, str(source) if source_entry == "absolute" else "")
# Demonstrate the original lookup selects the stale build artifact.
assert identity_module.importlib.metadata.version("obliteratus") == "0.0.0"
resolved, metadata_path, _sites = identity_module._installed_obliteratus_distribution()
assert resolved.version == "1.2.3"
assert metadata_path == site / "obliteratus-1.2.3.dist-info"
assert installed_package_set_digest() == expected
(egg / "PKG-INFO").write_text("Name: obliteratus\nVersion: 9.9.9\n", encoding="utf-8")
assert installed_package_set_digest() == expected
(site / "dependency-1.2.3.dist-info" / "RECORD").write_text("changed,,\n", encoding="utf-8")
assert installed_package_set_digest() != expected
def test_source_egg_info_alone_is_not_an_installed_distribution(
tmp_path, monkeypatch, installed_environment,
):
egg = tmp_path / "checkout" / "obliteratus.egg-info"
egg.mkdir(parents=True)
(egg / "PKG-INFO").write_text("Name: obliteratus\nVersion: 0.0.0\n", encoding="utf-8")
identity_module.sys.path.insert(0, str(egg.parent))
with pytest.raises(ContractError, match="exactly one installed obliteratus wheel.*--no-editable"):
installed_package_set_digest()
def test_installed_egg_info_cannot_replace_wheel_metadata(installed_environment):
egg = installed_environment / "obliteratus.egg-info"
egg.mkdir()
(egg / "PKG-INFO").write_text("Name: obliteratus\nVersion: 0.0.0\n", encoding="utf-8")
with pytest.raises(ContractError, match="installed .dist-info wheel"):
installed_package_set_digest()
def test_disagreeing_installed_distributions_fail_closed(installed_environment):
_wheel(installed_environment)
_wheel(installed_environment, version="9.9.9")
with pytest.raises(ContractError, match="duplicate installations are ambiguous"):
installed_package_set_digest()
def test_visible_external_wheel_conflict_fails_closed(tmp_path, installed_environment):
_wheel(installed_environment)
external = tmp_path / "other-installation"
_wheel(external, version="9.9.9")
identity_module.sys.path.insert(0, str(external))
with pytest.raises(ContractError, match="distributions disagree"):
installed_package_set_digest()
def test_visible_site_alias_resolves_to_the_same_installed_wheel(tmp_path, installed_environment):
installed = _wheel(installed_environment)
alias = tmp_path / "site-alias"
alias.symlink_to(installed_environment, target_is_directory=True)
identity_module.sys.path[:] = [str(alias)]
assert installed_package_set_digest() == installed_package_set_digest([installed])
def test_metadata_from_one_site_cannot_describe_package_in_another(
monkeypatch, installed_environment,
):
site = installed_environment
other_site = site.parent / "platlib"
_wheel(site)
other_package = other_site / "obliteratus"
other_package.mkdir(parents=True)
(other_package / "__init__.py").write_text("VALUE = 1\n", encoding="utf-8")
monkeypatch.setattr(
identity_module.sysconfig, "get_path",
lambda key: str(other_site if key == "purelib" else site),
)
with pytest.raises(ContractError, match="RECORD does not own"):
installed_package_set_digest()
@pytest.mark.parametrize("broken", ["record", "ownership", "package", "alias"])
def test_installed_wheel_requires_record_owned_package(installed_environment, broken):
site = installed_environment
_wheel(site)
record = site / "obliteratus-1.2.3.dist-info" / "RECORD"
package = site / "obliteratus" / "__init__.py"
if broken == "record":
record.unlink()
elif broken == "ownership":
record.write_text("other.py,,\n", encoding="utf-8")
else:
package.unlink()
if broken == "alias":
target = site / "other.py"
target.write_text("VALUE = 1\n", encoding="utf-8")
package.symlink_to(target)
with pytest.raises(ContractError, match="RECORD"):
installed_package_set_digest()
def test_installed_identity_retains_dependency_metadata_checks(installed_environment):
_wheel(installed_environment)
_wheel(installed_environment, "dependency")
record = installed_environment / "dependency-1.2.3.dist-info" / "RECORD"
record.unlink()
with pytest.raises(ContractError, match="RECORD"):
installed_package_set_digest()
record.write_text("dependency/__init__.py,,\n", encoding="utf-8")
_wheel(installed_environment, "dependency", version="9.9.9")
with pytest.raises(ContractError, match="duplicate name"):
installed_package_set_digest()
def test_installation_paths_outside_active_prefix_are_rejected(
tmp_path, monkeypatch, installed_environment,
):
monkeypatch.setattr(identity_module.sysconfig, "get_path", lambda _key: str(tmp_path))
with pytest.raises(ContractError, match="under sys.prefix"):
installed_package_set_digest()
def test_installed_package_set_digest_is_order_independent_and_content_bound():
first = _distribution("Example_Package")
second = _distribution("Dependency")
@@ -143,9 +306,9 @@ def test_installed_package_set_refuses_unreadable_empty_or_unbounded_sets(monkey
installed_package_set_digest([_distribution("one"), _distribution("two")])
def test_installed_package_set_defaults_to_the_live_distribution_iterator(monkeypatch):
def test_installed_package_set_defaults_to_the_validated_live_distribution_iterator(monkeypatch):
live = [_distribution("alpha"), _distribution("beta")]
monkeypatch.setattr(identity_module.importlib.metadata, "distributions", lambda: iter(live))
monkeypatch.setattr(identity_module, "_installed_package_distributions", lambda: iter(live))
assert installed_package_set_digest() == installed_package_set_digest(live)