From a377c78eb385d3f3cb83635fbd65b8a508c40393 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:11:19 +0000 Subject: [PATCH 1/2] Entry identity: reusable outputs in conda; warn on an uncertain first write Conda installs setuptools as an .egg-info without RECORD, and brick_identity's closure (every extra included) reached it, so every entry record written in a conda environment was uncertain and every rerun refused with ENTRY_IDENTITY_UNCERTAIN (setuptools: RECORD missing). - entry_identity: the installers pip, setuptools and wheel are neither listed nor followed in the requirement closure (INSTALL_TOOLS); every other library without RECORD stays uncertain (ADR 0007 (b)); a caller's explicit name is still identified. uncertain_library names the library behind an uncertain brick part. - entry_record: write_entry_record warns (EntryIdentityWarning, text from identity_warning) that an output written under an uncertain identity will never be reused. - entry_errors: uncertain_code_fix; the ENTRY_IDENTITY_UNCERTAIN fix names an uncertain library and why instead of telling the user to reinstall a brick that is already a released install. - Tests with egg-info distributions in a temporary site folder; docs (contract 21.2/21.4, plan 12 question 93), CHANGELOG Unreleased (v0.10.1). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp98tSnytZ9QCrHt6297 --- AGENTS.md | 3 +- CHANGELOG.md | 26 ++++++ docs/contract.md | 15 +++- docs/plan.md | 15 ++++ src/morphobricks_preprocessing/__init__.py | 4 + .../entry_errors.py | 53 ++++++++++-- .../entry_identity.py | 40 +++++++-- .../entry_record.py | 38 ++++++++- tests/code_identity_tree.py | 22 ++++- tests/test_entry_identity.py | 84 +++++++++++++++++++ tests/test_entry_record.py | 40 ++++++++- 11 files changed, 321 insertions(+), 19 deletions(-) create mode 100644 tests/test_entry_identity.py diff --git a/AGENTS.md b/AGENTS.md index b513a96f..91b99efb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,7 +232,8 @@ src/morphobricks_preprocessing/ 0011 settings file, Q10), folder_values (no pixel), settings_template entry_record.py morphobricks_entry.json: build_record, write_entry_record, check_entry_record, EntryResult, reuse_or_refuse (RE10); entry_identity.py brick_identity (every - file of the brick hashed against RECORD, libraries by RECORD digest); + file of the brick hashed against RECORD, libraries by RECORD digest; + pip, setuptools and wheel left out: INSTALL_TOOLS, v0.10.1); entry_publish.py default_output, check_output_place, staging_folder, publish (renameat2 RENAME_NOREPLACE, or an exclusive mkdir) notebook_entry_card.py the card "Run on a validated folder" of every brick (ADR 0007 Q6) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..4dbbef02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,32 @@ The design is [`docs/design-v0.4.md`](docs/design-v0.4.md), imported unchanged f are in [docs/plan.md](docs/plan.md) §12. (The v0.3 to v0.4 migration guide was removed in v0.5.1: no run before v0.5.1 is read.) +## Unreleased (v0.10.1) + +### Fixed + +- **An entry output is reusable in a conda environment** (Spec ADR 0007 RE10). Conda installs + `setuptools` as an `.egg-info` with no `RECORD`, and `brick_identity` followed every + requirement of the brick, every extra included, down to it: every record written there was + `uncertain`, so every rerun and `check` of the output was refused with + `ENTRY_IDENTITY_UNCERTAIN: ... (setuptools: RECORD missing)`. The installers `pip`, + `setuptools` and `wheel` are now neither listed nor followed in the identity's closure + (`entry_identity.INSTALL_TOOLS`): no brick computes a value with them. Any other library + without a `RECORD`, or editable, still makes the identity uncertain (ADR 0007 (b)); a name a + brick passes in `libraries` is identified whatever it is. An output whose v0.10.0 record lists + one of them is another identity for v0.10.1 (`ENTRY_OUTPUT_EXISTS` naming it); upgrading + preprocessing changes every brick's identity anyway, preprocessing being one of its libraries + (plan §12 question 93). +- **A first run under an uncertain identity says so.** `write_entry_record` writes the record and + warns with `EntryIdentityWarning` (text from the new `identity_warning`, both re-exported) that + the output will never be reused, naming the reason and the fix, instead of only the next run + failing. +- **The refusal's fix names the actual cause.** When the brick is a released install and a + library is what is uncertain, the fix of `ENTRY_IDENTITY_UNCERTAIN` names that library (no + `RECORD`: reinstall it with `pip install --force-reinstall --no-deps "=="`; or + an editable install) and says the brick needs no change, instead of "Install a released + ``" (`entry_errors.uncertain_code_fix`, `entry_identity.uncertain_library`). + ## v0.10.0 (3 December 2026) Minor release with a **breaking change of file format**: the histogram table is diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..d26ff526 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1751,7 +1751,12 @@ no image of the run. **21.2 Entry refusals** (`entry_errors`). `EntryError` (`code`, `message`, `fix`, `subjects`; `as_json()` for the command line's stderr): `ENTRY_SETTING_MISSING`, `ENTRY_SETTING_INVALID`, `ENTRY_OUTPUT_PLACE`, `ENTRY_OUTPUT_EXISTS`, `ENTRY_OUTPUT_INCOMPLETE`, `ENTRY_IDENTITY_UNCERTAIN`, -one constructor each, with the ADR's texts under its revision R2 (choices are settings). +one constructor each, with the ADR's texts under its revision R2 (choices are settings). Ahead of +the ADR (v0.10.1, plan §12 question 93): when the brick is a released install and a library of +its identity is what is uncertain, the fix of `ENTRY_IDENTITY_UNCERTAIN` cases (a)-(c) names that +library and why (`uncertain_code_fix`: no `RECORD`, with the `pip install --force-reinstall +--no-deps "=="` that writes one, or an editable install) instead of telling the +user to reinstall the brick. **21.3 Settings** (`entry_settings`, `entry_declaration`). A brick declares its settings in its ADR 0011 `defaults.toml` plus a static `entry_settings.json` keyed `
.` (`type`, @@ -1768,7 +1773,13 @@ canonical JSON (sorted keys, UTF-8, LF), written last: `entry_version` (1), `bri `source`, `resolver`, `settings`, `execution`, `locations`, `outputs`, `identity` (the SHA-256 of the canonical JSON of `entry_version`, `brick`, `run_folder` without its path and the table's file SHA-256, `resolver`, and the settings with `affects_values`) and `written_at`. Reuse or refuse -(`reuse_or_refuse`) follows ADR 0007 RE10; publication is exclusive (`publish`). +(`reuse_or_refuse`) follows ADR 0007 RE10; publication is exclusive (`publish`). The libraries +of `brick` are the brick's requirements, directly or through another, every extra included, +**except the installers `pip`, `setuptools` and `wheel`** (`entry_identity.INSTALL_TOOLS`, v0.10.1, +plan §12 question 93), which are neither listed nor followed; a name the brick passes in +`libraries` is identified whatever it is. `write_entry_record` of a record whose `brick` is +`uncertain` writes it and warns (`EntryIdentityWarning`, text `identity_warning`) that the output +will never be reused, naming the reason and the fix. **21.5 Test helpers.** `testing_spy.decoder_spy` counts every pixel-decoding route; `testing_folder_states.derive_state` and `report_state` make the folder states of ADR 0007 row E2. diff --git a/docs/plan.md b/docs/plan.md index a391f787..2a6935c0 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1819,3 +1819,18 @@ Raised during review; to be decided before the milestones that need them: hashes is `RUN_FOLDER_CONTENT_NOT_RECORDED` (ahead of the ADR, Spec issue 84); masks stay `fingerprint` for now (the run records no mask hash; a separate issue). +93. Why was an entry output never reused in a conda environment, and what is left out of the + code identity? *Decided (3 December 2026, in the session fixing the v0.10.0 wave's + entry-identity gap; for the owner's review):* conda installs `setuptools` as an `.egg-info` + with no `RECORD`, and the identity's closure, every extra included, reached it, so every + record was `uncertain` (ADR 0007 (b)) and every rerun refused. The installers `pip`, + `setuptools` and `wheel` leave the closure (`entry_identity.INSTALL_TOOLS`): they install and + build distributions and no brick computes a value with them, so they are not libraries "the + brick may compute with". The smallest change the ADR allows: dropping extras would make the + identity weaker than MorphoFeature's `brick_cache` key (which takes every extra) and would not + remove `setuptools`, which some libraries require with no extra (torch on Python 3.12); + identifying an `.egg-info` by name and version would contradict ADR 0007 (b), which keeps + every other library without a `RECORD` uncertain. A first run under an uncertain identity now + warns that its output will never be reused (`EntryIdentityWarning`), and the refusal's fix + names an uncertain library rather than the brick. The ADR's record paragraph is to say that + the installers are not followed (a Spec note for the owner). diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index 31457c35..a0daf251 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -99,12 +99,14 @@ ) from .entry_record import ( ENTRY_FILENAME, + EntryIdentityWarning, EntryResult, brick_identity, build_record, check_entry_record, check_output_place, default_output, + identity_warning, publish, reuse_or_refuse, staging_folder, @@ -372,6 +374,7 @@ "DiscoveryResult", "EntryDeclaration", "EntryError", + "EntryIdentityWarning", "EntryResult", "EntrySettings", "FileEntry", @@ -510,6 +513,7 @@ "he_tissue_mask_array", "header_axes", "header_axis_issue", + "identity_warning", "image_type_issues", "inspect_experiment", "inspect_image", diff --git a/src/morphobricks_preprocessing/entry_errors.py b/src/morphobricks_preprocessing/entry_errors.py index 751dc530..29ae5af0 100644 --- a/src/morphobricks_preprocessing/entry_errors.py +++ b/src/morphobricks_preprocessing/entry_errors.py @@ -229,8 +229,50 @@ def entry_output_incomplete(output: str | Path, brick: str, reason: str) -> Entr ) +def uncertain_code_fix( + brick: str = "the brick", library: tuple[str, str | None, str] | None = None +) -> str: + """Return the fix of ``ENTRY_IDENTITY_UNCERTAIN`` cases (a)-(c): the installed code. + + Parameters + ---------- + brick + The brick's distribution name. + library + When a library, not the brick, is what is uncertain: its name, installed version and + why (``"editable install"`` or ``"RECORD missing"``, from + :func:`.entry_identity.library_identity`). + The ADR's text names the brick; telling the user to reinstall a brick that is already a + released install would not help, so the fix names the library instead. + """ + if library is None: + return ( + f"Install a released {brick} (not editable, its files as its RECORD lists them), " + "or give another --output." + ) + name, version, why = library + pinned = f"{name}=={version}" if version else name + if why == "RECORD missing": + return ( + f"The library {name} {version or ''}".rstrip() + + " is installed without a RECORD file (conda and setup.py installs write none), " + f"so its files cannot be identified; {brick} itself needs no change. Reinstall " + f'{name} with pip (pip install --force-reinstall --no-deps "{pinned}"), or give ' + "another --output." + ) + return ( + f"The library {name} is an editable install; {brick} itself needs no change. Install a " + f'released {name} (pip install "{pinned}"), or give another --output.' + ) + + def entry_identity_uncertain( - output: str | Path, reason: str, case: str, brick: str = "the brick" + output: str | Path, + reason: str, + case: str, + brick: str = "the brick", + *, + library: tuple[str, str | None, str] | None = None, ) -> EntryError: """Return ``ENTRY_IDENTITY_UNCERTAIN``: the output cannot be compared with this run. @@ -245,14 +287,15 @@ def entry_identity_uncertain( :data:`UNCERTAIN_MOVED` ((e)); it chooses the fix. brick The brick's distribution name, for case (a)-(c)'s fix. + library + For case (a)-(c), the library that is uncertain when the brick itself is not + (:func:`.entry_identity.uncertain_library`); the fix then names it + (:func:`uncertain_code_fix`). """ if case not in _UNCERTAIN_CASES: raise ValueError(f"{case!r} is not one of {_UNCERTAIN_CASES}") fix = { - UNCERTAIN_CODE: ( - f"Install a released {brick} (not editable, its files as its RECORD lists them), " - "or give another --output." - ), + UNCERTAIN_CODE: uncertain_code_fix(brick, library), UNCERTAIN_RECORD: "Give another --output.", UNCERTAIN_MOVED: ( "Open the run folder with the experiment and masks folders at the location the " diff --git a/src/morphobricks_preprocessing/entry_identity.py b/src/morphobricks_preprocessing/entry_identity.py index 4d0abced..f89726f8 100644 --- a/src/morphobricks_preprocessing/entry_identity.py +++ b/src/morphobricks_preprocessing/entry_identity.py @@ -5,14 +5,21 @@ commit, with **every installed file of the brick hashed** against ``RECORD`` on each run (:func:`.code_identity.code_identity`, owner decision of 19 November 2026); the Python version and the machine; every library the brick may compute with (each requirement of its -distribution, directly or through another, whatever its extra or marker; the names a caller -adds, such as MorphoFeature's ``RESULT_LIBRARIES``; every installed ``nvidia-*``), each by name, +distribution, directly or through another, whatever its extra or marker, except the installers +:data:`INSTALL_TOOLS`; the names a caller adds, such as MorphoFeature's ``RESULT_LIBRARIES``; +every installed ``nvidia-*``), each by name, version, Git commit and the SHA-256 of its ``RECORD``, with **no per-file hashing of libraries**; the thread setting (recorded in the ``brick`` part but left out of the record's identity digest: ADR 0007 RE7, owner decision 3 of 1 December 2026); a provider manifest's and the model weights' SHA-256. An editable install of the brick or of a library, a brick or library without ``RECORD``, or a brick file that differs from its ``RECORD`` makes the identity ``uncertain`` (never reused). + +The installers ``pip``, ``setuptools`` and ``wheel`` are not followed as requirements (v0.10.1): +they install and build distributions, no brick computes a value with them, and conda installs +``setuptools`` as an ``.egg-info`` without ``RECORD``, which made every entry output written in a +conda environment uncertain (never reused). A caller that names one in ``libraries`` still has +it identified. """ from __future__ import annotations @@ -37,6 +44,8 @@ "NUMBA_NUM_THREADS", ) """The thread variables MorphoFeature's ``brick_cache`` keys on (its ``threads.py``).""" +INSTALL_TOOLS = frozenset({"pip", "setuptools", "wheel"}) +"""Installers left out of the requirement closure: no brick computes with them (v0.10.1).""" _REQUIREMENT_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?") @@ -57,7 +66,8 @@ def _normalized(name: str) -> str: def _requirements(name: str) -> set[str]: """Return every distribution ``name`` requires, directly or through an installed one. - Every requirement counts, whatever its extra or marker (MorphoFeature's ``brick_cache``). + Every requirement counts, whatever its extra or marker (MorphoFeature's ``brick_cache``), + except the installers :data:`INSTALL_TOOLS`, which are neither listed nor followed. """ found: set[str] = set() pending = [_normalized(name)] @@ -68,7 +78,9 @@ def _requirements(name: str) -> set[str]: continue # recorded as absent for requirement in requires: match = _REQUIREMENT_NAME.match(requirement.strip()) - if match and _normalized(match.group()) not in found: + if not match or _normalized(match.group()) in INSTALL_TOOLS: + continue + if _normalized(match.group()) not in found: found.add(_normalized(match.group())) pending.append(_normalized(match.group())) return found @@ -111,6 +123,23 @@ def library_identity(name: str) -> dict[str, object]: return found +def uncertain_library(brick: Mapping[str, object]) -> tuple[str, str | None, str] | None: + """Return the library that makes a ``brick`` part uncertain: name, version and why. + + None when the brick is certain or when its own code is what is uncertain (the brick's + reason comes first, as in :func:`brick_identity`). + """ + code = brick.get("code") + if not brick.get("uncertain") or not isinstance(code, Mapping) or not code.get("verified"): + return None + libraries = brick.get("libraries") + for name, found in (libraries if isinstance(libraries, Mapping) else {}).items(): + if isinstance(found, Mapping) and found.get("uncertain"): + version = found.get("version") + return str(name), version if isinstance(version, str) else None, str(found["uncertain"]) + return None + + def thread_setting(threads: Mapping[str, object] | None = None) -> dict[str, object]: """Return the thread setting of the identity (RE7, MorphoFeature's ``thread_identity``). @@ -141,7 +170,8 @@ def brick_identity( The brick's ID, as the output name uses it. libraries Libraries the brick computes with besides its requirements (MorphoFeature's - ``RESULT_LIBRARIES``); every installed ``nvidia-*`` is always added. + ``RESULT_LIBRARIES``), identified even when one is in :data:`INSTALL_TOOLS`; every + installed ``nvidia-*`` is always added. provider_manifest_sha256 For a MorphoFeature provider, its manifest's SHA-256. weights diff --git a/src/morphobricks_preprocessing/entry_record.py b/src/morphobricks_preprocessing/entry_record.py index 53a5daf5..502b419b 100644 --- a/src/morphobricks_preprocessing/entry_record.py +++ b/src/morphobricks_preprocessing/entry_record.py @@ -43,6 +43,7 @@ import json import os import re +import warnings from collections.abc import Iterable, Mapping from dataclasses import dataclass from pathlib import Path @@ -56,10 +57,12 @@ entry_identity_uncertain, entry_output_exists, entry_output_incomplete, + uncertain_code_fix, ) from .entry_identity import brick_identity as brick_identity from .entry_identity import library_identity as library_identity from .entry_identity import plain as _plain +from .entry_identity import uncertain_library as uncertain_library from .entry_publish import ENTRY_FILENAME as ENTRY_FILENAME from .entry_publish import check_output_place as check_output_place from .entry_publish import default_output as default_output @@ -90,6 +93,29 @@ class EntryRecordError(ValueError): """A ``morphobricks_entry.json`` that is not a record this package reads (the reason).""" +class EntryIdentityWarning(UserWarning): + """An output written under an uncertain code identity: it will never be reused (RE10).""" + + +def identity_warning(record: Mapping, output: str | os.PathLike | None = None) -> str | None: + """Return what a first run under an uncertain identity tells its user, or None if certain. + + ADR 0007 RE10 publishes such an output and never reuses it; saying so when it is written + spares the user a refusal they cannot explain on the next run. ``output`` is the published + output's path, when known (:func:`write_entry_record` writes into the staging folder). + """ + brick = record["brick"] + if not brick.get("uncertain"): + return None + fix = uncertain_code_fix(str(brick.get("distribution")), uncertain_library(brick)) + subject = "This output" if output is None else f"The output {output}" + return ( + f"{subject} is written, but its code identity is uncertain ({brick['uncertain']}), so " + "it will never be reused: a later run or check with this output is refused with " + f"ENTRY_IDENTITY_UNCERTAIN. {fix}" + ) + + @dataclass(frozen=True) class EntryResult: """What a brick's entry returns (ADR 0007 "The entry contract"). @@ -254,10 +280,14 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path: """Write ``record`` as ``morphobricks_entry.json`` in ``folder`` (canonical, UTF-8, LF). Call it last: the record marks a complete output. It is checked by :func:`check_entry_record` - before it is written, and never replaces an existing record. + before it is written, and never replaces an existing record. A record whose ``brick`` is + uncertain is written and an :class:`EntryIdentityWarning` (:func:`identity_warning`) says that + the output will never be reused. """ data = _plain(record) _checked(data, Path(folder) / ENTRY_FILENAME) + if (message := identity_warning(data)) is not None: + warnings.warn(message, EntryIdentityWarning, stacklevel=2) text = json.dumps(data, sort_keys=True, ensure_ascii=False, indent=1) + "\n" path = Path(folder) / ENTRY_FILENAME with open(path, "x", encoding="utf-8", newline="\n") as handle: @@ -475,7 +505,11 @@ def reuse_or_refuse( return None if record["brick"].get("uncertain"): raise entry_identity_uncertain( - folder, record["brick"]["uncertain"], UNCERTAIN_CODE, record["brick"]["distribution"] + folder, + record["brick"]["uncertain"], + UNCERTAIN_CODE, + record["brick"]["distribution"], + library=uncertain_library(record["brick"]), ) path = folder / ENTRY_FILENAME if not path.is_file() or path.is_symlink(): diff --git a/tests/code_identity_tree.py b/tests/code_identity_tree.py index 08bc3060..040521d3 100644 --- a/tests/code_identity_tree.py +++ b/tests/code_identity_tree.py @@ -19,14 +19,19 @@ def _hash(data): return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode() -def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT): - """Install ``files`` as the distribution ``fakepkg`` 1.0 under ``site``; return it.""" +def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT, requires=()): + """Install ``files`` as the distribution ``fakepkg`` 1.0 under ``site``; return it. + + ``requires`` are its ``Requires-Dist`` lines. + """ info = site / "fakepkg-1.0.dist-info" info.mkdir(parents=True) for name, data in files.items(): (site / name).parent.mkdir(parents=True, exist_ok=True) (site / name).write_bytes(data) - (info / "METADATA").write_bytes(b"Metadata-Version: 2.1\nName: fakepkg\nVersion: 1.0\n") + lines = ["Metadata-Version: 2.1", "Name: fakepkg", "Version: 1.0"] + lines += [f"Requires-Dist: {requirement}" for requirement in requires] + (info / "METADATA").write_text("\n".join(lines) + "\n", encoding="utf-8") url = {"url": "file:///src/fakepkg"} url |= {"dir_info": {"editable": True}} if editable else {"vcs_info": {"commit_id": commit}} (info / "direct_url.json").write_text(json.dumps(url), encoding="utf-8") @@ -41,6 +46,17 @@ def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT): return metadata.PathDistribution(info) +def install_egg_info(site, name, version, requires=()): + """Install ``name`` as conda installs ``setuptools``: an ``.egg-info`` with no ``RECORD``.""" + info = site / f"{name}-{version}-py3.egg-info" + info.mkdir(parents=True) + (info / "PKG-INFO").write_text( + f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding="utf-8" + ) + (info / "requires.txt").write_text("".join(f"{r}\n" for r in requires), encoding="utf-8") + return metadata.PathDistribution(info) + + def modules_of(site, names=("fakepkg", "fakepkg.mod")): """Imported modules of the installation, as ``sys.modules`` would hold them.""" paths = {"fakepkg": "fakepkg/__init__.py", "fakepkg.mod": "fakepkg/mod.py"} diff --git a/tests/test_entry_identity.py b/tests/test_entry_identity.py new file mode 100644 index 00000000..53f49b64 --- /dev/null +++ b/tests/test_entry_identity.py @@ -0,0 +1,84 @@ +"""The requirement closure of an entry's code identity (Spec ADR 0007 "The run record"). + +A conda environment installs ``setuptools`` as an ``.egg-info`` with no ``RECORD``; every entry +output written there was uncertain (never reused) because the closure, every extra included, +reached it. The installers pip, setuptools and wheel are left out of the closure (v0.10.1); any +other library without a ``RECORD`` stays uncertain (ADR 0007 (b)), and the refusal's fix names +that library instead of telling the user to reinstall the brick. +""" + +from __future__ import annotations + +from code_identity_tree import install, install_egg_info +from morphobricks_preprocessing import entry_identity +from morphobricks_preprocessing.entry_errors import ( + UNCERTAIN_CODE, + entry_identity_uncertain, + uncertain_code_fix, +) + + +def test_a_conda_setuptools_egg_info_no_longer_makes_the_identity_uncertain(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site, requires=("setuptools>=60", 'wheel; extra == "build"', "pip")) + install_egg_info(site, "setuptools", "65.6.3", requires=("eggy",)) + install_egg_info(site, "wheel", "0.41.0") + install_egg_info(site, "pip", "24.0") + monkeypatch.syspath_prepend(str(site)) + # The fake egg-info is what metadata finds: without the exclusion it would be uncertain. + assert entry_identity.library_identity("setuptools")["uncertain"] == "RECORD missing" + identity = entry_identity.brick_identity("fakepkg", "fake") + assert identity["uncertain"] is None + assert not {"setuptools", "wheel", "pip", "eggy"} & set(identity["libraries"]) + assert entry_identity.uncertain_library(identity) is None + + +def test_an_installer_the_caller_names_is_still_identified(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site) + install_egg_info(site, "setuptools", "65.6.3") + monkeypatch.syspath_prepend(str(site)) + identity = entry_identity.brick_identity("fakepkg", "fake", libraries=["setuptools"]) + assert identity["uncertain"] == "setuptools: RECORD missing" + + +def test_another_egg_info_library_stays_uncertain_and_the_fix_names_it(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site, requires=("eggy>=2",)) + install_egg_info(site, "eggy", "2.0") + monkeypatch.syspath_prepend(str(site)) + identity = entry_identity.brick_identity("fakepkg", "fake") + assert identity["code"]["verified"] is True # the brick itself is a released install + assert identity["uncertain"] == "eggy: RECORD missing" + library = entry_identity.uncertain_library(identity) + assert library == ("eggy", "2.0", "RECORD missing") + error = entry_identity_uncertain( + "/out", identity["uncertain"], UNCERTAIN_CODE, "fakepkg", library=library + ) + assert "Install a released fakepkg" not in error.message + assert "(eggy: RECORD missing)" in error.message + assert error.fix == ( + "The library eggy 2.0 is installed without a RECORD file (conda and setup.py installs " + "write none), so its files cannot be identified; fakepkg itself needs no change. " + 'Reinstall eggy with pip (pip install --force-reinstall --no-deps "eggy==2.0"), or give ' + "another --output." + ) + + +def test_the_fix_for_the_brick_itself_is_the_adrs(): + assert uncertain_code_fix("fakepkg") == ( + "Install a released fakepkg (not editable, its files as its RECORD lists them), or give " + "another --output." + ) + editable = uncertain_code_fix("fakepkg", ("lib", "1.0", "editable install")) + assert editable.startswith("The library lib is an editable install; fakepkg itself") + assert 'pip install "lib==1.0"' in editable + + +def test_an_uncertain_brick_comes_before_its_libraries(): + brick = { + "uncertain": "demo: editable install", + "code": {"verified": False}, + "libraries": {"eggy": {"version": "2.0", "uncertain": "RECORD missing"}}, + } + assert entry_identity.uncertain_library(brick) is None diff --git a/tests/test_entry_record.py b/tests/test_entry_record.py index 9a6b9053..27d608fe 100644 --- a/tests/test_entry_record.py +++ b/tests/test_entry_record.py @@ -12,6 +12,7 @@ import json import os import sys +import warnings import pytest from morphobricks_normalization.contracts import ResolverVersionError @@ -163,12 +164,49 @@ def test_uncertain_identities_are_refused(run): def test_a_first_run_under_an_uncertain_identity_is_published_and_never_reused(run): output = entry.default_output(run.output, "demo") editable = dict(BRICK, uncertain="demo: editable install") - published, record = _compute(run, output, brick=editable) + with pytest.warns(entry.EntryIdentityWarning, match="will never be reused") as caught: + published, record = _compute(run, output, brick=editable) + assert len(caught) == 1 and "(demo: editable install)" in str(caught[0].message) + assert "Install a released demo" in str(caught[0].message) assert published and record["brick"]["uncertain"] == "demo: editable install" with pytest.raises(EntryError, match="computed under an uncertain identity"): entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) +def test_a_certain_first_run_warns_nothing(run): + with warnings.catch_warnings(): + warnings.simplefilter("error", entry.EntryIdentityWarning) + _compute(run, entry.default_output(run.output, "demo")) + + +def test_an_uncertain_library_is_named_on_first_write_and_in_the_refusal(run): + """A released brick with one library installed without RECORD: the fix names the library.""" + libraries = dict( + BRICK["libraries"], + eggy={ + "version": "2.0", + "vcs_commit": None, + "record_sha256": None, + "uncertain": "RECORD missing", + }, + ) + brick = dict(BRICK, libraries=libraries, uncertain="eggy: RECORD missing") + output = entry.default_output(run.output, "demo") + with pytest.warns(entry.EntryIdentityWarning) as caught: + _compute(run, output, brick=brick) + message = str(caught[0].message) + assert "Reinstall eggy with pip" in message and "Install a released demo" not in message + assert entry.identity_warning(_record(run, brick=brick), output).startswith( + f"The output {output} is written, but its code identity is uncertain" + ) + with pytest.raises(EntryError) as raised: + entry.reuse_or_refuse(output, _record(run, brick=brick), supported_resolver_versions=(3,)) + assert raised.value.code == "ENTRY_IDENTITY_UNCERTAIN" + assert "(eggy: RECORD missing)" in raised.value.message + assert raised.value.fix.startswith("The library eggy 2.0 is installed without a RECORD file") + assert "demo itself needs no change" in raised.value.fix + + def test_an_unsupported_resolver_version_is_refused(run): output = entry.default_output(run.output, "demo") _compute(run, output) From c065049d4b8e21c7717186e06560f05a1f638fd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:53:50 +0000 Subject: [PATCH 2/2] Entry identity: warn only after the record is written; force the editable fix - write_entry_record warned before the exclusive open, so a record that was not written (one already there) still said the output was written; the warning now follows the write. - The fix for an editable library said pip install "==", which pip skips as already satisfied; it now forces the reinstall (--force-reinstall --no-deps), as the RECORD-missing fix does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp98tSnytZ9QCrHt6297 --- src/morphobricks_preprocessing/entry_errors.py | 7 +++++-- src/morphobricks_preprocessing/entry_record.py | 5 +++-- tests/test_entry_identity.py | 3 ++- tests/test_entry_record.py | 12 ++++++++++++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/morphobricks_preprocessing/entry_errors.py b/src/morphobricks_preprocessing/entry_errors.py index 29ae5af0..46f1cfa2 100644 --- a/src/morphobricks_preprocessing/entry_errors.py +++ b/src/morphobricks_preprocessing/entry_errors.py @@ -243,7 +243,9 @@ def uncertain_code_fix( why (``"editable install"`` or ``"RECORD missing"``, from :func:`.entry_identity.library_identity`). The ADR's text names the brick; telling the user to reinstall a brick that is already a - released install would not help, so the fix names the library instead. + released install would not help, so the fix names the library instead. Both library + fixes force the reinstall: pip leaves an installed version that already satisfies the + pin (an editable one included) as it is. """ if library is None: return ( @@ -262,7 +264,8 @@ def uncertain_code_fix( ) return ( f"The library {name} is an editable install; {brick} itself needs no change. Install a " - f'released {name} (pip install "{pinned}"), or give another --output.' + f'released {name} (pip install --force-reinstall --no-deps "{pinned}"), or give ' + "another --output." ) diff --git a/src/morphobricks_preprocessing/entry_record.py b/src/morphobricks_preprocessing/entry_record.py index 502b419b..2daa7c69 100644 --- a/src/morphobricks_preprocessing/entry_record.py +++ b/src/morphobricks_preprocessing/entry_record.py @@ -286,14 +286,15 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path: """ data = _plain(record) _checked(data, Path(folder) / ENTRY_FILENAME) - if (message := identity_warning(data)) is not None: - warnings.warn(message, EntryIdentityWarning, stacklevel=2) text = json.dumps(data, sort_keys=True, ensure_ascii=False, indent=1) + "\n" path = Path(folder) / ENTRY_FILENAME with open(path, "x", encoding="utf-8", newline="\n") as handle: handle.write(text) handle.flush() os.fsync(handle.fileno()) + # Only once the record is on disk: the warning says the output is written. + if (message := identity_warning(data)) is not None: + warnings.warn(message, EntryIdentityWarning, stacklevel=2) return path diff --git a/tests/test_entry_identity.py b/tests/test_entry_identity.py index 53f49b64..2d1eb0dc 100644 --- a/tests/test_entry_identity.py +++ b/tests/test_entry_identity.py @@ -72,7 +72,8 @@ def test_the_fix_for_the_brick_itself_is_the_adrs(): ) editable = uncertain_code_fix("fakepkg", ("lib", "1.0", "editable install")) assert editable.startswith("The library lib is an editable install; fakepkg itself") - assert 'pip install "lib==1.0"' in editable + # A plain install of the same version would be "already satisfied": pip must reinstall. + assert 'pip install --force-reinstall --no-deps "lib==1.0"' in editable def test_an_uncertain_brick_comes_before_its_libraries(): diff --git a/tests/test_entry_record.py b/tests/test_entry_record.py index 27d608fe..403aba22 100644 --- a/tests/test_entry_record.py +++ b/tests/test_entry_record.py @@ -173,6 +173,18 @@ def test_a_first_run_under_an_uncertain_identity_is_published_and_never_reused(r entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) +def test_no_warning_when_the_record_is_not_written(run, tmp_path): + editable = dict(BRICK, uncertain="demo: editable install") + record = _record(run, brick=editable) + folder = tmp_path / "out" + folder.mkdir() + (folder / entry.ENTRY_FILENAME).write_text("{}", encoding="utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("error", entry.EntryIdentityWarning) + with pytest.raises(FileExistsError): + entry.write_entry_record(folder, record) + + def test_a_certain_first_run_warns_nothing(run): with warnings.catch_warnings(): warnings.simplefilter("error", entry.EntryIdentityWarning)