From b26f765110b1515b763f7e6eeae694942498cb01 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:39:57 +0000 Subject: [PATCH 01/11] Segmentation hand-off: read channels by ID and write masks as preprocessing expects Add segmentation_handoff (images_to_segment, segmentation_input, mask_path, write_mask) and segmentation_record (versioned provenance file). The masks step skips segmentation_record.json silently. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- AGENTS.md | 5 + CHANGELOG.md | 12 + docs/contract.md | 23 ++ pyproject.toml | 2 + src/morphobricks_preprocessing/__init__.py | 17 + src/morphobricks_preprocessing/masks/files.py | 10 +- .../segmentation_handoff.py | 285 +++++++++++++ .../segmentation_record.py | 330 +++++++++++++++ tests/test_segmentation_handoff.py | 386 ++++++++++++++++++ 9 files changed, 1066 insertions(+), 4 deletions(-) create mode 100644 src/morphobricks_preprocessing/segmentation_handoff.py create mode 100644 src/morphobricks_preprocessing/segmentation_record.py create mode 100644 tests/test_segmentation_handoff.py diff --git a/AGENTS.md b/AGENTS.md index 43c7251e..4e4b6577 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -246,6 +246,11 @@ src/morphobricks_preprocessing/ masks.binary.label_binary; Spec ADR 0005) and objects_read_plan (its peak memory from the header: stored plane, int32 result and labelling_bytes; #316) + segmentation_handoff.py images_to_segment, segmentation_input (channels by canonical ID through + resolve_request), mask_path and write_mask (a checked, compressed int32 YX TIFF, + atomic, never over an existing mask unless asked) for a segmentation + notebook; numpy and tifffile only (contract §15.5); segmentation_record.py + SegmentationRecord and read/write of //segmentation_record.json mask_conversion.py RunInputs.binary_to_instances / classes_to_binary (Spec ADR 0005 BM12, step 2b): new mask files from a checked mask, refused before any read or write (check_class_image, collisions, idempotent retry); mask_lineage.py their diff --git a/CHANGELOG.md b/CHANGELOG.md index 249309e2..b9fc009d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,18 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Segmentation hand-off** (owner request of 21 November 2026, step 1 of the Cellpose notebook + plan): `segmentation_handoff` and `segmentation_record` (numpy and tifffile only; no + segmentation tool is imported). `images_to_segment` lists the run's images that have no mask + of a type yet, `segmentation_input` reads channels **by canonical ID** through + `resolve_request` as `(C, Y, X)` stored values (the resolver's refusals unchanged, 2D only), + `write_mask` writes a checked label image as a zlib-compressed `int32` `YX` TIFF at + `///.tif`, atomically and never over an existing + mask unless asked (a masks folder inside the experiment or the output folder is refused), and + `SegmentationRecord` with `write_record` and `read_record` keeps one versioned + `segmentation_record.json` per mask type. The masks step skips that file silently instead of + warning `mask_without_image`. Contract §15.5. + - **Tag this repeat folder (all conditions)** on *Tag channels* (owner request of 20 November 2026): one row of tags per biological-repeat **folder name** and channel count; set once, it is saved for every condition's imaging units in that folder (technical repeats included), diff --git a/docs/contract.md b/docs/contract.md index 90f2db6c..eac2fd1f 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1283,6 +1283,29 @@ returns can be declared, checked or reused as a run's mask, and its record has n stated, not refused (nothing is reused in memory). **For MorphoBricks runs the run route (§15.3, with lineage) remains the route.** +### 15.5 Segmentation hand-off (masks made by an outside tool, by channel ID) + +`morphobricks_preprocessing.segmentation_handoff` and `.segmentation_record` (numpy and +tifffile only; no segmentation tool is imported or required) are what a segmentation notebook +needs from this brick. They make no decision for the tool and guess nothing. + +| Function | Rule | +|---|---| +| `images_to_segment(inputs, mask_type, masks_root)` | The run's images with no mask of that type: none in the image's folder of `/` named as its position ID (§1), in any case and with any TIFF extension (§15 pairing). Excluded images are not in the run, so never listed. Refuses a masks folder that breaks the folder rules (§15 Folder), and a mask type that is not one folder name. | +| `segmentation_input(inputs, channel_ids, fov, z=0, t=0)` | The channels **by canonical ID** as a `(C, Y, X)` array of the stored values, in the order of `channel_ids`. Resolved with `RunInputs.resolve_request(Request(channel_ids))` and `require()`: every refusal of the resolver passes through with its code and message (`A_SCOPE_INCOMPLETE` for a channel some images lack: choose channels every image has; `A_RGB_NOT_SUPPORTED`). Each channel is read at the C index the image stores it at (`FovSelection.index_of`), never at a position. An image with Z or T above 1 is refused: 2D only. | +| `mask_path(masks_root, mask_type, fov)` | `///.tif` (the first layout of §15). | +| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. An existing mask (or another TIFF of the same image name) is refused unless `overwrite=True`, and then only the file at `mask_path` is replaced. The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | + +`//segmentation_record.json` (`SegmentationRecord`, `write_record`, `read_record`, +`record_version` 1) is provenance only: `mask_type`, `tool` and `tool_version`, `model` +(`name`, `file` or null, `sha256`), `parameters` (a JSON object), `channel_ids`, `device` +(`cuda`, `cpu` or `mps`, always stated), `run_folder`, `run_manifest_sha256`, and `images` (the +image's path relative to the experiment, `status` `written`, `skipped` or `failed`, and a +`message`, required for `failed`). It is checked on writing and on reading; an unknown +version, an unknown or missing key, or a value outside its set is refused, never repaired. The +masks step skips this file silently (it is not a mask), and nothing reads it to decide +anything. + ## 16. Shared rules for other bricks (MorphoBricks D86) Rules every MorphoBricks brick applies in one way, so they live here as public functions diff --git a/pyproject.toml b/pyproject.toml index c62619ed..bb136461 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -345,6 +345,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.masks.objects" = "pure" "morphobricks_preprocessing.mask_rules" = "pure" "morphobricks_preprocessing.mask_lineage" = "io" +"morphobricks_preprocessing.segmentation_handoff" = "io" +"morphobricks_preprocessing.segmentation_record" = "io" "morphobricks_preprocessing.mask_conversion" = "orchestration" "morphobricks_preprocessing.lineage_schema" = "pure" "morphobricks_preprocessing.code_identity" = "io" diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index f34efba1..1360438b 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -235,6 +235,14 @@ ResolvedRequest, VolumeNotSupportedError, ) +from .segmentation_handoff import images_to_segment, mask_path, segmentation_input, write_mask +from .segmentation_record import ( + SegmentationError, + SegmentationRecord, + SegmentedImage, + read_record, + write_record, +) from .sources import check_sources from .unrecorded import UnrecordedFiles, unrecorded_files from .validation import Severity, ValidationIssue, has_errors @@ -345,6 +353,9 @@ "MaskContradictsRepresentationError", "MaskUncheckedError", "RgbNotSupportedError", + "SegmentationError", + "SegmentationRecord", + "SegmentedImage", "VolumeNotSupportedError", "RunReportUnreadableError", "RunStoppedError", @@ -363,6 +374,10 @@ "ResolvedRequest", "UnrecordedFiles", "UnrecordedFilesError", + "images_to_segment", + "mask_path", + "read_record", + "segmentation_input", "unrecorded_files", "Fov", "LazyImage", @@ -468,7 +483,9 @@ "write_calibration", "write_experiment_design", "write_manifest", + "write_mask", "write_mask_report", + "write_record", "write_target_refusal", "zarr_available", ] diff --git a/src/morphobricks_preprocessing/masks/files.py b/src/morphobricks_preprocessing/masks/files.py index 90e6d2f1..ffab5c46 100644 --- a/src/morphobricks_preprocessing/masks/files.py +++ b/src/morphobricks_preprocessing/masks/files.py @@ -27,6 +27,7 @@ is_nfc, non_nfc_mask_types_issue, ) +from ..segmentation_record import RECORD_FILENAME from ..validation import ValidationIssue, agree, error, has_errors, plural, warning from ..zarr_input import ( NgffError, @@ -147,8 +148,9 @@ def _folder_masks( image the warning ``mask_of_excluded_image``: neither is used (design v0.4 §3 keeps the severity of every existing check). ``images`` are the analysed images' paths (excluded images left out). Links are followed only inside the masks folder (:mod:`..links`). The - conversion helpers' ``mask_lineage.jsonl`` and temporary files are skipped silently, like - system files (:func:`..mask_lineage.is_conversion_file`, Spec ADR 0005 BM12). + conversion helpers' ``mask_lineage.jsonl`` and temporary files and a segmentation tool's + ``segmentation_record.json`` are skipped silently, like system files + (:func:`..mask_lineage.is_conversion_file`, Spec ADR 0005 BM12; contract §15.5). """ by_key, by_leaf = {}, {} for leaf in discovery.leaves: @@ -193,8 +195,8 @@ def _folder_masks( def _skipped(name: str) -> bool: - """Return True for system files and the conversion helpers' lineage and temporary files.""" - return is_system_name(name) or is_conversion_file(name) + """Return True for system, conversion-helper and ``segmentation_record.json`` files (§15.5).""" + return is_system_name(name) or is_conversion_file(name) or name == RECORD_FILENAME def _suffix_matches(relative: Path, by_leaf: Mapping[str, list]) -> list[tuple[str, str]]: diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py new file mode 100644 index 00000000..d9a01c16 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -0,0 +1,285 @@ +"""The hand-off to a segmentation tool: images in by channel ID, masks out as §15 expects them. + +A segmentation tool (Cellpose in the shipped notebook) runs outside this brick. This module +is everything the tool's notebook needs from preprocessing, with numpy and tifffile only, and +imports no segmentation tool (contract §15.5): + +- :func:`images_to_segment`: the run's images that have no mask of a mask type yet; +- :func:`segmentation_input`: the channels asked for **by canonical channel ID**, as a + ``(C, Y, X)`` array of the stored values in the order asked, never by position; +- :func:`mask_path` and :func:`write_mask`: one label image per image at + ``///.tif``, checked against the image, written as + a compressed ``int32`` TIFF, atomically, and never over a mask that is already there unless + asked; +- the provenance file of the type (:mod:`.segmentation_record`). + +Nothing is guessed. A channel is resolved by :meth:`.run_inputs.RunInputs.resolve_request`, +whose refusals pass through unchanged (a channel that some images lack is +``A_SCOPE_INCOMPLETE``: choose channels every image has). Images with more than one Z plane or +time point are refused: this hand-off is 2D only. A mask is never filled, rescaled or +converted: wrong labels are refused before anything is written. +""" + +from __future__ import annotations + +import os +import tempfile +from pathlib import Path + +import numpy as np +import tifffile + +from ._io import give_output_mode +from .folder_rules import masks_folder_issues +from .links import relative_inside +from .run_inputs import Fov, RunInputs +from .run_inputs_request import Request +from .segmentation_record import SegmentationError, check_mask_type + +INT32_MAX = 2_147_483_647 +"""The largest label every brick accepts (contract §15, §16).""" +_SUFFIXES = (".ome.tiff", ".ome.tif", ".tiff", ".tif") # the TIFF names pairing accepts (§15) + + +def images_to_segment( + inputs: RunInputs, mask_type: str, masks_root: str | os.PathLike +) -> tuple[Fov, ...]: + """Return the run's images that have no mask of ``mask_type`` yet, sorted by path. + + An image has a mask when its folder in the mask type's folder holds a TIFF named as the + image's position ID, in any case and with any TIFF extension (the pairing of contract + §15). Excluded images are not in the run and are never listed. + + Parameters + ---------- + inputs + The opened run. + mask_type + The mask type, one folder name (``Cells``). + masks_root + The masks folder. + + Raises + ------ + SegmentationError + For a mask type that is not one folder name, or a masks folder inside the + experiment or the output folder (or holding them). + """ + check_mask_type(mask_type) + _check_folders(inputs, masks_root) + folders: dict[Path, frozenset[str]] = {} + found = [] + for fov in inputs.fovs(): + folder = _folder(masks_root, mask_type, fov) + if folder not in folders: + folders[folder] = _stems(folder) + if fov.key[3].casefold() not in folders[folder]: + found.append(fov) + return tuple(found) + + +def segmentation_input( + inputs: RunInputs, channel_ids: tuple[str, ...] | list[str], fov: Fov, z: int = 0, t: int = 0 +) -> np.ndarray: + """Read the channels ``channel_ids`` of one image as a ``(C, Y, X)`` array of stored values. + + The channels are resolved by ID for the whole run (``Request(channel_ids)``), then each is + read at the C index **this image** stores it at (``FovSelection.index_of``), so a channel + that sits at another position in other repeats is still the same stain. The result is in + the order of ``channel_ids``, with the stored pixel type: nothing is scaled or converted. + + Parameters + ---------- + inputs + The opened run. + channel_ids + Canonical channel IDs, at least one, each once. + fov + The image (one of ``inputs.fovs()``). + z, t + The plane; 0 for the only plane of a 2D image. + + Raises + ------ + SegmentationError + For no channel, a channel twice, or an image with more than one Z plane or time point. + RunInputsError + The resolver's refusal, with its code and message unchanged (``A_SCOPE_INCOMPLETE`` + for a channel some images lack, ``A_RGB_NOT_SUPPORTED``, ...). + """ + ids = tuple(channel_ids) + if not ids or len(set(ids)) != len(ids): + raise SegmentationError("Name at least one channel ID, each once.") + _check_2d(fov) + selections = inputs.resolve_request(Request(ids)).require() + chosen = next((s for s in selections if s.relative_path == fov.relative_path), None) + if chosen is None: + raise SegmentationError(f"{fov.relative_path} is not an image of this run.") + plane = inputs.read_plane(fov, z=z, t=t) + return np.stack([plane[chosen.index_of(channel_id)] for channel_id in ids]) + + +def mask_path(masks_root: str | os.PathLike, mask_type: str, fov: Fov) -> Path: + """Return where the mask of ``mask_type`` for ``fov`` is: the layout of contract §15. + + ``///.tif``: the image's folders as they + are in the experiment, and its name without its extensions (``a.ome.tif`` -> ``a.tif``). + + Raises + ------ + SegmentationError + For a mask type that is not one folder name. + """ + check_mask_type(mask_type) + return _folder(masks_root, mask_type, fov) / f"{fov.key[3]}.tif" + + +def write_mask( + masks_root: str | os.PathLike, + mask_type: str, + fov: Fov, + labels: np.ndarray, + inputs: RunInputs, + *, + overwrite: bool = False, +) -> Path: + """Write ``labels`` as the mask of ``mask_type`` for ``fov``, as preprocessing expects it. + + The labels must be 2D with the image's Y and X (header only; no pixel is read), of an + integer or boolean type, with values from 0 to 2,147,483,647. They are written as a + zlib-compressed ``int32`` TIFF with the axes named ``YX``, to a temporary file and then + moved into place, so a reader never sees half a mask. Nothing is converted other than the + integer width and nothing is filled. + + Parameters + ---------- + masks_root + The masks folder, outside the experiment and the output folder; created if missing. + mask_type + The mask type, one folder name. + fov + The image the mask belongs to. + labels + The label image, 0 for the background. + inputs + The opened run (the image's size, and the experiment and output folders). + overwrite + Replace a mask that is already there. Without it an existing mask is refused. + + Returns + ------- + Path + The file written. + + Raises + ------ + SegmentationError + For labels that are not 2D, not the image's size, floating point or complex, negative + or too large; an image with more than one Z plane or time point; a mask that exists + without ``overwrite`` (or another TIFF of the same name); or a masks folder inside the + experiment or the output folder. + """ + target = mask_path(masks_root, mask_type, fov) + _check_folders(inputs, masks_root) + _check_2d(fov) + data = _checked_labels(labels, inputs.plane_shape(fov), fov.relative_path) + others = sorted(n for n in _names(target.parent) if _stem(n) == fov.key[3].casefold()) + if others and (not overwrite or others != [target.name]): + raise SegmentationError( + f"The {mask_type} mask of {fov.relative_path} already exists " + f"({', '.join(others)} in {target.parent}). Use overwrite=True to replace " + f"{target.name}; a file with another name must be moved away first." + ) + target.parent.mkdir(parents=True, exist_ok=True) + handle, temporary = tempfile.mkstemp( + prefix=f".{target.name}.", suffix=".tmp", dir=target.parent + ) + os.close(handle) + try: + tifffile.imwrite( + temporary, data, photometric="minisblack", compression="zlib", metadata={"axes": "YX"} + ) + give_output_mode(temporary, target) + os.replace(temporary, target) + except BaseException: + Path(temporary).unlink(missing_ok=True) + raise + return target + + +def _checked_labels(labels: np.ndarray, shape: tuple[int, int], image: str) -> np.ndarray: + """Return ``labels`` as an int32 array, or refuse them (see :func:`write_mask`).""" + array = np.asarray(labels) + if array.ndim != 2: + raise SegmentationError( + f"The labels for {image} have {array.ndim} dimension(s); a mask is 2D (Y, X)." + ) + if array.shape != tuple(shape): + raise SegmentationError( + f"The labels for {image} are {array.shape[0]} x {array.shape[1]} (Y x X) but the " + f"image is {shape[0]} x {shape[1]}. Segment the image as it is; never resize a mask." + ) + if array.dtype.kind not in "iub": + raise SegmentationError( + f"The labels for {image} are {array.dtype}; a mask holds integer labels (or " + "boolean). Convert them yourself if they really are whole numbers." + ) + low, high = int(array.min()), int(array.max()) + if low < 0: + raise SegmentationError(f"The labels for {image} hold a negative value ({low}).") + if high > INT32_MAX: + raise SegmentationError( + f"The labels for {image} hold {high}, above the limit {INT32_MAX:,} (int32) that " + "every brick shares." + ) + return array.astype(np.int32) + + +def _check_2d(fov: Fov) -> None: + """Refuse an image with several Z planes or time points (2D only for now).""" + if fov.z_count > 1 or fov.t_count > 1: + raise SegmentationError( + f"{fov.relative_path} has {fov.z_count} Z plane(s) and {fov.t_count} time " + "point(s). Segmentation here is 2D only: images with Z or T above 1 are not " + "supported yet." + ) + + +def _check_folders(inputs: RunInputs, masks_root: str | os.PathLike) -> None: + """Refuse a masks folder inside the experiment or the output folder (or holding them).""" + issues = masks_folder_issues(masks_root, inputs.experiment_root, inputs.output_folder) + if not issues and relative_inside(Path(masks_root).resolve(), inputs.output_folder): + raise SegmentationError( + f"The masks folder {masks_root} is inside the output folder of the run. Choose a " + "masks folder next to the experiment and output folders." + ) + if issues: + issue = issues[0] + raise SegmentationError(f"{issue.message} {issue.action} ({issue.code})") + + +def _folder(masks_root: str | os.PathLike, mask_type: str, fov: Fov) -> Path: + """Return the folder of ``fov``'s mask: the type's folder plus the image's own folders.""" + return Path(masks_root, mask_type, *Path(fov.relative_path).parent.parts) + + +def _names(folder: Path) -> list[str]: + """Return the names of the files in ``folder`` (none if it does not exist).""" + try: + return [e.name for e in os.scandir(folder) if e.is_file()] + except FileNotFoundError: + return [] + + +def _stem(name: str) -> str | None: + """Return a TIFF file's name without its extension, lower case; None for other files.""" + lower = name.casefold() + for suffix in _SUFFIXES: + if lower.endswith(suffix): + return lower[: -len(suffix)] + return None + + +def _stems(folder: Path) -> frozenset[str]: + """Return the lower-case stems of the TIFF files in ``folder``.""" + return frozenset(s for s in map(_stem, _names(folder)) if s is not None) diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py new file mode 100644 index 00000000..d4cd7d47 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -0,0 +1,330 @@ +"""The provenance file of one mask type made by a segmentation tool (contract §15.5). + +A segmentation tool (Cellpose in the shipped notebook) writes its masks under +``//`` with :func:`.segmentation_handoff.write_mask`, and one +``segmentation_record.json`` beside them says how they were made: the tool and its version, +the model (a name, and the weights file with its SHA-256), the parameters, the channel IDs +that were read, the device that ran it, the run it read (folder and manifest SHA-256) and one +entry per image (written, skipped or failed, with the message). The file is provenance only: +nothing in preprocessing reads it back to decide anything, and a mask is a mask whether or not +a record exists. + +The record is versioned (:data:`RECORD_VERSION`). :func:`read_record` checks everything it +reads and refuses a version it does not know, an unknown key, a wrong type or a value outside +the allowed set; nothing is repaired or defaulted. The module needs only the standard library. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from ._io import write_text_atomic + +RECORD_VERSION = 1 +"""The version of the record this module writes and reads.""" +RECORD_FILENAME = "segmentation_record.json" +"""The record's name, directly inside the mask type's folder.""" +DEVICES = ("cuda", "cpu", "mps") +"""The device the tool ran on, always stated (no silent fallback).""" +STATUSES = ("written", "skipped", "failed") +"""What happened to one image.""" +_SHA256 = re.compile(r"[0-9a-f]{64}") + + +class SegmentationError(ValueError): + """A segmentation hand-off or record that is refused; the message says what to do.""" + + +@dataclass(frozen=True) +class SegmentedImage: + """What happened to one image of the run. + + Attributes + ---------- + image + The image's path relative to the experiment, as the run's manifest records it. + status + ``written``, ``skipped`` (a mask was already there) or ``failed``. + message + Why, in plain words; required for ``failed`` (an error is never dropped). + """ + + image: str + status: str + message: str = "" + + +@dataclass(frozen=True) +class SegmentationRecord: + """How the masks of one mask type were made. + + Attributes + ---------- + mask_type + The mask type (the name of the folder holding the masks and this record). + tool, tool_version + The segmentation tool and its exact version (e.g. ``cellpose``, ``4.2.1.1``). + model_name + The model as the tool names it (e.g. ``cpsam_v2``), or the name the user gave a custom + model. + model_sha256 + The SHA-256 of the weights file, 64 lowercase hexadecimal characters. + model_file + The weights file's name or path, or None when the tool gives none. + parameters + The tool's parameters, a JSON object (diameter, thresholds, and so on). + channel_ids + The canonical channel IDs the tool read, in the order given to it. + device + ``cuda``, ``cpu`` or ``mps``: the device that ran, never inferred. + run_folder + The preprocessing run's output folder, as the user gave it. + run_manifest_sha256 + The SHA-256 of that run's ``run_manifest.json`` when the images were read. + images + One entry per image handled, in the order handled. + """ + + mask_type: str + tool: str + tool_version: str + model_name: str + model_sha256: str + parameters: dict[str, Any] + channel_ids: tuple[str, ...] + device: str + run_folder: str + run_manifest_sha256: str + images: tuple[SegmentedImage, ...] = () + model_file: str | None = None + record_version: int = field(default=RECORD_VERSION, init=False) + + def __post_init__(self) -> None: + """Refuse a record that could not be read back (the same checks as reading).""" + _check(self.to_dict()) + + def to_dict(self) -> dict[str, Any]: + """Return the record as the JSON object written to the file.""" + return { + "record_version": self.record_version, + "mask_type": self.mask_type, + "tool": self.tool, + "tool_version": self.tool_version, + "model": { + "name": self.model_name, + "file": self.model_file, + "sha256": self.model_sha256, + }, + "parameters": dict(self.parameters), + "channel_ids": list(self.channel_ids), + "device": self.device, + "run_folder": self.run_folder, + "run_manifest_sha256": self.run_manifest_sha256, + "images": [ + {"image": i.image, "status": i.status, "message": i.message} for i in self.images + ], + } + + @classmethod + def from_dict(cls, data: object) -> SegmentationRecord: + """Build a record from a JSON object, checking all of it. + + Raises + ------ + SegmentationError + For an unknown ``record_version``, a missing or unknown key, a value of the wrong + type or outside its allowed set. + """ + _check(data) + model = data["model"] + return cls( + mask_type=data["mask_type"], + tool=data["tool"], + tool_version=data["tool_version"], + model_name=model["name"], + model_sha256=model["sha256"], + model_file=model["file"], + parameters=dict(data["parameters"]), + channel_ids=tuple(data["channel_ids"]), + device=data["device"], + run_folder=data["run_folder"], + run_manifest_sha256=data["run_manifest_sha256"], + images=tuple( + SegmentedImage(i["image"], i["status"], i["message"]) for i in data["images"] + ), + ) + + +_KEYS = frozenset( + { + "record_version", + "mask_type", + "tool", + "tool_version", + "model", + "parameters", + "channel_ids", + "device", + "run_folder", + "run_manifest_sha256", + "images", + } +) +_MODEL_KEYS = frozenset({"name", "file", "sha256"}) +_IMAGE_KEYS = frozenset({"image", "status", "message"}) + + +def _check(data: object) -> None: + """Refuse an object that is not a version 1 record (module docstring).""" + if not isinstance(data, dict): + raise SegmentationError("The segmentation record is not a JSON object.") + version = data.get("record_version") + if version != RECORD_VERSION or isinstance(version, bool): + raise SegmentationError( + f"The segmentation record has version {version!r}; this release reads version " + f"{RECORD_VERSION} only. Segment again with this release, or use the release " + "that wrote it." + ) + _keys(data, _KEYS, "the record") + for key in ("mask_type", "tool", "tool_version", "run_folder"): + _text(data[key], key) + _hash(data["run_manifest_sha256"], "run_manifest_sha256") + if data["device"] not in DEVICES: + raise SegmentationError( + f"device must be one of {', '.join(DEVICES)}, not {data['device']!r}." + ) + if not isinstance(data["parameters"], dict): + raise SegmentationError("parameters must be a JSON object.") + try: + json.dumps(data["parameters"], allow_nan=False) + except (TypeError, ValueError) as exc: + raise SegmentationError(f"parameters must be plain JSON values ({exc}).") from None + _model(data["model"]) + ids = data["channel_ids"] + if not isinstance(ids, (list, tuple)) or not ids: + raise SegmentationError("channel_ids must list at least one channel ID.") + for channel_id in ids: + _text(channel_id, "a channel ID") + if len(set(ids)) != len(ids): + raise SegmentationError("channel_ids names a channel twice.") + if not isinstance(data["images"], (list, tuple)): + raise SegmentationError("images must be a list.") + for entry in data["images"]: + _image(entry) + + +def _keys(data: object, expected: frozenset[str], what: str) -> None: + """Refuse an object without exactly the ``expected`` keys.""" + if not isinstance(data, dict): + raise SegmentationError(f"{what} must be a JSON object.") + missing, extra = sorted(expected - data.keys()), sorted(data.keys() - expected) + if missing or extra: + found = [f"missing {', '.join(missing)}"] * bool(missing) + found += [f"unknown {', '.join(map(str, extra))}"] * bool(extra) + raise SegmentationError(f"{what} has the wrong keys: {'; '.join(found)}.") + + +def _text(value: object, what: str) -> None: + """Refuse anything but a non-empty string.""" + if not isinstance(value, str) or not value.strip(): + raise SegmentationError(f"{what} must be a non-empty text, not {value!r}.") + + +def _hash(value: object, what: str) -> None: + """Refuse anything but 64 lowercase hexadecimal characters.""" + if not isinstance(value, str) or not _SHA256.fullmatch(value): + raise SegmentationError(f"{what} must be a SHA-256 (64 lowercase hexadecimal digits).") + + +def _model(model: object) -> None: + """Refuse a model entry without a name and a SHA-256 (a file or None).""" + _keys(model, _MODEL_KEYS, "model") + _text(model["name"], "the model name") + _hash(model["sha256"], "the model sha256") + if model["file"] is not None: + _text(model["file"], "the model file") + + +def _image(entry: object) -> None: + """Refuse an image entry with an unknown status, or a failure without a message.""" + _keys(entry, _IMAGE_KEYS, "an image entry") + _text(entry["image"], "the image path") + if entry["status"] not in STATUSES: + raise SegmentationError( + f"status must be one of {', '.join(STATUSES)}, not {entry['status']!r}." + ) + if not isinstance(entry["message"], str): + raise SegmentationError("an image entry's message must be a text.") + if entry["status"] == "failed" and not entry["message"].strip(): + raise SegmentationError(f"{entry['image']} failed without a message; say why.") + + +def check_mask_type(mask_type: str) -> None: + """Refuse a mask type that is not the name of one folder.""" + if not mask_type or mask_type in {".", ".."} or Path(mask_type).name != mask_type: + raise SegmentationError(f"{mask_type!r} is not a mask type: it names one folder.") + + +def record_path(masks_root: str | Path, mask_type: str) -> Path: + """Return where the record of ``mask_type`` is, ``//segmentation_record.json``.""" + check_mask_type(mask_type) + return Path(masks_root) / mask_type / RECORD_FILENAME + + +def write_record(masks_root: str | Path, mask_type: str, record: SegmentationRecord) -> Path: + """Write the record of ``mask_type`` atomically, replacing an earlier one. + + Parameters + ---------- + masks_root + The masks folder. + mask_type + The mask type; it must be the record's own. + record + The record. + + Returns + ------- + Path + The file written. + + Raises + ------ + SegmentationError + If ``mask_type`` is not one folder name or is not the record's. + """ + path = record_path(masks_root, mask_type) + if record.mask_type != mask_type: + raise SegmentationError( + f"The record is of mask type {record.mask_type!r}, not {mask_type!r}." + ) + text = json.dumps(record.to_dict(), indent=2, ensure_ascii=False, allow_nan=False) + return write_text_atomic(path, text + "\n", parents=True) + + +def read_record(masks_root: str | Path, mask_type: str) -> SegmentationRecord: + """Read and check the record of ``mask_type``. + + Raises + ------ + SegmentationError + If there is no record, it is not JSON, it is of another version, or it is not valid + (:meth:`SegmentationRecord.from_dict`), or it names another mask type. + """ + path = record_path(masks_root, mask_type) + try: + data = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + raise SegmentationError(f"There is no segmentation record at {path}.") from None + except (OSError, ValueError) as exc: + raise SegmentationError(f"The segmentation record {path} cannot be read ({exc}).") from None + record = SegmentationRecord.from_dict(data) + if record.mask_type != mask_type: + raise SegmentationError( + f"The record at {path} is of mask type {record.mask_type!r}, not {mask_type!r}." + ) + return record diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py new file mode 100644 index 00000000..bc4013fd --- /dev/null +++ b/tests/test_segmentation_handoff.py @@ -0,0 +1,386 @@ +"""The segmentation hand-off (contract §15.5): channels in by ID, masks out as §15 expects. + +The run is the owner's mixed-channel case: DNA, ACTIN and TUB everywhere, a fourth stain EXTRA +only in ``Biological_repeat_2``, listed first there so that the shared stains sit at other C +indices in that repeat. Each stain's pixels lie in their own range (``LEVELS``), so the tests +see at once which stain a plane holds, whatever its position. +""" + +import dataclasses +import json +import os +from types import SimpleNamespace + +import numpy as np +import pytest +import tifffile + +from described_tree import check_masks, run_described +from description_tree import MAPPING +from morphobricks_preprocessing import Request +from morphobricks_preprocessing.manifest import MANIFEST_FILENAME +from morphobricks_preprocessing.run_inputs import RunInputs, RunInputsError +from morphobricks_preprocessing.segmentation_handoff import ( + images_to_segment, + mask_path, + segmentation_input, + write_mask, +) +from morphobricks_preprocessing.segmentation_record import ( + RECORD_FILENAME, + SegmentationError, + SegmentationRecord, + SegmentedImage, + read_record, + write_record, +) +from test_stage3_channels import LEVELS, described_run, extra_stain + +EXTRA_FIRST = ( + b'channels = ["DNA", "ACTIN", "TUB", "EXTRA"]', + b'channels = ["EXTRA", "DNA", "ACTIN", "TUB"]', +) +MASKS_SECTION = b'\n[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"\n' +REPEAT_2 = "Biological_repeat_2" + + +@pytest.fixture +def run(tmp_path): + data = extra_stain().replace(*EXTRA_FIRST) + result, out, _ = described_run(tmp_path, data) + assert result.written, [(i.code, i.message) for i in result.issues] + return SimpleNamespace( + inputs=RunInputs.open(out), + out=out, + experiment=tmp_path / "exp", + masks=tmp_path / "masks", + data=data, + ) + + +def labels_like(run, fov, value=1): + height, width = run.inputs.plane_shape(fov) + labels = np.zeros((height, width), np.uint16) + labels[1:4, 1:4] = value + return labels + + +def record(**changes): + fields = { + "mask_type": "Cells", + "tool": "cellpose", + "tool_version": "4.2.1.1", + "model_name": "cpsam_v2", + "model_sha256": "ab" * 32, + "model_file": "cpsam_v2.pt", + "parameters": {"diameter": None, "flow_threshold": 0.4}, + "channel_ids": ("ACTIN", "DNA"), + "device": "cpu", + "run_folder": "/runs/out", + "run_manifest_sha256": "cd" * 32, + "images": (SegmentedImage("a/b.tif", "written"), SegmentedImage("a/c.tif", "skipped", "x")), + } + return SegmentationRecord(**{**fields, **changes}) + + +# segmentation_input ----------------------------------------------------------------------- + + +def test_channels_are_picked_by_id_at_each_units_own_index(run): + fovs = run.inputs.fovs() + assert {f.repeat_group for f in fovs} == { + "Biological_repeat_1", + REPEAT_2, + "Biological_repeat_3", + } + for fov in fovs: + image = segmentation_input(run.inputs, ("ACTIN", "DNA"), fov) + assert image.shape == (2, 8, 8) and image.dtype == np.uint8 + actin, dna = image + assert LEVELS["ACTIN"] <= actin.min() and actin.max() < LEVELS["ACTIN"] + 20 + assert LEVELS["DNA"] <= dna.min() and dna.max() < LEVELS["DNA"] + 20 + # The stored values, from the C index this image stores each ID at. + stored = tifffile.imread(run.experiment / fov.relative_path) + assert fov.channel_ids.index("DNA") == (1 if fov.repeat_group == REPEAT_2 else 0) + np.testing.assert_array_equal(dna, stored[fov.channel_ids.index("DNA")]) + np.testing.assert_array_equal(actin, stored[fov.channel_ids.index("ACTIN")]) + + +def test_the_order_given_is_the_order_returned(run): + fov = next(f for f in run.inputs.fovs() if f.repeat_group == REPEAT_2) + forward = segmentation_input(run.inputs, ["DNA", "TUB"], fov) + backward = segmentation_input(run.inputs, ["TUB", "DNA"], fov) + np.testing.assert_array_equal(forward, backward[::-1]) + assert segmentation_input(run.inputs, ("DNA",), fov).shape == (1, 8, 8) + + +def test_a_channel_some_images_lack_is_refused_with_the_resolvers_code(run): + fov = run.inputs.fovs()[0] + with pytest.raises(RunInputsError) as caught: + segmentation_input(run.inputs, ("DNA", "EXTRA"), fov) + (refusal,) = run.inputs.resolve_request(Request(("DNA", "EXTRA"))).refusals + assert refusal.code == "A_SCOPE_INCOMPLETE" + assert str(caught.value) == refusal.message + assert getattr(caught.value, "code", None) == "A_SCOPE_INCOMPLETE" + + +def test_even_an_image_that_has_the_channel_is_refused_when_others_lack_it(run): + stained = next(f for f in run.inputs.fovs() if f.repeat_group == REPEAT_2) + assert "EXTRA" in stained.channel_ids + with pytest.raises(RunInputsError, match="EXTRA"): + segmentation_input(run.inputs, ("EXTRA",), stained) + + +@pytest.mark.parametrize("ids", [(), ("DNA", "DNA")]) +def test_no_channel_or_a_channel_twice_is_refused(run, ids): + with pytest.raises(SegmentationError, match="at least one channel"): + segmentation_input(run.inputs, ids, run.inputs.fovs()[0]) + + +@pytest.mark.parametrize("counts", [{"z_count": 3}, {"t_count": 2}]) +def test_an_image_with_z_or_t_above_one_is_refused(run, counts): + fov = dataclasses.replace(run.inputs.fovs()[0], **counts) + with pytest.raises(SegmentationError, match="2D only"): + segmentation_input(run.inputs, ("DNA",), fov) + with pytest.raises(SegmentationError, match="2D only"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert not run.masks.exists() + + +# images_to_segment and mask_path ----------------------------------------------------------- + + +def test_mask_path_follows_the_layout_of_contract_15(run): + fov = run.inputs.fovs()[0] + assert fov.relative_path == "Control/Biological_repeat_1/img0.tif" + assert mask_path(run.masks, "Cells", fov) == ( + run.masks / "Cells" / "Control" / "Biological_repeat_1" / "img0.tif" + ) + for bad in ("", "..", "a/b", "."): + with pytest.raises(SegmentationError, match="one folder"): + mask_path(run.masks, bad, fov) + + +def test_images_to_segment_before_and_after_writing_some_masks(run): + fovs = run.inputs.fovs() + assert len(fovs) == 12 + assert images_to_segment(run.inputs, "Cells", run.masks) == fovs # no masks folder yet + for fov in fovs[:5]: + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert images_to_segment(run.inputs, "Cells", run.masks) == fovs[5:] + assert images_to_segment(run.inputs, "Nuclei", run.masks) == fovs # another type + for fov in fovs[5:]: + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert images_to_segment(run.inputs, "Cells", run.masks) == () + + +def test_a_mask_with_another_case_or_tiff_extension_counts_as_made(run): + first, second, third = run.inputs.fovs()[:3] + folder = run.masks / "Cells" / "Control" / "Biological_repeat_1" + folder.mkdir(parents=True) + (folder / "IMG0.TIFF").write_bytes(b"") + (folder / "img1.ome.tif").write_bytes(b"") + (folder / "note.txt").write_bytes(b"") + left = images_to_segment(run.inputs, "Cells", run.masks) + assert first not in left and second not in left and third in left + with pytest.raises(SegmentationError, match="already exists"): + write_mask(run.masks, "Cells", first, labels_like(run, first), run.inputs, overwrite=True) + + +def test_excluded_images_are_never_listed(tmp_path): + data = extra_stain() + result, out, _ = described_run(tmp_path, data) + assert result.written + excluded = "Control/Biological_repeat_1/img0.tif" + rerun = run_described(tmp_path / "exp", MAPPING, output_folder=out, exclude=[excluded]) + assert rerun.written, [(i.code, i.message) for i in rerun.issues] + inputs = RunInputs.open(out) + listed = [f.relative_path for f in images_to_segment(inputs, "Cells", tmp_path / "masks")] + assert excluded not in listed and len(listed) == 11 + + +# write_mask -------------------------------------------------------------------------------- + + +def test_write_mask_writes_a_compressed_int32_yx_tiff(run): + fov = run.inputs.fovs()[0] + path = write_mask(run.masks, "Cells", fov, labels_like(run, fov, 7), run.inputs) + assert path == mask_path(run.masks, "Cells", fov) + with tifffile.TiffFile(path) as tif: + assert tif.series[0].axes == "YX" + assert tif.pages[0].dtype == np.int32 and tif.pages[0].compression.name == "ADOBE_DEFLATE" + stored = tifffile.imread(path) + assert stored.dtype == np.int32 and stored.max() == 7 and stored.shape == (8, 8) + assert [p.name for p in path.parent.iterdir() if p.name.startswith(".")] == [] # no temp left + + +def test_write_mask_accepts_boolean_and_any_integer_type(run): + fovs = run.inputs.fovs() + for fov, dtype in zip(fovs, (np.bool_, np.uint8, np.int64, np.uint64), strict=False): + labels = labels_like(run, fov).astype(dtype) + stored = tifffile.imread(write_mask(run.masks, "Cells", fov, labels, run.inputs)) + np.testing.assert_array_equal(stored, labels.astype(np.int32)) + top = np.zeros((8, 8), np.int64) + top[0, 0] = 2_147_483_647 + path = write_mask(run.masks, "Cells", fovs[5], top, run.inputs) + assert tifffile.imread(path).max() == 2_147_483_647 + + +def test_write_mask_refuses_labels_that_are_not_a_mask(run): + fov = run.inputs.fovs()[0] + good = labels_like(run, fov) + wrong = { + "3D": (np.zeros((1, 8, 8), np.uint8), "2D"), + "1D": (np.zeros(8, np.uint8), "2D"), + "wrong size": (np.zeros((8, 9), np.uint8), "never resize"), + "transposed": (np.zeros((9, 8), np.uint8), "never resize"), + "float": (good.astype(np.float32), "integer"), + "whole floats": (good.astype(np.float64), "integer"), + "negative": (good.astype(np.int16) - 1, "negative"), + "too large": (good.astype(np.int64) + 2_147_483_647, "above the limit"), + "too large unsigned": (good.astype(np.uint64) + 2**40, "above the limit"), + } + for _name, (labels, message) in wrong.items(): + with pytest.raises(SegmentationError, match=message): + write_mask(run.masks, "Cells", fov, labels, run.inputs) + assert not run.masks.exists() # nothing was created + + +def test_write_mask_never_overwrites_unless_asked(run): + fov = run.inputs.fovs()[0] + path = write_mask(run.masks, "Cells", fov, labels_like(run, fov, 1), run.inputs) + before = path.read_bytes() + with pytest.raises(SegmentationError, match="already exists"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 2), run.inputs) + assert path.read_bytes() == before + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 2), run.inputs, overwrite=True) + assert tifffile.imread(path).max() == 2 + + +def test_a_failed_write_leaves_the_earlier_mask_and_no_temporary_file(run, monkeypatch): + fov = run.inputs.fovs()[0] + path = write_mask(run.masks, "Cells", fov, labels_like(run, fov, 1), run.inputs) + before = path.read_bytes() + + def broken(*args, **kwargs): + raise OSError("disk full") + + monkeypatch.setattr(tifffile, "imwrite", broken) + with pytest.raises(OSError, match="disk full"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 2), run.inputs, overwrite=True) + assert path.read_bytes() == before + assert sorted(os.listdir(path.parent)) == [path.name] + + +def test_write_mask_refuses_a_masks_folder_inside_the_experiment_or_output(run): + fov = run.inputs.fovs()[0] + for folder, code in ( + (run.experiment / "masks", "masks_inside_experiment"), + (run.experiment, "masks_inside_experiment"), + (run.out / "masks", "inside the output folder"), + (run.out, "output_inside_masks"), + ): + with pytest.raises(SegmentationError, match=code): + write_mask(folder, "Cells", fov, labels_like(run, fov), run.inputs) + with pytest.raises(SegmentationError, match=code): + images_to_segment(run.inputs, "Cells", folder) + assert not (run.experiment / "masks").exists() and not (run.out / "masks").exists() + with pytest.raises(SegmentationError, match="experiment_inside_masks"): + write_mask(run.experiment.parent, "Cells", fov, labels_like(run, fov), run.inputs) + + +def test_masks_written_here_pass_preprocessings_own_mask_checks(run): + fovs = run.inputs.fovs() + for fov in fovs: + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 3), run.inputs) + write_record(run.masks, "Cells", record()) # the record beside the masks is not a mask + (run.out / "morphobricks.toml").write_bytes(run.data + MASKS_SECTION) + again = run_described(run.experiment, MAPPING, output_folder=run.out, masks_folder=run.masks) + assert again.written, [(i.code, i.message) for i in again.issues] + assert [i.code for i in again.issues if i.code.startswith(("mask", "unreadable_mask"))] == [] + manifest = json.loads((run.out / MANIFEST_FILENAME).read_text(encoding="utf-8")) + entries = manifest["masks"]["files"] + assert sorted(e["image"] for e in entries) == sorted(f.relative_path for f in fovs) + assert {e["type"] for e in entries} == {"Cells"} + reopened = RunInputs.open(check_masks(run.out)) # the mask step reads every mask + assert reopened.mask_types() == ("Cells",) + mask = reopened.read_mask(fovs[0].relative_path, "Cells") + assert mask.dtype == np.int32 and mask.shape == (8, 8) and mask.max() == 3 + assert images_to_segment(reopened, "Cells", run.masks) == () + + +# The record -------------------------------------------------------------------------------- + + +def test_the_record_round_trips_through_its_file(run): + original = record() + path = write_record(run.masks, "Cells", original) + assert path == run.masks / "Cells" / RECORD_FILENAME + assert json.loads(path.read_text(encoding="utf-8"))["record_version"] == 1 + assert read_record(run.masks, "Cells") == original + assert SegmentationRecord.from_dict(original.to_dict()) == original + assert path.read_bytes() == path.read_bytes().replace(b"\r\n", b"\n") + changed = record(device="cuda", images=()) + write_record(run.masks, "Cells", changed) # an earlier record is replaced + assert read_record(run.masks, "Cells") == changed + + +def test_an_unknown_record_version_is_refused(run): + path = write_record(run.masks, "Cells", record()) + for version in (2, 0, "1", True, None): + data = json.loads(path.read_text(encoding="utf-8")) + data["record_version"] = version + path.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(SegmentationError, match="version"): + read_record(run.masks, "Cells") + + +def test_a_record_that_is_not_valid_is_refused(run): + path = write_record(run.masks, "Cells", record()) + good = json.loads(path.read_text(encoding="utf-8")) + + def broken(edit): + data = json.loads(json.dumps(good)) + edit(data) + path.write_text(json.dumps(data), encoding="utf-8") + return pytest.raises(SegmentationError) + + with broken(lambda d: d.update(device="gpu")): + read_record(run.masks, "Cells") + with broken(lambda d: d.update(extra=1)): + read_record(run.masks, "Cells") + with broken(lambda d: d.pop("tool")): + read_record(run.masks, "Cells") + with broken(lambda d: d["model"].update(sha256="xyz")): + read_record(run.masks, "Cells") + with broken(lambda d: d.update(channel_ids=[])): + read_record(run.masks, "Cells") + with broken(lambda d: d["images"][0].update(status="done")): + read_record(run.masks, "Cells") + with broken(lambda d: d.update(mask_type="Nuclei")): + read_record(run.masks, "Cells") + path.write_text("not json", encoding="utf-8") + with pytest.raises(SegmentationError, match="cannot be read"): + read_record(run.masks, "Cells") + with pytest.raises(SegmentationError, match="no segmentation record"): + read_record(run.masks, "Nuclei") + + +def test_a_record_cannot_be_built_without_what_it_needs(): + with pytest.raises(SegmentationError, match="failed without a message"): + record(images=(SegmentedImage("a.tif", "failed"),)) + with pytest.raises(SegmentationError, match="device"): + record(device="") + with pytest.raises(SegmentationError, match="SHA-256"): + record(model_sha256="") + with pytest.raises(SegmentationError, match="plain JSON"): + record(parameters={"diameter": float("nan")}) + with pytest.raises(SegmentationError, match="twice"): + record(channel_ids=("DNA", "DNA")) + + +def test_write_record_refuses_another_masks_type_than_the_records(run): + with pytest.raises(SegmentationError, match="not 'Nuclei'"): + write_record(run.masks, "Nuclei", record()) + with pytest.raises(SegmentationError, match="one folder"): + write_record(run.masks, "../x", record(mask_type="../x")) From 30ec3667f77c7821a9f52c624f9205aa446b583e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 06:01:15 +0000 Subject: [PATCH 02/11] Segmentation hand-off: use the run's own mask pairing, publish strictly, resolve once Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- AGENTS.md | 3 +- CHANGELOG.md | 2 +- docs/contract.md | 6 +- src/morphobricks_preprocessing/__init__.py | 19 +- src/morphobricks_preprocessing/masks/files.py | 13 +- .../segmentation_handoff.py | 190 +++++++++++++----- tests/test_segmentation_handoff.py | 158 +++++++++++++++ 7 files changed, 324 insertions(+), 67 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4e4b6577..daca7c47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -246,7 +246,8 @@ src/morphobricks_preprocessing/ masks.binary.label_binary; Spec ADR 0005) and objects_read_plan (its peak memory from the header: stored plane, int32 result and labelling_bytes; #316) - segmentation_handoff.py images_to_segment, segmentation_input (channels by canonical ID through + segmentation_handoff.py images_to_segment (the run's own mask pairing), segmentation_input and + resolve_segmentation/SegmentationPlan (channels by canonical ID through resolve_request), mask_path and write_mask (a checked, compressed int32 YX TIFF, atomic, never over an existing mask unless asked) for a segmentation notebook; numpy and tifffile only (contract §15.5); segmentation_record.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b9fc009d..56d728e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,7 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. mask unless asked (a masks folder inside the experiment or the output folder is refused), and `SegmentationRecord` with `write_record` and `read_record` keeps one versioned `segmentation_record.json` per mask type. The masks step skips that file silently instead of - warning `mask_without_image`. Contract §15.5. + warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. Contract §15.5. - **Tag this repeat folder (all conditions)** on *Tag channels* (owner request of 20 November 2026): one row of tags per biological-repeat **folder name** and channel count; set once, it diff --git a/docs/contract.md b/docs/contract.md index eac2fd1f..39338804 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1291,10 +1291,10 @@ needs from this brick. They make no decision for the tool and guess nothing. | Function | Rule | |---|---| -| `images_to_segment(inputs, mask_type, masks_root)` | The run's images with no mask of that type: none in the image's folder of `/` named as its position ID (§1), in any case and with any TIFF extension (§15 pairing). Excluded images are not in the run, so never listed. Refuses a masks folder that breaks the folder rules (§15 Folder), and a mask type that is not one folder name. | -| `segmentation_input(inputs, channel_ids, fov, z=0, t=0)` | The channels **by canonical ID** as a `(C, Y, X)` array of the stored values, in the order of `channel_ids`. Resolved with `RunInputs.resolve_request(Request(channel_ids))` and `require()`: every refusal of the resolver passes through with its code and message (`A_SCOPE_INCOMPLETE` for a channel some images lack: choose channels every image has; `A_RGB_NOT_SUPPORTED`). Each channel is read at the C index the image stores it at (`FovSelection.index_of`), never at a position. An image with Z or T above 1 is refused: 2D only. | +| `images_to_segment(inputs, mask_type, masks_root)` | The run's images with no mask of that type, decided by **preprocessing's own pairing** of the masks folder (the function the run and the mask step use), so the list and the next run cannot disagree: either layout of §15, any case in folders, name and type (`cells` is `Cells`), any TIFF extension. Excluded images are not in the run, so never listed. Refuses a masks folder that breaks the folder rules (§15 Folder) or that the run itself would refuse (an ambiguous mask, a link leaving the folder), and a mask type that is not one folder name. | +| `segmentation_input(inputs, channel_ids, fov, z=0, t=0)` | The channels **by canonical ID** as a `(C, Y, X)` array of the stored values, in the order of `channel_ids`. Resolved with `RunInputs.resolve_request(Request(channel_ids))` and `require()`: every refusal of the resolver passes through with its code and message (`A_SCOPE_INCOMPLETE` for a channel some images lack: choose channels every image has; `A_RGB_NOT_SUPPORTED`). Each channel is read at the C index the image stores it at (`FovSelection.index_of`), never at a position. An image with Z or T above 1 is refused: 2D only. `resolve_segmentation(inputs, channel_ids)` resolves once for the whole run and returns a `SegmentationPlan` whose `read(fov, z=0, t=0)` gives the same array; `segmentation_input` resolves on every call, so a batch uses the plan. | | `mask_path(masks_root, mask_type, fov)` | `///.tif` (the first layout of §15). | -| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. An existing mask (or another TIFF of the same image name) is refused unless `overwrite=True`, and then only the file at `mask_path` is replaced. The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | +| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. A mask that the run's pairing finds for this image and type (any case, either layout, any extension) is refused, naming it, unless `overwrite=True`; then only the file at `mask_path` is replaced, and a twin elsewhere is still refused. Without `overwrite` the file is published with a hard link, which fails if the target exists, so two writers never replace each other's mask (a file system without hard links falls back to the check made before writing). The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | `//segmentation_record.json` (`SegmentationRecord`, `write_record`, `read_record`, `record_version` 1) is provenance only: `mask_type`, `tool` and `tool_version`, `model` diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index 1360438b..4108862b 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -235,7 +235,14 @@ ResolvedRequest, VolumeNotSupportedError, ) -from .segmentation_handoff import images_to_segment, mask_path, segmentation_input, write_mask +from .segmentation_handoff import ( + SegmentationPlan, + images_to_segment, + mask_path, + resolve_segmentation, + segmentation_input, + write_mask, +) from .segmentation_record import ( SegmentationError, SegmentationRecord, @@ -354,6 +361,7 @@ "MaskUncheckedError", "RgbNotSupportedError", "SegmentationError", + "SegmentationPlan", "SegmentationRecord", "SegmentedImage", "VolumeNotSupportedError", @@ -374,10 +382,6 @@ "ResolvedRequest", "UnrecordedFiles", "UnrecordedFilesError", - "images_to_segment", - "mask_path", - "read_record", - "segmentation_input", "unrecorded_files", "Fov", "LazyImage", @@ -411,6 +415,8 @@ "check_sources", "check_table", "convert_experiment", + "images_to_segment", + "mask_path", "preview_conversion", "declared_mapping", "default_output_folder", @@ -464,11 +470,13 @@ "read_mask_file", "read_physical_sizes", "read_plane", + "read_record", "read_sample_plane", "reconcile_design", "reference_axes", "repeat_boxes", "repeat_distributions", + "resolve_segmentation", "review_axes", "review_calibration", "review_image_type", @@ -477,6 +485,7 @@ "same_pixel_size", "sample_planes", "scan_masks", + "segmentation_input", "series_axes_from_metadata", "space_unit", "to_micrometers", diff --git a/src/morphobricks_preprocessing/masks/files.py b/src/morphobricks_preprocessing/masks/files.py index ffab5c46..ab9277d8 100644 --- a/src/morphobricks_preprocessing/masks/files.py +++ b/src/morphobricks_preprocessing/masks/files.py @@ -148,9 +148,10 @@ def _folder_masks( image the warning ``mask_of_excluded_image``: neither is used (design v0.4 §3 keeps the severity of every existing check). ``images`` are the analysed images' paths (excluded images left out). Links are followed only inside the masks folder (:mod:`..links`). The - conversion helpers' ``mask_lineage.jsonl`` and temporary files and a segmentation tool's - ``segmentation_record.json`` are skipped silently, like system files - (:func:`..mask_lineage.is_conversion_file`, Spec ADR 0005 BM12; contract §15.5). + conversion helpers' ``mask_lineage.jsonl`` and temporary files are skipped silently, like + system files (:func:`..mask_lineage.is_conversion_file`, Spec ADR 0005 BM12), and so is a + segmentation tool's ``segmentation_record.json`` directly in a type folder (contract + §15.5); the same name anywhere else is an unpaired file and warns. """ by_key, by_leaf = {}, {} for leaf in discovery.leaves: @@ -164,6 +165,8 @@ def _folder_masks( links = LinkGuard(folder, "masks folder") for path, real in links.files(folder, _skipped): relative = path.relative_to(folder) # a broken link is kept: its reader names it + if len(relative.parts) == 2 and relative.name == RECORD_FILENAME: + continue # a segmentation tool's provenance, at the type folder's root only (§15.5) if not is_tiff_name(path.name): (loose if len(relative.parts) == 1 else unpaired).append(relative.as_posix()) continue @@ -195,8 +198,8 @@ def _folder_masks( def _skipped(name: str) -> bool: - """Return True for system, conversion-helper and ``segmentation_record.json`` files (§15.5).""" - return is_system_name(name) or is_conversion_file(name) or name == RECORD_FILENAME + """Return True for system files and the conversion helpers' lineage and temporary files.""" + return is_system_name(name) or is_conversion_file(name) def _suffix_matches(relative: Path, by_leaf: Mapping[str, list]) -> list[tuple[str, str]]: diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index d9a01c16..5c7b0280 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -24,21 +24,25 @@ import os import tempfile +from dataclasses import dataclass from pathlib import Path import numpy as np import tifffile from ._io import give_output_mode +from .discovery import discover_experiment from .folder_rules import masks_folder_issues from .links import relative_inside +from .masks import FOLDER +from .masks.files import _folder_masks +from .masks.model import MaskFile from .run_inputs import Fov, RunInputs -from .run_inputs_request import Request +from .run_inputs_request import FovSelection, Request from .segmentation_record import SegmentationError, check_mask_type INT32_MAX = 2_147_483_647 """The largest label every brick accepts (contract §15, §16).""" -_SUFFIXES = (".ome.tiff", ".ome.tif", ".tiff", ".tif") # the TIFF names pairing accepts (§15) def images_to_segment( @@ -46,9 +50,11 @@ def images_to_segment( ) -> tuple[Fov, ...]: """Return the run's images that have no mask of ``mask_type`` yet, sorted by path. - An image has a mask when its folder in the mask type's folder holds a TIFF named as the - image's position ID, in any case and with any TIFF extension (the pairing of contract - §15). Excluded images are not in the run and are never listed. + "Has a mask" is decided by preprocessing's own pairing of the masks folder + (:func:`.masks.files._folder_masks`, the one the run and the mask step use), so this list + and the next run can never disagree: either layout of contract §15, any case in the + folders, the name and the type, any TIFF extension. Excluded images are not in the run and + are never listed. Parameters ---------- @@ -62,20 +68,75 @@ def images_to_segment( Raises ------ SegmentationError - For a mask type that is not one folder name, or a masks folder inside the - experiment or the output folder (or holding them). + For a mask type that is not one folder name, a masks folder inside the experiment or + the output folder (or holding them), or a masks folder the run itself would refuse + (an ambiguous mask, a link leaving the folder). """ check_mask_type(mask_type) _check_folders(inputs, masks_root) - folders: dict[Path, frozenset[str]] = {} - found = [] - for fov in inputs.fovs(): - folder = _folder(masks_root, mask_type, fov) - if folder not in folders: - folders[folder] = _stems(folder) - if fov.key[3].casefold() not in folders[folder]: - found.append(fov) - return tuple(found) + made = {m.image for m in _paired(inputs, masks_root, mask_type)} + return tuple(fov for fov in inputs.fovs() if fov.relative_path not in made) + + +@dataclass(frozen=True) +class SegmentationPlan: + """The channels of one request resolved once for the whole run, read image by image. + + Attributes + ---------- + inputs + The opened run. + channel_ids + The canonical channel IDs, in the order they are returned. + selections + The resolver's selection of each image, by its path relative to the experiment. + """ + + inputs: RunInputs + channel_ids: tuple[str, ...] + selections: dict[str, FovSelection] + + def read(self, fov: Fov, z: int = 0, t: int = 0) -> np.ndarray: + """Read the planned channels of one image as a ``(C, Y, X)`` array of stored values. + + Each channel is read at the C index this image stores it at + (``FovSelection.index_of``), in the order of :attr:`channel_ids`; nothing is scaled + or converted. + + Raises + ------ + SegmentationError + For an image with more than one Z plane or time point, or one not in the run. + """ + _check_2d(fov) + chosen = self.selections.get(fov.relative_path) + if chosen is None: + raise SegmentationError(f"{fov.relative_path} is not an image of this run.") + plane = self.inputs.read_plane(fov, z=z, t=t) + return np.stack([plane[chosen.index_of(channel_id)] for channel_id in self.channel_ids]) + + +def resolve_segmentation( + inputs: RunInputs, channel_ids: tuple[str, ...] | list[str] +) -> SegmentationPlan: + """Resolve ``channel_ids`` by ID for the whole run once; read each image with ``plan.read``. + + Resolving costs a pass over the run's manifest, so a batch resolves once and reads many + images (:func:`segmentation_input` resolves on every call). + + Raises + ------ + SegmentationError + For no channel, or a channel twice. + RunInputsError + The resolver's refusal, with its code and message unchanged (``A_SCOPE_INCOMPLETE`` + for a channel some images lack, ``A_RGB_NOT_SUPPORTED``, ...). + """ + ids = tuple(channel_ids) + if not ids or len(set(ids)) != len(ids): + raise SegmentationError("Name at least one channel ID, each once.") + selections = inputs.resolve_request(Request(ids)).require() + return SegmentationPlan(inputs, ids, {s.relative_path: s for s in selections}) def segmentation_input( @@ -87,6 +148,8 @@ def segmentation_input( read at the C index **this image** stores it at (``FovSelection.index_of``), so a channel that sits at another position in other repeats is still the same stain. The result is in the order of ``channel_ids``, with the stored pixel type: nothing is scaled or converted. + It resolves on every call: a batch calls :func:`resolve_segmentation` once and reads each + image with ``plan.read``. Parameters ---------- @@ -107,16 +170,8 @@ def segmentation_input( The resolver's refusal, with its code and message unchanged (``A_SCOPE_INCOMPLETE`` for a channel some images lack, ``A_RGB_NOT_SUPPORTED``, ...). """ - ids = tuple(channel_ids) - if not ids or len(set(ids)) != len(ids): - raise SegmentationError("Name at least one channel ID, each once.") _check_2d(fov) - selections = inputs.resolve_request(Request(ids)).require() - chosen = next((s for s in selections if s.relative_path == fov.relative_path), None) - if chosen is None: - raise SegmentationError(f"{fov.relative_path} is not an image of this run.") - plane = inputs.read_plane(fov, z=z, t=t) - return np.stack([plane[chosen.index_of(channel_id)] for channel_id in ids]) + return resolve_segmentation(inputs, channel_ids).read(fov, z=z, t=t) def mask_path(masks_root: str | os.PathLike, mask_type: str, fov: Fov) -> Path: @@ -183,12 +238,16 @@ def write_mask( _check_folders(inputs, masks_root) _check_2d(fov) data = _checked_labels(labels, inputs.plane_shape(fov), fov.relative_path) - others = sorted(n for n in _names(target.parent) if _stem(n) == fov.key[3].casefold()) - if others and (not overwrite or others != [target.name]): + wanted = target.relative_to(masks_root).as_posix() + twins = sorted( + m.path for m in _paired(inputs, masks_root, mask_type) if m.image == fov.relative_path + ) + if twins and (not overwrite or twins != [wanted]): raise SegmentationError( f"The {mask_type} mask of {fov.relative_path} already exists " - f"({', '.join(others)} in {target.parent}). Use overwrite=True to replace " - f"{target.name}; a file with another name must be moved away first." + f"({', '.join(twins)} in {masks_root}). Use overwrite=True to replace {wanted}; " + "a mask of this image and type in another place or case, or in the other layout, " + "must be moved away first (the next run would refuse both as duplicate_mask)." ) target.parent.mkdir(parents=True, exist_ok=True) handle, temporary = tempfile.mkstemp( @@ -200,13 +259,62 @@ def write_mask( temporary, data, photometric="minisblack", compression="zlib", metadata={"axes": "YX"} ) give_output_mode(temporary, target) - os.replace(temporary, target) + _publish(Path(temporary), target, overwrite, f"The {mask_type} mask of {fov.relative_path}") except BaseException: Path(temporary).unlink(missing_ok=True) raise return target +def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: + """Move the finished ``temporary`` file to ``target``; never over a file unless asked. + + Without ``overwrite`` the file is hard-linked (which fails if ``target`` exists, in one + step), so two writers cannot replace each other's mask between a check and the move. A + file system without hard links (some network mounts) falls back to the check just made + before writing, then :func:`os.replace`. + """ + if overwrite: + os.replace(temporary, target) + return + try: + os.link(temporary, target) + except FileExistsError: + raise SegmentationError( + f"{what} appeared at {target} while it was being written; nothing was replaced. " + "Use overwrite=True to replace it." + ) from None + except OSError: # no hard links here: the earlier check is all there is + if target.exists(): + raise SegmentationError(f"{what} exists at {target}; nothing was replaced.") from None + os.replace(temporary, target) + return + temporary.unlink() + + +def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> list[MaskFile]: + """Return the TIFF masks of ``mask_type`` that preprocessing's pairing finds (any case). + + Uses the run's own function (:func:`.masks.files._folder_masks`) on the experiment as it + is now and the recorded images, so both layouts of contract §15 and any case count, exactly + as at the next run. A masks folder the run would refuse is refused here too. + """ + folder = Path(masks_root) + if not folder.is_dir(): + return [] + discovery = discover_experiment(inputs.experiment_root, inputs.output_folder) + found, issues = _folder_masks( + folder.resolve(), discovery, {entry.relative_path for entry in inputs.files} + ) + refusing = [issue for issue in issues if issue.is_error] + if refusing: + first = refusing[0] + raise SegmentationError(f"{first.message} {first.action} ({first.code})") + return [ + m for m in found if m.source == FOLDER and m.mask_type.casefold() == mask_type.casefold() + ] + + def _checked_labels(labels: np.ndarray, shape: tuple[int, int], image: str) -> np.ndarray: """Return ``labels`` as an int32 array, or refuse them (see :func:`write_mask`).""" array = np.asarray(labels) @@ -261,25 +369,3 @@ def _check_folders(inputs: RunInputs, masks_root: str | os.PathLike) -> None: def _folder(masks_root: str | os.PathLike, mask_type: str, fov: Fov) -> Path: """Return the folder of ``fov``'s mask: the type's folder plus the image's own folders.""" return Path(masks_root, mask_type, *Path(fov.relative_path).parent.parts) - - -def _names(folder: Path) -> list[str]: - """Return the names of the files in ``folder`` (none if it does not exist).""" - try: - return [e.name for e in os.scandir(folder) if e.is_file()] - except FileNotFoundError: - return [] - - -def _stem(name: str) -> str | None: - """Return a TIFF file's name without its extension, lower case; None for other files.""" - lower = name.casefold() - for suffix in _SUFFIXES: - if lower.endswith(suffix): - return lower[: -len(suffix)] - return None - - -def _stems(folder: Path) -> frozenset[str]: - """Return the lower-case stems of the TIFF files in ``folder``.""" - return frozenset(s for s in map(_stem, _names(folder)) if s is not None) diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index bc4013fd..7e22b3b8 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -7,6 +7,7 @@ """ import dataclasses +import errno import json import os from types import SimpleNamespace @@ -23,6 +24,7 @@ from morphobricks_preprocessing.segmentation_handoff import ( images_to_segment, mask_path, + resolve_segmentation, segmentation_input, write_mask, ) @@ -384,3 +386,159 @@ def test_write_record_refuses_another_masks_type_than_the_records(run): write_record(run.masks, "Nuclei", record()) with pytest.raises(SegmentationError, match="one folder"): write_record(run.masks, "../x", record(mask_type="../x")) + + +# The pairing is the run's own: any case, either layout (review of #367) ------------------------ + + +def twin_cases(run): + """Return the existing masks of ``img0`` that the run would pair, each in its own tree.""" + return { + "other case": run.masks / "cells" / "control" / "biological_repeat_1" / "img0.tif", + "second layout": run.masks / "Control" / "Biological_repeat_1" / "img0_Cells.tif", + } + + +@pytest.mark.parametrize("case", ["other case", "second layout"]) +def test_a_mask_the_run_would_pair_counts_as_made(run, case): + fovs = run.inputs.fovs() + first = fovs[0] + assert first.relative_path == "Control/Biological_repeat_1/img0.tif" + twin = twin_cases(run)[case] + twin.parent.mkdir(parents=True) + twin.write_bytes(b"") + assert images_to_segment(run.inputs, "Cells", run.masks) == fovs[1:] + assert images_to_segment(run.inputs, "CELLS", run.masks) == fovs[1:] # a type is one name + for overwrite in (False, True): + with pytest.raises(SegmentationError, match="already exists") as caught: + write_mask( + run.masks, "Cells", first, labels_like(run, first), run.inputs, overwrite=overwrite + ) + assert twin.relative_to(run.masks).as_posix() in str(caught.value) + assert not mask_path(run.masks, "Cells", first).exists() + + +def test_overwrite_replaces_only_the_file_at_mask_path_and_refuses_a_twin_elsewhere(run): + first = run.inputs.fovs()[0] + path = write_mask(run.masks, "Cells", first, labels_like(run, first, 1), run.inputs) + write_mask(run.masks, "Cells", first, labels_like(run, first, 2), run.inputs, overwrite=True) + assert tifffile.imread(path).max() == 2 + twin = twin_cases(run)["second layout"] + twin.parent.mkdir(parents=True) + twin.write_bytes(b"") + before = path.read_bytes() + with pytest.raises(SegmentationError, match="img0_Cells.tif"): + write_mask( + run.masks, "Cells", first, labels_like(run, first, 3), run.inputs, overwrite=True + ) + assert path.read_bytes() == before and twin.read_bytes() == b"" + + +def test_a_masks_folder_the_run_would_refuse_is_refused(run, tmp_path): + fovs = run.inputs.fovs() + outside = tmp_path / "elsewhere.tif" + outside.write_bytes(b"") + folder = run.masks / "Cells" / "Control" / "Biological_repeat_1" + folder.mkdir(parents=True) + (folder / "img1.tif").symlink_to(outside) # a link leaving the masks folder (§1 links) + with pytest.raises(SegmentationError, match="link"): + images_to_segment(run.inputs, "Cells", run.masks) + with pytest.raises(SegmentationError, match="link"): + write_mask(run.masks, "Cells", fovs[5], labels_like(run, fovs[5]), run.inputs) + assert not mask_path(run.masks, "Cells", fovs[5]).exists() + + +# Publishing never replaces a mask another writer made in between ---------------------------- + + +def test_a_mask_that_appears_before_publishing_is_never_replaced(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = mask_path(run.masks, "Cells", fov) + real = os.link + + def racing(source, destination, **kwargs): + destination = os.fspath(destination) + with open(destination, "wb") as other: # the other writer's mask, made after our check + other.write(b"other writer") + return real(source, destination, **kwargs) + + monkeypatch.setattr(os, "link", racing) + with pytest.raises(SegmentationError, match="appeared"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert target.read_bytes() == b"other writer" + assert sorted(os.listdir(target.parent)) == [target.name] # our temporary file is gone + + +def test_without_hard_links_the_mask_is_still_written(run, monkeypatch): + fov = run.inputs.fovs()[0] + + def no_links(*args, **kwargs): + raise OSError(errno.EPERM, "hard links are not supported here") + + monkeypatch.setattr(os, "link", no_links) + path = write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) + assert tifffile.imread(path).max() == 4 + assert sorted(os.listdir(path.parent)) == [path.name] + with pytest.raises(SegmentationError, match="already exists"): # the check still refuses + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + + +# The record file is skipped at the type folder's root only ------------------------------------ + + +def test_a_stray_file_named_like_the_record_still_gets_its_warning(run): + for fov in run.inputs.fovs(): + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 3), run.inputs) + write_record(run.masks, "Cells", record()) + stray = run.masks / "Cells" / "Control" / RECORD_FILENAME + stray.write_text("{}", encoding="utf-8") + (run.out / "morphobricks.toml").write_bytes(run.data + MASKS_SECTION) + again = run_described(run.experiment, MAPPING, output_folder=run.out, masks_folder=run.masks) + assert again.written, [(i.code, i.message) for i in again.issues] + (warning,) = [i for i in again.issues if i.code == "mask_without_image"] + assert list(warning.paths) == [f"Cells/Control/{RECORD_FILENAME}"] + + +# One resolution for a whole batch ---------------------------------------------------------------- + + +def test_a_plan_reads_what_segmentation_input_reads(run): + plan = resolve_segmentation(run.inputs, ["TUB", "DNA"]) + assert plan.channel_ids == ("TUB", "DNA") + for fov in run.inputs.fovs(): + np.testing.assert_array_equal( + plan.read(fov), segmentation_input(run.inputs, ("TUB", "DNA"), fov) + ) + + +def test_a_batch_resolves_once(run, monkeypatch): + calls = [] + original = RunInputs.resolve_request + + def counting(self, request): + calls.append(request) + return original(self, request) + + monkeypatch.setattr(RunInputs, "resolve_request", counting) + plan = resolve_segmentation(run.inputs, ("DNA",)) + for fov in run.inputs.fovs(): + plan.read(fov) + assert len(calls) == 1 + segmentation_input(run.inputs, ("DNA",), run.inputs.fovs()[0]) + assert len(calls) == 2 # the one-image form resolves on every call + + +def test_a_plan_refuses_as_the_resolver_does_and_as_the_wrapper_does(run): + with pytest.raises(RunInputsError) as caught: + resolve_segmentation(run.inputs, ("DNA", "EXTRA")) + assert getattr(caught.value, "code", None) == "A_SCOPE_INCOMPLETE" + for ids in ((), ("DNA", "DNA")): + with pytest.raises(SegmentationError, match="at least one channel"): + resolve_segmentation(run.inputs, ids) + plan = resolve_segmentation(run.inputs, ("DNA",)) + fov = dataclasses.replace(run.inputs.fovs()[0], t_count=2) + with pytest.raises(SegmentationError, match="2D only"): + plan.read(fov) + other = dataclasses.replace(run.inputs.fovs()[0], relative_path="nowhere.tif") + with pytest.raises(SegmentationError, match="not an image of this run"): + plan.read(other) From 4532c7de45bcf741ee81e3785a856dda0d6b3b7e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 06:54:35 +0000 Subject: [PATCH 03/11] Segmentation hand-off: append-only record, strict mask types, duplicate checks, no silent replace Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- AGENTS.md | 3 +- CHANGELOG.md | 8 +- docs/contract.md | 34 ++- src/morphobricks_preprocessing/__init__.py | 4 + .../segmentation_handoff.py | 47 ++- .../segmentation_record.py | 273 ++++++++++++++---- tests/test_segmentation_handoff.py | 168 ++++------- tests/test_segmentation_record.py | 257 +++++++++++++++++ 8 files changed, 599 insertions(+), 195 deletions(-) create mode 100644 tests/test_segmentation_record.py diff --git a/AGENTS.md b/AGENTS.md index daca7c47..0804b470 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -251,7 +251,8 @@ src/morphobricks_preprocessing/ resolve_request), mask_path and write_mask (a checked, compressed int32 YX TIFF, atomic, never over an existing mask unless asked) for a segmentation notebook; numpy and tifffile only (contract §15.5); segmentation_record.py - SegmentationRecord and read/write of //segmentation_record.json + SegmentationRecord/SegmentationBatch and the append-only history file + //segmentation_record.json (mask type checked like a discovered one) mask_conversion.py RunInputs.binary_to_instances / classes_to_binary (Spec ADR 0005 BM12, step 2b): new mask files from a checked mask, refused before any read or write (check_class_image, collisions, idempotent retry); mask_lineage.py their diff --git a/CHANGELOG.md b/CHANGELOG.md index 56d728e4..0df106df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,8 +24,12 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. `write_mask` writes a checked label image as a zlib-compressed `int32` `YX` TIFF at `///.tif`, atomically and never over an existing mask unless asked (a masks folder inside the experiment or the output folder is refused), and - `SegmentationRecord` with `write_record` and `read_record` keeps one versioned - `segmentation_record.json` per mask type. The masks step skips that file silently instead of + `SegmentationRecord`, `SegmentationBatch`, `write_record` and `read_record` keep one versioned, + append-only `segmentation_record.json` per mask type (a batch per run of the tool, each + written mask with its SHA-256, so a second model never erases the first's provenance); a mask + type is checked like any discovered one (`NA`, whitespace, NFC); duplicate and ambiguous masks + and a type spelled two ways are refused before writing; a file system without hard links is + refused, never silently replaced. The masks step skips that file silently instead of warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. Contract §15.5. - **Tag this repeat folder (all conditions)** on *Tag channels* (owner request of 20 November diff --git a/docs/contract.md b/docs/contract.md index 39338804..eb98c609 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1296,15 +1296,31 @@ needs from this brick. They make no decision for the tool and guess nothing. | `mask_path(masks_root, mask_type, fov)` | `///.tif` (the first layout of §15). | | `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. A mask that the run's pairing finds for this image and type (any case, either layout, any extension) is refused, naming it, unless `overwrite=True`; then only the file at `mask_path` is replaced, and a twin elsewhere is still refused. Without `overwrite` the file is published with a hard link, which fails if the target exists, so two writers never replace each other's mask (a file system without hard links falls back to the check made before writing). The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | -`//segmentation_record.json` (`SegmentationRecord`, `write_record`, `read_record`, -`record_version` 1) is provenance only: `mask_type`, `tool` and `tool_version`, `model` -(`name`, `file` or null, `sha256`), `parameters` (a JSON object), `channel_ids`, `device` -(`cuda`, `cpu` or `mps`, always stated), `run_folder`, `run_manifest_sha256`, and `images` (the -image's path relative to the experiment, `status` `written`, `skipped` or `failed`, and a -`message`, required for `failed`). It is checked on writing and on reading; an unknown -version, an unknown or missing key, or a value outside its set is refused, never repaired. The -masks step skips this file silently (it is not a mask), and nothing reads it to decide -anything. +`//segmentation_record.json` (`SegmentationRecord`, `SegmentationBatch`, +`write_record`, `read_record`, `mask_sha256`, `record_version` 1) is provenance only and an +**append-only history of batches**, so a second batch (another model, other parameters) never +erases how the first batch's masks were made. A batch holds `batch_id` (unique in the file), +`tool` and `tool_version`, `model` (`name`, `file` or null, `sha256`), `parameters` (a JSON +object), `channel_ids`, `device` (`cuda`, `cpu` or `mps`, always stated), `run_folder`, +`run_manifest_sha256`, and `images`: one entry per image (its path relative to the experiment, +once per batch), `status` `written`, `skipped` or `failed`, a `message` (required for +`failed`) and `mask_sha256`, the SHA-256 of the file written (required for `written`, null +otherwise). `write_record` adds a batch; the same `batch_id` again (a batch written as it +progresses) is accepted only if everything but the images is equal and no earlier entry is +dropped or changed, otherwise it is refused and the file is left as it was. +`SegmentationRecord.latest(image)` gives the newest written entry of an image. The record is +checked on writing and on reading; an unknown version, an unknown or missing key, a value +outside its set, a batch ID twice or an image twice in a batch is refused, never repaired. +The mask type is checked with the rules the masks step applies to a discovered type +(`check_identity_text`: no surrounding whitespace, not `NA`, `nan`, `none`, `null`, `n/a` or +``; Unicode NFC; one folder name) before anything is written. The masks step skips this +file silently when it is directly in a type folder (it is not a mask; the same name deeper +warns `mask_without_image`), and nothing reads it to decide anything. + +The helper refuses what the run would refuse, before writing: an ambiguous mask or a link +leaving the folder, a mask type spelled in two ways (`mask_names_differ_in_case`) and an image +with two masks of the type (`duplicate_mask`). A file system without hard links (for example a +Google Drive mount) is refused for `overwrite=False` with a message, never silently replaced. ## 16. Shared rules for other bricks (MorphoBricks D86) diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index 4108862b..0235f46e 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -244,9 +244,11 @@ write_mask, ) from .segmentation_record import ( + SegmentationBatch, SegmentationError, SegmentationRecord, SegmentedImage, + mask_sha256, read_record, write_record, ) @@ -360,6 +362,7 @@ "MaskContradictsRepresentationError", "MaskUncheckedError", "RgbNotSupportedError", + "SegmentationBatch", "SegmentationError", "SegmentationPlan", "SegmentationRecord", @@ -417,6 +420,7 @@ "convert_experiment", "images_to_segment", "mask_path", + "mask_sha256", "preview_conversion", "declared_mapping", "default_output_folder", diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index 5c7b0280..06e82331 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -271,8 +271,9 @@ def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: Without ``overwrite`` the file is hard-linked (which fails if ``target`` exists, in one step), so two writers cannot replace each other's mask between a check and the move. A - file system without hard links (some network mounts) falls back to the check just made - before writing, then :func:`os.replace`. + file system without hard links (some network mounts, such as a Google Drive mount) is + refused: there is no way to publish without the risk of replacing, and a silent + replacement is never made. """ if overwrite: os.replace(temporary, target) @@ -284,20 +285,29 @@ def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: f"{what} appeared at {target} while it was being written; nothing was replaced. " "Use overwrite=True to replace it." ) from None - except OSError: # no hard links here: the earlier check is all there is - if target.exists(): - raise SegmentationError(f"{what} exists at {target}; nothing was replaced.") from None - os.replace(temporary, target) - return + except OSError as exc: + raise SegmentationError( + f"{what} was not written: this file system cannot publish a file without the risk " + f"of replacing another ({exc}). Write the masks to a folder on a local disk and " + "copy them, or use overwrite=True if replacing is what you want." + ) from None temporary.unlink() def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> list[MaskFile]: - """Return the TIFF masks of ``mask_type`` that preprocessing's pairing finds (any case). + """Return the TIFF masks of ``mask_type`` that preprocessing's pairing finds. Uses the run's own function (:func:`.masks.files._folder_masks`) on the experiment as it - is now and the recorded images, so both layouts of contract §15 and any case count, exactly - as at the next run. A masks folder the run would refuse is refused here too. + is now and the recorded images, so both layouts of contract §15 and any case in the + folders and names count, exactly as at the next run. Refused here as the run refuses them: + an ambiguous mask or a link leaving the folder (any error of the pairing), the type + spelled in two ways (``mask_names_differ_in_case``), and an image with two masks of the + type (``duplicate_mask``). + + Raises + ------ + SegmentationError + For any of those, naming the files. """ folder = Path(masks_root) if not folder.is_dir(): @@ -310,9 +320,24 @@ def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> if refusing: first = refusing[0] raise SegmentationError(f"{first.message} {first.action} ({first.code})") - return [ + same = [ m for m in found if m.source == FOLDER and m.mask_type.casefold() == mask_type.casefold() ] + spellings = sorted({m.mask_type for m in same} | {mask_type}) + if len(spellings) > 1: + raise SegmentationError( + f"The mask type is spelled {' and '.join(map(repr, spellings))}: names that differ " + "only in case are refused by the run (mask_names_differ_in_case). Use one spelling " + "and rename the folders or files of the other." + ) + images = [m.image for m in same] + twice = sorted({m.path for m in same if images.count(m.image) > 1}) + if twice: + raise SegmentationError( + f"Some images already have two masks of the type {mask_type}: {', '.join(twice)}. " + "The run refuses this (duplicate_mask); keep one mask per image and type." + ) + return same def _checked_labels(labels: np.ndarray, shape: tuple[int, int], image: str) -> np.ndarray: diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py index d4cd7d47..eb7f9664 100644 --- a/src/morphobricks_preprocessing/segmentation_record.py +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -1,28 +1,35 @@ -"""The provenance file of one mask type made by a segmentation tool (contract §15.5). +"""The provenance file of one mask type made by segmentation tools (contract §15.5). A segmentation tool (Cellpose in the shipped notebook) writes its masks under ``//`` with :func:`.segmentation_handoff.write_mask`, and one -``segmentation_record.json`` beside them says how they were made: the tool and its version, -the model (a name, and the weights file with its SHA-256), the parameters, the channel IDs -that were read, the device that ran it, the run it read (folder and manifest SHA-256) and one -entry per image (written, skipped or failed, with the message). The file is provenance only: -nothing in preprocessing reads it back to decide anything, and a mask is a mask whether or not -a record exists. +``segmentation_record.json`` beside them says how they were made. The file is an append-only +history of **batches**: each :class:`SegmentationBatch` holds the tool and its version, the +model (a name, and the weights file with its SHA-256), the parameters, the channel IDs read, +the device, the run read (folder and manifest SHA-256) and one entry per image (written, +skipped or failed, with the message and, for a written mask, the SHA-256 of the file). A +second batch with another model is added beside the first, never over it, so every mask keeps +the provenance of the batch that wrote it (the latest written entry of an image is the one +that holds). The file is provenance only: nothing in preprocessing reads it back to decide +anything, and a mask is a mask whether or not a record exists. The record is versioned (:data:`RECORD_VERSION`). :func:`read_record` checks everything it -reads and refuses a version it does not know, an unknown key, a wrong type or a value outside -the allowed set; nothing is repaired or defaulted. The module needs only the standard library. +reads and refuses a version it does not know, an unknown key, a wrong type, a value outside +its allowed set, a batch ID twice and an image twice in one batch; nothing is repaired or +defaulted. A mask type is checked with the rules every brick applies to a name +(:func:`.discovery.check_identity_text`, NFC), before anything is written. """ from __future__ import annotations import json import re -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any -from ._io import write_text_atomic +from ._io import file_sha256, write_text_atomic +from .discovery import IdentityError, check_identity_text +from .name_issues import is_nfc RECORD_VERSION = 1 """The version of the record this module writes and reads.""" @@ -41,7 +48,7 @@ class SegmentationError(ValueError): @dataclass(frozen=True) class SegmentedImage: - """What happened to one image of the run. + """What happened to one image in one batch. Attributes ---------- @@ -51,21 +58,25 @@ class SegmentedImage: ``written``, ``skipped`` (a mask was already there) or ``failed``. message Why, in plain words; required for ``failed`` (an error is never dropped). + mask_sha256 + The SHA-256 of the mask file written (:func:`mask_sha256`): required for ``written``, + None otherwise. """ image: str status: str message: str = "" + mask_sha256: str | None = None @dataclass(frozen=True) -class SegmentationRecord: - """How the masks of one mask type were made. +class SegmentationBatch: + """One run of a segmentation tool over some images: how its masks were made. Attributes ---------- - mask_type - The mask type (the name of the folder holding the masks and this record). + batch_id + The caller's identifier of the batch (for example its start time), unique in the file. tool, tool_version The segmentation tool and its exact version (e.g. ``cellpose``, ``4.2.1.1``). model_name @@ -86,10 +97,10 @@ class SegmentationRecord: run_manifest_sha256 The SHA-256 of that run's ``run_manifest.json`` when the images were read. images - One entry per image handled, in the order handled. + One entry per image handled, each image once. """ - mask_type: str + batch_id: str tool: str tool_version: str model_name: str @@ -101,17 +112,15 @@ class SegmentationRecord: run_manifest_sha256: str images: tuple[SegmentedImage, ...] = () model_file: str | None = None - record_version: int = field(default=RECORD_VERSION, init=False) def __post_init__(self) -> None: - """Refuse a record that could not be read back (the same checks as reading).""" - _check(self.to_dict()) + """Refuse a batch that could not be read back (the same checks as reading).""" + _batch(self.to_dict()) def to_dict(self) -> dict[str, Any]: - """Return the record as the JSON object written to the file.""" + """Return the batch as the JSON object kept in the file.""" return { - "record_version": self.record_version, - "mask_type": self.mask_type, + "batch_id": self.batch_id, "tool": self.tool, "tool_version": self.tool_version, "model": { @@ -125,24 +134,23 @@ def to_dict(self) -> dict[str, Any]: "run_folder": self.run_folder, "run_manifest_sha256": self.run_manifest_sha256, "images": [ - {"image": i.image, "status": i.status, "message": i.message} for i in self.images + { + "image": i.image, + "status": i.status, + "message": i.message, + "mask_sha256": i.mask_sha256, + } + for i in self.images ], } @classmethod - def from_dict(cls, data: object) -> SegmentationRecord: - """Build a record from a JSON object, checking all of it. - - Raises - ------ - SegmentationError - For an unknown ``record_version``, a missing or unknown key, a value of the wrong - type or outside its allowed set. - """ - _check(data) + def from_dict(cls, data: object) -> SegmentationBatch: + """Build a batch from a JSON object, checking all of it (:class:`SegmentationError`).""" + data = _batch(data) model = data["model"] return cls( - mask_type=data["mask_type"], + batch_id=data["batch_id"], tool=data["tool"], tool_version=data["tool_version"], model_name=model["name"], @@ -154,15 +162,75 @@ def from_dict(cls, data: object) -> SegmentationRecord: run_folder=data["run_folder"], run_manifest_sha256=data["run_manifest_sha256"], images=tuple( - SegmentedImage(i["image"], i["status"], i["message"]) for i in data["images"] + SegmentedImage(i["image"], i["status"], i["message"], i["mask_sha256"]) + for i in data["images"] ), ) + def same_provenance(self, other: SegmentationBatch) -> bool: + """Return True if ``other`` was made the same way (everything but its images).""" + return replace(self, images=()) == replace(other, images=()) + + +@dataclass(frozen=True) +class SegmentationRecord: + """The history of one mask type: every batch that made or skipped its masks, in order. + + Attributes + ---------- + mask_type + The mask type (the name of the folder holding the masks and this record). + batches + The batches, oldest first; batch IDs are unique. + """ + + mask_type: str + batches: tuple[SegmentationBatch, ...] = () + record_version: int = field(default=RECORD_VERSION, init=False) + + def __post_init__(self) -> None: + """Refuse a record that could not be read back (the same checks as reading).""" + _check(self.to_dict()) + + def to_dict(self) -> dict[str, Any]: + """Return the record as the JSON object written to the file.""" + return { + "record_version": self.record_version, + "mask_type": self.mask_type, + "batches": [b.to_dict() for b in self.batches], + } + + @classmethod + def from_dict(cls, data: object) -> SegmentationRecord: + """Build a record from a JSON object, checking all of it. + + Raises + ------ + SegmentationError + For an unknown ``record_version``, a missing or unknown key, a value of the wrong + type or outside its allowed set, a batch ID twice, or an image twice in a batch. + """ + data = _check(data) + return cls( + data["mask_type"], tuple(SegmentationBatch.from_dict(b) for b in data["batches"]) + ) + + def latest(self, image: str) -> tuple[SegmentationBatch, SegmentedImage] | None: + """Return the newest batch and entry that wrote the mask of ``image``, or None. -_KEYS = frozenset( + A mask replaced by a later batch (``overwrite=True``) belongs to that later batch. + """ + for batch in reversed(self.batches): + for entry in batch.images: + if entry.image == image and entry.status == "written": + return batch, entry + return None + + +_KEYS = frozenset({"record_version", "mask_type", "batches"}) +_BATCH_KEYS = frozenset( { - "record_version", - "mask_type", + "batch_id", "tool", "tool_version", "model", @@ -175,11 +243,11 @@ def from_dict(cls, data: object) -> SegmentationRecord: } ) _MODEL_KEYS = frozenset({"name", "file", "sha256"}) -_IMAGE_KEYS = frozenset({"image", "status", "message"}) +_IMAGE_KEYS = frozenset({"image", "status", "message", "mask_sha256"}) -def _check(data: object) -> None: - """Refuse an object that is not a version 1 record (module docstring).""" +def _check(data: object) -> dict[str, Any]: + """Return ``data`` if it is a version 1 record, else refuse (module docstring).""" if not isinstance(data, dict): raise SegmentationError("The segmentation record is not a JSON object.") version = data.get("record_version") @@ -190,7 +258,21 @@ def _check(data: object) -> None: "that wrote it." ) _keys(data, _KEYS, "the record") - for key in ("mask_type", "tool", "tool_version", "run_folder"): + check_mask_type(data["mask_type"]) + if not isinstance(data["batches"], (list, tuple)): + raise SegmentationError("batches must be a list.") + for batch in data["batches"]: + _batch(batch) + ids = [b["batch_id"] for b in data["batches"]] + if len(set(ids)) != len(ids): + raise SegmentationError("The record names a batch ID twice.") + return data + + +def _batch(data: object) -> dict[str, Any]: + """Return ``data`` if it is a valid batch, else refuse.""" + data = _keys(data, _BATCH_KEYS, "a batch") + for key in ("batch_id", "tool", "tool_version", "run_folder"): _text(data[key], key) _hash(data["run_manifest_sha256"], "run_manifest_sha256") if data["device"] not in DEVICES: @@ -215,10 +297,18 @@ def _check(data: object) -> None: raise SegmentationError("images must be a list.") for entry in data["images"]: _image(entry) + images = [entry["image"] for entry in data["images"]] + twice = sorted({name for name in images if images.count(name) > 1}) + if twice: + raise SegmentationError( + f"The batch {data['batch_id']!r} has more than one entry for {', '.join(twice)}; " + "an image has one status in a batch." + ) + return data -def _keys(data: object, expected: frozenset[str], what: str) -> None: - """Refuse an object without exactly the ``expected`` keys.""" +def _keys(data: object, expected: frozenset[str], what: str) -> dict[str, Any]: + """Return ``data`` if it is an object with exactly the ``expected`` keys, else refuse.""" if not isinstance(data, dict): raise SegmentationError(f"{what} must be a JSON object.") missing, extra = sorted(expected - data.keys()), sorted(data.keys() - expected) @@ -226,6 +316,7 @@ def _keys(data: object, expected: frozenset[str], what: str) -> None: found = [f"missing {', '.join(missing)}"] * bool(missing) found += [f"unknown {', '.join(map(str, extra))}"] * bool(extra) raise SegmentationError(f"{what} has the wrong keys: {'; '.join(found)}.") + return data def _text(value: object, what: str) -> None: @@ -242,7 +333,7 @@ def _hash(value: object, what: str) -> None: def _model(model: object) -> None: """Refuse a model entry without a name and a SHA-256 (a file or None).""" - _keys(model, _MODEL_KEYS, "model") + model = _keys(model, _MODEL_KEYS, "model") _text(model["name"], "the model name") _hash(model["sha256"], "the model sha256") if model["file"] is not None: @@ -250,8 +341,8 @@ def _model(model: object) -> None: def _image(entry: object) -> None: - """Refuse an image entry with an unknown status, or a failure without a message.""" - _keys(entry, _IMAGE_KEYS, "an image entry") + """Refuse an entry with an unknown status, a failure without a message, or a bad hash.""" + entry = _keys(entry, _IMAGE_KEYS, "an image entry") _text(entry["image"], "the image path") if entry["status"] not in STATUSES: raise SegmentationError( @@ -261,31 +352,67 @@ def _image(entry: object) -> None: raise SegmentationError("an image entry's message must be a text.") if entry["status"] == "failed" and not entry["message"].strip(): raise SegmentationError(f"{entry['image']} failed without a message; say why.") + if entry["status"] == "written": + _hash(entry["mask_sha256"], f"the mask_sha256 of {entry['image']}") + elif entry["mask_sha256"] is not None: + raise SegmentationError( + f"{entry['image']} is {entry['status']}, so it has no mask_sha256 of its own." + ) def check_mask_type(mask_type: str) -> None: - """Refuse a mask type that is not the name of one folder.""" - if not mask_type or mask_type in {".", ".."} or Path(mask_type).name != mask_type: + """Refuse a mask type that preprocessing would refuse, or that is not one folder name. + + The rules are the ones the masks step applies to a discovered type: text with no leading + or trailing whitespace that does not read as a missing value in tables (``NA``, ``nan``, + ...) (:func:`.discovery.check_identity_text`), in Unicode NFC (never converted), and the + name of one folder (no separator, not ``.`` or ``..``). + + Raises + ------ + SegmentationError + Naming what is wrong. + """ + try: + check_identity_text(mask_type, "mask type") + except IdentityError as exc: + raise SegmentationError(f"{exc}. Choose another mask type.") from None + if not is_nfc(mask_type): + raise SegmentationError( + f"The mask type {mask_type!r} is not in Unicode NFC form (an accent stored as a " + "separate character). Retype it, or choose another mask type." + ) + if mask_type in {".", ".."} or Path(mask_type).name != mask_type or "\\" in mask_type: raise SegmentationError(f"{mask_type!r} is not a mask type: it names one folder.") +def mask_sha256(path: str | Path) -> str: + """Return the SHA-256 of a mask file's bytes, for the entry of a written image.""" + return file_sha256(path) + + def record_path(masks_root: str | Path, mask_type: str) -> Path: """Return where the record of ``mask_type`` is, ``//segmentation_record.json``.""" check_mask_type(mask_type) return Path(masks_root) / mask_type / RECORD_FILENAME -def write_record(masks_root: str | Path, mask_type: str, record: SegmentationRecord) -> Path: - """Write the record of ``mask_type`` atomically, replacing an earlier one. +def write_record(masks_root: str | Path, mask_type: str, batch: SegmentationBatch) -> Path: + """Add ``batch`` to the record of ``mask_type`` (atomically); earlier batches are kept. + + A batch ID not yet in the file is appended. The same batch ID again (a batch written as it + progresses) replaces that batch only if it was made the same way (everything but the + images is equal) and keeps every entry it already had unchanged: provenance is only ever + added. Anything else is refused and the file is left as it was. Parameters ---------- masks_root The masks folder. mask_type - The mask type; it must be the record's own. - record - The record. + The mask type, checked as :func:`check_mask_type` does. + batch + The batch. Returns ------- @@ -295,13 +422,37 @@ def write_record(masks_root: str | Path, mask_type: str, record: SegmentationRec Raises ------ SegmentationError - If ``mask_type`` is not one folder name or is not the record's. + For a mask type preprocessing would refuse, an existing record that is not valid, a + batch ID already used by a batch made another way or whose earlier entries the new + one drops or changes. """ path = record_path(masks_root, mask_type) - if record.mask_type != mask_type: - raise SegmentationError( - f"The record is of mask type {record.mask_type!r}, not {mask_type!r}." - ) + earlier = read_record(masks_root, mask_type) if path.exists() else SegmentationRecord(mask_type) + batches = list(earlier.batches) + for index, old in enumerate(batches): + if old.batch_id != batch.batch_id: + continue + kept = {(e.image, e.status, e.message, e.mask_sha256) for e in batch.images} + lost = [ + e.image for e in old.images if (e.image, e.status, e.message, e.mask_sha256) not in kept + ] + if not old.same_provenance(batch): + problem = "was made another way (tool, model, parameters, channels, device or run)" + elif lost: + problem = f"would lose or change its entries for {', '.join(lost)}" + else: + problem = "" + if problem: + raise SegmentationError( + f"The batch {batch.batch_id!r} is already in the record of {mask_type} and " + f"{problem}. Give a new batch its own batch_id: earlier provenance is never " + "replaced." + ) + batches[index] = batch + break + else: + batches.append(batch) + record = SegmentationRecord(mask_type, tuple(batches)) text = json.dumps(record.to_dict(), indent=2, ensure_ascii=False, allow_nan=False) return write_text_atomic(path, text + "\n", parents=True) diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index 7e22b3b8..fd5654b9 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -31,11 +31,9 @@ from morphobricks_preprocessing.segmentation_record import ( RECORD_FILENAME, SegmentationError, - SegmentationRecord, - SegmentedImage, - read_record, write_record, ) +from test_segmentation_record import batch from test_stage3_channels import LEVELS, described_run, extra_stain EXTRA_FIRST = ( @@ -44,6 +42,7 @@ ) MASKS_SECTION = b'\n[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"\n' REPEAT_2 = "Biological_repeat_2" +EXPECTED_ROUND_TRIP_ISSUES = [] @pytest.fixture @@ -67,24 +66,6 @@ def labels_like(run, fov, value=1): return labels -def record(**changes): - fields = { - "mask_type": "Cells", - "tool": "cellpose", - "tool_version": "4.2.1.1", - "model_name": "cpsam_v2", - "model_sha256": "ab" * 32, - "model_file": "cpsam_v2.pt", - "parameters": {"diameter": None, "flow_threshold": 0.4}, - "channel_ids": ("ACTIN", "DNA"), - "device": "cpu", - "run_folder": "/runs/out", - "run_manifest_sha256": "cd" * 32, - "images": (SegmentedImage("a/b.tif", "written"), SegmentedImage("a/c.tif", "skipped", "x")), - } - return SegmentationRecord(**{**fields, **changes}) - - # segmentation_input ----------------------------------------------------------------------- @@ -159,7 +140,7 @@ def test_mask_path_follows_the_layout_of_contract_15(run): run.masks / "Cells" / "Control" / "Biological_repeat_1" / "img0.tif" ) for bad in ("", "..", "a/b", "."): - with pytest.raises(SegmentationError, match="one folder"): + with pytest.raises(SegmentationError, match="mask type|one folder"): mask_path(run.masks, bad, fov) @@ -228,6 +209,18 @@ def test_write_mask_accepts_boolean_and_any_integer_type(run): assert tifffile.imread(path).max() == 2_147_483_647 +@pytest.mark.parametrize("name", ["NA", "nan", " Cells", "Cells ", "Cafe\u0301", "a/b", ".."]) +def test_a_mask_type_preprocessing_would_refuse_is_refused_before_anything_is_written(run, name): + fov = run.inputs.fovs()[0] + with pytest.raises(SegmentationError): + write_mask(run.masks, name, fov, labels_like(run, fov), run.inputs) + with pytest.raises(SegmentationError): + images_to_segment(run.inputs, name, run.masks) + with pytest.raises(SegmentationError): + mask_path(run.masks, name, fov) + assert not run.masks.exists() + + def test_write_mask_refuses_labels_that_are_not_a_mask(run): fov = run.inputs.fovs()[0] good = labels_like(run, fov) @@ -295,11 +288,11 @@ def test_masks_written_here_pass_preprocessings_own_mask_checks(run): fovs = run.inputs.fovs() for fov in fovs: write_mask(run.masks, "Cells", fov, labels_like(run, fov, 3), run.inputs) - write_record(run.masks, "Cells", record()) # the record beside the masks is not a mask + write_record(run.masks, "Cells", batch()) # the record beside the masks is not a mask (run.out / "morphobricks.toml").write_bytes(run.data + MASKS_SECTION) again = run_described(run.experiment, MAPPING, output_folder=run.out, masks_folder=run.masks) assert again.written, [(i.code, i.message) for i in again.issues] - assert [i.code for i in again.issues if i.code.startswith(("mask", "unreadable_mask"))] == [] + assert sorted(i.code for i in again.issues) == EXPECTED_ROUND_TRIP_ISSUES manifest = json.loads((run.out / MANIFEST_FILENAME).read_text(encoding="utf-8")) entries = manifest["masks"]["files"] assert sorted(e["image"] for e in entries) == sorted(f.relative_path for f in fovs) @@ -311,95 +304,18 @@ def test_masks_written_here_pass_preprocessings_own_mask_checks(run): assert images_to_segment(reopened, "Cells", run.masks) == () -# The record -------------------------------------------------------------------------------- - - -def test_the_record_round_trips_through_its_file(run): - original = record() - path = write_record(run.masks, "Cells", original) - assert path == run.masks / "Cells" / RECORD_FILENAME - assert json.loads(path.read_text(encoding="utf-8"))["record_version"] == 1 - assert read_record(run.masks, "Cells") == original - assert SegmentationRecord.from_dict(original.to_dict()) == original - assert path.read_bytes() == path.read_bytes().replace(b"\r\n", b"\n") - changed = record(device="cuda", images=()) - write_record(run.masks, "Cells", changed) # an earlier record is replaced - assert read_record(run.masks, "Cells") == changed - - -def test_an_unknown_record_version_is_refused(run): - path = write_record(run.masks, "Cells", record()) - for version in (2, 0, "1", True, None): - data = json.loads(path.read_text(encoding="utf-8")) - data["record_version"] = version - path.write_text(json.dumps(data), encoding="utf-8") - with pytest.raises(SegmentationError, match="version"): - read_record(run.masks, "Cells") - - -def test_a_record_that_is_not_valid_is_refused(run): - path = write_record(run.masks, "Cells", record()) - good = json.loads(path.read_text(encoding="utf-8")) - - def broken(edit): - data = json.loads(json.dumps(good)) - edit(data) - path.write_text(json.dumps(data), encoding="utf-8") - return pytest.raises(SegmentationError) - - with broken(lambda d: d.update(device="gpu")): - read_record(run.masks, "Cells") - with broken(lambda d: d.update(extra=1)): - read_record(run.masks, "Cells") - with broken(lambda d: d.pop("tool")): - read_record(run.masks, "Cells") - with broken(lambda d: d["model"].update(sha256="xyz")): - read_record(run.masks, "Cells") - with broken(lambda d: d.update(channel_ids=[])): - read_record(run.masks, "Cells") - with broken(lambda d: d["images"][0].update(status="done")): - read_record(run.masks, "Cells") - with broken(lambda d: d.update(mask_type="Nuclei")): - read_record(run.masks, "Cells") - path.write_text("not json", encoding="utf-8") - with pytest.raises(SegmentationError, match="cannot be read"): - read_record(run.masks, "Cells") - with pytest.raises(SegmentationError, match="no segmentation record"): - read_record(run.masks, "Nuclei") - - -def test_a_record_cannot_be_built_without_what_it_needs(): - with pytest.raises(SegmentationError, match="failed without a message"): - record(images=(SegmentedImage("a.tif", "failed"),)) - with pytest.raises(SegmentationError, match="device"): - record(device="") - with pytest.raises(SegmentationError, match="SHA-256"): - record(model_sha256="") - with pytest.raises(SegmentationError, match="plain JSON"): - record(parameters={"diameter": float("nan")}) - with pytest.raises(SegmentationError, match="twice"): - record(channel_ids=("DNA", "DNA")) - - -def test_write_record_refuses_another_masks_type_than_the_records(run): - with pytest.raises(SegmentationError, match="not 'Nuclei'"): - write_record(run.masks, "Nuclei", record()) - with pytest.raises(SegmentationError, match="one folder"): - write_record(run.masks, "../x", record(mask_type="../x")) - - # The pairing is the run's own: any case, either layout (review of #367) ------------------------ def twin_cases(run): """Return the existing masks of ``img0`` that the run would pair, each in its own tree.""" return { - "other case": run.masks / "cells" / "control" / "biological_repeat_1" / "img0.tif", + "other case path": run.masks / "Cells" / "control" / "biological_repeat_1" / "img0.tif", "second layout": run.masks / "Control" / "Biological_repeat_1" / "img0_Cells.tif", } -@pytest.mark.parametrize("case", ["other case", "second layout"]) +@pytest.mark.parametrize("case", ["other case path", "second layout"]) def test_a_mask_the_run_would_pair_counts_as_made(run, case): fovs = run.inputs.fovs() first = fovs[0] @@ -408,7 +324,6 @@ def test_a_mask_the_run_would_pair_counts_as_made(run, case): twin.parent.mkdir(parents=True) twin.write_bytes(b"") assert images_to_segment(run.inputs, "Cells", run.masks) == fovs[1:] - assert images_to_segment(run.inputs, "CELLS", run.masks) == fovs[1:] # a type is one name for overwrite in (False, True): with pytest.raises(SegmentationError, match="already exists") as caught: write_mask( @@ -418,6 +333,36 @@ def test_a_mask_the_run_would_pair_counts_as_made(run, case): assert not mask_path(run.masks, "Cells", first).exists() +@pytest.mark.parametrize("spelling", ["cells", "CELLS"]) +def test_a_type_spelled_in_two_ways_is_refused_as_the_run_refuses_it(run, spelling): + twin = run.masks / spelling / "Control" / "Biological_repeat_1" / "img0.tif" + twin.parent.mkdir(parents=True) + twin.write_bytes(b"") + first = run.inputs.fovs()[0] + with pytest.raises(SegmentationError, match="mask_names_differ_in_case"): + images_to_segment(run.inputs, "Cells", run.masks) + with pytest.raises(SegmentationError, match="mask_names_differ_in_case"): + write_mask(run.masks, "Cells", first, labels_like(run, first), run.inputs) + assert not mask_path(run.masks, "Cells", first).exists() + + +def test_two_masks_of_one_image_and_type_are_refused_before_writing(run): + fovs = run.inputs.fovs() + write_mask(run.masks, "Cells", fovs[0], labels_like(run, fovs[0]), run.inputs) + twin = twin_cases(run)["second layout"] # the other layout: the same image and type again + twin.parent.mkdir(parents=True) + twin.write_bytes(b"") + with pytest.raises(SegmentationError, match="duplicate_mask"): + write_mask( + run.masks, "Cells", fovs[0], labels_like(run, fovs[0]), run.inputs, overwrite=True + ) + with pytest.raises(SegmentationError, match="duplicate_mask"): + write_mask(run.masks, "Cells", fovs[3], labels_like(run, fovs[3]), run.inputs) + with pytest.raises(SegmentationError, match="duplicate_mask"): + images_to_segment(run.inputs, "Cells", run.masks) + assert not mask_path(run.masks, "Cells", fovs[3]).exists() + + def test_overwrite_replaces_only_the_file_at_mask_path_and_refuses_a_twin_elsewhere(run): first = run.inputs.fovs()[0] path = write_mask(run.masks, "Cells", first, labels_like(run, first, 1), run.inputs) @@ -469,18 +414,19 @@ def racing(source, destination, **kwargs): assert sorted(os.listdir(target.parent)) == [target.name] # our temporary file is gone -def test_without_hard_links_the_mask_is_still_written(run, monkeypatch): +def test_without_hard_links_the_mask_is_refused_and_nothing_is_written(run, monkeypatch): fov = run.inputs.fovs()[0] def no_links(*args, **kwargs): raise OSError(errno.EPERM, "hard links are not supported here") monkeypatch.setattr(os, "link", no_links) - path = write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) - assert tifffile.imread(path).max() == 4 - assert sorted(os.listdir(path.parent)) == [path.name] - with pytest.raises(SegmentationError, match="already exists"): # the check still refuses - write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + with pytest.raises(SegmentationError, match="cannot publish a file without the risk"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) + folder = mask_path(run.masks, "Cells", fov).parent + assert os.listdir(folder) == [] # no mask, no temporary file + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs, overwrite=True) + assert tifffile.imread(mask_path(run.masks, "Cells", fov)).max() == 4 # asked for it # The record file is skipped at the type folder's root only ------------------------------------ @@ -489,7 +435,7 @@ def no_links(*args, **kwargs): def test_a_stray_file_named_like_the_record_still_gets_its_warning(run): for fov in run.inputs.fovs(): write_mask(run.masks, "Cells", fov, labels_like(run, fov, 3), run.inputs) - write_record(run.masks, "Cells", record()) + write_record(run.masks, "Cells", batch()) stray = run.masks / "Cells" / "Control" / RECORD_FILENAME stray.write_text("{}", encoding="utf-8") (run.out / "morphobricks.toml").write_bytes(run.data + MASKS_SECTION) diff --git a/tests/test_segmentation_record.py b/tests/test_segmentation_record.py new file mode 100644 index 00000000..e0d30ac1 --- /dev/null +++ b/tests/test_segmentation_record.py @@ -0,0 +1,257 @@ +"""The segmentation record (contract §15.5): an append-only history of batches. + +Each batch keeps how its masks were made (tool, model and its SHA-256, parameters, channel IDs, +device, run and manifest SHA-256) and one entry per image with the SHA-256 of a written mask, +so a second batch with another model never erases the provenance of the first. +""" + +import hashlib +import json + +import pytest + +from morphobricks_preprocessing.segmentation_record import ( + RECORD_FILENAME, + SegmentationBatch, + SegmentationError, + SegmentationRecord, + SegmentedImage, + mask_sha256, + read_record, + write_record, +) + +MASK = "ef" * 32 + + +def batch(**changes): + fields = { + "batch_id": "2026-11-21T10:00:00Z", + "tool": "cellpose", + "tool_version": "4.2.1.1", + "model_name": "cpsam_v2", + "model_sha256": "ab" * 32, + "model_file": "cpsam_v2.pt", + "parameters": {"diameter": None, "flow_threshold": 0.4}, + "channel_ids": ("ACTIN", "DNA"), + "device": "cpu", + "run_folder": "/runs/out", + "run_manifest_sha256": "cd" * 32, + "images": ( + SegmentedImage("a/b.tif", "written", mask_sha256=MASK), + SegmentedImage("a/c.tif", "skipped", "a mask was already there"), + SegmentedImage("a/d.tif", "failed", "out of memory"), + ), + } + return SegmentationBatch(**{**fields, **changes}) + + +def second(**changes): + """A later batch made with another model, which also wrote a/b.tif again.""" + fields = { + "batch_id": "2026-11-22T09:00:00Z", + "model_name": "cpdino", + "model_sha256": "12" * 32, + "model_file": None, + "device": "cuda", + "images": (SegmentedImage("a/b.tif", "written", mask_sha256="34" * 32),), + } + return batch(**{**fields, **changes}) + + +def test_the_record_round_trips_through_its_file(tmp_path): + first = batch() + path = write_record(tmp_path, "Cells", first) + assert path == tmp_path / "Cells" / RECORD_FILENAME + data = json.loads(path.read_text(encoding="utf-8")) + assert data["record_version"] == 1 and [b["batch_id"] for b in data["batches"]] == [ + first.batch_id + ] + original = SegmentationRecord("Cells", (first,)) + assert read_record(tmp_path, "Cells") == original + assert SegmentationRecord.from_dict(original.to_dict()) == original + assert b"\r" not in path.read_bytes() + + +def test_a_second_batch_with_another_model_keeps_both_provenances(tmp_path): + write_record(tmp_path, "Cells", batch()) + write_record(tmp_path, "Cells", second()) + record = read_record(tmp_path, "Cells") + assert [b.model_name for b in record.batches] == ["cpsam_v2", "cpdino"] + assert [b.device for b in record.batches] == ["cpu", "cuda"] + assert record.batches[0] == batch() # the first batch is exactly as it was + assert record.batches[0].images[0].mask_sha256 == MASK + # The mask of a/b.tif was replaced by the second batch: it holds that batch's provenance. + newest, entry = record.latest("a/b.tif") + assert (newest.model_name, entry.mask_sha256) == ("cpdino", "34" * 32) + assert record.latest("a/c.tif") is None and record.latest("nowhere.tif") is None + + +def test_the_same_batch_can_grow_but_never_change_or_lose_entries(tmp_path): + early = batch(images=(SegmentedImage("a/b.tif", "written", mask_sha256=MASK),)) + write_record(tmp_path, "Cells", early) + grown = batch(images=(*early.images, SegmentedImage("a/c.tif", "failed", "disk full"))) + write_record(tmp_path, "Cells", grown) + assert read_record(tmp_path, "Cells").batches == (grown,) + path = tmp_path / "Cells" / RECORD_FILENAME + before = path.read_bytes() + refused = { + "another model": (batch(model_name="cpsam", images=grown.images), "made another way"), + "other channels": (batch(channel_ids=("DNA",), images=grown.images), "made another way"), + "entry dropped": (batch(images=early.images), "would lose"), + "entry changed": ( + batch(images=(SegmentedImage("a/b.tif", "written", mask_sha256="99" * 32),)), + "would lose", + ), + } + for _name, (changed, message) in refused.items(): + with pytest.raises(SegmentationError, match=message): + write_record(tmp_path, "Cells", changed) + assert path.read_bytes() == before # the record is exactly as it was + + +def test_an_image_twice_in_a_batch_is_refused_whatever_its_statuses(): + twice = ( + SegmentedImage("a/b.tif", "written", mask_sha256=MASK), + SegmentedImage("a/b.tif", "failed", "out of memory"), + ) + with pytest.raises(SegmentationError, match="more than one entry for a/b.tif"): + batch(images=twice) + with pytest.raises(SegmentationError, match="more than one entry"): + batch(images=(twice[0], twice[0])) + + +def test_a_contradictory_duplicate_entry_in_a_file_is_refused_on_reading(tmp_path): + path = write_record(tmp_path, "Cells", batch()) + data = json.loads(path.read_text(encoding="utf-8")) + data["batches"][0]["images"].append( + {"image": "a/b.tif", "status": "failed", "message": "x", "mask_sha256": None} + ) + path.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(SegmentationError, match="more than one entry for a/b.tif"): + read_record(tmp_path, "Cells") + + +def test_a_written_mask_needs_its_sha256_and_only_a_written_mask_has_one(): + with pytest.raises(SegmentationError, match="mask_sha256"): + batch(images=(SegmentedImage("a/b.tif", "written"),)) + with pytest.raises(SegmentationError, match="mask_sha256"): + batch(images=(SegmentedImage("a/b.tif", "written", mask_sha256="nope"),)) + with pytest.raises(SegmentationError, match="no mask_sha256"): + batch(images=(SegmentedImage("a/b.tif", "skipped", mask_sha256=MASK),)) + + +def test_mask_sha256_is_the_hash_of_the_files_bytes(tmp_path): + path = tmp_path / "mask.tif" + path.write_bytes(b"some mask bytes") + assert mask_sha256(path) == hashlib.sha256(b"some mask bytes").hexdigest() + + +def test_the_same_batch_id_in_a_file_twice_is_refused(tmp_path): + path = write_record(tmp_path, "Cells", batch()) + data = json.loads(path.read_text(encoding="utf-8")) + data["batches"].append(data["batches"][0]) + path.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(SegmentationError, match="batch ID twice"): + read_record(tmp_path, "Cells") + + +def test_an_unknown_record_version_is_refused(tmp_path): + path = write_record(tmp_path, "Cells", batch()) + for version in (2, 0, "1", True, None): + data = json.loads(path.read_text(encoding="utf-8")) + data["record_version"] = version + path.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(SegmentationError, match="version"): + read_record(tmp_path, "Cells") + with pytest.raises(SegmentationError, match="version"): + write_record(tmp_path, "Cells", second()) # an unreadable record is never replaced + + +def test_a_record_that_is_not_valid_is_refused(tmp_path): + path = write_record(tmp_path, "Cells", batch()) + good = json.loads(path.read_text(encoding="utf-8")) + edits = { + "device": lambda d: d["batches"][0].update(device="gpu"), + "unknown key": lambda d: d.update(extra=1), + "missing key": lambda d: d["batches"][0].pop("tool"), + "model hash": lambda d: d["batches"][0]["model"].update(sha256="xyz"), + "no channel": lambda d: d["batches"][0].update(channel_ids=[]), + "status": lambda d: d["batches"][0]["images"][0].update(status="done"), + "other type": lambda d: d.update(mask_type="Nuclei"), + "missing value type": lambda d: d.update(mask_type="NA"), + } + for _name, edit in edits.items(): + data = json.loads(json.dumps(good)) + edit(data) + path.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(SegmentationError): + read_record(tmp_path, "Cells") + path.write_text("not json", encoding="utf-8") + with pytest.raises(SegmentationError, match="cannot be read"): + read_record(tmp_path, "Cells") + with pytest.raises(SegmentationError, match="no segmentation record"): + read_record(tmp_path, "Nuclei") + + +def test_a_batch_cannot_be_built_without_what_it_needs(): + with pytest.raises(SegmentationError, match="failed without a message"): + batch(images=(SegmentedImage("a.tif", "failed"),)) + with pytest.raises(SegmentationError, match="device"): + batch(device="") + with pytest.raises(SegmentationError, match="SHA-256"): + batch(model_sha256="") + with pytest.raises(SegmentationError, match="plain JSON"): + batch(parameters={"diameter": float("nan")}) + with pytest.raises(SegmentationError, match="twice"): + batch(channel_ids=("DNA", "DNA")) + with pytest.raises(SegmentationError, match="batch_id"): + batch(batch_id=" ") + + +@pytest.mark.parametrize( + "name", + [ + "NA", + "na", + "nan", + "None", + "null", + "n/a", + "", + "", + " Cells", + "Cells ", + "Café", + "a/b", + "..", + ".", + "a\\b", + ], +) +def test_a_mask_type_preprocessing_would_refuse_is_refused_before_anything_is_written( + tmp_path, name +): + with pytest.raises(SegmentationError): + write_record(tmp_path, name, batch()) + with pytest.raises(SegmentationError): + read_record(tmp_path, name) + with pytest.raises(SegmentationError): + SegmentationRecord(name) + assert list(tmp_path.iterdir()) == [] + + +def test_a_decomposed_name_is_refused_but_its_composed_form_is_not(tmp_path): + with pytest.raises(SegmentationError, match="NFC"): + write_record(tmp_path, "Café", batch()) + write_record(tmp_path, "Caf\u00e9", batch()) + assert read_record(tmp_path, "Caf\u00e9").mask_type == "Caf\u00e9" + + +def test_write_record_refuses_a_record_of_another_type_on_disk(tmp_path): + path = write_record(tmp_path, "Cells", batch()) + other = tmp_path / "Nuclei" + other.mkdir() + (other / RECORD_FILENAME).write_bytes(path.read_bytes()) # a Cells record in Nuclei/ + with pytest.raises(SegmentationError, match="is of mask type 'Cells', not 'Nuclei'"): + write_record(tmp_path, "Nuclei", second()) From 7e944a5c9a8dcc55b55d6e7f7dceece79ed5e085 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:01:31 +0000 Subject: [PATCH 04/11] Segmentation hand-off: publish masks with an exclusive create, no hard links needed Without overwrite the target name is claimed with O_CREAT|O_EXCL and the finished file is moved over our own empty placeholder, so two writers never replace each other's mask on any file system (a Google Drive mount has no hard links). A failed move removes the placeholder only while it is still empty. Contract 15.5 now matches the code (it still described a hard-link fallback). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- AGENTS.md | 2 +- CHANGELOG.md | 4 +- docs/contract.md | 6 +- .../segmentation_handoff.py | 33 +++++--- tests/test_segmentation_handoff.py | 79 +++++++++++++++---- 5 files changed, 89 insertions(+), 35 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0804b470..996c8f9e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -249,7 +249,7 @@ src/morphobricks_preprocessing/ segmentation_handoff.py images_to_segment (the run's own mask pairing), segmentation_input and resolve_segmentation/SegmentationPlan (channels by canonical ID through resolve_request), mask_path and write_mask (a checked, compressed int32 YX TIFF, - atomic, never over an existing mask unless asked) for a segmentation + atomic, claimed exclusively, never over an existing mask unless asked) for a segmentation notebook; numpy and tifffile only (contract §15.5); segmentation_record.py SegmentationRecord/SegmentationBatch and the append-only history file //segmentation_record.json (mask type checked like a discovered one) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0df106df..672e66a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,8 +28,8 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. append-only `segmentation_record.json` per mask type (a batch per run of the tool, each written mask with its SHA-256, so a second model never erases the first's provenance); a mask type is checked like any discovered one (`NA`, whitespace, NFC); duplicate and ambiguous masks - and a type spelled two ways are refused before writing; a file system without hard links is - refused, never silently replaced. The masks step skips that file silently instead of + and a type spelled two ways are refused before writing; a mask is claimed with an exclusive create and + then moved into place, so it is never silently replaced and needs no hard links (Google Drive). The masks step skips that file silently instead of warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. Contract §15.5. - **Tag this repeat folder (all conditions)** on *Tag channels* (owner request of 20 November diff --git a/docs/contract.md b/docs/contract.md index eb98c609..2d8e3548 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1294,7 +1294,7 @@ needs from this brick. They make no decision for the tool and guess nothing. | `images_to_segment(inputs, mask_type, masks_root)` | The run's images with no mask of that type, decided by **preprocessing's own pairing** of the masks folder (the function the run and the mask step use), so the list and the next run cannot disagree: either layout of §15, any case in folders, name and type (`cells` is `Cells`), any TIFF extension. Excluded images are not in the run, so never listed. Refuses a masks folder that breaks the folder rules (§15 Folder) or that the run itself would refuse (an ambiguous mask, a link leaving the folder), and a mask type that is not one folder name. | | `segmentation_input(inputs, channel_ids, fov, z=0, t=0)` | The channels **by canonical ID** as a `(C, Y, X)` array of the stored values, in the order of `channel_ids`. Resolved with `RunInputs.resolve_request(Request(channel_ids))` and `require()`: every refusal of the resolver passes through with its code and message (`A_SCOPE_INCOMPLETE` for a channel some images lack: choose channels every image has; `A_RGB_NOT_SUPPORTED`). Each channel is read at the C index the image stores it at (`FovSelection.index_of`), never at a position. An image with Z or T above 1 is refused: 2D only. `resolve_segmentation(inputs, channel_ids)` resolves once for the whole run and returns a `SegmentationPlan` whose `read(fov, z=0, t=0)` gives the same array; `segmentation_input` resolves on every call, so a batch uses the plan. | | `mask_path(masks_root, mask_type, fov)` | `///.tif` (the first layout of §15). | -| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. A mask that the run's pairing finds for this image and type (any case, either layout, any extension) is refused, naming it, unless `overwrite=True`; then only the file at `mask_path` is replaced, and a twin elsewhere is still refused. Without `overwrite` the file is published with a hard link, which fails if the target exists, so two writers never replace each other's mask (a file system without hard links falls back to the check made before writing). The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | +| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. A mask that the run's pairing finds for this image and type (any case, either layout, any extension) is refused, naming it, unless `overwrite=True`; then only the file at `mask_path` is replaced, and a twin elsewhere is still refused. Without `overwrite` the name is first claimed with an exclusive create (`O_CREAT | O_EXCL`, which fails if anything is there) and the finished file is then moved over that empty placeholder, so two writers never replace each other's mask and no hard links are needed (a Google Drive mount has none); a failed move removes the placeholder (only while empty), and a process killed in between leaves an empty file that the next write refuses as an existing mask. The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | `//segmentation_record.json` (`SegmentationRecord`, `SegmentationBatch`, `write_record`, `read_record`, `mask_sha256`, `record_version` 1) is provenance only and an @@ -1319,8 +1319,8 @@ warns `mask_without_image`), and nothing reads it to decide anything. The helper refuses what the run would refuse, before writing: an ambiguous mask or a link leaving the folder, a mask type spelled in two ways (`mask_names_differ_in_case`) and an image -with two masks of the type (`duplicate_mask`). A file system without hard links (for example a -Google Drive mount) is refused for `overwrite=False` with a message, never silently replaced. +with two masks of the type (`duplicate_mask`). A mask is never silently replaced: without `overwrite` the name is claimed exclusively, so +it works on a file system without hard links (a Google Drive mount) too. ## 16. Shared rules for other bricks (MorphoBricks D86) diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index 06e82331..bc84807e 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -269,29 +269,36 @@ def write_mask( def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: """Move the finished ``temporary`` file to ``target``; never over a file unless asked. - Without ``overwrite`` the file is hard-linked (which fails if ``target`` exists, in one - step), so two writers cannot replace each other's mask between a check and the move. A - file system without hard links (some network mounts, such as a Google Drive mount) is - refused: there is no way to publish without the risk of replacing, and a silent - replacement is never made. + Without ``overwrite`` the name is first **claimed** with an exclusive create + (``O_CREAT | O_EXCL``, one step that fails if anything is there, a link included), then + the finished file is moved over our own empty placeholder. Two writers cannot both claim + the name, so neither replaces the other's mask, and this needs no hard links (a Google + Drive mount has none). A reader never sees half a mask: the real file arrives in one + move. For that instant the name holds an empty file; if the move fails the placeholder is + removed again (only while it is still empty, so another writer's file is never touched). + A process killed between the claim and the move leaves the empty file, which the next + write refuses as an existing mask: delete it, then write again. """ if overwrite: os.replace(temporary, target) return try: - os.link(temporary, target) + claimed = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o666) except FileExistsError: raise SegmentationError( f"{what} appeared at {target} while it was being written; nothing was replaced. " "Use overwrite=True to replace it." ) from None - except OSError as exc: - raise SegmentationError( - f"{what} was not written: this file system cannot publish a file without the risk " - f"of replacing another ({exc}). Write the masks to a folder on a local disk and " - "copy them, or use overwrite=True if replacing is what you want." - ) from None - temporary.unlink() + try: + os.close(claimed) + os.replace(temporary, target) + except BaseException: + try: + if target.stat().st_size == 0: # still our placeholder, not another writer's mask + target.unlink() + except OSError: + pass + raise def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> list[MaskFile]: diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index fd5654b9..069f6323 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -396,37 +396,84 @@ def test_a_masks_folder_the_run_would_refuse_is_refused(run, tmp_path): # Publishing never replaces a mask another writer made in between ---------------------------- -def test_a_mask_that_appears_before_publishing_is_never_replaced(run, monkeypatch): +def test_a_mask_that_appears_before_claiming_is_never_replaced(run, monkeypatch): fov = run.inputs.fovs()[0] target = mask_path(run.masks, "Cells", fov) - real = os.link + real = os.open - def racing(source, destination, **kwargs): - destination = os.fspath(destination) - with open(destination, "wb") as other: # the other writer's mask, made after our check - other.write(b"other writer") - return real(source, destination, **kwargs) + def racing(path, flags, *args, **kwargs): + if os.fspath(path) == os.fspath(target): + with open(target, "wb") as other: # the other writer's mask, made after our check + other.write(b"other writer") + return real(path, flags, *args, **kwargs) - monkeypatch.setattr(os, "link", racing) + monkeypatch.setattr(os, "open", racing) with pytest.raises(SegmentationError, match="appeared"): write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) assert target.read_bytes() == b"other writer" assert sorted(os.listdir(target.parent)) == [target.name] # our temporary file is gone -def test_without_hard_links_the_mask_is_refused_and_nothing_is_written(run, monkeypatch): +def test_two_writers_one_claims_the_name_and_the_other_is_refused(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = mask_path(run.masks, "Cells", fov) + real, seen = os.replace, {} + + def second_writer_in_the_window(source, destination, **kwargs): + if os.fspath(destination) == os.fspath(target) and "size" not in seen: + seen["size"] = target.stat().st_size # the claim is an empty file, not half a mask + with pytest.raises(SegmentationError, match="already exists"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 9), run.inputs) + return real(source, destination, **kwargs) + + monkeypatch.setattr(os, "replace", second_writer_in_the_window) + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) + assert seen["size"] == 0 + assert tifffile.imread(target).max() == 4 # the first writer's mask, untouched by the second + assert os.listdir(target.parent) == [target.name] + + +def test_a_failure_after_the_claim_leaves_no_placeholder_and_no_temporary_file(run, monkeypatch): + fov = run.inputs.fovs()[0] + + def failing(source, destination, **kwargs): + raise OSError(errno.EIO, "disk error") + + monkeypatch.setattr(os, "replace", failing) + with pytest.raises(OSError, match="disk error"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert os.listdir(mask_path(run.masks, "Cells", fov).parent) == [] + monkeypatch.undo() + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) # nothing blocks it + + +def test_a_failed_move_keeps_a_file_another_writer_put_there(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = mask_path(run.masks, "Cells", fov) + + def failing(source, destination, **kwargs): + target.write_bytes(b"other writer") # replaced our placeholder with a real mask + raise OSError(errno.EIO, "disk error") + + monkeypatch.setattr(os, "replace", failing) + with pytest.raises(OSError, match="disk error"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert target.read_bytes() == b"other writer" + + +def test_without_hard_links_the_mask_is_written_and_never_replaced(run, monkeypatch): fov = run.inputs.fovs()[0] def no_links(*args, **kwargs): raise OSError(errno.EPERM, "hard links are not supported here") - monkeypatch.setattr(os, "link", no_links) - with pytest.raises(SegmentationError, match="cannot publish a file without the risk"): - write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) - folder = mask_path(run.masks, "Cells", fov).parent - assert os.listdir(folder) == [] # no mask, no temporary file - write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs, overwrite=True) - assert tifffile.imread(mask_path(run.masks, "Cells", fov)).max() == 4 # asked for it + monkeypatch.setattr(os, "link", no_links) # a Google Drive mount + target = write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) + assert tifffile.imread(target).max() == 4 + assert os.listdir(target.parent) == [target.name] + with pytest.raises(SegmentationError, match="already exists"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 5), run.inputs) + assert tifffile.imread(target).max() == 4 # The record file is skipped at the type folder's root only ------------------------------------ From ff2415006203b32c45bca27f9ff5338c5e0b4967 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:54:43 +0000 Subject: [PATCH 05/11] Segmentation hand-off tests: assert on names listed from disk, so a case-insensitive file system passes On Windows and macOS the twin spelled in another case is the mask path itself, so 'the mask path does not exist' cannot hold there. Assert instead that the only file under the masks folder is the untouched twin (stricter on every platform). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- tests/test_segmentation_handoff.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index 069f6323..bb95bd6f 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -315,6 +315,19 @@ def twin_cases(run): } +def assert_only_the_twin_is_on_disk(run, twin): + """Nothing was written beside the twin, and the twin is untouched. + + On a file system that ignores case (Windows, macOS) the twin and the mask path are one file, so + "the mask path does not exist" cannot be asserted there; the names listed from disk can. + """ + files = [path for path in run.masks.rglob("*") if path.is_file()] + assert [path.relative_to(run.masks).as_posix() for path in files] == [ + twin.relative_to(run.masks).as_posix() + ] + assert twin.read_bytes() == b"" + + @pytest.mark.parametrize("case", ["other case path", "second layout"]) def test_a_mask_the_run_would_pair_counts_as_made(run, case): fovs = run.inputs.fovs() @@ -330,7 +343,7 @@ def test_a_mask_the_run_would_pair_counts_as_made(run, case): run.masks, "Cells", first, labels_like(run, first), run.inputs, overwrite=overwrite ) assert twin.relative_to(run.masks).as_posix() in str(caught.value) - assert not mask_path(run.masks, "Cells", first).exists() + assert_only_the_twin_is_on_disk(run, twin) @pytest.mark.parametrize("spelling", ["cells", "CELLS"]) @@ -343,7 +356,7 @@ def test_a_type_spelled_in_two_ways_is_refused_as_the_run_refuses_it(run, spelli images_to_segment(run.inputs, "Cells", run.masks) with pytest.raises(SegmentationError, match="mask_names_differ_in_case"): write_mask(run.masks, "Cells", first, labels_like(run, first), run.inputs) - assert not mask_path(run.masks, "Cells", first).exists() + assert_only_the_twin_is_on_disk(run, twin) def test_two_masks_of_one_image_and_type_are_refused_before_writing(run): From de7f844f67602474c637e6c37bed20b16e563873 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 11:52:58 +0000 Subject: [PATCH 06/11] Segmentation hand-off: one set of run rules incl. OME-Zarr labels, locked record writes, unique batch IDs The pairing now also counts the label images inside OME-Zarr images and applies the run's own _name_issues and _duplicate_issues instead of a second copy of those rules, so an OME-Zarr image with a labels/ mask is not listed and write_mask refuses it. write_record holds an exclusive lock file while it rewrites the record. new_batch_id() makes a unique batch ID. The contract says the exclusive create protects writers on one computer only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 2 +- docs/contract.md | 6 +- src/morphobricks_preprocessing/__init__.py | 2 + .../segmentation_handoff.py | 80 ++++++++++--------- .../segmentation_record.py | 73 +++++++++++++++-- tests/test_segmentation_handoff.py | 30 ++++++- tests/test_segmentation_record.py | 42 ++++++++++ 7 files changed, 185 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4674b57d..bf1b17f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,7 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. type is checked like any discovered one (`NA`, whitespace, NFC); duplicate and ambiguous masks and a type spelled two ways are refused before writing; a mask is claimed with an exclusive create and then moved into place, so it is never silently replaced and needs no hard links (Google Drive). The masks step skips that file silently instead of - warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. Contract §15.5. + warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. The pairing also counts the label images inside OME-Zarr images and applies the run's own `_name_issues` and `_duplicate_issues` (no second copy of the rules), so an OME-Zarr image that has a `labels/Cells` mask is not listed and is refused by `write_mask`. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, refused at once when held) while it rewrites the record, and `new_batch_id()` makes a batch ID unique even within one second. The exclusive create and the lock protect writers on one computer only, not two Colab sessions on one Drive folder. Contract §15.5. - **Channel-identity check after the run** (contract §14.1, design `channel-identity-check-2026-11-21` in MorphoFeature's `claude/restart-doc`): from the image summaries the intensity checks already make (no pixel read), every imaging unit's channel is diff --git a/docs/contract.md b/docs/contract.md index 68c262ff..db99a868 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1312,10 +1312,10 @@ needs from this brick. They make no decision for the tool and guess nothing. | Function | Rule | |---|---| -| `images_to_segment(inputs, mask_type, masks_root)` | The run's images with no mask of that type, decided by **preprocessing's own pairing** of the masks folder (the function the run and the mask step use), so the list and the next run cannot disagree: either layout of §15, any case in folders, name and type (`cells` is `Cells`), any TIFF extension. Excluded images are not in the run, so never listed. Refuses a masks folder that breaks the folder rules (§15 Folder) or that the run itself would refuse (an ambiguous mask, a link leaving the folder), and a mask type that is not one folder name. | +| `images_to_segment(inputs, mask_type, masks_root)` | The run's images with no mask of that type, decided by **preprocessing's own pairing**: the masks folder and the label images inside OME-Zarr images (the discovery the run and the mask step use), checked by the run's own rules (`mask_names_differ_in_case`, `duplicate_mask`), so the list and the next run cannot disagree: either layout of §15, any case in folders, name and type (`cells` is `Cells`), any TIFF extension; an OME-Zarr image with a label image of the type has its mask and is not listed. Excluded images are not in the run, so never listed. Refuses a masks folder that breaks the folder rules (§15 Folder) or that the run itself would refuse (an ambiguous mask, a link leaving the folder), and a mask type that is not one folder name. | | `segmentation_input(inputs, channel_ids, fov, z=0, t=0)` | The channels **by canonical ID** as a `(C, Y, X)` array of the stored values, in the order of `channel_ids`. Resolved with `RunInputs.resolve_request(Request(channel_ids))` and `require()`: every refusal of the resolver passes through with its code and message (`A_SCOPE_INCOMPLETE` for a channel some images lack: choose channels every image has; `A_RGB_NOT_SUPPORTED`). Each channel is read at the C index the image stores it at (`FovSelection.index_of`), never at a position. An image with Z or T above 1 is refused: 2D only. `resolve_segmentation(inputs, channel_ids)` resolves once for the whole run and returns a `SegmentationPlan` whose `read(fov, z=0, t=0)` gives the same array; `segmentation_input` resolves on every call, so a batch uses the plan. | | `mask_path(masks_root, mask_type, fov)` | `///.tif` (the first layout of §15). | -| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. A mask that the run's pairing finds for this image and type (any case, either layout, any extension) is refused, naming it, unless `overwrite=True`; then only the file at `mask_path` is replaced, and a twin elsewhere is still refused. Without `overwrite` the name is first claimed with an exclusive create (`O_CREAT | O_EXCL`, which fails if anything is there) and the finished file is then moved over that empty placeholder, so two writers never replace each other's mask and no hard links are needed (a Google Drive mount has none); a failed move removes the placeholder (only while empty), and a process killed in between leaves an empty file that the next write refuses as an existing mask. The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | +| `write_mask(masks_root, mask_type, fov, labels, inputs, *, overwrite=False)` | Checks the labels first, then writes: 2D, the image's Y and X (header only), an integer or boolean type (floating point is refused even when whole), values from 0 to 2,147,483,647. Writes `int32` with zlib compression and the axes named `YX`, to a temporary file moved into place, so a reader never sees half a mask. A mask that the run's pairing finds for this image and type (any case, either layout, any extension, or a label image inside an OME-Zarr image) is refused, naming it, unless `overwrite=True`; then only the file at `mask_path` is replaced, and a twin elsewhere is still refused. Without `overwrite` the name is first claimed with an exclusive create (`O_CREAT | O_EXCL`, which fails if anything is there) and the finished file is then moved over that empty placeholder, so two writers never replace each other's mask and no hard links are needed (a Google Drive mount has none); a failed move removes the placeholder (only while empty), and a process killed in between leaves an empty file that the next write refuses as an existing mask. The masks folder may not be inside the experiment or the output folder, nor hold either (the folder rules of §15 and `masks_inside_output`). Images with Z or T above 1 are refused. | `//segmentation_record.json` (`SegmentationRecord`, `SegmentationBatch`, `write_record`, `read_record`, `mask_sha256`, `record_version` 1) is provenance only and an @@ -1326,7 +1326,7 @@ object), `channel_ids`, `device` (`cuda`, `cpu` or `mps`, always stated), `run_f `run_manifest_sha256`, and `images`: one entry per image (its path relative to the experiment, once per batch), `status` `written`, `skipped` or `failed`, a `message` (required for `failed`) and `mask_sha256`, the SHA-256 of the file written (required for `written`, null -otherwise). `write_record` adds a batch; the same `batch_id` again (a batch written as it +otherwise). `new_batch_id()` makes a batch ID that is unique (the UTC start time and 8 random hex characters, so two batches started in the same second differ); an ID chosen by the caller must be unique too, since a repeated one is refused only when the record is written, after the masks. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, beside the record, created with `O_CREAT | O_EXCL` and removed at the end) while it reads, changes and rewrites the record, and refuses at once, naming the holder, when another writer holds it (it never waits; delete the file only when no writer is running). `write_record` adds a batch; the same `batch_id` again (a batch written as it progresses) is accepted only if everything but the images is equal and no earlier entry is dropped or changed, otherwise it is refused and the file is left as it was. `SegmentationRecord.latest(image)` gives the newest written entry of an image. The record is diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index 36056c32..b7f512ad 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -255,6 +255,7 @@ SegmentationRecord, SegmentedImage, mask_sha256, + new_batch_id, read_record, write_record, ) @@ -466,6 +467,7 @@ "mask_thresholds", "named_axes", "ngff_label_names", + "new_batch_id", "open_ngff", "open_ngff_labels", "pair_counts", diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index bc84807e..bc402f84 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -35,11 +35,13 @@ from .folder_rules import masks_folder_issues from .links import relative_inside from .masks import FOLDER -from .masks.files import _folder_masks +from .masks.files import _duplicate_issues, _folder_masks, _label_masks, _name_issues from .masks.model import MaskFile +from .metadata import OME_ZARR, TiffMetadata from .run_inputs import Fov, RunInputs from .run_inputs_request import FovSelection, Request from .segmentation_record import SegmentationError, check_mask_type +from .zarr_input import is_zarr_name INT32_MAX = 2_147_483_647 """The largest label every brick accepts (contract §15, §16).""" @@ -50,11 +52,13 @@ def images_to_segment( ) -> tuple[Fov, ...]: """Return the run's images that have no mask of ``mask_type`` yet, sorted by path. - "Has a mask" is decided by preprocessing's own pairing of the masks folder - (:func:`.masks.files._folder_masks`, the one the run and the mask step use), so this list - and the next run can never disagree: either layout of contract §15, any case in the - folders, the name and the type, any TIFF extension. Excluded images are not in the run and - are never listed. + "Has a mask" is decided by preprocessing's own pairing: the masks folder + (:func:`.masks.files._folder_masks`) and the label images inside OME-Zarr images + (:func:`.masks.files._label_masks`), the sources the run and the mask step use, so this + list and the next run can never disagree: either layout of contract §15, any case in the + folders, the name and the type, any TIFF extension. An OME-Zarr image with a label image of + the type has its mask and is not listed. Excluded images are not in the run and are never + listed. Parameters ---------- @@ -302,49 +306,49 @@ def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> list[MaskFile]: - """Return the TIFF masks of ``mask_type`` that preprocessing's pairing finds. + """Return the masks of ``mask_type`` that preprocessing's pairing finds, of any source. - Uses the run's own function (:func:`.masks.files._folder_masks`) on the experiment as it - is now and the recorded images, so both layouts of contract §15 and any case in the - folders and names count, exactly as at the next run. Refused here as the run refuses them: - an ambiguous mask or a link leaving the folder (any error of the pairing), the type - spelled in two ways (``mask_names_differ_in_case``), and an image with two masks of the - type (``duplicate_mask``). + Built from the discovery the run uses: the TIFF masks of the masks folder + (:func:`.masks.files._folder_masks`) and the label images of the OME-Zarr images + (:func:`.masks.files._label_masks`), then the run's own checks on them + (:func:`.masks.files._name_issues`, :func:`.masks.files._duplicate_issues`), so the rules + are the run's and exist once. Refused here as the run refuses them: an ambiguous mask or a + link leaving the folder (any error of the pairing), a label group that cannot be read, the + type spelled in two ways (``mask_names_differ_in_case``, ``mask_type`` itself counted) and + an image with two masks of one type (``duplicate_mask``), whichever the two sources. Raises ------ SegmentationError For any of those, naming the files. """ - folder = Path(masks_root) - if not folder.is_dir(): - return [] discovery = discover_experiment(inputs.experiment_root, inputs.output_folder) - found, issues = _folder_masks( - folder.resolve(), discovery, {entry.relative_path for entry in inputs.files} - ) + paths = {entry.relative_path for entry in inputs.files} + found: list[MaskFile] = [] + issues = [] + folder = Path(masks_root) + if folder.is_dir(): + found, issues = _folder_masks(folder.resolve(), discovery, paths) + zarr_images = { + path: TiffMetadata(relative_path=path, readable=True, kind=OME_ZARR) + for path in paths + if is_zarr_name(path.rsplit("/", 1)[-1]) + } + labels, unreadable = _label_masks(discovery.root, zarr_images) + found = [*found, *labels] + if unreadable: + raise SegmentationError( + f"The label images of {', '.join(sorted(unreadable))} cannot be read; the run " + "reports them as unreadable_mask. Repair or remove them first." + ) + asked = MaskFile("", mask_type, mask_type, FOLDER) # the spelling being asked for counts too + issues = [*issues, *_name_issues([*found, asked]), *_duplicate_issues(found)] refusing = [issue for issue in issues if issue.is_error] if refusing: first = refusing[0] - raise SegmentationError(f"{first.message} {first.action} ({first.code})") - same = [ - m for m in found if m.source == FOLDER and m.mask_type.casefold() == mask_type.casefold() - ] - spellings = sorted({m.mask_type for m in same} | {mask_type}) - if len(spellings) > 1: - raise SegmentationError( - f"The mask type is spelled {' and '.join(map(repr, spellings))}: names that differ " - "only in case are refused by the run (mask_names_differ_in_case). Use one spelling " - "and rename the folders or files of the other." - ) - images = [m.image for m in same] - twice = sorted({m.path for m in same if images.count(m.image) > 1}) - if twice: - raise SegmentationError( - f"Some images already have two masks of the type {mask_type}: {', '.join(twice)}. " - "The run refuses this (duplicate_mask); keep one mask per image and type." - ) - return same + named = f" ({', '.join(first.paths)})" if first.paths else "" + raise SegmentationError(f"{first.message}{named} {first.action} ({first.code})") + return [m for m in found if m.mask_type == mask_type] def _checked_labels(labels: np.ndarray, shape: tuple[int, int], image: str) -> np.ndarray: diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py index eb7f9664..cb3ea14a 100644 --- a/src/morphobricks_preprocessing/segmentation_record.py +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -22,8 +22,14 @@ from __future__ import annotations import json +import os import re +import socket +import uuid +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import dataclass, field, replace +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -35,6 +41,8 @@ """The version of the record this module writes and reads.""" RECORD_FILENAME = "segmentation_record.json" """The record's name, directly inside the mask type's folder.""" +RECORD_LOCK_FILENAME = ".segmentation_record.lock" +"""The lock a writer holds beside the record while it reads, changes and rewrites it.""" DEVICES = ("cuda", "cpu", "mps") """The device the tool ran on, always stated (no silent fallback).""" STATUSES = ("written", "skipped", "failed") @@ -76,7 +84,9 @@ class SegmentationBatch: Attributes ---------- batch_id - The caller's identifier of the batch (for example its start time), unique in the file. + The identifier of the batch, unique in the file. Make it with :func:`new_batch_id`; an + identifier chosen by the caller (a start time to the second, say) must be unique too, + and a repeated one is refused only when the record is written, after the masks. tool, tool_version The segmentation tool and its exact version (e.g. ``cellpose``, ``4.2.1.1``). model_name @@ -391,6 +401,47 @@ def mask_sha256(path: str | Path) -> str: return file_sha256(path) +def new_batch_id() -> str: + """Return a batch ID that no other batch has: the UTC start time and a random suffix. + + Two batches started in the same second still differ (``2026-11-21T10:00:00Z-3fa9c2d1``), + so a second batch is never refused for the ID after its masks were written. + """ + stamp = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + return f"{stamp}-{uuid.uuid4().hex[:8]}" + + +@contextmanager +def _record_lock(path: Path) -> Iterator[None]: + """Hold an exclusive lock file beside the record for the block; refuse if it is held. + + The file is created with ``O_CREAT | O_EXCL`` (as the run's lock is) and removed at the + end, also on an error. It never waits: a held lock is refused at once, naming its holder. + It protects the writers of one computer; a file system shared by several computers (a + Drive folder open in two Colab sessions) does not make the exclusive create reliable. + """ + lock = path.with_name(RECORD_LOCK_FILENAME) + path.parent.mkdir(parents=True, exist_ok=True) + try: + handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + except FileExistsError: + try: + holder = lock.read_text(encoding="utf-8").strip() or "an unknown writer" + except OSError: + holder = "an unknown writer" + raise SegmentationError( + f"The record {path} is being written by {holder} ({lock.name} exists). Wait for " + "it to finish and write again; if no writer is running (it was killed), delete " + f"{lock} yourself." + ) from None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(f"process {os.getpid()} on {socket.gethostname()}\n") + yield + finally: + lock.unlink(missing_ok=True) + + def record_path(masks_root: str | Path, mask_type: str) -> Path: """Return where the record of ``mask_type`` is, ``//segmentation_record.json``.""" check_mask_type(mask_type) @@ -427,7 +478,17 @@ def write_record(masks_root: str | Path, mask_type: str, batch: SegmentationBatc one drops or changes. """ path = record_path(masks_root, mask_type) - earlier = read_record(masks_root, mask_type) if path.exists() else SegmentationRecord(mask_type) + with _record_lock(path): + earlier = ( + read_record(masks_root, mask_type) if path.exists() else SegmentationRecord(mask_type) + ) + record = _with_batch(earlier, batch) + text = json.dumps(record.to_dict(), indent=2, ensure_ascii=False, allow_nan=False) + return write_text_atomic(path, text + "\n", parents=True) + + +def _with_batch(earlier: SegmentationRecord, batch: SegmentationBatch) -> SegmentationRecord: + """Return ``earlier`` with ``batch`` added or, for its own ID again, extended (or refuse).""" batches = list(earlier.batches) for index, old in enumerate(batches): if old.batch_id != batch.batch_id: @@ -444,17 +505,15 @@ def write_record(masks_root: str | Path, mask_type: str, batch: SegmentationBatc problem = "" if problem: raise SegmentationError( - f"The batch {batch.batch_id!r} is already in the record of {mask_type} and " - f"{problem}. Give a new batch its own batch_id: earlier provenance is never " + f"The batch {batch.batch_id!r} is already in the record of {earlier.mask_type} " + f"and {problem}. Give a new batch its own batch_id: earlier provenance is never " "replaced." ) batches[index] = batch break else: batches.append(batch) - record = SegmentationRecord(mask_type, tuple(batches)) - text = json.dumps(record.to_dict(), indent=2, ensure_ascii=False, allow_nan=False) - return write_text_atomic(path, text + "\n", parents=True) + return SegmentationRecord(earlier.mask_type, tuple(batches)) def read_record(masks_root: str | Path, mask_type: str) -> SegmentationRecord: diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index bb95bd6f..5a7ab168 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -18,7 +18,7 @@ from described_tree import check_masks, run_described from description_tree import MAPPING -from morphobricks_preprocessing import Request +from morphobricks_preprocessing import Request, prefill_mapping from morphobricks_preprocessing.manifest import MANIFEST_FILENAME from morphobricks_preprocessing.run_inputs import RunInputs, RunInputsError from morphobricks_preprocessing.segmentation_handoff import ( @@ -35,6 +35,7 @@ ) from test_segmentation_record import batch from test_stage3_channels import LEVELS, described_run, extra_stain +from zarr_tree import write_labels, write_ngff EXTRA_FIRST = ( b'channels = ["DNA", "ACTIN", "TUB", "EXTRA"]', @@ -359,6 +360,33 @@ def test_a_type_spelled_in_two_ways_is_refused_as_the_run_refuses_it(run, spelli assert_only_the_twin_is_on_disk(run, twin) +def test_an_ome_zarr_image_with_a_label_image_of_the_type_has_its_mask(tmp_path): + pytest.importorskip("zarr") # runs with zarr 2 or 3 (OME-NGFF 0.4 labels) + image = np.zeros((6, 7), np.uint8) + labels = np.zeros((6, 7), np.uint16) + labels[1:3, 1:3] = 1 + write_labels(write_ngff(tmp_path / "exp/ctrl/a.ome.zarr", image, "yx"), {"Cells": labels}, "yx") + write_ngff(tmp_path / "exp/ctrl/b.ome.zarr", image, "yx") + result = run_described(tmp_path / "exp", prefill_mapping("YX")) + assert result.written, result.issues + inputs = RunInputs.open(check_masks(result.output_folder)) + masks = tmp_path / "masks" + by_path = {f.relative_path: f for f in inputs.fovs()} + assert set(by_path) == {"ctrl/a.ome.zarr", "ctrl/b.ome.zarr"} + # The run counts the label image as a's mask: a is not to be segmented again. + assert images_to_segment(inputs, "Cells", masks) == (by_path["ctrl/b.ome.zarr"],) + a = by_path["ctrl/a.ome.zarr"] + for overwrite in (False, True): + with pytest.raises(SegmentationError, match="already exists") as caught: + write_mask(masks, "Cells", a, labels, inputs, overwrite=overwrite) + assert "ctrl/a.ome.zarr/labels/Cells" in str(caught.value) + assert not masks.exists() + # b has none: its folder mask is written, and the next listing is then empty, no duplicate. + b = by_path["ctrl/b.ome.zarr"] + write_mask(masks, "Cells", b, labels, inputs) + assert images_to_segment(inputs, "Cells", masks) == () + + def test_two_masks_of_one_image_and_type_are_refused_before_writing(run): fovs = run.inputs.fovs() write_mask(run.masks, "Cells", fovs[0], labels_like(run, fovs[0]), run.inputs) diff --git a/tests/test_segmentation_record.py b/tests/test_segmentation_record.py index e0d30ac1..8b6e6ec9 100644 --- a/tests/test_segmentation_record.py +++ b/tests/test_segmentation_record.py @@ -12,11 +12,13 @@ from morphobricks_preprocessing.segmentation_record import ( RECORD_FILENAME, + RECORD_LOCK_FILENAME, SegmentationBatch, SegmentationError, SegmentationRecord, SegmentedImage, mask_sha256, + new_batch_id, read_record, write_record, ) @@ -255,3 +257,43 @@ def test_write_record_refuses_a_record_of_another_type_on_disk(tmp_path): (other / RECORD_FILENAME).write_bytes(path.read_bytes()) # a Cells record in Nuclei/ with pytest.raises(SegmentationError, match="is of mask type 'Cells', not 'Nuclei'"): write_record(tmp_path, "Nuclei", second()) + + +def test_a_held_lock_refuses_the_write_and_leaves_the_record_unchanged(tmp_path): + path = write_record(tmp_path, "Cells", batch()) + before = path.read_bytes() + lock = path.with_name(RECORD_LOCK_FILENAME) + lock.write_text("process 7 on another-pc\n", encoding="utf-8") + with pytest.raises(SegmentationError, match="process 7 on another-pc"): + write_record(tmp_path, "Cells", second()) + assert path.read_bytes() == before + assert lock.exists() # the other writer's lock is never removed by a refused writer + lock.unlink() + write_record(tmp_path, "Cells", second()) + assert len(read_record(tmp_path, "Cells").batches) == 2 + assert not lock.exists() # released after a successful write + + +def test_the_lock_is_released_when_the_write_is_refused(tmp_path): + write_record(tmp_path, "Cells", batch()) + with pytest.raises(SegmentationError, match="another way"): + write_record(tmp_path, "Cells", batch(tool="other")) + assert not (tmp_path / "Cells" / RECORD_LOCK_FILENAME).exists() + + +def test_two_batches_made_in_the_same_second_get_different_ids(tmp_path, monkeypatch): + class Frozen: + @staticmethod + def now(tz=None): + return real.now(tz).replace(microsecond=0, second=0) + + from morphobricks_preprocessing import segmentation_record as module + + real = module.datetime + monkeypatch.setattr(module, "datetime", Frozen) + first, again = new_batch_id(), new_batch_id() + assert first != again + assert first.rsplit("-", 1)[0] == again.rsplit("-", 1)[0] # the same stamp, another suffix + write_record(tmp_path, "Cells", batch(batch_id=first)) + write_record(tmp_path, "Cells", batch(batch_id=again, tool_version="9")) # no ID clash + assert [b.batch_id for b in read_record(tmp_path, "Cells").batches] == [first, again] From dd030024885b0f19a652a72c43c18bacab491730 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:15:03 +0000 Subject: [PATCH 07/11] Segmentation record: share the run's lock (lock_file.exclusive_lock); never remove a lock another writer holds Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 2 +- pyproject.toml | 1 + src/morphobricks_preprocessing/lock_file.py | 109 ++++++++++++++++++ src/morphobricks_preprocessing/run/lock.py | 70 ++--------- .../segmentation_record.py | 31 ++--- tests/test_modes_lock_report.py | 2 +- tests/test_segmentation_record.py | 11 +- 7 files changed, 142 insertions(+), 84 deletions(-) create mode 100644 src/morphobricks_preprocessing/lock_file.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cd98404..b150565b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. type is checked like any discovered one (`NA`, whitespace, NFC); duplicate and ambiguous masks and a type spelled two ways are refused before writing; a mask is claimed with an exclusive create and then moved into place, so it is never silently replaced and needs no hard links (Google Drive). The masks step skips that file silently instead of - warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. The pairing also counts the label images inside OME-Zarr images and applies the run's own `_name_issues` and `_duplicate_issues` (no second copy of the rules), so an OME-Zarr image that has a `labels/Cells` mask is not listed and is refused by `write_mask`. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, refused at once when held) while it rewrites the record, and `new_batch_id()` makes a batch ID unique even within one second. The exclusive create and the lock protect writers on one computer only, not two Colab sessions on one Drive folder. Contract §15.5. + warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. The pairing also counts the label images inside OME-Zarr images and applies the run's own `_name_issues` and `_duplicate_issues` (no second copy of the rules), so an OME-Zarr image that has a `labels/Cells` mask is not listed and is refused by `write_mask`. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, refused at once when held, removed only while it still names this writer) while it rewrites the record; it is the run's own lock, now in `lock_file.py` (`exclusive_lock`, `LockHolder`, `read_holder`) and shared with `run/lock.py`, and `new_batch_id()` makes a batch ID unique even within one second. The exclusive create and the lock protect writers on one computer only, not two Colab sessions on one Drive folder. Contract §15.5. - **Channel-identity check after the run** (contract §14.1, design `channel-identity-check-2026-11-21` in MorphoFeature's `claude/restart-doc`): from the image summaries the intensity checks already make (no pixel read), every imaging unit's channel is diff --git a/pyproject.toml b/pyproject.toml index 6b0c713f..653250cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -351,6 +351,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.mask_lineage" = "io" "morphobricks_preprocessing.segmentation_handoff" = "io" "morphobricks_preprocessing.segmentation_record" = "io" +"morphobricks_preprocessing.lock_file" = "io" "morphobricks_preprocessing.mask_conversion" = "orchestration" "morphobricks_preprocessing.lineage_schema" = "pure" "morphobricks_preprocessing.code_identity" = "io" diff --git a/src/morphobricks_preprocessing/lock_file.py b/src/morphobricks_preprocessing/lock_file.py new file mode 100644 index 00000000..1564838b --- /dev/null +++ b/src/morphobricks_preprocessing/lock_file.py @@ -0,0 +1,109 @@ +"""An exclusive lock file: created with ``O_EXCL``, naming its holder, removed only by it. + +The run's lock on its output folder (:mod:`.run.lock`) and the segmentation record's lock +(:mod:`.segmentation_record`) are both this lock. A held lock is refused at once and names +its holder; it never waits. It protects the writers of one computer: a file system shared by +several computers (a Drive folder open in two Colab sessions) does not make the exclusive +create reliable. +""" + +from __future__ import annotations + +import json +import os +import socket +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path + + +@dataclass(frozen=True) +class LockHolder: + """The run holding an output folder's lock. + + Attributes + ---------- + host + The computer it runs on. + pid + Its process ID on that computer (0 when the lock file cannot be read). + started_at + When it took the lock (UTC, ISO 8601), or empty when unknown. + """ + + host: str + pid: int + started_at: str = "" + + def describe(self) -> str: + """Name the holder in words, e.g. ``"process 412 on lab-pc, since 2026-11-02T10:00"``.""" + if not self.pid: + return "a run whose lock file cannot be read" + since = f", since {self.started_at}" if self.started_at else "" + return f"process {self.pid} on {self.host}{since}" + + +class LockHeldError(RuntimeError): + """Raised when another writer holds a lock file. + + Attributes + ---------- + path + The lock file. + holder + The writer holding it. + """ + + def __init__(self, path: Path, holder: LockHolder) -> None: + self.path = path + self.holder = holder + super().__init__(f"{path} is locked by {holder.describe()}") + + +def read_holder(path: Path) -> LockHolder | None: + """Return the holder recorded in the lock file ``path``, or None when it does not exist. + + A lock file that cannot be read gives a holder with ``pid`` 0. + """ + try: + data = json.loads(path.read_text(encoding="utf-8")) + return LockHolder(str(data["host"]), int(data["pid"]), str(data.get("started_at", ""))) + except FileNotFoundError: + return None + except (OSError, ValueError, KeyError, TypeError): + return LockHolder("", 0) + + +@contextmanager +def exclusive_lock(path: Path) -> Iterator[LockHolder]: + """Hold the lock file ``path`` for the block: created with ``O_CREAT | O_EXCL``. + + It records this process as its holder and is removed when the block ends, also on an + error, but only while it still names this process (a lock another writer took after a + user deleted this one is never removed). It never waits. + + Raises + ------ + LockHeldError + When the file exists: another writer holds it (named by its holder). + """ + holder = LockHolder( + socket.gethostname(), os.getpid(), datetime.now(UTC).isoformat(timespec="seconds") + ) + try: + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + except FileExistsError: + raise LockHeldError(path, read_holder(path) or LockHolder("", 0)) from None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(json.dumps(asdict(holder)) + "\n") + except BaseException: + path.unlink(missing_ok=True) # just created by this process: a lock it could not write + raise + try: + yield holder + finally: + if read_holder(path) == holder: + path.unlink(missing_ok=True) diff --git a/src/morphobricks_preprocessing/run/lock.py b/src/morphobricks_preprocessing/run/lock.py index 596cd3ba..1169f0f7 100644 --- a/src/morphobricks_preprocessing/run/lock.py +++ b/src/morphobricks_preprocessing/run/lock.py @@ -9,48 +9,20 @@ from __future__ import annotations -import json import os import socket from collections.abc import Iterator -from contextlib import contextmanager -from dataclasses import asdict, dataclass -from datetime import UTC, datetime +from contextlib import ExitStack, contextmanager from pathlib import Path +from ..lock_file import LockHeldError, LockHolder, exclusive_lock, read_holder from ..validation import ValidationIssue, error from .generation import finish_publication LOCK_FILENAME = ".morphobricks-preprocessing.lock" -@dataclass(frozen=True) -class LockHolder: - """The run holding an output folder's lock. - - Attributes - ---------- - host - The computer it runs on. - pid - Its process ID on that computer (0 when the lock file cannot be read). - started_at - When it took the lock (UTC, ISO 8601), or empty when unknown. - """ - - host: str - pid: int - started_at: str = "" - - def describe(self) -> str: - """Name the holder in words, e.g. ``"process 412 on lab-pc, since 2026-11-02T10:00"``.""" - if not self.pid: - return "a run whose lock file cannot be read" - since = f", since {self.started_at}" if self.started_at else "" - return f"process {self.pid} on {self.host}{since}" - - -class OutputLockedError(RuntimeError): +class OutputLockedError(LockHeldError): """Raised when another run holds the output folder's lock. Attributes @@ -59,11 +31,6 @@ class OutputLockedError(RuntimeError): The run holding it. """ - def __init__(self, path: Path, holder: LockHolder) -> None: - self.path = path - self.holder = holder - super().__init__(f"{path} is locked by {holder.describe()}") - def read_lock(output_folder: str | os.PathLike) -> LockHolder | None: """Return the holder of an output folder's lock, or None when it is not locked. @@ -78,14 +45,7 @@ def read_lock(output_folder: str | os.PathLike) -> LockHolder | None: LockHolder or None The holder; a lock file that cannot be read gives a holder with ``pid`` 0. """ - path = Path(output_folder) / LOCK_FILENAME - try: - data = json.loads(path.read_text(encoding="utf-8")) - return LockHolder(str(data["host"]), int(data["pid"]), str(data.get("started_at", ""))) - except FileNotFoundError: - return None - except (OSError, ValueError, KeyError, TypeError): - return LockHolder("", 0) + return read_holder(Path(output_folder) / LOCK_FILENAME) @contextmanager @@ -115,26 +75,14 @@ def output_lock(output_folder: str | os.PathLike) -> Iterator[LockHolder]: PublicationIncompleteError When an unfinished publication's files cannot be moved into place. """ - path = Path(output_folder) / LOCK_FILENAME - holder = LockHolder( - socket.gethostname(), os.getpid(), datetime.now(UTC).isoformat(timespec="seconds") - ) - try: - handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) - except FileExistsError: - raise OutputLockedError(path, read_lock(output_folder) or LockHolder("", 0)) from None - try: - with os.fdopen(handle, "w", encoding="utf-8") as stream: - stream.write(json.dumps(asdict(holder)) + "\n") - except BaseException: - path.unlink(missing_ok=True) # just created by this run: a lock it could not write - raise + stack = ExitStack() try: + holder = stack.enter_context(exclusive_lock(Path(output_folder) / LOCK_FILENAME)) + except LockHeldError as held: + raise OutputLockedError(held.path, held.holder) from None + with stack: finish_publication(Path(output_folder)) yield holder - finally: - if read_lock(output_folder) == holder: - path.unlink(missing_ok=True) def remove_stale_lock(output_folder: str | os.PathLike) -> LockHolder | None: diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py index cb3ea14a..88407f42 100644 --- a/src/morphobricks_preprocessing/segmentation_record.py +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -22,12 +22,10 @@ from __future__ import annotations import json -import os import re -import socket import uuid from collections.abc import Iterator -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager from dataclasses import dataclass, field, replace from datetime import UTC, datetime from pathlib import Path @@ -35,6 +33,7 @@ from ._io import file_sha256, write_text_atomic from .discovery import IdentityError, check_identity_text +from .lock_file import LockHeldError, exclusive_lock from .name_issues import is_nfc RECORD_VERSION = 1 @@ -415,31 +414,23 @@ def new_batch_id() -> str: def _record_lock(path: Path) -> Iterator[None]: """Hold an exclusive lock file beside the record for the block; refuse if it is held. - The file is created with ``O_CREAT | O_EXCL`` (as the run's lock is) and removed at the - end, also on an error. It never waits: a held lock is refused at once, naming its holder. + The run's own lock (:func:`.lock_file.exclusive_lock`): created with ``O_CREAT | O_EXCL``, + removed at the end (also on an error) while it still names this writer, never waited on. It protects the writers of one computer; a file system shared by several computers (a Drive folder open in two Colab sessions) does not make the exclusive create reliable. """ - lock = path.with_name(RECORD_LOCK_FILENAME) path.parent.mkdir(parents=True, exist_ok=True) + stack = ExitStack() try: - handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) - except FileExistsError: - try: - holder = lock.read_text(encoding="utf-8").strip() or "an unknown writer" - except OSError: - holder = "an unknown writer" + stack.enter_context(exclusive_lock(path.with_name(RECORD_LOCK_FILENAME))) + except LockHeldError as held: raise SegmentationError( - f"The record {path} is being written by {holder} ({lock.name} exists). Wait for " - "it to finish and write again; if no writer is running (it was killed), delete " - f"{lock} yourself." + f"The record {path} is being written by {held.holder.describe()} " + f"({held.path.name} exists). Wait for it to finish and write again; if no writer " + f"is running (it was killed), delete {held.path} yourself." ) from None - try: - with os.fdopen(handle, "w", encoding="utf-8") as stream: - stream.write(f"process {os.getpid()} on {socket.gethostname()}\n") + with stack: yield - finally: - lock.unlink(missing_ok=True) def record_path(masks_root: str | Path, mask_type: str) -> Path: diff --git a/tests/test_modes_lock_report.py b/tests/test_modes_lock_report.py index 9dea5fa8..a1b440c1 100644 --- a/tests/test_modes_lock_report.py +++ b/tests/test_modes_lock_report.py @@ -263,7 +263,7 @@ def broken(*args, **kwargs): def test_a_lock_that_cannot_be_written_is_not_left_behind(experiment, monkeypatch): - from morphobricks_preprocessing.run import lock as lock_module + from morphobricks_preprocessing import lock_file as lock_module def broken(*args, **kwargs): raise OSError("simulated: disk full") diff --git a/tests/test_segmentation_record.py b/tests/test_segmentation_record.py index 8b6e6ec9..ef681106 100644 --- a/tests/test_segmentation_record.py +++ b/tests/test_segmentation_record.py @@ -10,6 +10,7 @@ import pytest +from morphobricks_preprocessing.lock_file import LockHolder, exclusive_lock, read_holder from morphobricks_preprocessing.segmentation_record import ( RECORD_FILENAME, RECORD_LOCK_FILENAME, @@ -263,7 +264,7 @@ def test_a_held_lock_refuses_the_write_and_leaves_the_record_unchanged(tmp_path) path = write_record(tmp_path, "Cells", batch()) before = path.read_bytes() lock = path.with_name(RECORD_LOCK_FILENAME) - lock.write_text("process 7 on another-pc\n", encoding="utf-8") + lock.write_text('{"host": "another-pc", "pid": 7, "started_at": ""}\n', encoding="utf-8") with pytest.raises(SegmentationError, match="process 7 on another-pc"): write_record(tmp_path, "Cells", second()) assert path.read_bytes() == before @@ -281,6 +282,14 @@ def test_the_lock_is_released_when_the_write_is_refused(tmp_path): assert not (tmp_path / "Cells" / RECORD_LOCK_FILENAME).exists() +def test_a_lock_another_writer_took_meanwhile_is_never_removed(tmp_path): + lock = tmp_path / RECORD_LOCK_FILENAME + with exclusive_lock(lock): + lock.unlink() # the user deleted this writer's lock, and another writer took it + lock.write_text('{"host": "another-pc", "pid": 7, "started_at": ""}\n', encoding="utf-8") + assert read_holder(lock) == LockHolder("another-pc", 7) # still the other writer's + + def test_two_batches_made_in_the_same_second_get_different_ids(tmp_path, monkeypatch): class Frozen: @staticmethod From 30206eda073f7e98173356a97270a8b2d046835d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:18:03 +0000 Subject: [PATCH 08/11] Lock wording: the holder is any writer; the contract says the record lock is removed only by its writer Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- docs/contract.md | 2 +- src/morphobricks_preprocessing/lock_file.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/contract.md b/docs/contract.md index db99a868..7841d65a 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1326,7 +1326,7 @@ object), `channel_ids`, `device` (`cuda`, `cpu` or `mps`, always stated), `run_f `run_manifest_sha256`, and `images`: one entry per image (its path relative to the experiment, once per batch), `status` `written`, `skipped` or `failed`, a `message` (required for `failed`) and `mask_sha256`, the SHA-256 of the file written (required for `written`, null -otherwise). `new_batch_id()` makes a batch ID that is unique (the UTC start time and 8 random hex characters, so two batches started in the same second differ); an ID chosen by the caller must be unique too, since a repeated one is refused only when the record is written, after the masks. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, beside the record, created with `O_CREAT | O_EXCL` and removed at the end) while it reads, changes and rewrites the record, and refuses at once, naming the holder, when another writer holds it (it never waits; delete the file only when no writer is running). `write_record` adds a batch; the same `batch_id` again (a batch written as it +otherwise). `new_batch_id()` makes a batch ID that is unique (the UTC start time and 8 random hex characters, so two batches started in the same second differ); an ID chosen by the caller must be unique too, since a repeated one is refused only when the record is written, after the masks. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, beside the record, created with `O_CREAT | O_EXCL` and removed at the end only while it still names this writer; the run's own lock, `lock_file.exclusive_lock`) while it reads, changes and rewrites the record, and refuses at once, naming the holder, when another writer holds it (it never waits; delete the file only when no writer is running). `write_record` adds a batch; the same `batch_id` again (a batch written as it progresses) is accepted only if everything but the images is equal and no earlier entry is dropped or changed, otherwise it is refused and the file is left as it was. `SegmentationRecord.latest(image)` gives the newest written entry of an image. The record is diff --git a/src/morphobricks_preprocessing/lock_file.py b/src/morphobricks_preprocessing/lock_file.py index 1564838b..603044fe 100644 --- a/src/morphobricks_preprocessing/lock_file.py +++ b/src/morphobricks_preprocessing/lock_file.py @@ -21,7 +21,7 @@ @dataclass(frozen=True) class LockHolder: - """The run holding an output folder's lock. + """The process holding a lock file (a run's output folder lock or a record lock). Attributes ---------- @@ -40,7 +40,7 @@ class LockHolder: def describe(self) -> str: """Name the holder in words, e.g. ``"process 412 on lab-pc, since 2026-11-02T10:00"``.""" if not self.pid: - return "a run whose lock file cannot be read" + return "a writer whose lock file cannot be read" since = f", since {self.started_at}" if self.started_at else "" return f"process {self.pid} on {self.host}{since}" From 3fc6497ff45dae7914d64797282033f078ca3af9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:00:59 +0000 Subject: [PATCH 09/11] Segmentation hand-off: the run's name check for every discovered type, one write lock per type in both modes, a random token in lock holders Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 10 ++ docs/contract.md | 22 ++- src/morphobricks_preprocessing/lock_file.py | 23 +++- .../segmentation_handoff.py | 127 +++++++++++++----- .../segmentation_record.py | 18 ++- tests/test_segmentation_handoff.py | 2 +- tests/test_segmentation_record.py | 20 +++ tests/test_segmentation_write_lock.py | 90 +++++++++++++ 8 files changed, 264 insertions(+), 48 deletions(-) create mode 100644 tests/test_segmentation_write_lock.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 524df17a..db82fec9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,16 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. and a type spelled two ways are refused before writing; a mask is claimed with an exclusive create and then moved into place, so it is never silently replaced and needs no hard links (Google Drive). The masks step skips that file silently instead of warning `mask_without_image` (only directly in a type folder). "Has a mask" is decided by the run's own pairing (either layout, any case), `write_mask` refuses a twin elsewhere and never replaces a mask another writer made in between, and `resolve_segmentation` / `SegmentationPlan` resolve the channels once for a batch. The pairing also counts the label images inside OME-Zarr images and applies the run's own `_name_issues` and `_duplicate_issues` (no second copy of the rules), so an OME-Zarr image that has a `labels/Cells` mask is not listed and is refused by `write_mask`. `write_record` holds an exclusive lock file (`.segmentation_record.lock`, refused at once when held, removed only while it still names this writer) while it rewrites the record; it is the run's own lock, now in `lock_file.py` (`exclusive_lock`, `LockHolder`, `read_holder`) and shared with `run/lock.py`, and `new_batch_id()` makes a batch ID unique even within one second. The exclusive create and the lock protect writers on one computer only, not two Colab sessions on one Drive folder. Contract §15.5. +- **Segmentation hand-off, audit fixes (PR #367)**: the helper now applies the run's own + `_description_name_issues` to every discovered mask type (an unrelated type `NA` or a decomposed + name is refused by `images_to_segment` and `write_mask` as the next described run refuses it, + `R_MASK_TYPE_NAME_INVALID`); `write_mask` holds one exclusive per-type write lock + (`//.segmentation_write.lock`, refused at once, never waited on) from the twin check + to the published mask in both modes, so a default writer can no longer replace the finished mask + of a concurrent `overwrite=True` writer (contract §15.5 also documents the transient zero-byte + placeholder and that preprocessing must not run on the masks folder during a batch). `LockHolder` + gains a random `token`, written in the lock file and compared on removal (a lock without one, + from an older run, still reads, token `""`). - **Channel-identity check after the run** (contract §14.1, design `channel-identity-check-2026-11-21` in MorphoFeature's `claude/restart-doc`): from the image summaries the intensity checks already make (no pixel read), every imaging unit's channel is diff --git a/docs/contract.md b/docs/contract.md index 3997cd57..676f7e23 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1340,9 +1340,25 @@ file silently when it is directly in a type folder (it is not a mask; the same n warns `mask_without_image`), and nothing reads it to decide anything. The helper refuses what the run would refuse, before writing: an ambiguous mask or a link -leaving the folder, a mask type spelled in two ways (`mask_names_differ_in_case`) and an image -with two masks of the type (`duplicate_mask`). A mask is never silently replaced: without `overwrite` the name is claimed exclusively, so -it works on a file system without hard links (a Google Drive mount) too. +leaving the folder, **any discovered mask type** that cannot be a `source_type` (the run's +`_description_name_issues`: `R_MASK_TYPE_NAME_INVALID`, a decomposed name; also for a type +other than the one asked for), a mask type spelled in two ways (`mask_names_differ_in_case`) +and an image with two masks of the type (`duplicate_mask`). A mask is never silently replaced: +without `overwrite` the name is claimed exclusively, so it works on a file system without hard +links (a Google Drive mount) too. + +`write_mask` holds one exclusive write lock per mask type, `//.segmentation_write.lock` +(the run's lock file mechanism, `lock_file.exclusive_lock`), from the check for another mask of +the image to the published file, **in both modes**: an overwriting writer and a default writer +can never replace each other's mask. A held lock is refused at once, naming its holder, and +never waited on; a killed writer leaves it, and the message says to delete it. Like the +record's lock it is a dot-file, skipped by the masks step. A lock holder carries a random +token, so a lock deleted and retaken is never removed by its earlier holder. Limits: the lock +protects the writers of one computer (not a Drive folder open in two Colab sessions); a +reader may briefly see a **zero-byte placeholder** at the mask's name while a mask is being +written (the claim before the move); and preprocessing must **not be run on the masks folder +during a batch** (a run could read that placeholder or a half-written batch). A placeholder +left by a killed writer is deleted by hand. ## 16. Shared rules for other bricks (MorphoBricks D86) diff --git a/src/morphobricks_preprocessing/lock_file.py b/src/morphobricks_preprocessing/lock_file.py index 603044fe..e058ea2b 100644 --- a/src/morphobricks_preprocessing/lock_file.py +++ b/src/morphobricks_preprocessing/lock_file.py @@ -12,6 +12,7 @@ import json import os import socket +import uuid from collections.abc import Iterator from contextlib import contextmanager from dataclasses import asdict, dataclass @@ -31,11 +32,16 @@ class LockHolder: Its process ID on that computer (0 when the lock file cannot be read). started_at When it took the lock (UTC, ISO 8601), or empty when unknown. + token + A random ID of this one holding (``uuid4`` hex), so two holders of the same process and + second (two threads, a lock deleted and retaken) are never taken for each other; empty + for a lock file written without one (an older run lock). """ host: str pid: int started_at: str = "" + token: str = "" def describe(self) -> str: """Name the holder in words, e.g. ``"process 412 on lab-pc, since 2026-11-02T10:00"``.""" @@ -69,7 +75,12 @@ def read_holder(path: Path) -> LockHolder | None: """ try: data = json.loads(path.read_text(encoding="utf-8")) - return LockHolder(str(data["host"]), int(data["pid"]), str(data.get("started_at", ""))) + return LockHolder( + str(data["host"]), + int(data["pid"]), + str(data.get("started_at", "")), + str(data.get("token", "")), + ) except FileNotFoundError: return None except (OSError, ValueError, KeyError, TypeError): @@ -81,8 +92,9 @@ def exclusive_lock(path: Path) -> Iterator[LockHolder]: """Hold the lock file ``path`` for the block: created with ``O_CREAT | O_EXCL``. It records this process as its holder and is removed when the block ends, also on an - error, but only while it still names this process (a lock another writer took after a - user deleted this one is never removed). It never waits. + error, but only while it still names this holder, token included (a lock another writer + took after a user deleted this one is never removed, even from the same process). It never + waits. Raises ------ @@ -90,7 +102,10 @@ def exclusive_lock(path: Path) -> Iterator[LockHolder]: When the file exists: another writer holds it (named by its holder). """ holder = LockHolder( - socket.gethostname(), os.getpid(), datetime.now(UTC).isoformat(timespec="seconds") + socket.gethostname(), + os.getpid(), + datetime.now(UTC).isoformat(timespec="seconds"), + uuid.uuid4().hex, ) try: handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index bc402f84..dee93139 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -24,6 +24,8 @@ import os import tempfile +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path @@ -35,14 +37,24 @@ from .folder_rules import masks_folder_issues from .links import relative_inside from .masks import FOLDER -from .masks.files import _duplicate_issues, _folder_masks, _label_masks, _name_issues +from .masks.files import ( + _description_name_issues, + _duplicate_issues, + _folder_masks, + _label_masks, + _name_issues, +) from .masks.model import MaskFile from .metadata import OME_ZARR, TiffMetadata from .run_inputs import Fov, RunInputs from .run_inputs_request import FovSelection, Request -from .segmentation_record import SegmentationError, check_mask_type +from .segmentation_record import SegmentationError, check_mask_type, hold_lock from .zarr_input import is_zarr_name +WRITE_LOCK_FILENAME = ".segmentation_write.lock" +"""The lock a writer holds in a type folder from the twin check to the published mask. A +dot-file, so the run's masks discovery skips it like the record's lock.""" + INT32_MAX = 2_147_483_647 """The largest label every brick accepts (contract §15, §16).""" @@ -208,7 +220,9 @@ def write_mask( integer or boolean type, with values from 0 to 2,147,483,647. They are written as a zlib-compressed ``int32`` TIFF with the axes named ``YX``, to a temporary file and then moved into place, so a reader never sees half a mask. Nothing is converted other than the - integer width and nothing is filled. + integer width and nothing is filled. One writer at a time works on a mask type: its write + lock is held from the check for another mask of the image to the published file, in both + modes, so an overwriting writer and a default one can never replace each other's mask. Parameters ---------- @@ -235,41 +249,79 @@ def write_mask( SegmentationError For labels that are not 2D, not the image's size, floating point or complex, negative or too large; an image with more than one Z plane or time point; a mask that exists - without ``overwrite`` (or another TIFF of the same name); or a masks folder inside the - experiment or the output folder. + without ``overwrite`` (or another TIFF of the same name); a masks folder inside the + experiment or the output folder; or another writer holding the type's write lock + (``//.segmentation_write.lock``), which is refused at once and names the + holder. """ target = mask_path(masks_root, mask_type, fov) _check_folders(inputs, masks_root) _check_2d(fov) data = _checked_labels(labels, inputs.plane_shape(fov), fov.relative_path) - wanted = target.relative_to(masks_root).as_posix() - twins = sorted( - m.path for m in _paired(inputs, masks_root, mask_type) if m.image == fov.relative_path - ) - if twins and (not overwrite or twins != [wanted]): - raise SegmentationError( - f"The {mask_type} mask of {fov.relative_path} already exists " - f"({', '.join(twins)} in {masks_root}). Use overwrite=True to replace {wanted}; " - "a mask of this image and type in another place or case, or in the other layout, " - "must be moved away first (the next run would refuse both as duplicate_mask)." + type_folder = Path(masks_root) / mask_type + with ( + _no_empty_folders_if_refused(type_folder, target.parent), + hold_lock(type_folder / WRITE_LOCK_FILENAME, f"The {mask_type} masks in {masks_root}"), + ): # one writer per type for the twin check, the claim and the publish, in both modes + wanted = target.relative_to(masks_root).as_posix() + twins = sorted( + m.path for m in _paired(inputs, masks_root, mask_type) if m.image == fov.relative_path ) - target.parent.mkdir(parents=True, exist_ok=True) - handle, temporary = tempfile.mkstemp( - prefix=f".{target.name}.", suffix=".tmp", dir=target.parent - ) - os.close(handle) - try: - tifffile.imwrite( - temporary, data, photometric="minisblack", compression="zlib", metadata={"axes": "YX"} + if twins and (not overwrite or twins != [wanted]): + raise SegmentationError( + f"The {mask_type} mask of {fov.relative_path} already exists " + f"({', '.join(twins)} in {masks_root}). Use overwrite=True to replace {wanted}; " + "a mask of this image and type in another place or case, or in the other layout, " + "must be moved away first (the next run would refuse both as duplicate_mask)." + ) + target.parent.mkdir(parents=True, exist_ok=True) + handle, temporary = tempfile.mkstemp( + prefix=f".{target.name}.", suffix=".tmp", dir=target.parent ) - give_output_mode(temporary, target) - _publish(Path(temporary), target, overwrite, f"The {mask_type} mask of {fov.relative_path}") - except BaseException: - Path(temporary).unlink(missing_ok=True) - raise + os.close(handle) + try: + tifffile.imwrite( + temporary, + data, + photometric="minisblack", + compression="zlib", + metadata={"axes": "YX"}, + ) + give_output_mode(temporary, target) + _publish( + Path(temporary), target, overwrite, f"The {mask_type} mask of {fov.relative_path}" + ) + except BaseException: + Path(temporary).unlink(missing_ok=True) + raise return target +@contextmanager +def _no_empty_folders_if_refused(type_folder: Path, leaf: Path) -> Iterator[None]: + """Remove the folders this call created (``type_folder`` down to ``leaf``) if it is refused. + + A refused write leaves nothing behind, not even the empty folders the lock needed. + """ + created = None # the topmost folder this call has to make + for folder in (type_folder, *type_folder.parents): + if folder.exists(): + break + created = folder + try: + yield + except SegmentationError: + folder = leaf + while created is not None and (folder == created or created in folder.parents): + try: + if folder.exists(): # a folder not made yet (refused before it) is skipped + folder.rmdir() + except OSError: + break # not empty: something else is in it + folder = folder.parent + raise + + def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: """Move the finished ``temporary`` file to ``target``; never over a file unless asked. @@ -311,11 +363,13 @@ def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> Built from the discovery the run uses: the TIFF masks of the masks folder (:func:`.masks.files._folder_masks`) and the label images of the OME-Zarr images (:func:`.masks.files._label_masks`), then the run's own checks on them - (:func:`.masks.files._name_issues`, :func:`.masks.files._duplicate_issues`), so the rules - are the run's and exist once. Refused here as the run refuses them: an ambiguous mask or a - link leaving the folder (any error of the pairing), a label group that cannot be read, the - type spelled in two ways (``mask_names_differ_in_case``, ``mask_type`` itself counted) and - an image with two masks of one type (``duplicate_mask``), whichever the two sources. + (:func:`.masks.files._name_issues`, :func:`.masks.files._description_name_issues`, + :func:`.masks.files._duplicate_issues`), so the rules are the run's and exist once. Refused + here as the run refuses them: an ambiguous mask or a link leaving the folder (any error of + the pairing), a label group that cannot be read, any discovered mask type that cannot be a + ``source_type`` (``R_MASK_TYPE_NAME_INVALID``, a decomposed name), the type spelled in two + ways (``mask_names_differ_in_case``, ``mask_type`` itself counted) and an image with two + masks of one type (``duplicate_mask``), whichever the two sources. Raises ------ @@ -342,7 +396,12 @@ def _paired(inputs: RunInputs, masks_root: str | os.PathLike, mask_type: str) -> "reports them as unreadable_mask. Repair or remove them first." ) asked = MaskFile("", mask_type, mask_type, FOLDER) # the spelling being asked for counts too - issues = [*issues, *_name_issues([*found, asked]), *_duplicate_issues(found)] + issues = [ + *issues, + *_name_issues([*found, asked]), + *_description_name_issues(found), + *_duplicate_issues(found), + ] refusing = [issue for issue in issues if issue.is_error] if refusing: first = refusing[0] diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py index 88407f42..ea92357e 100644 --- a/src/morphobricks_preprocessing/segmentation_record.py +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -25,7 +25,7 @@ import re import uuid from collections.abc import Iterator -from contextlib import ExitStack, contextmanager +from contextlib import AbstractContextManager, ExitStack, contextmanager from dataclasses import dataclass, field, replace from datetime import UTC, datetime from pathlib import Path @@ -411,21 +411,22 @@ def new_batch_id() -> str: @contextmanager -def _record_lock(path: Path) -> Iterator[None]: - """Hold an exclusive lock file beside the record for the block; refuse if it is held. +def hold_lock(lock: Path, what: str) -> Iterator[None]: + """Hold the exclusive lock file ``lock`` for the block; refuse at once if it is held. The run's own lock (:func:`.lock_file.exclusive_lock`): created with ``O_CREAT | O_EXCL``, removed at the end (also on an error) while it still names this writer, never waited on. It protects the writers of one computer; a file system shared by several computers (a Drive folder open in two Colab sessions) does not make the exclusive create reliable. + ``what`` names what is being written, for the refusal that names the holder. """ - path.parent.mkdir(parents=True, exist_ok=True) + lock.parent.mkdir(parents=True, exist_ok=True) stack = ExitStack() try: - stack.enter_context(exclusive_lock(path.with_name(RECORD_LOCK_FILENAME))) + stack.enter_context(exclusive_lock(lock)) except LockHeldError as held: raise SegmentationError( - f"The record {path} is being written by {held.holder.describe()} " + f"{what} is being written by {held.holder.describe()} " f"({held.path.name} exists). Wait for it to finish and write again; if no writer " f"is running (it was killed), delete {held.path} yourself." ) from None @@ -433,6 +434,11 @@ def _record_lock(path: Path) -> Iterator[None]: yield +def _record_lock(path: Path) -> AbstractContextManager[None]: + """Hold the lock beside the record ``path`` for the block (:func:`hold_lock`).""" + return hold_lock(path.with_name(RECORD_LOCK_FILENAME), f"The record {path}") + + def record_path(masks_root: str | Path, mask_type: str) -> Path: """Return where the record of ``mask_type`` is, ``//segmentation_record.json``.""" check_mask_type(mask_type) diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index 5a7ab168..849fcc93 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -463,7 +463,7 @@ def test_two_writers_one_claims_the_name_and_the_other_is_refused(run, monkeypat def second_writer_in_the_window(source, destination, **kwargs): if os.fspath(destination) == os.fspath(target) and "size" not in seen: seen["size"] = target.stat().st_size # the claim is an empty file, not half a mask - with pytest.raises(SegmentationError, match="already exists"): + with pytest.raises(SegmentationError, match="is being written by"): # the type's lock write_mask(run.masks, "Cells", fov, labels_like(run, fov, 9), run.inputs) return real(source, destination, **kwargs) diff --git a/tests/test_segmentation_record.py b/tests/test_segmentation_record.py index ef681106..dbfd3d7f 100644 --- a/tests/test_segmentation_record.py +++ b/tests/test_segmentation_record.py @@ -290,6 +290,26 @@ def test_a_lock_another_writer_took_meanwhile_is_never_removed(tmp_path): assert read_holder(lock) == LockHolder("another-pc", 7) # still the other writer's +def test_a_holder_carries_a_random_token_and_an_older_lock_without_one_still_reads(tmp_path): + lock = tmp_path / RECORD_LOCK_FILENAME + with exclusive_lock(lock) as holder: + assert len(holder.token) == 32 and read_holder(lock) == holder + with exclusive_lock(lock) as again: + assert again.token != holder.token + lock.write_text('{"host": "old-pc", "pid": 7, "started_at": "x"}\n', encoding="utf-8") + assert read_holder(lock) == LockHolder("old-pc", 7, "x", "") + + +def test_a_lock_retaken_by_the_same_process_in_the_same_second_is_never_removed(tmp_path): + lock = tmp_path / RECORD_LOCK_FILENAME + with exclusive_lock(lock) as first: + lock.unlink() + with exclusive_lock(lock) as second: # same host, PID and second; another holding + assert second.token != first.token + lock.write_text(json.dumps({**first.__dict__, "token": "other"}), encoding="utf-8") + assert lock.exists() # the first holder's exit did not remove the other's lock + + def test_two_batches_made_in_the_same_second_get_different_ids(tmp_path, monkeypatch): class Frozen: @staticmethod diff --git a/tests/test_segmentation_write_lock.py b/tests/test_segmentation_write_lock.py new file mode 100644 index 00000000..75bc7dc8 --- /dev/null +++ b/tests/test_segmentation_write_lock.py @@ -0,0 +1,90 @@ +"""The hand-off's name parity with the run and its per-type write lock (audit of PR #367). + +Fixtures and helpers are those of ``test_segmentation_handoff``. +""" + +import os + +import pytest +import tifffile + +from morphobricks_preprocessing.lock_file import exclusive_lock +from morphobricks_preprocessing.segmentation_handoff import ( + WRITE_LOCK_FILENAME, + images_to_segment, + mask_path, + write_mask, +) +from morphobricks_preprocessing.segmentation_record import SegmentationError +from test_segmentation_handoff import labels_like +from test_segmentation_handoff import run as handoff_run + +run = handoff_run # the fixture of the hand-off tests, under its own name + +# Name parity with the run, for every discovered type (audit B1) -------------------------------- + + +@pytest.mark.parametrize("other", ["NA", "Cafe\u0301"]) +def test_an_unrelated_type_the_run_would_refuse_is_refused_before_writing(run, other): + first = run.inputs.fovs()[0] + stray = run.masks / other / "Control" / "Biological_repeat_1" / "img0.tif" + stray.parent.mkdir(parents=True) + stray.write_bytes(b"") + code = "R_MASK_TYPE_NAME_INVALID" if other == "NA" else "R_FOLDER_NOT_NFC" + with pytest.raises(SegmentationError, match=code): + images_to_segment(run.inputs, "Cells", run.masks) + with pytest.raises(SegmentationError, match=code): + write_mask(run.masks, "Cells", first, labels_like(run, first), run.inputs) + files = [p.relative_to(run.masks).as_posix() for p in run.masks.rglob("*") if p.is_file()] + assert files == [stray.relative_to(run.masks).as_posix()] + + +# One write lock per type, both modes (audit B2) -------------------------------------------------- + + +@pytest.mark.parametrize("overwrite", [False, True]) +def test_a_held_write_lock_refuses_the_writer_in_both_modes(run, overwrite): + fov = run.inputs.fovs()[0] + lock = run.masks / "Cells" / WRITE_LOCK_FILENAME + lock.parent.mkdir(parents=True) + with exclusive_lock(lock): + with pytest.raises(SegmentationError, match="is being written by process"): + write_mask( + run.masks, "Cells", fov, labels_like(run, fov), run.inputs, overwrite=overwrite + ) + files = [p for p in run.masks.rglob("*") if p.is_file()] + assert files == [lock] # nothing was written, and the other writer's lock stays + assert not lock.exists() + + +def test_a_default_writer_never_replaces_a_concurrent_overwriting_writers_mask(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = mask_path(run.masks, "Cells", fov) + real, seen = os.replace, {} + + def overwriting_writer_in_the_window(source, destination, **kwargs): + if os.fspath(destination) == os.fspath(target) and "refused" not in seen: + with pytest.raises(SegmentationError, match="is being written by"): + write_mask( + run.masks, "Cells", fov, labels_like(run, fov, 9), run.inputs, overwrite=True + ) + seen["refused"] = True + return real(source, destination, **kwargs) + + monkeypatch.setattr(os, "replace", overwriting_writer_in_the_window) + write_mask(run.masks, "Cells", fov, labels_like(run, fov, 4), run.inputs) + assert seen["refused"] + assert tifffile.imread(target).max() == 4 + assert os.listdir(target.parent) == [target.name] + assert not (run.masks / "Cells" / WRITE_LOCK_FILENAME).exists() # released at the end + + +def test_the_write_lock_is_released_after_a_refusal_and_is_not_a_mask(run): + fov = run.inputs.fovs()[0] + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + with pytest.raises(SegmentationError, match="already exists"): + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert not (run.masks / "Cells" / WRITE_LOCK_FILENAME).exists() + # A lock left in the type folder is skipped silently by the run's own masks discovery. + (run.masks / "Cells" / WRITE_LOCK_FILENAME).write_text("{}", encoding="utf-8") + assert images_to_segment(run.inputs, "Cells", run.masks) == run.inputs.fovs()[1:] From 050e98c08b504eaf0450afe4b60019761901ae2a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:04:58 +0000 Subject: [PATCH 10/11] write_mask: check for a twin before and under the write lock; no folder cleanup after the lock A refusal before the lock creates nothing; the check under the lock catches a mask published meanwhile. The cleanup that ran after the lock was released could remove a folder another writer had just created. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- .../segmentation_handoff.py | 64 ++++++++----------- tests/test_segmentation_handoff.py | 3 +- 2 files changed, 28 insertions(+), 39 deletions(-) diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index dee93139..32cf6e6c 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -24,8 +24,6 @@ import os import tempfile -from collections.abc import Iterator -from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path @@ -259,21 +257,10 @@ def write_mask( _check_2d(fov) data = _checked_labels(labels, inputs.plane_shape(fov), fov.relative_path) type_folder = Path(masks_root) / mask_type - with ( - _no_empty_folders_if_refused(type_folder, target.parent), - hold_lock(type_folder / WRITE_LOCK_FILENAME, f"The {mask_type} masks in {masks_root}"), - ): # one writer per type for the twin check, the claim and the publish, in both modes - wanted = target.relative_to(masks_root).as_posix() - twins = sorted( - m.path for m in _paired(inputs, masks_root, mask_type) if m.image == fov.relative_path - ) - if twins and (not overwrite or twins != [wanted]): - raise SegmentationError( - f"The {mask_type} mask of {fov.relative_path} already exists " - f"({', '.join(twins)} in {masks_root}). Use overwrite=True to replace {wanted}; " - "a mask of this image and type in another place or case, or in the other layout, " - "must be moved away first (the next run would refuse both as duplicate_mask)." - ) + _refuse_twins(inputs, masks_root, mask_type, fov, target, overwrite) # nothing made if refused + with hold_lock(type_folder / WRITE_LOCK_FILENAME, f"The {mask_type} masks in {masks_root}"): + # one writer per type for the twin check, the claim and the publish, in both modes + _refuse_twins(inputs, masks_root, mask_type, fov, target, overwrite) target.parent.mkdir(parents=True, exist_ok=True) handle, temporary = tempfile.mkstemp( prefix=f".{target.name}.", suffix=".tmp", dir=target.parent @@ -297,29 +284,30 @@ def write_mask( return target -@contextmanager -def _no_empty_folders_if_refused(type_folder: Path, leaf: Path) -> Iterator[None]: - """Remove the folders this call created (``type_folder`` down to ``leaf``) if it is refused. +def _refuse_twins( + inputs: RunInputs, + masks_root: str | os.PathLike, + mask_type: str, + fov: Fov, + target: Path, + overwrite: bool, +) -> None: + """Refuse a mask of ``fov`` and ``mask_type`` that the run pairs, unless it is ``target``. - A refused write leaves nothing behind, not even the empty folders the lock needed. + Checked once before the write lock (a refusal then creates nothing, not even the lock's + folder) and again under the lock (another writer may have published meanwhile). """ - created = None # the topmost folder this call has to make - for folder in (type_folder, *type_folder.parents): - if folder.exists(): - break - created = folder - try: - yield - except SegmentationError: - folder = leaf - while created is not None and (folder == created or created in folder.parents): - try: - if folder.exists(): # a folder not made yet (refused before it) is skipped - folder.rmdir() - except OSError: - break # not empty: something else is in it - folder = folder.parent - raise + wanted = target.relative_to(masks_root).as_posix() + twins = sorted( + m.path for m in _paired(inputs, masks_root, mask_type) if m.image == fov.relative_path + ) + if twins and (not overwrite or twins != [wanted]): + raise SegmentationError( + f"The {mask_type} mask of {fov.relative_path} already exists " + f"({', '.join(twins)} in {masks_root}). Use overwrite=True to replace {wanted}; " + "a mask of this image and type in another place or case, or in the other layout, " + "must be moved away first (the next run would refuse both as duplicate_mask)." + ) def _publish(temporary: Path, target: Path, overwrite: bool, what: str) -> None: diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index 849fcc93..2080469d 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -463,7 +463,8 @@ def test_two_writers_one_claims_the_name_and_the_other_is_refused(run, monkeypat def second_writer_in_the_window(source, destination, **kwargs): if os.fspath(destination) == os.fspath(target) and "size" not in seen: seen["size"] = target.stat().st_size # the claim is an empty file, not half a mask - with pytest.raises(SegmentationError, match="is being written by"): # the type's lock + # refused before the lock (the claim already counts as a mask) or by the type's lock + with pytest.raises(SegmentationError, match="already exists|is being written by"): write_mask(run.masks, "Cells", fov, labels_like(run, fov, 9), run.inputs) return real(source, destination, **kwargs) From 7a0a52141a131f478eaaac3d07042cc39f14ca81 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:15:04 +0000 Subject: [PATCH 11/11] write_mask: on_published callback, called under the write lock Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 4 +- docs/contract.md | 2 +- .../segmentation_handoff.py | 9 ++++ tests/test_segmentation_write_lock.py | 44 +++++++++++++++++++ 4 files changed, 57 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db82fec9..52319cd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,7 +47,9 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. of a concurrent `overwrite=True` writer (contract §15.5 also documents the transient zero-byte placeholder and that preprocessing must not run on the masks folder during a batch). `LockHolder` gains a random `token`, written in the lock file and compared on removal (a lock without one, - from an older run, still reads, token `""`). + from an older run, still reads, token `""`). `write_mask(..., on_published=callable)` calls it with the + published path while the write lock is still held (not when refused; its error propagates, the mask + stays), so a caller can hash or stamp the file before another writer can replace it. - **Channel-identity check after the run** (contract §14.1, design `channel-identity-check-2026-11-21` in MorphoFeature's `claude/restart-doc`): from the image summaries the intensity checks already make (no pixel read), every imaging unit's channel is diff --git a/docs/contract.md b/docs/contract.md index 676f7e23..42fde9ad 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1352,7 +1352,7 @@ links (a Google Drive mount) too. the image to the published file, **in both modes**: an overwriting writer and a default writer can never replace each other's mask. A held lock is refused at once, naming its holder, and never waited on; a killed writer leaves it, and the message says to delete it. Like the -record's lock it is a dot-file, skipped by the masks step. A lock holder carries a random +record's lock it is a dot-file, skipped by the masks step. The optional `on_published(path)` callback runs right after the publish, still under the lock (take a hash or file stamp there; it is not called when the write is refused, and an error it raises propagates with the mask left published). A lock holder carries a random token, so a lock deleted and retaken is never removed by its earlier holder. Limits: the lock protects the writers of one computer (not a Drive folder open in two Colab sessions); a reader may briefly see a **zero-byte placeholder** at the mask's name while a mask is being diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index 32cf6e6c..15bf9dd8 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -24,6 +24,7 @@ import os import tempfile +from collections.abc import Callable from dataclasses import dataclass from pathlib import Path @@ -211,6 +212,7 @@ def write_mask( inputs: RunInputs, *, overwrite: bool = False, + on_published: Callable[[Path], None] | None = None, ) -> Path: """Write ``labels`` as the mask of ``mask_type`` for ``fov``, as preprocessing expects it. @@ -236,6 +238,11 @@ def write_mask( The opened run (the image's size, and the experiment and output folders). overwrite Replace a mask that is already there. Without it an existing mask is refused. + on_published + Called with the published mask's path right after it is published, while the type's + write lock is still held (so the file cannot be replaced meanwhile: hash or stamp it + here). Not called when the write is refused. An error it raises propagates; the mask + stays published and the caller decides what to do with it. Returns ------- @@ -281,6 +288,8 @@ def write_mask( except BaseException: Path(temporary).unlink(missing_ok=True) raise + if on_published is not None: + on_published(target) # still under the lock; an error propagates, the mask stays return target diff --git a/tests/test_segmentation_write_lock.py b/tests/test_segmentation_write_lock.py index 75bc7dc8..8eea7269 100644 --- a/tests/test_segmentation_write_lock.py +++ b/tests/test_segmentation_write_lock.py @@ -88,3 +88,47 @@ def test_the_write_lock_is_released_after_a_refusal_and_is_not_a_mask(run): # A lock left in the type folder is skipped silently by the run's own masks discovery. (run.masks / "Cells" / WRITE_LOCK_FILENAME).write_text("{}", encoding="utf-8") assert images_to_segment(run.inputs, "Cells", run.masks) == run.inputs.fovs()[1:] + + +# on_published runs under the write lock --------------------------------------------------------- + + +def test_on_published_runs_under_the_lock_with_the_published_path(run): + fov = run.inputs.fovs()[0] + lock = run.masks / "Cells" / WRITE_LOCK_FILENAME + seen = [] + + def callback(path): + seen.append((path, lock.exists(), path.is_file())) + + target = write_mask( + run.masks, "Cells", fov, labels_like(run, fov), run.inputs, on_published=callback + ) + assert seen == [(target, True, True)] + assert target == mask_path(run.masks, "Cells", fov) + assert not lock.exists() + + +def test_on_published_is_not_called_when_the_write_is_refused(run): + fov = run.inputs.fovs()[0] + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + calls = [] + with pytest.raises(SegmentationError, match="already exists"): + write_mask( + run.masks, "Cells", fov, labels_like(run, fov), run.inputs, on_published=calls.append + ) + assert calls == [] + + +def test_a_raising_on_published_propagates_and_the_mask_stays_published(run): + fov = run.inputs.fovs()[0] + + def callback(path): + raise RuntimeError("hash failed") + + with pytest.raises(RuntimeError, match="hash failed"): + write_mask( + run.masks, "Cells", fov, labels_like(run, fov), run.inputs, on_published=callback + ) + assert mask_path(run.masks, "Cells", fov).is_file() + assert not (run.masks / "Cells" / WRITE_LOCK_FILENAME).exists() # the lock is released