diff --git a/AGENTS.md b/AGENTS.md index 3f0a1ba7..a08debba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -260,6 +260,13 @@ 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 (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, 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) 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 ea0ed455..52319cd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,33 @@ 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`, `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 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 `""`). `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 d13dc0a5..42fde9ad 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1305,6 +1305,61 @@ 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, 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, 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 +**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). `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 +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, **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. 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 +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) Rules every MorphoBricks brick applies in one way, so they live here as public functions diff --git a/pyproject.toml b/pyproject.toml index f1486e8d..5ab72545 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -362,6 +362,9 @@ 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.lock_file" = "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 3d81ee64..b7f512ad 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -241,6 +241,24 @@ ResolvedRequest, VolumeNotSupportedError, ) +from .segmentation_handoff import ( + SegmentationPlan, + images_to_segment, + mask_path, + resolve_segmentation, + segmentation_input, + write_mask, +) +from .segmentation_record import ( + SegmentationBatch, + SegmentationError, + SegmentationRecord, + SegmentedImage, + mask_sha256, + new_batch_id, + read_record, + write_record, +) from .sources import check_sources from .unrecorded import UnrecordedFiles, unrecorded_files from .validation import Severity, ValidationIssue, has_errors @@ -354,6 +372,11 @@ "MaskContradictsRepresentationError", "MaskUncheckedError", "RgbNotSupportedError", + "SegmentationBatch", + "SegmentationError", + "SegmentationPlan", + "SegmentationRecord", + "SegmentedImage", "VolumeNotSupportedError", "RunReportUnreadableError", "RunStoppedError", @@ -406,6 +429,9 @@ "check_sources", "check_table", "convert_experiment", + "images_to_segment", + "mask_path", + "mask_sha256", "preview_conversion", "declared_mapping", "default_output_folder", @@ -441,6 +467,7 @@ "mask_thresholds", "named_axes", "ngff_label_names", + "new_batch_id", "open_ngff", "open_ngff_labels", "pair_counts", @@ -459,11 +486,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", @@ -472,13 +501,16 @@ "same_pixel_size", "sample_planes", "scan_masks", + "segmentation_input", "series_axes_from_metadata", "space_unit", "to_micrometers", "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/lock_file.py b/src/morphobricks_preprocessing/lock_file.py new file mode 100644 index 00000000..e058ea2b --- /dev/null +++ b/src/morphobricks_preprocessing/lock_file.py @@ -0,0 +1,124 @@ +"""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 +import uuid +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 process holding a lock file (a run's output folder lock or a record 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. + 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"``.""" + if not self.pid: + 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}" + + +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", "")), + str(data.get("token", "")), + ) + 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 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 + ------ + 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"), + uuid.uuid4().hex, + ) + 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/masks/files.py b/src/morphobricks_preprocessing/masks/files.py index 90e6d2f1..ab9277d8 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, @@ -148,7 +149,9 @@ def _folder_masks( 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). + 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: @@ -162,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 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_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py new file mode 100644 index 00000000..15bf9dd8 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -0,0 +1,463 @@ +"""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 collections.abc import Callable +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 ( + _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, 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).""" + + +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. + + "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 + ---------- + 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, 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) + 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( + 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. + It resolves on every call: a batch calls :func:`resolve_segmentation` once and reads each + image with ``plan.read``. + + 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``, ...). + """ + _check_2d(fov) + 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: + """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, + on_published: Callable[[Path], None] | None = None, +) -> 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. 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 + ---------- + 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. + 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 + ------- + 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); 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) + type_folder = Path(masks_root) / mask_type + _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 + ) + 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 + if on_published is not None: + on_published(target) # still under the lock; an error propagates, the mask stays + return target + + +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``. + + 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). + """ + 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: + """Move the finished ``temporary`` file to ``target``; never over a file unless asked. + + 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: + 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 + 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]: + """Return the masks of ``mask_type`` that preprocessing's pairing finds, of any source. + + 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._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 + ------ + SegmentationError + For any of those, naming the files. + """ + discovery = discover_experiment(inputs.experiment_root, inputs.output_folder) + 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]), + *_description_name_issues(found), + *_duplicate_issues(found), + ] + refusing = [issue for issue in issues if issue.is_error] + if refusing: + first = refusing[0] + 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: + """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) diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py new file mode 100644 index 00000000..ea92357e --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -0,0 +1,537 @@ +"""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 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, 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 +import uuid +from collections.abc import Iterator +from contextlib import AbstractContextManager, ExitStack, contextmanager +from dataclasses import dataclass, field, replace +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +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 +"""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") +"""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 in one batch. + + 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). + 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 SegmentationBatch: + """One run of a segmentation tool over some images: how its masks were made. + + Attributes + ---------- + batch_id + 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 + 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, each image once. + """ + + batch_id: 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 + + def __post_init__(self) -> None: + """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 batch as the JSON object kept in the file.""" + return { + "batch_id": self.batch_id, + "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, + "mask_sha256": i.mask_sha256, + } + for i in self.images + ], + } + + @classmethod + 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( + batch_id=data["batch_id"], + 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"], 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. + + 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( + { + "batch_id", + "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", "mask_sha256"}) + + +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") + 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") + 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: + 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) + 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) -> 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) + 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)}.") + return data + + +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).""" + model = _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 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( + 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.") + 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 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 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 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. + """ + lock.parent.mkdir(parents=True, exist_ok=True) + stack = ExitStack() + try: + stack.enter_context(exclusive_lock(lock)) + except LockHeldError as held: + raise SegmentationError( + 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 + with stack: + 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) + return Path(masks_root) / mask_type / RECORD_FILENAME + + +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, checked as :func:`check_mask_type` does. + batch + The batch. + + Returns + ------- + Path + The file written. + + Raises + ------ + SegmentationError + 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) + 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: + 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 {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) + return SegmentationRecord(earlier.mask_type, tuple(batches)) + + +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_modes_lock_report.py b/tests/test_modes_lock_report.py index 47a70210..0d215b77 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_handoff.py b/tests/test_segmentation_handoff.py new file mode 100644 index 00000000..2080469d --- /dev/null +++ b/tests/test_segmentation_handoff.py @@ -0,0 +1,579 @@ +"""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 errno +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, prefill_mapping +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, + resolve_segmentation, + segmentation_input, + write_mask, +) +from morphobricks_preprocessing.segmentation_record import ( + RECORD_FILENAME, + SegmentationError, + write_record, +) +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"]', + b'channels = ["EXTRA", "DNA", "ACTIN", "TUB"]', +) +MASKS_SECTION = b'\n[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"\n' +REPEAT_2 = "Biological_repeat_2" +EXPECTED_ROUND_TRIP_ISSUES = [] + + +@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 + + +# 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="mask type|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 + + +@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) + 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", 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 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) + 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 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 path": run.masks / "Cells" / "control" / "biological_repeat_1" / "img0.tif", + "second layout": run.masks / "Control" / "Biological_repeat_1" / "img0_Cells.tif", + } + + +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() + 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:] + 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_only_the_twin_is_on_disk(run, twin) + + +@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_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) + 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) + 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_claiming_is_never_replaced(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = mask_path(run.masks, "Cells", fov) + real = os.open + + 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, "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_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 + # 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) + + 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) # 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 ------------------------------------ + + +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", batch()) + 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) diff --git a/tests/test_segmentation_record.py b/tests/test_segmentation_record.py new file mode 100644 index 00000000..dbfd3d7f --- /dev/null +++ b/tests/test_segmentation_record.py @@ -0,0 +1,328 @@ +"""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.lock_file import LockHolder, exclusive_lock, read_holder +from morphobricks_preprocessing.segmentation_record import ( + RECORD_FILENAME, + RECORD_LOCK_FILENAME, + SegmentationBatch, + SegmentationError, + SegmentationRecord, + SegmentedImage, + mask_sha256, + new_batch_id, + 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()) + + +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('{"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 + 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_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_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 + 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] diff --git a/tests/test_segmentation_write_lock.py b/tests/test_segmentation_write_lock.py new file mode 100644 index 00000000..8eea7269 --- /dev/null +++ b/tests/test_segmentation_write_lock.py @@ -0,0 +1,134 @@ +"""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:] + + +# 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