Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<name>==<version>"`; or
an editable install) and says the brick needs no change, instead of "Install a released
`<brick>`" (`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
Expand Down
15 changes: 13 additions & 2 deletions docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<name>==<version>"` 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 `<section>.<key>` (`type`,
Expand All @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
4 changes: 4 additions & 0 deletions src/morphobricks_preprocessing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -372,6 +374,7 @@
"DiscoveryResult",
"EntryDeclaration",
"EntryError",
"EntryIdentityWarning",
"EntryResult",
"EntrySettings",
"FileEntry",
Expand Down Expand Up @@ -510,6 +513,7 @@
"he_tissue_mask_array",
"header_axes",
"header_axis_issue",
"identity_warning",
"image_type_issues",
"inspect_experiment",
"inspect_image",
Expand Down
56 changes: 51 additions & 5 deletions src/morphobricks_preprocessing/entry_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,53 @@ 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. 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 (
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 --force-reinstall --no-deps "{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.

Expand All @@ -245,14 +290,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 "
Expand Down
40 changes: 35 additions & 5 deletions src/morphobricks_preprocessing/entry_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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])?")


Expand All @@ -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)]
Expand All @@ -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
Expand Down Expand Up @@ -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``).

Expand Down Expand Up @@ -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
Expand Down
39 changes: 37 additions & 2 deletions src/morphobricks_preprocessing/entry_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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").
Expand Down Expand Up @@ -254,7 +280,9 @@ 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)
Expand All @@ -264,6 +292,9 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path:
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


Expand Down Expand Up @@ -475,7 +506,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():
Expand Down
Loading
Loading