From cdb592d7b3950096e4c74f05c01e04d64488edef Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 11:41:28 +0000 Subject: [PATCH 01/22] Cellpose glue for the segmentation hand-off (step 2): verified model, device and weights segmentation_cellpose and segmentation_cellpose_model import Cellpose, torch and DINOv3 only inside functions; Cellpose 4.2.1.1 is pinned and is not a dependency. A model is one of the four built-in names or an existing file, validated before loading; after loading the weights file and the device must be the ones asked for (Cellpose would substitute cpsam_v2, fall back to the CPU or download weights silently); the weights are hashed for the record. Channels come from resolve_segmentation as a (C, Y, X) stack with channel_axis=0 (at most three); a blank diameter is recorded as the model's native scale, never 0. run_batch writes each mask with write_mask and records every image as written, skipped or failed in the existing SegmentationBatch. notebook_cellpose holds the widgets behind the notebook. Tests run against a stand-in for Cellpose and torch (tests/cellpose_stub.py). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- pyproject.toml | 3 + .../notebook_cellpose.py | 349 ++++++++++++ .../segmentation_cellpose.py | 485 ++++++++++++++++ .../segmentation_cellpose_model.py | 368 ++++++++++++ tests/cellpose_stub.py | 134 +++++ tests/test_segmentation_cellpose.py | 529 ++++++++++++++++++ 6 files changed, 1868 insertions(+) create mode 100644 src/morphobricks_preprocessing/notebook_cellpose.py create mode 100644 src/morphobricks_preprocessing/segmentation_cellpose.py create mode 100644 src/morphobricks_preprocessing/segmentation_cellpose_model.py create mode 100644 tests/cellpose_stub.py create mode 100644 tests/test_segmentation_cellpose.py diff --git a/pyproject.toml b/pyproject.toml index 6b0c713..874a486 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -171,6 +171,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.report_view" = "pure" "morphobricks_preprocessing.notebook_axes_quick" = "ui" "morphobricks_preprocessing.notebook_channel_thumbs" = "ui" +"morphobricks_preprocessing.notebook_cellpose" = "ui" "morphobricks_preprocessing.notebook_channels" = "ui" "morphobricks_preprocessing.notebook_channel_moves" = "ui" "morphobricks_preprocessing.notebook_channels_grid" = "ui" @@ -349,6 +350,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.masks.objects" = "pure" "morphobricks_preprocessing.mask_rules" = "pure" "morphobricks_preprocessing.mask_lineage" = "io" +"morphobricks_preprocessing.segmentation_cellpose" = "io" +"morphobricks_preprocessing.segmentation_cellpose_model" = "io" "morphobricks_preprocessing.segmentation_handoff" = "io" "morphobricks_preprocessing.segmentation_record" = "io" "morphobricks_preprocessing.mask_conversion" = "orchestration" diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py new file mode 100644 index 0000000..9e9d714 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -0,0 +1,349 @@ +"""The widgets and the one object behind the Cellpose notebook (``MorphoBricks_Cellpose.ipynb``). + +Every code cell of the notebook is one call on :class:`CellposeWorkflow`; the logic is in +:mod:`.segmentation_cellpose` (and the hand-off it builds on), this module only shows it: the +channel dropdowns, the preview figure, the progress line and the final table. A refusal of the +hand-off or of the run is shown **verbatim** and stops the cell (:class:`CellStop`). Needs the +``notebook`` extra (``ipywidgets``, ``matplotlib``); Cellpose is imported only when a model is +loaded. +""" + +from __future__ import annotations + +import functools +import time +from collections.abc import Callable +from pathlib import Path +from typing import ParamSpec, TypeVar + +import ipywidgets as widgets +import numpy as np +from IPython.display import display +from matplotlib.figure import Figure + +from . import segmentation_cellpose as cp +from .notebook_progress import progress_html +from .notebook_style import STYLE_CSS, status, table, tiles +from .run_inputs import RunInputs, RunInputsError +from .segmentation_handoff import SegmentationPlan, images_to_segment, resolve_segmentation +from .segmentation_record import SegmentationError, check_mask_type + +NONE = "(none)" +P = ParamSpec("P") +T = TypeVar("T") +REFUSALS = (SegmentationError, RunInputsError) +"""What the hand-off and the run refuse with; their messages are shown unchanged.""" + + +class CellStop(RuntimeError): + """Stop a notebook cell with its message on one line, without a traceback.""" + + def _render_traceback_(self) -> list: + return [str(self)] + + +def stops(method: Callable[P, T]) -> Callable[P, T]: + """Turn a refusal of the hand-off or of the run into a :class:`CellStop` with its message.""" + + @functools.wraps(method) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: + try: + return method(*args, **kwargs) + except REFUSALS as exc: + raise CellStop(str(exc)) from exc + + return wrapper + + +def _card(kind: str, title: str, lines: tuple[str, ...] = ()) -> widgets.HTML: + """Return a status card as a widget, with the notebook's look.""" + return widgets.HTML(f"
{status(kind, title, lines)}
") + + +class ChannelPicker: + """Up to three dropdowns of the run's channel IDs, resolved by ID as soon as they change. + + The options are the channel IDs of the run; one that not every image has says so, and + choosing it shows the resolver's refusal (``A_SCOPE_INCOMPLETE``) unchanged under the + dropdowns. :attr:`plan` is the resolved selection, or None while the choice is refused. + """ + + def __init__(self, inputs: RunInputs) -> None: + """Build the dropdowns for ``inputs`` and resolve the first choice.""" + self.inputs = inputs + coverage = cp.channel_coverage(inputs) + shared = [c for c, (have, total) in coverage.items() if have == total] + options = [ + (c if have == total else f"{c} (in {have} of {total} images)", c) + for c, (have, total) in coverage.items() + ] + first = shared[0] if shared else next(iter(coverage), "") + self.dropdowns = [ + widgets.Dropdown(options=options, value=first, description="Channel 1"), + *( + widgets.Dropdown( + options=[(NONE, ""), *options], value="", description=f"Channel {n}" + ) + for n in (2, 3) + ), + ] + self.message = widgets.HTML() + self.plan: SegmentationPlan | None = None + self.refusal = "" + for dropdown in self.dropdowns: + dropdown.observe(self._changed, names="value") + self._changed() + + @property + def channel_ids(self) -> tuple[str, ...]: + """The chosen channel IDs, in the order of the dropdowns (blank ones left out).""" + return tuple(d.value for d in self.dropdowns if d.value) + + def _changed(self, _change: object = None) -> None: + """Resolve the choice; show what was resolved, or the refusal verbatim.""" + try: + cp.check_channel_count(self.channel_ids) + self.plan = resolve_segmentation(self.inputs, self.channel_ids) + self.refusal = "" + note = _card("ok", "Channels: " + ", ".join(self.channel_ids)) + except REFUSALS as exc: + self.plan, self.refusal = None, str(exc) + note = _card("error", "These channels cannot be used", (self.refusal,)) + self.message.value = note.value + + def box(self) -> widgets.VBox: + """Return the dropdowns and the message under them.""" + return widgets.VBox([*self.dropdowns, self.message]) + + +def preview_figure(stack: np.ndarray, labels: np.ndarray, channel_ids: tuple[str, ...]) -> Figure: + """Return the preview: each channel (display contrast only) and the outlines of the labels. + + The contrast stretch is for the eye: the stack that was segmented, and the masks, are the + stored values and are never changed by it. + """ + shown = cp.display_contrast(stack) + outlines = cp.label_outlines(labels) + figure = Figure(figsize=(4 * (len(shown) + 1), 4)) + axes = figure.subplots(1, len(shown) + 1, squeeze=False)[0] + for axis, channel, name in zip(axes, shown, channel_ids, strict=False): + axis.imshow(channel, cmap="gray", vmin=0, vmax=1) + axis.set_title(f"{name} (display contrast)") + overlay = np.repeat(shown[0][..., None], 3, axis=-1) + overlay[outlines] = (1.0, 0.85, 0.0) + axes[-1].imshow(overlay) + axes[-1].set_title(f"Cellpose: {int(labels.max())} objects") + for axis in axes: + axis.axis("off") + figure.tight_layout() + return figure + + +class CellposeWorkflow: + """The Cellpose notebook's state: the run, the channels, the model and the batch. + + Each notebook cell calls one method; a method that needs an earlier cell says which one. + ``shown`` keeps the HTML of every card shown (for tests and for reading the notebook back). + """ + + def __init__(self) -> None: + """Start with nothing chosen.""" + self.inputs: RunInputs | None = None + self.masks_root: Path | None = None + self.mask_type = "" + self.picker: ChannelPicker | None = None + self.loaded: cp.LoadedModel | None = None + self.settings: cp.Settings | None = None + self.result: cp.BatchResult | None = None + self.shown: list[str] = [] + + def _show(self, widget: widgets.Widget) -> None: + """Display ``widget`` (the style sheet goes first, once).""" + if not self.shown: + display(widgets.HTML(STYLE_CSS)) + self.shown.append(getattr(widget, "value", "")) + display(widget) + + def _need(self, what: str, cell: int) -> None: + """Refuse a step whose earlier cell has not run.""" + missing = { + "run": self.inputs is None, + "channels": self.picker is None, + "model": self.loaded is None, + }[what] + if missing: + raise SegmentationError(f"Run cell {cell} first.") + + @stops + def open(self, run_folder: str, masks_folder: str) -> None: + """Open the run and say what it holds (cell 3).""" + if not masks_folder.strip(): + raise SegmentationError("Give the masks folder (outside the experiment and the run).") + inputs = cp.open_run(run_folder) + self.inputs, self.masks_root = inputs, Path(masks_folder.strip()) + self.picker = self.loaded = self.result = None + coverage = cp.channel_coverage(inputs) + lines = [ + f"{c}: in {have} of {total} images" + ("" if have == total else " (partial)") + for c, (have, total) in coverage.items() + ] + deep = cp.non_2d_images(inputs) + if deep: + lines.append( + f"{len(deep)} image(s) have Z or T above 1 and will fail: segmentation here is " + f"2D only ({deep[0]}...)." + ) + self._show( + _card( + "warn" if deep else "ok", f"Run opened: {len(inputs.fovs())} images", tuple(lines) + ) + ) + + @stops + def choose_channels(self, mask_type: str) -> None: + """Check the mask type and show the channel dropdowns (cell 4).""" + self._need("run", 3) + check_mask_type(mask_type) + todo = images_to_segment(self.inputs, mask_type, self.masks_root) + self.mask_type, self.loaded = mask_type, None + self.picker = ChannelPicker(self.inputs) + self._show( + _card( + "info", + f"Mask type {mask_type}: {len(todo)} of {len(self.inputs.fovs())} images " + "have no mask yet", + ) + ) + self._show(self.picker.box()) + + @stops + def set_settings( + self, + diameter: str, + flow_threshold: float, + cellprob_threshold: float, + normalize: bool, + batch_size: int, + ) -> None: + """Check the inference settings (cell 5); a blank diameter is the model's native scale.""" + self.settings = cp.Settings( + cp.diameter_from_text(diameter), + flow_threshold, + cellprob_threshold, + normalize, + batch_size, + ) + + @stops + def load( + self, + model: str, + custom_model_file: str, + device: str, + download_weights: bool, + install_dino: bool, + ) -> None: + """Say what loading does, then load the verified model (cell 5).""" + self._need("channels", 4) + if self.picker.plan is None: + raise SegmentationError(self.picker.refusal) + if self.settings is None: + raise SegmentationError("Set the settings first: run set_settings in cell 5.") + chosen = custom_model_file.strip() or model + if install_dino and chosen in cp.DINO_MODELS: + self._show(_card("info", "Installing DINOv3", (" ".join(cp.dinov3_install_command()),))) + cp.install_dinov3() + self._show( + _card( + "info", + f"Loading {chosen} on {device}", + ( + "Built-in weights are downloaded from Hugging Face on first use; they are " + "downloaded only if the download box is ticked.", + ), + ) + ) + self.loaded = cp.load_model(chosen, device, allow_download=download_weights) + loaded, diameter = self.loaded, self.settings.diameter + self._show( + _card( + "ok", + f"Model {loaded.name} loaded on {loaded.device}", + ( + f"Weights file: {loaded.file}", + f"SHA-256: {loaded.sha256}", + f"Network {loaded.backbone}, tile size {loaded.tile_size}", + "Diameter: " + + ( + f"{diameter:g} pixels" + if diameter is not None + else "blank = " + cp.NATIVE_SCALE + ), + ), + ) + ) + + @stops + def preview(self, image: str = "") -> None: + """Segment one image and show it with the outlines; nothing is written (cell 6).""" + self._need("model", 5) + fovs = self.inputs.fovs() + todo = images_to_segment(self.inputs, self.mask_type, self.masks_root) + by_path = {f.relative_path: f for f in fovs} + if image.strip() and image.strip() not in by_path: + raise SegmentationError( + f"{image.strip()!r} is not an image of this run. Leave it blank, or use a path " + f"such as {fovs[0].relative_path}." + ) + fov = by_path[image.strip()] if image.strip() else (todo or fovs)[0] + stack = self.picker.plan.read(fov) + labels = cp.segment_image(self.loaded, self.settings, stack) + self._show(_card("info", f"Preview of {fov.relative_path} (nothing is written)")) + display(preview_figure(stack, labels, self.picker.plan.channel_ids)) + + @stops + def run(self, overwrite: bool = False) -> cp.BatchResult: + """Segment the images, write the masks and the record, and show the table (cell 7).""" + self._need("model", 5) + job = cp.SegmentationJob( + self.inputs, + self.picker.plan, + self.loaded, + self.settings, + self.mask_type, + self.masks_root, + overwrite, + ) + bar = widgets.HTML() + display(bar) + started = time.monotonic() + + def progress(done: int, total: int, item: str) -> None: + bar.value = progress_html("Segmenting", done, total, item, time.monotonic() - started) + + self.result = result = cp.run_batch(job, progress=progress) + counts = result.counts() + rows = [["Image", "Status", "Message"], *map(list, result.rows())] + failed = counts["failed"] + self._show( + widgets.HTML( + "
" + + tiles( + [ + ("✅", str(counts["written"]), "written"), + ("⏩", str(counts["skipped"]), "skipped"), + ("❌", str(failed), "failed"), + ] + ) + + table(rows) + + "
" + ) + ) + return result + + @stops + def next_steps(self) -> None: + """Say what to do now that the masks are made (the closing cell).""" + self._need("channels", 4) + lines = cp.next_steps_lines(self.mask_type, self.masks_root) + self._show(_card("info", "Next steps", lines)) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py new file mode 100644 index 0000000..6c2fdb8 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -0,0 +1,485 @@ +"""Cellpose glue for the segmentation hand-off: nothing asked for is silently replaced. + +The shipped Cellpose notebook (``notebooks/MorphoBricks_Cellpose.ipynb``) segments the images of a +described run with Cellpose and writes the masks with :func:`.segmentation_handoff.write_mask`. +Cellpose is **not** a dependency of this brick and is imported only inside functions +(``cellpose``, ``torch``, ``dinov3``), so importing this module, and discovery, stay inert. The +pinned release is :data:`CELLPOSE_VERSION` (4.2.1.1); another version is refused. + +Loading a model (:func:`load_model`, in :mod:`.segmentation_cellpose_model`, re-exported here) +refuses what Cellpose 4.2.1.1 would do silently: substitute ``cpsam_v2`` for a model it cannot +find, fall back from the GPU to the CPU, and download uncached weights. This module adds the +rest of what an audit of the Cellpose hand-off asked for: + +- **Channels by ID.** The channels are resolved by canonical ID + (:func:`.segmentation_handoff.resolve_segmentation`) and passed as a ``(C, Y, X)`` stack with + ``channel_axis=0``. Cellpose reads only the **first three** channels and drops the rest by + position, so more than three are refused (:func:`check_channel_count`). +- **Diameter.** Blank means the model's native scale: Cellpose 4.2.1.1 does **not** estimate a + diameter. A diameter is in pixels and never 0 (:class:`Settings`). +- **Record.** Every effective setting goes into the batch's parameters + (:func:`inference_parameters`), every image into the batch with its outcome, written, skipped + or failed with the error (:func:`run_batch`); nothing is dropped. + +Mask paths, pairing, the mask-type rules, writing, the folder rules and the record are the +hand-off's own (:mod:`.segmentation_handoff`, :mod:`.segmentation_record`); nothing is repeated. +""" + +from __future__ import annotations + +import math +import os +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import numpy as np + +from ._io import file_sha256 +from .manifest import MANIFEST_FILENAME +from .run_inputs import Fov, RunInputs +from .segmentation_cellpose_model import ( + BUILTIN_MODELS, + CELLPOSE_VERSION, + DEFAULT_MODEL, + DINO_MODELS, + DINOV3_COMMIT, + DINOV3_URL, + LoadedModel, + ModelChoice, + check_device, + check_dinov3, + choose_model, + dinov3_install_command, + install_dinov3, + installed_dinov3_commit, + installed_version, + load_model, + weights_file, +) +from .segmentation_handoff import SegmentationPlan, images_to_segment, write_mask +from .segmentation_record import ( + SegmentationBatch, + SegmentationError, + SegmentedImage, + check_mask_type, + mask_sha256, + write_record, +) + +__all__ = [ + "BUILTIN_MODELS", + "CELLPOSE_VERSION", + "DEFAULT_MODEL", + "DINOV3_COMMIT", + "DINOV3_URL", + "DINO_MODELS", + "LoadedModel", + "ModelChoice", + "Settings", + "check_device", + "check_dinov3", + "choose_model", + "dinov3_install_command", + "install_dinov3", + "installed_dinov3_commit", + "installed_version", + "load_model", + "weights_file", +] + +TOOL = "cellpose" +MAX_CHANNELS = 3 +"""Cellpose 4.2.1.1 reads at most three channels and drops the rest silently.""" +TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 +"""Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" +NORMALIZE_PERCENTILE = [1.0, 99.0] +NATIVE_SCALE = ( + "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " + "diameter means the model's own scale" +) +IMAGE_SKIPPED = "a mask of this type is already there; not replaced (overwrite is off)" + + +# --- settings and what is asked for ----------------------------------------------------------- + + +@dataclass(frozen=True) +class Settings: + """The inference settings the user chooses. + + Attributes + ---------- + diameter + Cell diameter in **pixels**, or None for the model's native scale (Cellpose 4.2.1.1 + does not estimate a diameter). Never 0. + flow_threshold + Flow error threshold, 0 or more (Cellpose's default 0.4). + cellprob_threshold + Cell probability threshold (Cellpose's default 0). + normalize + Cellpose's own normalisation: each channel to its 1st to 99th percentile. False + passes the stored values unchanged. + batch_size + Tiles run together on the device, 1 or more. + """ + + diameter: float | None = None + flow_threshold: float = 0.4 + cellprob_threshold: float = 0.0 + normalize: bool = True + batch_size: int = 8 + + def __post_init__(self) -> None: + """Refuse a value Cellpose would accept but this brick will not record as it is.""" + if self.diameter is not None and not _positive(self.diameter): + raise SegmentationError( + f"The diameter must be a positive number of pixels, or blank for the model's " + f"native scale; got {self.diameter!r}. Zero is refused: it would silently mean " + "the native scale." + ) + if not _finite(self.flow_threshold) or self.flow_threshold < 0: + raise SegmentationError( + f"The flow threshold must be 0 or more, not {self.flow_threshold!r}." + ) + if not _finite(self.cellprob_threshold): + raise SegmentationError( + f"The cell probability threshold must be a number, not {self.cellprob_threshold!r}." + ) + if not isinstance(self.normalize, bool): + raise SegmentationError("normalize is on or off.") + if ( + isinstance(self.batch_size, bool) + or not isinstance(self.batch_size, int) + or self.batch_size < 1 + ): + raise SegmentationError( + f"The batch size must be a whole number, 1 or more, not {self.batch_size!r}." + ) + + +def _finite(value: object) -> bool: + """Return True for a real number that is neither NaN nor infinite (a bool is not one).""" + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def _positive(value: object) -> bool: + """Return True for a finite number above 0.""" + return _finite(value) and value > 0 # type: ignore[operator] + + +def diameter_from_text(text: str) -> float | None: + """Return the diameter typed in a text field: blank is None (native scale), else pixels. + + Raises + ------ + SegmentationError + For text that is not a positive number (0 included). + """ + if not text.strip(): + return None + try: + value = float(text) + except ValueError: + raise SegmentationError( + f"The diameter {text!r} is not a number. Type pixels (for example 30) or leave it " + "blank." + ) from None + return Settings(diameter=value).diameter + + +# --- one image -------------------------------------------------------------------------------- + + +def eval_arguments(loaded: LoadedModel, settings: Settings) -> dict[str, Any]: + """Return every argument given to ``model.eval``, the effective inference settings. + + ``channel_axis`` is 0: the stack from :meth:`.segmentation_handoff.SegmentationPlan.read` + is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size and the other + values Cellpose would default are given explicitly, so what is recorded is what ran. + """ + return { + "batch_size": settings.batch_size, + "resample": True, + "channel_axis": 0, + "normalize": {"normalize": settings.normalize, "percentile": list(NORMALIZE_PERCENTILE)}, + "diameter": settings.diameter, + "flow_threshold": settings.flow_threshold, + "cellprob_threshold": settings.cellprob_threshold, + "do_3D": False, + "min_size": MIN_SIZE, + "max_size_fraction": MAX_SIZE_FRACTION, + "augment": False, + "tile_overlap": TILE_OVERLAP, + "bsize": loaded.tile_size, + } + + +def check_channel_count(channel_ids: Sequence[str]) -> None: + """Refuse more channels than Cellpose reads (it would silently use the first three).""" + if len(channel_ids) > MAX_CHANNELS: + raise SegmentationError( + f"Cellpose {CELLPOSE_VERSION} reads at most {MAX_CHANNELS} channels and would " + f"silently drop the others by position; {len(channel_ids)} were chosen " + f"({', '.join(channel_ids)}). Choose {MAX_CHANNELS} or fewer." + ) + + +def segment_image(loaded: LoadedModel, settings: Settings, stack: np.ndarray) -> np.ndarray: + """Segment one ``(C, Y, X)`` stack (the chosen channels, in the order chosen). + + Returns + ------- + numpy.ndarray + The 2D integer label image Cellpose returns (0 is background); it is not changed. + + Raises + ------ + SegmentationError + For a stack that is not ``(C, Y, X)`` with 1 to 3 channels, or a result that is not a + 2D label image. + """ + array = np.asarray(stack) + if array.ndim != 3: + raise SegmentationError(f"The stack is {array.ndim}D; Cellpose gets (C, Y, X).") + check_channel_count([f"channel {i}" for i in range(array.shape[0])]) + out = loaded.model.eval(array, **eval_arguments(loaded, settings)) + labels = np.asarray(out[0] if isinstance(out, tuple) else out) + if labels.ndim != 2: + raise SegmentationError(f"Cellpose returned {labels.ndim}D labels; a mask is 2D (Y, X).") + return labels + + +def inference_parameters( + loaded: LoadedModel, settings: Settings, channel_ids: Sequence[str] +) -> dict[str, Any]: + """Return the parameters of a batch for the record: every effective setting, plain JSON. + + The diameter is in pixels, or null with the statement that it is the model's native + scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). + """ + arguments = eval_arguments(loaded, settings) + scale = 1.0 if settings.diameter is None else 30.0 / settings.diameter + return { + **arguments, + "diameter_unit": "pixels" if settings.diameter is not None else NATIVE_SCALE, + "rescale": scale, + "channel_ids_order": list(channel_ids), + "device_type": loaded.device, + "backbone": loaded.backbone, + "use_bfloat16": True, + "cellpose_version": CELLPOSE_VERSION, + "dinov3_commit": loaded.dinov3_commit, + } + + +# --- the batch -------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class SegmentationJob: + """Everything one batch needs: the run, the channels, the model, the settings and the target. + + Attributes + ---------- + inputs, plan + The opened run and its channels resolved once (``resolve_segmentation``). + loaded, settings + The verified model and the inference settings. + mask_type, masks_root + The mask type and the masks folder. + overwrite + Replace masks that are already there (default: skip them). + """ + + inputs: RunInputs + plan: SegmentationPlan + loaded: LoadedModel + settings: Settings + mask_type: str + masks_root: Path + overwrite: bool = False + + +@dataclass(frozen=True) +class BatchResult: + """What a batch did: its record entry and where the record was written. + + Attributes + ---------- + batch + The batch as recorded (one entry per image handled). + record + The record file, or None when no image was handled. + """ + + batch: SegmentationBatch + record: Path | None + + def rows(self) -> tuple[tuple[str, str, str], ...]: + """Return ``(image, status, message)`` for every image: nothing is left out.""" + return tuple((i.image, i.status, i.message) for i in self.batch.images) + + def counts(self) -> dict[str, int]: + """Return how many images were written, skipped and failed.""" + statuses = [i.status for i in self.batch.images] + return {s: statuses.count(s) for s in ("written", "skipped", "failed")} + + +def non_2d_images(inputs: RunInputs) -> tuple[str, ...]: + """Return the images with more than one Z plane or time point (refused: 2D only for now).""" + return tuple(f.relative_path for f in inputs.fovs() if f.z_count > 1 or f.t_count > 1) + + +def _segment_one(job: SegmentationJob, fov: Fov) -> SegmentedImage: + """Segment and write one image; any failure is returned as a ``failed`` entry.""" + try: + labels = segment_image(job.loaded, job.settings, job.plan.read(fov)) + path = write_mask( + job.masks_root, job.mask_type, fov, labels, job.inputs, overwrite=job.overwrite + ) + return SegmentedImage(fov.relative_path, "written", mask_sha256=mask_sha256(path)) + except Exception as exc: # per-image failures are reported in the table, never dropped + return SegmentedImage(fov.relative_path, "failed", f"{type(exc).__name__}: {exc}") + + +def _batch(job: SegmentationJob, batch_id: str, images: list[SegmentedImage]) -> SegmentationBatch: + """Return the record entry of the batch as it stands.""" + loaded = job.loaded + return SegmentationBatch( + batch_id=batch_id, + tool=TOOL, + tool_version=CELLPOSE_VERSION, + model_name=loaded.name, + model_sha256=loaded.sha256, + model_file=loaded.file, + parameters=inference_parameters(loaded, job.settings, job.plan.channel_ids), + channel_ids=job.plan.channel_ids, + device=loaded.device, + run_folder=os.fspath(job.inputs.output_folder), + run_manifest_sha256=file_sha256(job.inputs.output_folder / MANIFEST_FILENAME), + images=tuple(images), + ) + + +def run_batch( + job: SegmentationJob, + fovs: Sequence[Fov] | None = None, + *, + progress: Callable[[int, int, str], None] | None = None, + batch_id: str | None = None, +) -> BatchResult: + """Segment images one at a time, write each mask and record every outcome. + + Images that already have a mask of the type are ``skipped`` (never replaced) unless + ``job.overwrite``; an image that fails is ``failed`` with the error and the batch goes on. + The record is written even when the batch is interrupted, with the images done so far. + + Parameters + ---------- + job + The batch (:class:`SegmentationJob`). + fovs + The images to handle; by default all the run's images. + progress + Called as ``progress(done, total, image)`` before each image and once at the end. + batch_id + The record's batch ID; by default the start time (UTC). + + Raises + ------ + SegmentationError + For a masks folder or mask type the hand-off refuses, or a record that cannot be + written (the masks written stay). + """ + chosen = tuple(job.inputs.fovs() if fovs is None else fovs) + missing = { + f.relative_path for f in images_to_segment(job.inputs, job.mask_type, job.masks_root) + } + started = batch_id or datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + entries: list[SegmentedImage] = [] + try: + for done, fov in enumerate(chosen): + if progress is not None: + progress(done, len(chosen), fov.relative_path) + if job.overwrite or fov.relative_path in missing: + entries.append(_segment_one(job, fov)) + else: + entries.append(SegmentedImage(fov.relative_path, "skipped", IMAGE_SKIPPED)) + if progress is not None: + progress(len(chosen), len(chosen), "") + finally: + batch = _batch(job, started, entries) + record = write_record(job.masks_root, job.mask_type, batch) if entries else None + return BatchResult(batch, record) + + +# --- the run, the channels and what is shown -------------------------------------------------- + + +def open_run(run_folder: str) -> RunInputs: + """Open the run in ``run_folder`` (preprocessing's own checks; refusals are unchanged). + + Raises + ------ + SegmentationError + For a blank folder. + RunInputsError + For a run that cannot be opened (:meth:`.run_inputs.RunInputs.open`). + """ + if not run_folder.strip(): + raise SegmentationError("Give the run's output folder (the one holding run_manifest.json).") + return RunInputs.open(Path(run_folder.strip())) + + +def channel_coverage(inputs: RunInputs) -> dict[str, tuple[int, int]]: + """Return ``{channel ID: (images that have it, images)}``, in the order first met.""" + fovs = inputs.fovs() + order = dict.fromkeys(c for f in fovs for c in (f.channel_ids or ())) + return {c: (sum(c in (f.channel_ids or ()) for f in fovs), len(fovs)) for c in order} + + +def display_contrast(stack: np.ndarray, low: float = 1.0, high: float = 99.0) -> np.ndarray: + """Return ``stack`` as float32 in 0 to 1, each channel stretched between two percentiles. + + For **display only** (the preview): a new array, the stack is never changed, and nothing + of it is ever written. A channel with no spread shows as 0. + """ + shown = np.zeros(np.shape(stack), np.float32) + for index, channel in enumerate(np.asarray(stack, dtype=np.float64)): + lo, hi = np.percentile(channel, [low, high]) + if hi > lo: + shown[index] = np.clip((channel - lo) / (hi - lo), 0.0, 1.0) + return shown + + +def label_outlines(labels: np.ndarray) -> np.ndarray: + """Return a boolean image that is True on the boundary pixels of every label (display).""" + lab = np.asarray(labels) + edge = np.zeros(lab.shape, bool) + edge[:, :-1] |= lab[:, :-1] != lab[:, 1:] + edge[:-1, :] |= lab[:-1, :] != lab[1:, :] + return edge & (lab > 0) + + +def next_steps_lines(mask_type: str, masks_root: str | os.PathLike) -> tuple[str, ...]: + """Return what to do after the masks are made, as lines of text. + + Raises + ------ + SegmentationError + For a mask type preprocessing would refuse. + """ + check_mask_type(mask_type) + return ( + f"1. Declare the new mask type in the experiment description, in the preprocessing " + f"notebook (step 4, Masks) or by adding to morphobricks.toml: [masks.{mask_type}] " + f'source_type = "{mask_type}" representation = "instances".', + "2. Save the description.", + f"3. Run preprocessing again with the masks folder {os.fspath(masks_root)} (the " + "histograms are reused; the masks are read and checked).", + "4. Describe the masks (step 4 of the preprocessing notebook).", + "5. Then continue with MorphoFeature.", + ) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py new file mode 100644 index 0000000..f2d37bb --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -0,0 +1,368 @@ +"""Loading a Cellpose model without substitution, device fallback or silent download. + +Part of :mod:`.segmentation_cellpose` (which re-exports these names). Cellpose, ``torch`` and +``dinov3`` are imported only inside the functions here, so importing this module stays inert; +the pinned release is :data:`CELLPOSE_VERSION` and another one is refused. + +Cellpose 4.2.1.1 replaces a model name or path it cannot find by ``cpsam_v2`` with a log +warning, turns an unavailable GPU into the CPU, and downloads uncached built-in weights. Each +is checked here: the model is one of :data:`BUILTIN_MODELS` or an existing file (validated +before loading); the weights file the loaded model reports must be the one asked for; every +weight must sit on the stated device (an unavailable one is refused up front); and uncached +weights are downloaded only with ``allow_download``. The weights file is hashed for the record. +""" + +from __future__ import annotations + +import importlib +import importlib.metadata +import importlib.util +import json +import os +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path +from types import ModuleType + +from ._io import file_sha256 +from .segmentation_record import DEVICES, SegmentationError + +CELLPOSE_VERSION = "4.2.1.1" +"""The only Cellpose release this brick runs (the notebook installs it).""" +BUILTIN_MODELS = ("cpsam_v2", "cpsam", "cpdino", "cpdino-vitb") +"""The built-in models of Cellpose 4.2.1.1, the first being the default.""" +DEFAULT_MODEL = BUILTIN_MODELS[0] +DINO_MODELS = ("cpdino", "cpdino-vitb") +"""The built-in models that need the DINOv3 package (:data:`DINOV3_COMMIT`).""" +DINOV3_URL = "https://github.com/facebookresearch/dinov3" +DINOV3_COMMIT = "6876159a11b4df116f30f667f8c9888617df0751" +"""The DINOv3 commit installed for ``cpdino`` models (the head of its default branch on +22 November 2026); a model that needs DINOv3 runs only with exactly this commit installed.""" +SAM_TILE, DINO_TILE = 256, 384 +"""The tile size (``bsize``) of a SAM model and of a DINOv3 model.""" + + +@dataclass(frozen=True) +class ModelChoice: + """A model that passed :func:`choose_model`. + + Attributes + ---------- + name + The built-in name, or the file name of a custom model. + path + The custom model's absolute path, or None for a built-in model. + """ + + name: str + path: Path | None = None + + @property + def builtin(self) -> bool: + """Return True for one of :data:`BUILTIN_MODELS`.""" + return self.path is None + + +def choose_model(model: str | os.PathLike) -> ModelChoice: + """Validate the model asked for, before anything is loaded: a built-in name or a file. + + Cellpose 4.2.1.1 replaces a name or path it cannot find by ``cpsam_v2``; here that is a + refusal. The text must be exactly one of :data:`BUILTIN_MODELS` or the path of an existing + file (a folder is refused). Nothing is guessed from a near miss. + + Raises + ------ + SegmentationError + Naming the four models and the file rule. + """ + text = os.fspath(model) + if text in BUILTIN_MODELS: + return ModelChoice(text) + path = Path(text).expanduser() + if path.is_file(): + return ModelChoice(path.name, path.resolve()) + what = "is a folder, not a model file" if path.is_dir() else "is not a model name or a file" + raise SegmentationError( + f"The model {text!r} {what}. Choose one of {', '.join(BUILTIN_MODELS)}, or give the path " + "of an existing model file. Cellpose would silently use cpsam_v2 instead; this notebook " + "never substitutes a model. (Cellpose 3 models such as cyto3 are not supported by " + f"Cellpose {CELLPOSE_VERSION}.)" + ) + + +# --- Cellpose, torch and DINOv3, imported only here ------------------------------------------- + + +def installed_version(distribution: str) -> str | None: + """Return the installed version of a distribution, or None (a seam for the tests).""" + try: + return importlib.metadata.version(distribution) + except importlib.metadata.PackageNotFoundError: + return None + + +def _cellpose_models() -> ModuleType: + """Import ``cellpose.models`` of the pinned release, or refuse.""" + found = installed_version("cellpose") + if found != CELLPOSE_VERSION: + have = f"version {found} is installed" if found else "it is not installed" + raise SegmentationError( + f"This notebook runs Cellpose {CELLPOSE_VERSION}; {have}. Run the install cell, " + "then restart the runtime if it asks." + ) + return importlib.import_module("cellpose.models") + + +def _torch() -> ModuleType: + """Import torch, or refuse.""" + try: + return importlib.import_module("torch") + except ImportError: + raise SegmentationError( + "PyTorch is not installed. Run the install cell (Cellpose installs it)." + ) from None + + +def check_device(device: str) -> None: + """Refuse a device that is not one of :data:`.segmentation_record.DEVICES` or not available. + + There is no fallback: a GPU that is not there is a refusal that names the CPU as a choice + for the user to make, never a silent switch. + + Raises + ------ + SegmentationError + For an unknown device, or ``cuda`` or ``mps`` where PyTorch finds none. + """ + if device not in DEVICES: + raise SegmentationError(f"The device must be one of {', '.join(DEVICES)}, not {device!r}.") + if device == "cpu": + return + torch = _torch() + here = torch.cuda.is_available() if device == "cuda" else torch.backends.mps.is_available() + if not here: + raise SegmentationError( + f"The device {device} was asked for but is not available here. Nothing falls back " + "to the CPU. Switch the runtime to one with a GPU (Google Colab: Runtime > Change " + "runtime type), or choose the device cpu on purpose (much slower)." + ) + + +def weights_file(name: str) -> Path: + """Return where Cellpose keeps the weights of built-in model ``name`` (it may not exist yet).""" + return Path(os.fspath(_cellpose_models().MODEL_DIR)) / name + + +def installed_dinov3_commit() -> str | None: + """Return the Git commit the installed DINOv3 package came from, or None when unknown. + + Read from the ``direct_url.json`` that ``pip install git+...`` leaves in the package's + metadata; a package with no such record has an unknown commit and is never assumed to be + the pinned one. + """ + importlib.invalidate_caches() + for name in importlib.metadata.packages_distributions().get("dinov3", []): + text = importlib.metadata.distribution(name).read_text("direct_url.json") + if text: + commit = json.loads(text).get("vcs_info", {}).get("commit_id") + if commit: + return str(commit) + return None + + +def dinov3_install_command() -> list[str]: + """Return the ``pip`` command that installs DINOv3 at :data:`DINOV3_COMMIT`.""" + spec = f"git+{DINOV3_URL}@{DINOV3_COMMIT}" + return [sys.executable, "-m", "pip", "install", "--disable-pip-version-check", spec] + + +def install_dinov3() -> None: + """Install DINOv3 at the pinned commit (only ever called when the user chooses to). + + Raises + ------ + SegmentationError + When the installation fails. + """ + try: + subprocess.run(dinov3_install_command(), check=True) + except (subprocess.CalledProcessError, OSError) as exc: + raise SegmentationError( + f"DINOv3 could not be installed ({exc}). Check the output and the internet access." + ) from exc + + +def check_dinov3(models: ModuleType) -> str: + """Return the commit of the installed DINOv3 if it is the pinned one, else refuse. + + Cellpose imports DINOv3 when it is first imported, so DINOv3 installed after that needs a + restart of the runtime (the check says so). + """ + command = " ".join(dinov3_install_command()[2:]) + commit = installed_dinov3_commit() + if commit != DINOV3_COMMIT: + found = ( + f"commit {commit} is installed" + if commit + else "none is installed, or its commit is unknown" + ) + raise SegmentationError( + f"The DINOv3 models need DINOv3 at commit {DINOV3_COMMIT}; {found}. Tick the " + f"installation in the notebook (it runs: {command}), then restart the runtime." + ) + if not hasattr(models, "CPDINO"): + raise SegmentationError( + "DINOv3 is installed but Cellpose was imported before it. Restart the runtime, then " + "run the cells again." + ) + return commit + + +# --- loading and verifying a model ------------------------------------------------------------ + + +@dataclass(frozen=True) +class LoadedModel: + """A Cellpose model that was loaded and verified to be the one asked for. + + Attributes + ---------- + model + The Cellpose model object. + name, file + The name recorded (built-in name or the custom file's name) and the weights file + (its name for a built-in model, its absolute path for a custom one). + path + The weights file that was loaded. + sha256 + The SHA-256 of that file. + device + ``cuda``, ``cpu`` or ``mps``: where the model sits, as verified after loading. + backbone + Cellpose's name of the network (``sam_vitl``, ``dino_vitl``, ...). + tile_size + The tile size (``bsize``) used: 256 for a SAM network, 384 otherwise. + dinov3_commit + The DINOv3 commit for a DINOv3 network, else None. + """ + + model: object + name: str + file: str + path: Path + sha256: str + device: str + backbone: str + tile_size: int + dinov3_commit: str | None = None + + +def _expected(models: ModuleType, choice: ModelChoice, allow_download: bool) -> tuple[Path, str]: + """Return the weights file this model must be, and what to hand to Cellpose to load it. + + A built-in model already on disk is handed over by its absolute path, so Cellpose looks + nowhere else (not in the working folder, not in its list of user models) and cannot + download. One that is not on disk is handed over by name only when ``allow_download``. + """ + if choice.path is not None: + return choice.path, os.fspath(choice.path) + expected = Path(os.fspath(models.MODEL_DIR)) / choice.name + if expected.is_file(): + return expected, os.fspath(expected) + if not allow_download: + raise SegmentationError( + f"The weights of {choice.name} are not on this computer ({expected}). The built-in " + "weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. " + "Allow the download on purpose (tick it in the notebook) and run the cell again." + ) + if os.path.lexists(choice.name): + raise SegmentationError( + f"A file or folder named {choice.name} is in the working folder, and Cellpose would " + "load it instead of downloading the model. Change to another working folder." + ) + return expected, choice.name + + +def _construct(models: ModuleType, request: str, device: str) -> object: + """Build the Cellpose model on the stated device; any Cellpose failure is a refusal.""" + torch = _torch() + try: + return models.CellposeModel( + gpu=device != "cpu", + pretrained_model=request, + device=torch.device(device), + use_bfloat16=True, + ) + except Exception as exc: # Cellpose raises many types; none may leave a model half-chosen + raise SegmentationError( + f"Cellpose could not load {request}: {type(exc).__name__}: {exc}" + ) from exc + + +def _device_types(loaded: object) -> set[str]: + """Return the device types the loaded model reports (and its first weight, when it has one).""" + found = {str(loaded.device.type)} + parameters = getattr(getattr(loaded, "net", None), "parameters", None) + first = next(iter(parameters()), None) if callable(parameters) else None + if first is not None: + found.add(str(first.device.type)) + return found + + +def _verify(loaded: object, expected: Path, device: str, choice: ModelChoice) -> None: + """Refuse a model that is not the file or device asked for.""" + got = os.fspath(getattr(loaded, "pretrained_model", "")) + if not got or Path(got).resolve() != expected.resolve(): + raise SegmentationError( + f"Cellpose loaded {got or 'an unknown file'} instead of {expected} for {choice.name}: " + "it substituted another model. Nothing was segmented." + ) + if _device_types(loaded) != {device}: + raise SegmentationError( + f"The device {device} was asked for but the model sits on " + f"{', '.join(sorted(_device_types(loaded)))}. Nothing falls back to another device." + ) + + +def load_model( + model: str | os.PathLike, device: str, *, allow_download: bool = False +) -> LoadedModel: + """Load a Cellpose model, verified to be the weights file and device asked for. + + The order is: the model and device are validated, Cellpose's version is checked, the + weights must be on disk (or the download allowed), a DINOv3 model needs the pinned + DINOv3; then the model is loaded and **verified** (the weights file it reports is the one + asked for; every weight sits on the stated device), and the weights file is hashed. + + Raises + ------ + SegmentationError + For an unknown model or one that does not exist, a device that is not available or + not the one the model sits on, a substituted model, weights that are not downloaded + (and no ``allow_download``), another Cellpose version or another DINOv3 commit. + """ + choice = choose_model(model) + check_device(device) + models = _cellpose_models() + dino = choice.name in DINO_MODELS + commit = check_dinov3(models) if dino else None + expected, request = _expected(models, choice, allow_download) + loaded = _construct(models, request, device) + _verify(loaded, expected, device, choice) + backbone = getattr(loaded, "backbone", None) + if not isinstance(backbone, str): + raise SegmentationError("The loaded model does not say which network it is; refused.") + if backbone.startswith("dino") and commit is None: + commit = check_dinov3(models) + return LoadedModel( + model=loaded, + name=choice.name, + file=os.fspath(expected) if choice.path else expected.name, + path=expected, + sha256=file_sha256(expected), + device=device, + backbone=backbone, + tile_size=SAM_TILE if backbone == "sam_vitl" else DINO_TILE, + dinov3_commit=commit, + ) diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py new file mode 100644 index 0000000..7b4d422 --- /dev/null +++ b/tests/cellpose_stub.py @@ -0,0 +1,134 @@ +"""A stand-in for Cellpose 4.2.1.1 and torch, injected through ``sys.modules``. + +Cellpose is not a dependency of the brick and is not installed in CI. The stand-in keeps what +the real ``CellposeModel`` does that matters here, read from the 4.2.1.1 source: a name or path +it cannot find is replaced by ``cpsam_v2`` (downloaded if absent), a built-in name is looked for +in ``MODEL_DIR`` and fetched when missing, and ``pretrained_model`` / ``device`` / ``backbone`` +are set on the loaded model. Its ``eval`` records every call (the stack and the keywords) and +returns a fixed label image, so a test sees exactly what Cellpose was given. +""" + +import sys +import types +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +from morphobricks_preprocessing import segmentation_cellpose_model as model_module + +BUILTINS = ("cpsam_v2", "cpsam", "cpdino", "cpdino-vitb") + + +def weights_bytes(name): + return f"weights of {name}".encode() + + +def labels_for(shape): + labels = np.zeros(shape, np.uint16) + labels[1:4, 1:4] = 1 + labels[5:7, 5:7] = 2 + return labels + + +class Device: + def __init__(self, type): + self.type = type + + +def model_class(state): + """Return the stand-in ``CellposeModel`` class bound to ``state``.""" + + class Model: + def __init__(self, gpu=False, pretrained_model="cpsam_v2", device=None, **kwargs): + state.constructed.append( + SimpleNamespace(gpu=gpu, pretrained_model=pretrained_model, device=device, **kwargs) + ) + self.pretrained_model = state.substitute or self._resolve(pretrained_model) + self.device = Device(state.device_type or device.type) + dino = "dino" in Path(self.pretrained_model).name + self.backbone = "dino_vitl" if dino else "sam_vitl" + + @staticmethod + def _resolve(requested): + if Path(requested).exists(): + return requested + path = state.models_dir / requested + if requested not in BUILTINS: + return str(state.models_dir / "cpsam_v2") # the silent substitution + if not path.exists(): + state.downloaded.append(requested) + path.write_bytes(weights_bytes(requested)) + return str(path) + + def eval(self, x, **kwargs): + state.calls.append(SimpleNamespace(x=np.array(x), kwargs=kwargs)) + if state.fail is not None: + state.fail(x) + return labels_for(x.shape[1:]), [], [] + + return Model + + +def modules(state): + """Return the fake ``cellpose``, ``cellpose.models`` and ``torch`` modules.""" + models = types.ModuleType("cellpose.models") + models.MODEL_DIR = state.models_dir + models.CellposeModel = model_class(state) + if state.has_cpdino: + models.CPDINO = object + package = types.ModuleType("cellpose") + package.models = models + torch = types.ModuleType("torch") + torch.device = Device + torch.cuda = SimpleNamespace(is_available=lambda: state.cuda) + torch.backends = SimpleNamespace(mps=SimpleNamespace(is_available=lambda: state.mps)) + return {"cellpose": package, "cellpose.models": models, "torch": torch} + + +def install(monkeypatch, tmp_path, **options): + """Install the stand-in; return its state (calls, constructed, and switches to flip). + + Switches (set on the returned state before loading): ``cuda`` / ``mps`` availability, + ``substitute`` (the path every loaded model reports, whatever was asked), ``device_type`` + (the device every loaded model reports), ``fail`` (a function of the stack that raises), + ``version`` and ``dinov3_commit``. + """ + models_dir = tmp_path / "cellpose_models" + models_dir.mkdir(exist_ok=True) + state = SimpleNamespace( + calls=[], + constructed=[], + downloaded=[], + models_dir=models_dir, + cuda=False, + mps=False, + substitute=None, + device_type=None, + fail=None, + version="4.2.1.1", + dinov3_commit=model_module.DINOV3_COMMIT, + has_cpdino=True, + ) + for name, value in options.items(): + setattr(state, name, value) + for name in BUILTINS[:2]: + (models_dir / name).write_bytes(weights_bytes(name)) + for name, module in modules(state).items(): + monkeypatch.setitem(sys.modules, name, module) + real_version = model_module.installed_version + monkeypatch.setattr( + model_module, + "installed_version", + lambda name: state.version if name == "cellpose" else real_version(name), + ) + monkeypatch.setattr(model_module, "installed_dinov3_commit", lambda: state.dinov3_commit) + return state + + +def custom_model(tmp_path, name="my_model"): + """Write a custom model file and return its path.""" + path = tmp_path / "custom" / name + path.parent.mkdir(exist_ok=True) + path.write_bytes(weights_bytes(name)) + return path diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py new file mode 100644 index 0000000..54e674c --- /dev/null +++ b/tests/test_segmentation_cellpose.py @@ -0,0 +1,529 @@ +"""The Cellpose glue (step 2 of the segmentation hand-off), against a stand-in for Cellpose. + +Cellpose 4.2.1.1 substitutes a model it cannot find, falls back from the GPU to the CPU and +downloads uncached weights; the stand-in (``tests/cellpose_stub.py``) does the same, so each +refusal is tested against the behaviour it guards. The run is the hand-off tests' mixed-channel +case: DNA, ACTIN and TUB everywhere and a fourth stain listed first in one repeat, so a stain's +C index differs between repeats while its pixels (``LEVELS``) tell which stain a plane holds. +""" + +import dataclasses +import hashlib +import json +import subprocess +import sys +from types import SimpleNamespace + +import numpy as np +import pytest + +from cellpose_stub import custom_model, install, weights_bytes +from described_tree import check_masks, run_described +from description_tree import MAPPING +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing.manifest import MANIFEST_FILENAME +from morphobricks_preprocessing.run_inputs import RunInputs +from morphobricks_preprocessing.segmentation_handoff import ( + images_to_segment, + mask_path, + resolve_segmentation, +) +from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record +from test_segmentation_handoff import EXTRA_FIRST, MASKS_SECTION, REPEAT_2 +from test_stage3_channels import LEVELS, described_run, extra_stain + + +@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] + base = out.parent + return SimpleNamespace( + inputs=RunInputs.open(out), + out=out, + experiment=base / "exp", + masks=base / "masks", + data=data, + ) + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def make_job(run, ids=("TUB", "DNA"), model="cpsam_v2", device="cpu", settings=None, **extra): + loaded = cp.load_model(model, device) + return cp.SegmentationJob( + inputs=run.inputs, + plan=resolve_segmentation(run.inputs, ids), + loaded=loaded, + settings=settings or cp.Settings(), + mask_type="Cells", + masks_root=run.masks, + **extra, + ) + + +# inert import ------------------------------------------------------------------------------ + + +def test_importing_the_modules_imports_no_cellpose_torch_or_dinov3(): + code = ( + "import sys\n" + "import morphobricks_preprocessing\n" + "import morphobricks_preprocessing.segmentation_cellpose\n" + "import morphobricks_preprocessing.segmentation_cellpose_model\n" + "bad = [m for m in ('cellpose', 'torch', 'dinov3') if m in sys.modules]\n" + "assert not bad, bad\n" + ) + done = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True) + assert done.returncode == 0, done.stderr + + +# the model is validated before it is loaded (audit B7) -------------------------------------- + + +@pytest.mark.parametrize("name", ["cpsam_v2", "cpsam", "cpdino", "cpdino-vitb"]) +def test_the_four_built_in_names_are_accepted(name): + assert cp.choose_model(name) == cp.ModelChoice(name) + assert cp.DEFAULT_MODEL == "cpsam_v2" and cp.BUILTIN_MODELS[0] == "cpsam_v2" + + +@pytest.mark.parametrize("name", ["cpsam_v3", "cyto3", "nuclei", "CPSAM", "cpsam ", "", "no/such"]) +def test_a_name_or_path_that_is_not_a_model_is_refused_before_loading(stub, name): + with pytest.raises(SegmentationError, match="never substitutes a model"): + cp.load_model(name, "cpu") + assert stub.constructed == [] and stub.downloaded == [] # nothing loaded, nothing fetched + + +def test_a_custom_model_is_an_existing_file_not_a_folder(stub, tmp_path): + path = custom_model(tmp_path) + choice = cp.choose_model(path) + assert choice == cp.ModelChoice("my_model", path.resolve()) and not choice.builtin + with pytest.raises(SegmentationError, match="is a folder"): + cp.choose_model(path.parent) + with pytest.raises(SegmentationError, match="not a model name or a file"): + cp.choose_model(path.parent / "missing") + + +def test_a_built_in_model_on_disk_is_loaded_by_its_absolute_path(stub): + loaded = cp.load_model("cpsam", "cpu") + (built,) = stub.constructed + assert built.pretrained_model == str( + stub.models_dir / "cpsam" + ) # no name Cellpose could resolve + assert (loaded.name, loaded.file, loaded.device, loaded.tile_size) == ( + "cpsam", + "cpsam", + "cpu", + 256, + ) + + +def test_a_custom_model_is_loaded_by_its_absolute_path_and_recorded_by_it(stub, tmp_path): + path = custom_model(tmp_path) + loaded = cp.load_model(str(path), "cpu") + assert stub.constructed[0].pretrained_model == str(path.resolve()) + assert loaded.name == "my_model" and loaded.file == str(path.resolve()) + assert loaded.sha256 == hashlib.sha256(weights_bytes("my_model")).hexdigest() + + +def test_a_substituted_model_is_refused_after_loading(stub, tmp_path): + stub.substitute = str(stub.models_dir / "cpsam_v2") # Cellpose's silent fallback + with pytest.raises(SegmentationError, match="substituted another model"): + cp.load_model("cpsam", "cpu") + with pytest.raises(SegmentationError, match="substituted another model"): + cp.load_model(str(custom_model(tmp_path)), "cpu") + + +def test_the_stand_in_really_substitutes_what_the_checks_guard_against(stub): + # The unguarded call: an unknown name silently gives cpsam_v2 (4.2.1.1, models.py). + model = sys.modules["cellpose.models"].CellposeModel( + pretrained_model="no_such_model", device=sys.modules["torch"].device("cpu") + ) + assert model.pretrained_model.endswith("cpsam_v2") + + +# the device is explicit and verified (audit B8) --------------------------------------------- + + +def test_a_gpu_that_is_not_available_is_refused_and_never_replaced_by_the_cpu(stub): + for device in ("cuda", "mps"): + with pytest.raises(SegmentationError, match=f"{device} was asked for but is not available"): + cp.load_model("cpsam_v2", device) + assert stub.constructed == [] + + +def test_a_model_that_sits_on_another_device_than_asked_is_refused(stub): + stub.cuda, stub.device_type = True, "cpu" # Cellpose's silent GPU -> CPU fallback + with pytest.raises(SegmentationError, match="cuda was asked for but the model sits on cpu"): + cp.load_model("cpsam_v2", "cuda") + + +def test_the_gpu_is_used_when_asked_and_present(stub): + stub.cuda = True + loaded = cp.load_model("cpsam_v2", "cuda") + assert loaded.device == "cuda" and stub.constructed[0].gpu is True + assert stub.constructed[0].device.type == "cuda" + assert cp.load_model("cpsam_v2", "cpu").device == "cpu" + with pytest.raises(SegmentationError, match="must be one of"): + cp.load_model("cpsam_v2", "gpu") + + +# no silent download, the weights are hashed (audit B9) -------------------------------------- + + +def test_weights_that_are_not_on_disk_are_not_downloaded_unless_allowed(stub): + (stub.models_dir / "cpsam").unlink() + with pytest.raises(SegmentationError, match="Hugging Face"): + cp.load_model("cpsam", "cpu") + assert stub.constructed == [] and stub.downloaded == [] + loaded = cp.load_model("cpsam", "cpu", allow_download=True) + assert stub.downloaded == ["cpsam"] and stub.constructed[0].pretrained_model == "cpsam" + assert loaded.sha256 == hashlib.sha256(weights_bytes("cpsam")).hexdigest() + + +def test_a_file_in_the_working_folder_that_shadows_a_download_is_refused( + stub, tmp_path, monkeypatch +): + (stub.models_dir / "cpsam").unlink() + (tmp_path / "cpsam").write_bytes(b"not the model") + monkeypatch.chdir(tmp_path) + with pytest.raises(SegmentationError, match="working folder"): + cp.load_model("cpsam", "cpu", allow_download=True) + assert stub.constructed == [] + + +@pytest.mark.parametrize("found", [None, "4.2.0", "4.3.0"]) +def test_another_cellpose_version_or_none_is_refused(stub, found): + stub.version = found + with pytest.raises(SegmentationError, match="runs Cellpose 4.2.1.1"): + cp.load_model("cpsam_v2", "cpu") + assert stub.constructed == [] + + +def test_the_model_name_file_and_weights_hash_are_in_the_record(run, stub): + job = make_job(run) + result = cp.run_batch(job, batch_id="b1") + (batch,) = read_record(run.masks, "Cells").batches + assert batch == result.batch + assert (batch.tool, batch.tool_version) == ("cellpose", "4.2.1.1") + assert (batch.model_name, batch.model_file) == ("cpsam_v2", "cpsam_v2") + assert batch.model_sha256 == hashlib.sha256(weights_bytes("cpsam_v2")).hexdigest() + assert batch.device == "cpu" + manifest = (run.out / MANIFEST_FILENAME).read_bytes() + assert batch.run_manifest_sha256 == hashlib.sha256(manifest).hexdigest() + + +# DINOv3 models: installed only when chosen, at a pinned commit ------------------------------ + + +def test_the_dinov3_install_command_pins_the_commit(): + command = model_module.dinov3_install_command() + assert command[1:4] == ["-m", "pip", "install"] + assert command[-1] == f"git+https://github.com/facebookresearch/dinov3@{cp.DINOV3_COMMIT}" + assert len(cp.DINOV3_COMMIT) == 40 + + +@pytest.mark.parametrize("commit", [None, "0" * 40]) +def test_a_dino_model_needs_the_pinned_dinov3_commit(stub, commit): + stub.dinov3_commit = commit + with pytest.raises(SegmentationError, match=f"commit {cp.DINOV3_COMMIT}.*pip install"): + cp.load_model("cpdino", "cpu", allow_download=True) + assert stub.constructed == [] + cp.load_model("cpsam_v2", "cpu") # a SAM model needs no DINOv3 at all + + +def test_a_dino_model_needs_cellpose_to_have_imported_dinov3(monkeypatch, tmp_path): + state = install(monkeypatch, tmp_path, has_cpdino=False) + with pytest.raises(SegmentationError, match="Restart the runtime"): + cp.load_model("cpdino-vitb", "cpu", allow_download=True) + assert state.constructed == [] + + +def test_a_dino_model_records_the_dinov3_commit(run, stub): + loaded = cp.load_model("cpdino", "cpu", allow_download=True) + assert loaded.dinov3_commit == cp.DINOV3_COMMIT and loaded.tile_size == 384 + assert stub.downloaded == ["cpdino"] + params = cp.inference_parameters(loaded, cp.Settings(), ("DNA",)) + assert params["dinov3_commit"] == cp.DINOV3_COMMIT and params["bsize"] == 384 + + +def test_dinov3_is_installed_only_when_asked_and_a_failure_is_refused(monkeypatch): + ran = [] + monkeypatch.setattr(model_module.subprocess, "run", lambda cmd, check: ran.append(cmd)) + assert ran == [] # nothing ran on import or on choosing a model + model_module.install_dinov3() + assert ran == [model_module.dinov3_install_command()] + + def failing(cmd, check): + raise subprocess.CalledProcessError(1, cmd) + + monkeypatch.setattr(model_module.subprocess, "run", failing) + with pytest.raises(SegmentationError, match="could not be installed"): + model_module.install_dinov3() + + +# channels by ID, channel_axis=0 (audit: channels) ------------------------------------------- + + +def test_channel_axis_is_0_and_the_stack_follows_the_requested_ids_on_a_mixed_run(run, stub): + job = make_job(run, ids=("TUB", "DNA")) + result = cp.run_batch(job, batch_id="b1") + fovs = run.inputs.fovs() + assert result.counts() == {"written": len(fovs), "skipped": 0, "failed": 0} + assert {f.repeat_group for f in fovs} >= {REPEAT_2} # the repeat that stores EXTRA first + assert len(stub.calls) == len(fovs) + for call in stub.calls: + assert call.kwargs["channel_axis"] == 0 + assert call.x.shape == (2, 8, 8) + tub, dna = call.x + assert LEVELS["TUB"] <= tub.min() and tub.max() < LEVELS["TUB"] + 20 + assert LEVELS["DNA"] <= dna.min() and dna.max() < LEVELS["DNA"] + 20 + + +def test_three_channels_come_in_the_order_given(run, stub): + cp.run_batch(make_job(run, ids=("DNA", "ACTIN", "TUB")), batch_id="b1") + assert len(stub.calls) == len(run.inputs.fovs()) + for call in stub.calls: + assert call.x.shape == (3, 8, 8) + for plane, stain in zip(call.x, ("DNA", "ACTIN", "TUB"), strict=True): + assert LEVELS[stain] <= plane.min() and plane.max() < LEVELS[stain] + 20 + + +def test_a_channel_some_images_lack_is_refused_with_the_resolvers_message(run, stub): + with pytest.raises(Exception) as caught: + resolve_segmentation(run.inputs, ("DNA", "EXTRA")) + assert getattr(caught.value, "code", None) == "A_SCOPE_INCOMPLETE" + assert stub.calls == [] + + +def test_more_than_three_channels_are_refused_because_cellpose_drops_the_rest(stub): + cp.check_channel_count(("a", "b", "c")) + with pytest.raises(SegmentationError, match="at most 3 channels"): + cp.check_channel_count(("a", "b", "c", "d")) + loaded = cp.load_model("cpsam_v2", "cpu") + with pytest.raises(SegmentationError, match="at most 3 channels"): + cp.segment_image(loaded, cp.Settings(), np.zeros((4, 8, 8), np.uint8)) + assert stub.calls == [] + with pytest.raises(SegmentationError, match="Cellpose gets"): + cp.segment_image(loaded, cp.Settings(), np.zeros((8, 8), np.uint8)) + + +def test_coverage_names_how_many_images_have_each_channel(run): + coverage = cp.channel_coverage(run.inputs) + fovs = run.inputs.fovs() + stained = sum(f.repeat_group == REPEAT_2 for f in fovs) + assert list(coverage) == ["DNA", "ACTIN", "TUB", "EXTRA"] # the order first met + assert coverage["EXTRA"] == (stained, len(fovs)) and coverage["DNA"] == (len(fovs),) * 2 + + +# the diameter and the other settings (audit B7 effective settings) --------------------------- + + +def test_a_blank_diameter_is_the_native_scale_and_is_recorded_as_such(run, stub): + result = cp.run_batch(make_job(run), batch_id="b1") + assert all(call.kwargs["diameter"] is None for call in stub.calls) + params = result.batch.parameters + assert params["diameter"] is None and params["rescale"] == 1.0 + assert ( + "native scale" in params["diameter_unit"] and "does not estimate" in params["diameter_unit"] + ) + assert cp.diameter_from_text(" ") is None + + +def test_a_diameter_is_in_pixels_and_its_scale_is_recorded(run, stub): + result = cp.run_batch(make_job(run, settings=cp.Settings(diameter=40)), batch_id="b1") + assert all(call.kwargs["diameter"] == 40 for call in stub.calls) + assert result.batch.parameters["diameter_unit"] == "pixels" + assert result.batch.parameters["rescale"] == 0.75 + assert cp.diameter_from_text("30.5") == 30.5 + + +@pytest.mark.parametrize("text", ["0", "-3", "nan", "inf", "abc", "0.0"]) +def test_a_diameter_of_zero_or_not_a_positive_number_is_refused(text): + with pytest.raises(SegmentationError, match="diameter"): + cp.diameter_from_text(text) + for value in (0, -1, float("nan"), float("inf")): + with pytest.raises(SegmentationError, match="positive number of pixels"): + cp.Settings(diameter=value) + + +@pytest.mark.parametrize( + "changes", + [ + {"flow_threshold": -0.1}, + {"flow_threshold": float("nan")}, + {"cellprob_threshold": float("inf")}, + {"normalize": 1}, + {"batch_size": 0}, + {"batch_size": 2.5}, + ], +) +def test_other_settings_are_checked(changes): + with pytest.raises(SegmentationError): + cp.Settings(**changes) + + +def test_every_effective_setting_is_in_the_record(run, stub): + settings = cp.Settings( + diameter=25, flow_threshold=0.2, cellprob_threshold=-1.5, normalize=False, batch_size=4 + ) + batch = cp.run_batch(make_job(run, settings=settings), batch_id="b1").batch + params = read_record(run.masks, "Cells").batches[0].parameters + assert params == batch.parameters + assert (params["flow_threshold"], params["cellprob_threshold"]) == (0.2, -1.5) + assert params["normalize"] == {"normalize": False, "percentile": [1.0, 99.0]} + assert (params["batch_size"], params["bsize"], params["tile_overlap"]) == (4, 256, 0.1) + assert (params["device_type"], params["cellpose_version"]) == ("cpu", "4.2.1.1") + assert params["channel_axis"] == 0 and params["do_3D"] is False + assert params["channel_ids_order"] == ["TUB", "DNA"] and batch.channel_ids == ("TUB", "DNA") + for key in ("flow_threshold", "cellprob_threshold", "batch_size", "bsize", "normalize"): + assert stub.calls[0].kwargs[key] == params[key] # what ran is what was recorded + + +# per image: written, skipped or failed, never silently dropped ------------------------------- + + +def test_the_final_table_has_every_image_with_written_skipped_and_failed(run, stub): + fovs = run.inputs.fovs() + cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="first") # one mask exists already + stub.calls.clear() + + def fail_second(stack): + if len(stub.calls) == 2: + raise RuntimeError("out of memory") + + stub.fail = fail_second + result = cp.run_batch(make_job(run), batch_id="second") + rows = {image: (status, message) for image, status, message in result.rows()} + assert sorted(rows) == sorted(f.relative_path for f in fovs) # nothing left out + assert rows[fovs[0].relative_path] == ("skipped", cp.IMAGE_SKIPPED) + assert rows[fovs[2].relative_path] == ("failed", "RuntimeError: out of memory") + assert result.counts() == {"written": len(fovs) - 2, "skipped": 1, "failed": 1} + assert len(stub.calls) == len(fovs) - 1 # the skipped image was never segmented + assert not mask_path(run.masks, "Cells", fovs[2]).exists() + record = read_record(run.masks, "Cells") + assert [b.batch_id for b in record.batches] == ["first", "second"] + assert record.batches[1] == result.batch + + +def test_a_failed_image_does_not_stop_the_batch_and_the_next_batch_lists_it(run, stub): + stub.fail = lambda stack: ( + (_ for _ in ()).throw(ValueError("boom")) if len(stub.calls) == 1 else None + ) + result = cp.run_batch(make_job(run), batch_id="b1") + assert ( + result.counts()["failed"] == 1 and result.counts()["written"] == len(run.inputs.fovs()) - 1 + ) + (left,) = images_to_segment(run.inputs, "Cells", run.masks) + assert left.relative_path == run.inputs.fovs()[0].relative_path + + +def test_an_image_with_z_or_t_above_one_fails_with_the_2d_message(run, stub): + fovs = list(run.inputs.fovs()) + deep = dataclasses.replace(fovs[0], z_count=3) + result = cp.run_batch(make_job(run), fovs=[deep, *fovs[1:]], batch_id="b1") + status, message = result.rows()[0][1:] + assert status == "failed" and "2D only" in message + assert result.counts()["written"] == len(fovs) - 1 + assert cp.non_2d_images(run.inputs) == () + + +def test_overwrite_replaces_masks_and_adds_a_batch_without_erasing_the_first(run, stub): + cp.run_batch(make_job(run), batch_id="b1") + again = cp.run_batch(make_job(run), batch_id="b2") + assert again.counts()["skipped"] == len(run.inputs.fovs()) # never replaced by default + third = cp.run_batch(make_job(run, overwrite=True), batch_id="b3") + assert third.counts()["written"] == len(run.inputs.fovs()) + assert [b.batch_id for b in read_record(run.masks, "Cells").batches] == ["b1", "b2", "b3"] + + +def test_progress_is_reported_before_each_image_and_at_the_end(run, stub): + seen = [] + cp.run_batch(make_job(run), progress=lambda *args: seen.append(args), batch_id="b1") + fovs = run.inputs.fovs() + assert [done for done, _, _ in seen] == [*range(len(fovs)), len(fovs)] + assert seen[0][1:] == (len(fovs), fovs[0].relative_path) and seen[-1][2] == "" + + +def test_an_interrupted_batch_still_writes_its_record(run, stub): + def interrupt(stack): + if len(stub.calls) == 2: + raise KeyboardInterrupt + + stub.fail = interrupt + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run), batch_id="b1") + (batch,) = read_record(run.masks, "Cells").batches + assert [i.status for i in batch.images] == ["written"] + + +def test_a_mask_type_or_masks_folder_the_hand_off_refuses_is_refused_before_anything(run, stub): + job = dataclasses.replace(make_job(run), mask_type="NA") + with pytest.raises(SegmentationError): + cp.run_batch(job) + inside = dataclasses.replace(make_job(run), masks_root=run.experiment / "masks") + with pytest.raises(SegmentationError, match="masks_inside_experiment|inside"): + cp.run_batch(inside) + assert stub.calls == [] and not (run.experiment / "masks").exists() + + +# round trip: preprocessing reads the masks of the batch -------------------------------------- + + +def test_masks_of_the_batch_pass_preprocessings_own_mask_checks_on_a_rerun(run, stub): + result = cp.run_batch(make_job(run), batch_id="b1") + fovs = run.inputs.fovs() + assert result.counts()["written"] == len(fovs) + (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) == [] + reopened = RunInputs.open(check_masks(run.out)) + 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() == 2 + assert images_to_segment(reopened, "Cells", run.masks) == () + record = json.loads((run.masks / "Cells" / "segmentation_record.json").read_text("utf-8")) + assert record["batches"][0]["parameters"]["channel_axis"] == 0 + + +# what the preview shows, and the next steps --------------------------------------------------- + + +def test_the_display_contrast_is_per_channel_and_never_touches_the_stack(run): + fov = run.inputs.fovs()[0] + stack = resolve_segmentation(run.inputs, ("TUB", "DNA")).read(fov) + before = stack.copy() + shown = cp.display_contrast(stack) + np.testing.assert_array_equal(stack, before) + assert shown.dtype == np.float32 and shown.shape == stack.shape + assert shown.min() >= 0 and shown.max() <= 1 + assert shown[0].max() == 1.0 and shown[1].max() == 1.0 # each channel on its own range + assert cp.display_contrast(np.full((1, 4, 4), 7)).max() == 0 # no spread shows as 0 + + +def test_label_outlines_mark_the_boundary_of_every_label(): + labels = np.zeros((6, 6), np.uint16) + labels[1:5, 1:5] = 3 + edge = cp.label_outlines(labels) + assert edge.sum() > 0 and not edge[0].any() + assert not edge[labels == 0].any() # only inside a label + + +def test_next_steps_tell_how_to_declare_the_mask_type(tmp_path): + text = "\n".join(cp.next_steps_lines("Cells", tmp_path / "masks")) + assert "[masks.Cells]" in text and 'representation = "instances"' in text + assert str(tmp_path / "masks") in text and "MorphoFeature" in text + with pytest.raises(SegmentationError): + cp.next_steps_lines("NA", tmp_path) + + +def test_open_run_refuses_a_blank_folder_and_opens_a_run(run): + with pytest.raises(SegmentationError, match="output folder"): + cp.open_run(" ") + assert cp.open_run(str(run.out)).fovs() == run.inputs.fovs() From 6a9765dd3dd343088d8b58b95ae1900bb53834c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 11:45:04 +0000 Subject: [PATCH 02/22] Cellpose glue: batch IDs to the microsecond, refusals shown verbatim, fixture shared A batch started twice within one second got the same batch_id and was refused by the record; the ID now includes microseconds. The channel dropdowns show the resolver's multi-line refusal unchanged. The mixed-channel run is a shared fixture (mixed_run) for the Cellpose tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- .../notebook_cellpose.py | 14 +++++++++--- .../segmentation_cellpose.py | 4 ++-- tests/cellpose_stub.py | 22 +++++++++++++++++++ tests/conftest.py | 8 +++++++ tests/test_segmentation_cellpose.py | 19 ++++------------ 5 files changed, 47 insertions(+), 20 deletions(-) diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index 9e9d714..2d0a3a7 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -11,6 +11,7 @@ from __future__ import annotations import functools +import html import time from collections.abc import Callable from pathlib import Path @@ -55,9 +56,14 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: return wrapper -def _card(kind: str, title: str, lines: tuple[str, ...] = ()) -> widgets.HTML: +def _verbatim(text: str) -> str: + """Return ``text`` as an HTML block that keeps its line breaks and shows it unchanged.""" + return f"
{html.escape(text)}
" + + +def _card(kind: str, title: str, lines: tuple[str, ...] = (), *, raw: bool = False) -> widgets.HTML: """Return a status card as a widget, with the notebook's look.""" - return widgets.HTML(f"
{status(kind, title, lines)}
") + return widgets.HTML(f"
{status(kind, title, lines, raw=raw)}
") class ChannelPicker: @@ -108,7 +114,9 @@ def _changed(self, _change: object = None) -> None: note = _card("ok", "Channels: " + ", ".join(self.channel_ids)) except REFUSALS as exc: self.plan, self.refusal = None, str(exc) - note = _card("error", "These channels cannot be used", (self.refusal,)) + note = _card( + "error", "These channels cannot be used", (_verbatim(self.refusal),), raw=True + ) self.message.value = note.value def box(self) -> widgets.VBox: diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index 6c2fdb8..2fab33f 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -386,7 +386,7 @@ def run_batch( progress Called as ``progress(done, total, image)`` before each image and once at the end. batch_id - The record's batch ID; by default the start time (UTC). + The record's batch ID; by default the start time (UTC, to the microsecond). Raises ------ @@ -398,7 +398,7 @@ def run_batch( missing = { f.relative_path for f in images_to_segment(job.inputs, job.mask_type, job.masks_root) } - started = batch_id or datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + started = batch_id or datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ") entries: list[SegmentedImage] = [] try: for done, fov in enumerate(chosen): diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py index 7b4d422..f341dbb 100644 --- a/tests/cellpose_stub.py +++ b/tests/cellpose_stub.py @@ -16,6 +16,9 @@ import numpy as np from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing.run_inputs import RunInputs +from test_segmentation_handoff import EXTRA_FIRST +from test_stage3_channels import described_run, extra_stain BUILTINS = ("cpsam_v2", "cpsam", "cpdino", "cpdino-vitb") @@ -132,3 +135,22 @@ def custom_model(tmp_path, name="my_model"): path.parent.mkdir(exist_ok=True) path.write_bytes(weights_bytes(name)) return path + + +def mixed_run(tmp_path): + """Run the owner's mixed-channel case: DNA, ACTIN and TUB everywhere, EXTRA first in one repeat. + + Returns a namespace with the opened ``inputs``, the ``out`` (run), ``experiment`` and ``masks`` + folders and the description ``data``. + """ + 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] + base = out.parent + return SimpleNamespace( + inputs=RunInputs.open(out), + out=out, + experiment=base / "exp", + masks=base / "masks", + data=data, + ) diff --git a/tests/conftest.py b/tests/conftest.py index 34cb8c0..444ce9c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,6 +30,14 @@ def counting(page, index, *args): return reads +@pytest.fixture +def mixed_run(tmp_path): + """A described run with a fourth stain in one repeat (the Cellpose tests; no Cellpose).""" + from cellpose_stub import mixed_run as build + + return build(tmp_path) + + @pytest.fixture def statement_off(monkeypatch): """Open *Tag channels* with "same channels in the same order" unticked: the PR 17b blocks. diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py index 54e674c..00027e8 100644 --- a/tests/test_segmentation_cellpose.py +++ b/tests/test_segmentation_cellpose.py @@ -12,7 +12,6 @@ import json import subprocess import sys -from types import SimpleNamespace import numpy as np import pytest @@ -30,23 +29,13 @@ resolve_segmentation, ) from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record -from test_segmentation_handoff import EXTRA_FIRST, MASKS_SECTION, REPEAT_2 -from test_stage3_channels import LEVELS, described_run, extra_stain +from test_segmentation_handoff import MASKS_SECTION, REPEAT_2 +from test_stage3_channels import LEVELS @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] - base = out.parent - return SimpleNamespace( - inputs=RunInputs.open(out), - out=out, - experiment=base / "exp", - masks=base / "masks", - data=data, - ) +def run(mixed_run): + return mixed_run @pytest.fixture From 96acdc0216491a06655bcc34a84f538672ad7085 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 11:45:57 +0000 Subject: [PATCH 03/22] Cellpose notebook on a described run (step 2 of the segmentation hand-off) notebooks/MorphoBricks_Cellpose.ipynb: install (Cellpose 4.2.1.1 and the preprocessing commit with this code, pinned), Google Drive, open a run and a masks folder, mask type and channels by ID (dropdowns; a partial channel is refused with the resolver's message, shown unchanged), model and device (explicit), diameter and thresholds, preview with an overlay, batch with progress and a table of every image, and the next steps. Every code cell is one call on CellposeWorkflow. Headless tests run the cells on a synthetic mixed-channel run with a stand-in model, including the rerun of preprocessing on the masks. Docs: user guide, contract 15.5, README, AGENTS.md map, CHANGELOG, notebook version file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- AGENTS.md | 9 + CHANGELOG.md | 18 + README.md | 3 + docs/contract.md | 15 + docs/user_guide.md | 35 ++ notebooks/MorphoBricks_Cellpose.ipynb | 550 ++++++++++++++++++++++++ notebooks/notebook_latest_versions.yaml | 1 + tests/test_notebook_cellpose.py | 400 +++++++++++++++++ tests/test_notebook_file.py | 3 +- 9 files changed, 1033 insertions(+), 1 deletion(-) create mode 100644 notebooks/MorphoBricks_Cellpose.ipynb create mode 100644 tests/test_notebook_cellpose.py diff --git a/AGENTS.md b/AGENTS.md index 997c573..eb0a9f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -259,6 +259,15 @@ src/morphobricks_preprocessing/ 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) + segmentation_cellpose.py the Cellpose glue (step 2; cellpose, torch and dinov3 imported only inside + functions, Cellpose 4.2.1.1 pinned, not a dependency): Settings, diameter_from_text, + eval_arguments (channel_axis=0), segment_image, run_batch (every image written, skipped + or failed in a SegmentationBatch), channel_coverage, display_contrast (display only); + segmentation_cellpose_model.py choose_model (a built-in name or an existing file, + before loading), load_model (the weights file and device verified after loading, no + download without allow_download, SHA-256 recorded, DINOv3 at a pinned commit); + notebook_cellpose.py CellposeWorkflow, ChannelPicker, CellStop: the widgets behind + notebooks/MorphoBricks_Cellpose.ipynb 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 4674b57..a205336 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,24 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Cellpose notebook** (`notebooks/MorphoBricks_Cellpose.ipynb`, step 2 of the segmentation + hand-off; owner request of 21 November 2026): opens a described run, chooses the mask type and + the channels **by channel ID** (dropdowns; a channel only some images have is refused with + the resolver's `A_SCOPE_INCOMPLETE` message, shown unchanged), loads **Cellpose 4.2.1.1** + (`cpsam_v2` by default, `cpsam`, `cpdino`, `cpdino-vitb`, or a model file), previews one image, + segments every image without a mask and ends with a table of every image as written, skipped + or failed with its error, then says how to declare the new mask type and rerun preprocessing. + Cellpose is not a dependency: `segmentation_cellpose`, `segmentation_cellpose_model` and + `notebook_cellpose` import `cellpose`, `torch` and `dinov3` only inside functions. What + Cellpose 4.2.1.1 does silently is refused: a model name or file it cannot find becomes + `cpsam_v2` (the model is validated before loading and the loaded weights file must be the one + asked for), a missing GPU becomes the CPU (the device is stated, an unavailable one is refused, + and the model must sit on it), uncached weights are downloaded (only with the download box + ticked, after the notebook says they come from Hugging Face), channels beyond the first three + are dropped by position (more than three are refused), and no diameter means the model's native + scale, not an estimate (a blank diameter is recorded as the native scale, 0 is refused). The + SHA-256 and file name of the weights, every effective setting and the DINOv3 commit + (`cpdino` models, installed only when ticked) go into the `SegmentationBatch`. 2D images only. - **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 diff --git a/README.md b/README.md index c5f1499..953aa4f 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ Pre-alpha; the current release is v0.8.0 (what is planned next is in - Running an experiment end to end, updating earlier output incrementally, resuming interrupted runs and publishing results in one crash-consistent step - Reading a run from another brick: `RunInputs.open(output_folder)` +- A Cellpose notebook ([notebooks/MorphoBricks_Cellpose.ipynb](notebooks/MorphoBricks_Cellpose.ipynb)) + that makes masks for a described run, channels chosen by channel ID (Cellpose 4.2.1.1; not a + dependency of the brick) - A step-by-step notebook ([notebooks/MorphoBricks_Preprocessing.ipynb](notebooks/MorphoBricks_Preprocessing.ipynb)) and a command line (`morphobricks-preprocessing check` / `run` / `masks` / `calibrate` / `describe` / `convert`) diff --git a/docs/contract.md b/docs/contract.md index 68c262f..11e0d8a 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1343,6 +1343,21 @@ leaving the folder, a mask type spelled in two ways (`mask_names_differ_in_case` 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. +The shipped Cellpose notebook builds on this hand-off and adds no rule of its own to the masks +(`segmentation_cellpose`, `segmentation_cellpose_model`; Cellpose, `torch` and `dinov3` are +imported only inside functions, so importing the brick and discovery stay inert). Cellpose +4.2.1.1 is pinned and is not a dependency. Each of its silent behaviours is a refusal here: a +model is one of `cpsam_v2`, `cpsam`, `cpdino`, `cpdino-vitb` or an existing file, checked before +loading, and the weights file the loaded model reports must be the one asked for; a device +(`cuda`, `mps`, `cpu`) is always stated, an unavailable one is refused, and every weight must +sit on it after loading; uncached weights are downloaded only on an explicit request; more than +three channels are refused (Cellpose reads the first three by position); a blank diameter is +the model's native scale, never an estimate and never 0. The batch's `model` holds the model +name, the weights file name (or the custom file's path) and its SHA-256, and its `parameters` +every effective setting (diameter in pixels or null with its meaning, thresholds, normalisation, +batch and tile size, `channel_axis` 0, device type, versions and, for a DINOv3 model, the DINOv3 +commit). Two-dimensional images only. + ## 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/docs/user_guide.md b/docs/user_guide.md index fc4ecbb..0308530 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -232,6 +232,41 @@ Masks do not change `plane_histograms.csv`. They are checked and recorded for th that measure objects; the optional `masks` command (§5), or **Describe the masks** in the notebook's step 3 (§4), also tells how they relate. +### Making masks with Cellpose (optional) + +[`notebooks/MorphoBricks_Cellpose.ipynb`](../notebooks/MorphoBricks_Cellpose.ipynb) makes masks +for a run you already have (run preprocessing first and describe the experiment). Its cells: +install (Cellpose 4.2.1.1 and the preprocessing commit it is made for), Google Drive, open the +run's output folder and a masks folder, choose the mask type and **one to three channels by +channel ID**, choose the model, device and settings and load the model, preview one image, and +segment all images. Then: + +- **Channels.** You choose channels by ID (`DNA`, `ACTIN`), never by position. When some images + have a channel that others lack (a fourth stain in one biological repeat), only the channels + every image has can be used: the dropdown says which channel is partial, and choosing it + shows preprocessing's refusal (`A_SCOPE_INCOMPLETE`) unchanged. Cellpose reads at most three + channels, so more are refused. +- **Model.** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb` or a model file of your + own. A name or file that does not exist is refused: Cellpose itself would silently use + `cpsam_v2`. The weights of a built-in model are downloaded from Hugging Face on first use, + only if you tick the download box. `cpdino` models also need DINOv3, installed at a pinned + commit only if you tick its box (restart the runtime after installing it). +- **Device.** You choose `cuda`, `mps` or `cpu`. A GPU that is not available is refused, never + replaced by the CPU. +- **Diameter** is in pixels. Blank means the model's own native scale (Cellpose 4.2.1.1 does + not estimate a diameter); 0 is refused. +- **2D only.** An image with more than one Z plane or time point fails with a message that + says so. +- **Result.** One mask per image at `///.tif` + (2D, `int32`, 0 is background, the image's width and height), never over an existing mask + unless you tick overwrite, and `//segmentation_record.json` with the model's + file name and SHA-256, every setting, the channels, the device and each image as written, + skipped or failed. The final table lists every image, with the error of a failed one. + +Afterwards declare the mask type in the experiment description (for example `[masks.Cells]` +with `source_type = "Cells"` and `representation = "instances"`), save it, run preprocessing +again with the masks folder, **Describe the masks**, then continue with MorphoFeature. + ## 3. Supported images - **TIFF files:** `.tif` and `.tiff` (any case), including OME-TIFF and ImageJ hyperstacks. diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb new file mode 100644 index 0000000..a26221e --- /dev/null +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -0,0 +1,550 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "7fb27b941602401d91542211134fc71a", + "metadata": {}, + "source": [ + "# 🔬 MorphoBricks Cellpose\n", + "\n", + "Segments the images of a described MorphoBricks preprocessing run with **Cellpose 4.2.1.1** and writes the masks where preprocessing expects them. Your images are never changed: masks go to a separate masks folder, with a `segmentation_record.json` that says how they were made.\n", + "\n", + "### What it does\n", + "\n", + "Open a run → choose the mask type and the channels **by channel ID** → choose the model and device → preview one image → segment all images → rerun preprocessing with the masks folder.\n", + "\n", + "### Before you start\n", + "\n", + "- A finished preprocessing run (run `MorphoBricks_Preprocessing` first, with the experiment described). The run knows each image's axes and channel IDs; nothing is guessed here.\n", + "- A masks folder outside the experiment folder and the run's output folder.\n", + "- **Google Colab:** keep the run and the masks folder on Google Drive, under **/content/drive/MyDrive/**, and choose a GPU runtime (Runtime > Change runtime type).\n", + "- **JupyterLab / LabConstrictor:** use normal local paths.\n", + "\n", + "### Things to know\n", + "\n", + "- **2D images only for now.** An image with more than one Z plane or time point fails with a message that says so; it is never reduced to one plane.\n", + "- **Channels by ID, at most three.** You choose channels by their ID (for example `DNA`, `ACTIN`). In a run where some images have a channel that others lack, only the channels every image has can be used; the notebook shows the refusal as it is. Cellpose reads at most three channels and drops the rest by position, so more than three are refused.\n", + "- **Models:** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb`, or a model file of your own. A name or file Cellpose cannot find is **refused**; Cellpose itself would silently use `cpsam_v2` instead.\n", + "- **Downloads:** built-in weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. Nothing downloads unless you tick the download box in cell 5. The `cpdino` models also need DINOv3 (installed only if you tick its box, at a pinned commit).\n", + "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU.\n", + "- **Diameter:** in pixels. **Blank means the model's own native scale** (Cellpose 4.2.1.1 does not estimate a diameter). Zero is refused.\n", + "- Every setting that ran, the model's file name and its SHA-256 are written to the record.\n", + "\n", + "### How to run\n", + "\n", + "Run the code cells in order (click a cell and press **Shift + Enter**, or its ▶ button). After a restart of the runtime, run cell 1 again: it installs nothing that is already there." + ] + }, + { + "cell_type": "markdown", + "id": "acae54e37e7d407bbb7b55eff062a284", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **1. Install Cellpose and MorphoBricks preprocessing**\n", + "\n", + "Installs Cellpose 4.2.1.1 and the preprocessing commit this notebook is made for. Nothing is installed when it is already there, so running the cell again is safe. It prints **Ready** with the versions. It never installs DINOv3: that is a choice in cell 5." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9a63283cbaf04dbcab1f6479b197f3a8", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 1. Install Cellpose and MorphoBricks preprocessing\n", + "import subprocess\n", + "import sys\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback (Colab and Jupyter).\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if sys.version_info < (3, 11):\n", + " raise CellStop(\"Select a Python 3.11 or newer kernel, then run this cell again.\")\n", + "\n", + "import json\n", + "from importlib import invalidate_caches\n", + "from importlib.metadata import PackageNotFoundError, distribution, version\n", + "\n", + "# LabConstrictor version identifiers.\n", + "current_version = \"0.1.0\"\n", + "notebook_name = \"MorphoBricks_Cellpose\"\n", + "\n", + "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", + "# immutable source revision that holds this notebook's code.\n", + "CELLPOSE_VERSION = \"4.2.1.1\"\n", + "RELEASE_REF = \"6a9765dd3dd343088d8b58b95ae1900bb53834c5\"\n", + "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", + "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", + "\n", + "# True only to develop against the preprocessing already loaded in this kernel (a local\n", + "# checkout): the cell then says so and installs no other preprocessing.\n", + "DEVELOPMENT_OVERRIDE = False\n", + "SETUP_RECORD: dict = {}\n", + "\n", + "\n", + "def _version(name: str) -> str | None:\n", + " \"\"\"Return the installed version of a package, or None.\"\"\"\n", + " try:\n", + " return version(name)\n", + " except PackageNotFoundError:\n", + " return None\n", + "\n", + "\n", + "def _installed_commit(name: str) -> str | None:\n", + " \"\"\"Return the Git commit a package was installed from (pip's direct_url.json), or None.\"\"\"\n", + " try:\n", + " text = distribution(name).read_text(\"direct_url.json\")\n", + " except PackageNotFoundError:\n", + " return None\n", + " return json.loads(text).get(\"vcs_info\", {}).get(\"commit_id\") if text else None\n", + "\n", + "\n", + "def _install() -> None:\n", + " \"\"\"Install what is missing or differs from the pins, then report the versions.\"\"\"\n", + " wanted = []\n", + " if _version(\"cellpose\") != CELLPOSE_VERSION:\n", + " wanted.append(f\"cellpose=={CELLPOSE_VERSION}\")\n", + " preprocessing_ok = DEVELOPMENT_OVERRIDE or (\n", + " _installed_commit(\"morphobricks-preprocessing\") == RELEASE_REF\n", + " )\n", + " if not preprocessing_ok:\n", + " wanted.append(f\"morphobricks-preprocessing[{EXTRAS}] @ git+{REPOSITORY}@{RELEASE_REF}\")\n", + " if wanted:\n", + " print(\"Installing \" + \", \".join(wanted) + \"...\", flush=True)\n", + " try:\n", + " subprocess.run(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"--disable-pip-version-check\", *wanted],\n", + " check=True,\n", + " )\n", + " except (subprocess.CalledProcessError, OSError) as exc:\n", + " raise CellStop(\n", + " \"The installation failed. Check the installation output and internet access, \"\n", + " \"then run this cell again.\"\n", + " ) from exc\n", + " invalidate_caches()\n", + " if _version(\"cellpose\") != CELLPOSE_VERSION:\n", + " raise CellStop(\n", + " f\"Cellpose {CELLPOSE_VERSION} is not installed ({_version('cellpose')}). Restart \"\n", + " \"the runtime and run this cell again.\"\n", + " )\n", + " try:\n", + " from morphobricks_preprocessing import notebook_cellpose # noqa: F401\n", + " except ImportError as exc:\n", + " cause = \" \".join(f\"{type(exc).__name__}: {exc}\".split())\n", + " raise CellStop(f\"MorphoBricks preprocessing could not load ({cause}).\") from exc\n", + " SETUP_RECORD.clear()\n", + " SETUP_RECORD.update(\n", + " notebook_version=current_version,\n", + " preprocessing_version=_version(\"morphobricks-preprocessing\"),\n", + " cellpose_version=_version(\"cellpose\"),\n", + " release_ref=RELEASE_REF,\n", + " development_override=DEVELOPMENT_OVERRIDE,\n", + " )\n", + " override = (\n", + " \" DEVELOPMENT OVERRIDE is on: preprocessing is not the pinned commit.\"\n", + " if DEVELOPMENT_OVERRIDE\n", + " else \"\"\n", + " )\n", + " print(\n", + " f\"Ready: Cellpose {_version('cellpose')}; preprocessing \"\n", + " f\"{_version('morphobricks-preprocessing')} ({RELEASE_REF[:12]}).{override}\\n\"\n", + " f\"Notebook {current_version}.\\n\"\n", + " \"Next: run cell 2 (Mount Google Drive), then cell 3 (Open the run).\",\n", + " flush=True,\n", + " )\n", + "\n", + "\n", + "_install()" + ] + }, + { + "cell_type": "markdown", + "id": "8dd0d8092fe74a7c96281538738b07e2", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **2. Mount Google Drive**\n", + "\n", + "**Google Colab:** connects your Google Drive. Allow access in the window that opens; your Drive is then the folder **/content/drive/MyDrive**. Keep the experiment and the output folder there: everything else on a Colab runtime is wiped when it disconnects.\n", + "\n", + "**JupyterLab / LabConstrictor:** there is no Drive to mount. The cell only prints a note, and you use normal local paths in the app." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "72eea5119410473aa328ad9291626812", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 2. Mount Google Drive\n", + "import sys\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback (Colab and Jupyter).\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if \"google.colab\" in sys.modules:\n", + " from google.colab import drive\n", + "\n", + " print(\"Google Colab: connecting Google Drive...\", flush=True)\n", + " try:\n", + " drive.mount(\"/content/drive\")\n", + " except Exception as exc:\n", + " # The cause stays on the one line: a stop must never hide what failed.\n", + " cause = \" \".join(f\"{type(exc).__name__}: {exc}\".split())\n", + " raise CellStop(\n", + " f\"Google Drive could not be connected ({cause}). Allow Drive access, then run \"\n", + " \"this cell again.\"\n", + " ) from exc\n", + " print(\"Google Drive is connected: your files are in /content/drive/MyDrive.\", flush=True)\n", + "else:\n", + " print(\"Not Google Colab: there is no Google Drive to mount here, so nothing was done.\")" + ] + }, + { + "cell_type": "markdown", + "id": "8edb47106e1a46a883d545849b8ab81b", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **3. Open the preprocessing run**\n", + "\n", + "Give the run's output folder and the masks folder. The notebook opens the run with preprocessing's own checks and lists the channels with the number of images that have each. Cell 3 stops with the reason when the run cannot be opened (a run that was stopped, or images changed since the run)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10185d26023b46108eb7d9f57d49d2b3", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 3. Open the preprocessing run\n", + "# @markdown The run's **output folder** (it holds run_manifest.json) and the **masks\n", + "# @markdown folder** (outside the experiment and the run).\n", + "run_folder = \"\" # @param {type:\"string\"}\n", + "masks_folder = \"\" # @param {type:\"string\"}\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback.\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "try:\n", + " from morphobricks_preprocessing.notebook_cellpose import CellposeWorkflow\n", + "except ImportError as exc:\n", + " raise CellStop(\"Run cell 1 first: it installs what this notebook needs.\") from exc\n", + "\n", + "workflow = CellposeWorkflow()\n", + "workflow.open(run_folder, masks_folder)" + ] + }, + { + "cell_type": "markdown", + "id": "8763a12b2bbd4a93a75aff182afb95dc", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **4. Choose the mask type and the channels**\n", + "\n", + "The mask type is the name of the new masks (it becomes a folder in the masks folder and the name you declare in the experiment description). Choose one to three channels **by channel ID** in the dropdowns; their order is the order Cellpose gets them in. A channel that some images lack says so, and choosing it shows why it is refused." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7623eae2785240b9bd12b16a66d81610", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 4. Choose the mask type and the channels\n", + "# @markdown The mask type to make (one folder name, for example Cells or Nuclei).\n", + "mask_type = \"Cells\" # @param {type:\"string\"}\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback.\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if \"workflow\" not in globals():\n", + " raise CellStop(\"Run cell 3 first.\")\n", + "workflow.choose_channels(mask_type)" + ] + }, + { + "cell_type": "markdown", + "id": "7cdc8c89c7104fffa095e18ddfef8986", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **5. Choose the model and the settings, then load the model**\n", + "\n", + "Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box. The notebook loads the model, then checks that the weights file is the one you asked for and that the model is on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter is in pixels; blank is the model's native scale." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b118ea5561624da68c537baed56e602f", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 5. Choose the model and the settings, then load the model\n", + "# @markdown ### Model and device\n", + "model = \"cpsam_v2\" # @param [\"cpsam_v2\", \"cpsam\", \"cpdino\", \"cpdino-vitb\"]\n", + "# @markdown A model file of your own (leave blank to use the model above). A file\n", + "# @markdown that does not exist is refused.\n", + "custom_model_file = \"\" # @param {type:\"string\"}\n", + "# @markdown The device is never chosen for you: a GPU that is not available is\n", + "# @markdown refused, not replaced by the CPU.\n", + "device = \"cuda\" # @param [\"cuda\", \"mps\", \"cpu\"]\n", + "# @markdown Built-in weights are downloaded from Hugging Face on first use. Tick to\n", + "# @markdown allow that download.\n", + "download_weights = False # @param {type:\"boolean\"}\n", + "# @markdown The cpdino models need DINOv3 (installed at a pinned commit). Tick to install it now.\n", + "install_dinov3 = False # @param {type:\"boolean\"}\n", + "# @markdown ### Settings\n", + "# @markdown Diameter in pixels. Blank = the model's native scale (Cellpose 4.2.1.1\n", + "# @markdown does not estimate it). Never 0.\n", + "diameter = \"\" # @param {type:\"string\"}\n", + "flow_threshold = 0.4 # @param {type:\"number\"}\n", + "cellprob_threshold = 0.0 # @param {type:\"number\"}\n", + "# @markdown Cellpose's own normalisation (each channel to its 1st-99th percentile).\n", + "normalize = True # @param {type:\"boolean\"}\n", + "batch_size = 8 # @param {type:\"integer\"}\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback.\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if \"workflow\" not in globals():\n", + " raise CellStop(\"Run cell 3 first.\")\n", + "workflow.set_settings(diameter, flow_threshold, cellprob_threshold, normalize, batch_size)\n", + "workflow.load(model, custom_model_file, device, download_weights, install_dinov3)" + ] + }, + { + "cell_type": "markdown", + "id": "938c804e27f84196a10c8828c723f798", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **6. Preview one image**\n", + "\n", + "Segments one image and shows each channel (contrast stretched for display only; the masks and the stored values are never changed) and the outlines Cellpose found. Nothing is written. Change the settings in cell 5 and load again until it looks right." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "504fb2a444614c0babb325280ed9130a", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 6. Preview one image\n", + "# @markdown The image to preview, as its path in the run (blank = the first image\n", + "# @markdown without a mask). Nothing is written.\n", + "preview_image = \"\" # @param {type:\"string\"}\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback.\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if \"workflow\" not in globals():\n", + " raise CellStop(\"Run cell 3 first.\")\n", + "workflow.preview(preview_image)" + ] + }, + { + "cell_type": "markdown", + "id": "59bbdb311c014d738909a11f9e486628", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **7. Segment all images**\n", + "\n", + "Segments every image that has no mask of this type yet and writes each mask as a 2D integer image in the masks folder, then writes the record. A progress line shows how far it is. The table at the end lists **every** image as written, skipped or failed with the error: nothing is skipped silently, and one failed image does not stop the others." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b43b363d81ae4b689946ece5c682cd59", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 7. Segment all images\n", + "# @markdown Tick to replace masks that already exist. Otherwise images that already\n", + "# @markdown have a mask are skipped.\n", + "overwrite = False # @param {type:\"boolean\"}\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback.\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if \"workflow\" not in globals():\n", + " raise CellStop(\"Run cell 3 first.\")\n", + "result = workflow.run(overwrite)" + ] + }, + { + "cell_type": "markdown", + "id": "8a65eabff63a45729fe45fb5ade58bdc", + "metadata": {}, + "source": [ + "___\n", + "\n", + "## **8. What to do next**\n", + "\n", + "1. Declare the new mask type in the experiment description (preprocessing notebook, step 4, or `morphobricks.toml`): for example `[masks.Cells]` with `source_type = \"Cells\"` and `representation = \"instances\"`.\n", + "2. Save the description.\n", + "3. Run preprocessing again with the masks folder (the histograms are reused).\n", + "4. Describe the masks.\n", + "5. Then continue with MorphoFeature." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c3933fab20d04ec698c2621248eb3be0", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @title 8. What to do next\n", + "\n", + "\n", + "class CellStop(RuntimeError):\n", + " \"\"\"Stop this cell with its message on one line, without a traceback.\"\"\"\n", + "\n", + " def _render_traceback_(self) -> list:\n", + " return [str(self)]\n", + "\n", + "\n", + "if \"workflow\" not in globals():\n", + " raise CellStop(\"Run cell 3 first.\")\n", + "workflow.next_steps()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/notebooks/notebook_latest_versions.yaml b/notebooks/notebook_latest_versions.yaml index e07d981..fc19a66 100644 --- a/notebooks/notebook_latest_versions.yaml +++ b/notebooks/notebook_latest_versions.yaml @@ -1,3 +1,4 @@ # Latest version of each notebook, read by LabConstrictor's version check by notebook_name. # Equal to the notebook's current_version and its RELEASE_TAG without the "v" (README, "Notebook"). "MorphoBricks_Preprocessing": "0.8.0" +"MorphoBricks_Cellpose": "0.1.0" diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py new file mode 100644 index 0000000..678fae9 --- /dev/null +++ b/tests/test_notebook_cellpose.py @@ -0,0 +1,400 @@ +"""The Cellpose notebook file, and its cells run headless on a synthetic run with a stand-in model. + +Cellpose is not installed in CI, so the cells run in one namespace (as in a kernel) against the +stand-in of ``tests/cellpose_stub.py``; the install cell is run with the package installer +replaced. Like ``test_notebook_file.py`` this checks the file's shape (a Colab form with its +code hidden, Markdown above every code cell, the pins) and what the cells do. +""" + +import html +import json +import re +import subprocess +import sys +from pathlib import Path + +import pytest +import tifffile + +from cellpose_stub import custom_model, install +from morphobricks_preprocessing import notebook_cellpose +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing.manifest import MANIFEST_FILENAME +from morphobricks_preprocessing.segmentation_record import read_record +from test_segmentation_handoff import MASKS_SECTION + +ROOT = Path(__file__).parents[1] +NOTEBOOK = ROOT / "notebooks/MorphoBricks_Cellpose.ipynb" +VERSIONS = ROOT / "notebooks/notebook_latest_versions.yaml" +INSTALL, DRIVE, OPEN, CHANNELS, MODEL, PREVIEW, BATCH, NEXT = range(8) +TITLES = ( + "# @title 1. Install Cellpose and MorphoBricks preprocessing", + "# @title 2. Mount Google Drive", + "# @title 3. Open the preprocessing run", + "# @title 4. Choose the mask type and the channels", + "# @title 5. Choose the model and the settings, then load the model", + "# @title 6. Preview one image", + "# @title 7. Segment all images", + "# @title 8. What to do next", +) +HEADINGS = ( + "## **1. Install Cellpose and MorphoBricks preprocessing**", + "## **2. Mount Google Drive**", + "## **3. Open the preprocessing run**", + "## **4. Choose the mask type and the channels**", + "## **5. Choose the model and the settings, then load the model**", + "## **6. Preview one image**", + "## **7. Segment all images**", + "## **8. What to do next**", +) + + +def notebook(): + return json.loads(NOTEBOOK.read_text(encoding="utf-8")) + + +def source(number): + code = [c for c in notebook()["cells"] if c["cell_type"] == "code"] + return "".join(code[number]["source"]) + + +def setting(name): + match = re.search(rf'^{name} = "([^"]*)"$', source(INSTALL), re.M) + assert match is not None, f"the install cell sets no {name}" + return match.group(1) + + +def with_params(number, params): + """Return cell ``number`` with its Colab form fields set to ``params`` (each must exist).""" + text = source(number) + for name, value in params.items(): + text, count = re.subn( + rf"^{name} = .*?( # @param.*)$", rf"{name} = {value!r}\1", text, flags=re.M + ) + assert count == 1, f"cell {number + 1} has no form field {name}" + return text + + +def run_cell(namespace, number, **params): + exec(compile(with_params(number, params), f"", "exec"), namespace) + + +# the file --------------------------------------------------------------------------------------- + + +def test_the_notebook_is_an_introduction_and_eight_explained_code_cells(): + nb = notebook() + assert nb["nbformat"] == 4 + cells = nb["cells"] + assert [c["cell_type"] for c in cells] == ["markdown", *("markdown", "code") * 8] + intro = "".join(cells[0]["source"]) + for text in ( + "Cellpose 4.2.1.1", + "Hugging Face", + "2D images only", + "at most three", + "native scale", + ): + assert text in intro + code = [c for c in cells if c["cell_type"] == "code"] + assert [c["source"][0].rstrip("\n") for c in code] == list(TITLES) + for position, (heading, cell) in enumerate(zip(HEADINGS, code, strict=True)): + assert heading in "".join(cells[1 + 2 * position]["source"]).splitlines() + assert cells[2 + 2 * position] is cell or cells[2 + 2 * position] == cell + assert cell["outputs"] == [] and cell["execution_count"] is None + assert cell["metadata"].get("jupyter", {}).get("source_hidden") is True + assert cell["metadata"].get("cellView") == "form" + assert all("\\n" not in "".join(c["source"]) for c in cells if c["cell_type"] == "markdown") + + +def test_the_cells_stay_thin_the_logic_is_in_the_package(): + for number in range(OPEN, NEXT + 1): + text = source(number) + assert len(text.splitlines()) < 45 + for other in ("import cellpose", "from cellpose", "import torch", "tifffile", "np."): + assert other not in text # nothing here reads, computes or writes pixels + assert "workflow.run(" in source(BATCH) and "workflow.preview(" in source(PREVIEW) + assert "workflow.load(" in source(MODEL) and "workflow.choose_channels(" in source(CHANNELS) + + +def test_the_pins_are_cellpose_4_2_1_1_and_a_preprocessing_commit_with_this_code(): + assert setting("CELLPOSE_VERSION") == cp.CELLPOSE_VERSION == "4.2.1.1" + ref = setting("RELEASE_REF") + assert re.fullmatch(r"[0-9a-f]{40}", ref) + assert setting("REPOSITORY").endswith("CellMigrationLab/morphobricks-preprocessing.git") + assert "DEVELOPMENT_OVERRIDE = False" in source(INSTALL) + ours = ("src", "pyproject.toml") + probe = subprocess.run( + ["git", "-C", str(ROOT), "diff", "--quiet", ref, "HEAD", "--", *ours], capture_output=True + ) + if probe.returncode > 1: + pytest.skip("the pinned commit is not in this checkout (shallow clone or no git)") + # The notebook installs the package at RELEASE_REF: that commit must hold the code the + # notebook's cells call, so nothing under src/ may have changed since. + assert probe.returncode == 0, "src/ changed after RELEASE_REF: move the pin to the new commit" + + +def test_the_version_file_names_the_notebooks_current_version(): + index = dict( + re.fullmatch(r'"([^"]+)": "([^"]+)"', line).groups() + for line in VERSIONS.read_text(encoding="utf-8").splitlines() + if line and not line.startswith("#") + ) + assert ( + index[NOTEBOOK.stem] == setting("current_version") + and setting("notebook_name") == NOTEBOOK.stem + ) + + +# the install cell --------------------------------------------------------------------------------- + + +@pytest.fixture +def installer(monkeypatch): + """Run the install cell with the installer and the metadata replaced by a ledger.""" + state = type("S", (), {})() + state.versions = {"cellpose": "4.2.1.1", "morphobricks-preprocessing": "0.8.0"} + state.commit = setting("RELEASE_REF") + state.pip = [] + import importlib.metadata as metadata + + def fake_version(name): + if name not in state.versions: + raise metadata.PackageNotFoundError(name) + return state.versions[name] + + class Dist: + def read_text(self, name): + return json.dumps({"vcs_info": {"commit_id": state.commit}}) if state.commit else None + + def fake_run(command, check): + state.pip.append(command) + state.versions["cellpose"] = "4.2.1.1" + state.commit = setting("RELEASE_REF") + + monkeypatch.setattr(metadata, "version", fake_version) + monkeypatch.setattr(metadata, "distribution", lambda name: Dist()) + monkeypatch.setattr(subprocess, "run", fake_run) + return state + + +def test_the_install_cell_installs_nothing_that_is_already_there(installer, capsys): + namespace = {} + run_cell(namespace, INSTALL) + assert installer.pip == [] + out = capsys.readouterr().out + assert "Ready: Cellpose 4.2.1.1" in out and setting("RELEASE_REF")[:12] in out + assert namespace["SETUP_RECORD"]["cellpose_version"] == "4.2.1.1" + assert "dinov3" not in "".join(sys.modules) # DINOv3 is never installed by this cell + + +def test_the_install_cell_installs_the_pinned_versions_when_they_differ(installer): + installer.versions["cellpose"], installer.commit = "4.0.0", "0" * 40 + run_cell({}, INSTALL) + (command,) = installer.pip + assert command[1:4] == ["-m", "pip", "install"] + assert "cellpose==4.2.1.1" in command + assert any( + a.startswith("morphobricks-preprocessing[") and a.endswith(f"@{setting('RELEASE_REF')}") + for a in command + ) + assert not any("dinov3" in a for a in command) + + +# the cells run on a synthetic run ---------------------------------------------------------- + + +@pytest.fixture +def cells(mixed_run, monkeypatch, tmp_path): + state = install(monkeypatch, tmp_path) + namespace = {} + return type("C", (), {"ns": namespace, "stub": state, "run": mixed_run})() + + +def open_and_choose(cells, **extra): + run = cells.run + run_cell(cells.ns, OPEN, run_folder=str(run.out), masks_folder=str(run.masks)) + run_cell(cells.ns, CHANNELS, mask_type="Cells") + picker = cells.ns["workflow"].picker + for dropdown, value in zip(picker.dropdowns, extra.get("ids", ("TUB", "DNA", "")), strict=True): + dropdown.value = value + return picker + + +def test_the_cells_segment_a_mixed_run_end_to_end(cells): + run = cells.run + picker = open_and_choose(cells) + assert picker.channel_ids == ("TUB", "DNA") and picker.plan is not None + run_cell(cells.ns, MODEL, device="cpu", diameter="30", batch_size=4) + workflow = cells.ns["workflow"] + assert workflow.loaded.name == "cpsam_v2" and workflow.loaded.device == "cpu" + assert workflow.loaded.file == "cpsam_v2" + run_cell(cells.ns, PREVIEW) + assert len(cells.stub.calls) == 1 and not run.masks.exists() # a preview writes nothing + run_cell(cells.ns, BATCH) + result = cells.ns["result"] + fovs = run.inputs.fovs() + assert result.counts() == {"written": len(fovs), "skipped": 0, "failed": 0} + assert len(cells.stub.calls) == 1 + len(fovs) + table = workflow.shown[-1] + assert all(f.relative_path in table for f in fovs) and "written" in table + batch = read_record(run.masks, "Cells").batches[0] + assert batch.channel_ids == ("TUB", "DNA") and batch.parameters["diameter"] == 30.0 + assert batch.parameters["batch_size"] == 4 and batch.device == "cpu" + assert not list(run.masks.rglob("*.png")) # the preview figure is never saved + stored = tifffile.imread(run.masks / "Cells" / fovs[0].relative_path) + assert stored.dtype.name == "int32" and stored.shape == (8, 8) + + +def test_a_partial_channel_is_refused_and_the_message_is_shown_verbatim(cells): + picker = open_and_choose(cells, ids=("DNA", "EXTRA", "")) + assert picker.plan is None + assert "A_SCOPE_INCOMPLETE" in picker.refusal and "EXTRA" in picker.refusal + assert picker.refusal.startswith("The channel 'EXTRA' is present in 4 of 12 images") + assert html.escape(picker.refusal) in picker.message.value # shown to the user, unchanged + options = [label for label, _ in picker.dropdowns[1].options] + assert any( + label.startswith("EXTRA (in ") for label in options + ) # the dropdown says it is partial + with pytest.raises(notebook_cellpose.CellStop) as stopped: + run_cell(cells.ns, MODEL, device="cpu") + assert str(stopped.value) == picker.refusal and cells.stub.constructed == [] + + +def test_a_blank_diameter_is_the_native_scale_in_the_cell_and_the_record(cells): + open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + shown = " ".join(cells.ns["workflow"].shown) + assert "native scale" in shown and "does not estimate" in shown + run_cell(cells.ns, BATCH) + assert all(call.kwargs["diameter"] is None for call in cells.stub.calls) + assert read_record(cells.run.masks, "Cells").batches[0].parameters["diameter"] is None + + +@pytest.mark.parametrize("diameter", ["0", "-5", "abc"]) +def test_a_diameter_of_zero_stops_the_cell_with_the_reason(cells, diameter): + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="diameter"): + run_cell(cells.ns, MODEL, device="cpu", diameter=diameter) + assert cells.stub.constructed == [] + + +def test_a_gpu_that_is_not_there_stops_the_cell_and_nothing_loads(cells): + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="cuda was asked for but is not available"): + run_cell(cells.ns, MODEL) # the form's default device is cuda: no silent CPU + assert cells.stub.constructed == [] and cells.ns["workflow"].loaded is None + + +def test_an_unknown_or_missing_model_stops_the_cell_with_no_substitution(cells): + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="never substitutes"): + run_cell(cells.ns, MODEL, device="cpu", custom_model_file="/no/such/model") + assert cells.stub.constructed == [] + path = custom_model(cells.run.out.parent) + run_cell(cells.ns, MODEL, device="cpu", custom_model_file=str(path)) + assert cells.ns["workflow"].loaded.name == "my_model" + + +def test_the_weights_download_needs_its_box_and_the_cell_says_where_from(cells): + cells.stub.models_dir.joinpath("cpsam_v2").unlink() + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="Hugging Face"): + run_cell(cells.ns, MODEL, device="cpu") + assert cells.stub.downloaded == [] + assert "downloaded from Hugging Face on first use" in " ".join(cells.ns["workflow"].shown) + run_cell(cells.ns, MODEL, device="cpu", download_weights=True) + assert cells.stub.downloaded == ["cpsam_v2"] + + +def test_failures_are_in_the_final_table_and_the_batch_goes_on(cells): + open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + + def fail_third(stack): + if len(cells.stub.calls) == 3: + raise RuntimeError("out of memory") + + cells.stub.fail = fail_third + run_cell(cells.ns, BATCH) + result, fovs = cells.ns["result"], cells.run.inputs.fovs() + assert result.counts() == {"written": len(fovs) - 1, "skipped": 0, "failed": 1} + table = cells.ns["workflow"].shown[-1] + assert "RuntimeError: out of memory" in table and "failed" in table + run_cell(cells.ns, BATCH) # again: the written images are skipped, the failed one is redone + assert cells.ns["result"].counts() == {"written": 1, "skipped": len(fovs) - 1, "failed": 0} + + +def test_a_preview_names_an_image_of_the_run_or_is_refused(cells): + open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + with pytest.raises(notebook_cellpose.CellStop, match="not an image of this run"): + run_cell(cells.ns, PREVIEW, preview_image="nowhere.tif") + name = cells.run.inputs.fovs()[3].relative_path + run_cell(cells.ns, PREVIEW, preview_image=name) + assert name in cells.ns["workflow"].shown[-1] and len(cells.stub.calls) == 1 + + +def test_a_cell_run_too_early_says_which_cell_to_run_first(cells): + with pytest.raises(RuntimeError, match="Run cell 3 first"): + run_cell(cells.ns, CHANNELS) + run_cell(cells.ns, OPEN, run_folder=str(cells.run.out), masks_folder=str(cells.run.masks)) + with pytest.raises(RuntimeError, match="Run cell 4 first"): + run_cell(cells.ns, NEXT) + with pytest.raises(RuntimeError, match="Run cell 5 first"): + run_cell(cells.ns, BATCH) + + +def test_a_run_folder_that_is_not_a_run_stops_the_cell_with_the_reason(cells, tmp_path): + with pytest.raises(notebook_cellpose.CellStop): + run_cell( + cells.ns, OPEN, run_folder=str(tmp_path / "nothing"), masks_folder=str(tmp_path / "m") + ) + with pytest.raises(notebook_cellpose.CellStop, match="masks folder"): + run_cell(cells.ns, OPEN, run_folder=str(cells.run.out), masks_folder=" ") + with pytest.raises(notebook_cellpose.CellStop, match="inside"): + run_cell( + cells.ns, + OPEN, + run_folder=str(cells.run.out), + masks_folder=str(cells.run.experiment / "masks"), + ) + run_cell(cells.ns, CHANNELS, mask_type="Cells") + + +def test_a_mask_type_preprocessing_would_refuse_stops_the_cell(cells): + run_cell(cells.ns, OPEN, run_folder=str(cells.run.out), masks_folder=str(cells.run.masks)) + with pytest.raises(notebook_cellpose.CellStop): + run_cell(cells.ns, CHANNELS, mask_type="NA") + + +def test_the_closing_cell_gives_the_next_steps_and_the_masks_pass_a_rerun(cells): + from described_tree import check_masks, run_described + from description_tree import MAPPING + from morphobricks_preprocessing.run_inputs import RunInputs + from morphobricks_preprocessing.segmentation_handoff import images_to_segment + + run = cells.run + open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + run_cell(cells.ns, BATCH) + run_cell(cells.ns, NEXT) + text = cells.ns["workflow"].shown[-1] + for needle in ( + "[masks.Cells]", + "representation = ", + "Save the description", + "Run preprocessing again", + "Describe the masks", + "MorphoFeature", + str(run.masks), + ): + assert needle in text + (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) == [] + reopened = RunInputs.open(check_masks(run.out)) + assert reopened.mask_types() == ("Cells",) + assert images_to_segment(reopened, "Cells", run.masks) == () + assert (run.out / MANIFEST_FILENAME).is_file() diff --git a/tests/test_notebook_file.py b/tests/test_notebook_file.py index 3c9ada3..fd36070 100644 --- a/tests/test_notebook_file.py +++ b/tests/test_notebook_file.py @@ -220,7 +220,8 @@ def test_version_metadata_matches_labconstrictor_index(): for line in VERSIONS.read_text(encoding="utf-8").splitlines() if line and not line.startswith("#") ) - assert index == {NOTEBOOK.stem: _setting("current_version")} + # Other notebooks have their own entry (and their own test); this one is checked here. + assert index[NOTEBOOK.stem] == _setting("current_version") def _kernel_notebook(nbformat, *, roles=(INSTALL, DRIVE, RUN), colab_drive=None, override=True): From be8342fd8fb9e7460550b9fba4e3d500224eedf4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:00:46 +0000 Subject: [PATCH 04/22] Cellpose notebook: verify every weight's device, record the full run, reuse display code - Device: every parameter and buffer of the network must sit on the requested device type (model.device only repeats what Cellpose was given); the stand-in has a network now. - Record: weights downloaded in this session and their source, the full normalisation (Cellpose's defaults read at call time, copied) and the flow iterations (passed explicitly), and a note that Cellpose may run its post-processing on the CPU (documented, not refused). - The channel choice is resolved again before a preview or a batch (one refusal, nothing starts); an error while writing the record never hides the error that interrupted the batch. - Batch IDs come from new_batch_id(); the preview reuses preview_render's display_panel and outline. - Colab: restart notes for numpy/opencv and for DINOv3 (installed with --no-deps; the pin is the 22 Nov 2026 branch head, not verified against cpdino). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- AGENTS.md | 2 +- CHANGELOG.md | 7 +- docs/contract.md | 23 +++- docs/user_guide.md | 9 +- notebooks/MorphoBricks_Cellpose.ipynb | 30 ++++- .../notebook_cellpose.py | 57 +++++--- .../preview_render.py | 11 +- .../segmentation_cellpose.py | 114 +++++++++++----- .../segmentation_cellpose_model.py | 125 ++++++++++++++---- tests/cellpose_stub.py | 47 ++++++- tests/test_notebook_cellpose.py | 70 ++++++++++ tests/test_segmentation_cellpose.py | 66 +++++---- tests/test_segmentation_cellpose_record.py | 97 ++++++++++++++ 13 files changed, 527 insertions(+), 131 deletions(-) create mode 100644 tests/test_segmentation_cellpose_record.py diff --git a/AGENTS.md b/AGENTS.md index eb0a9f1..04134f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -262,7 +262,7 @@ src/morphobricks_preprocessing/ segmentation_cellpose.py the Cellpose glue (step 2; cellpose, torch and dinov3 imported only inside functions, Cellpose 4.2.1.1 pinned, not a dependency): Settings, diameter_from_text, eval_arguments (channel_axis=0), segment_image, run_batch (every image written, skipped - or failed in a SegmentationBatch), channel_coverage, display_contrast (display only); + or failed in a SegmentationBatch), channel_coverage (the preview reuses preview_render's display_panel and outline); segmentation_cellpose_model.py choose_model (a built-in name or an existing file, before loading), load_model (the weights file and device verified after loading, no download without allow_download, SHA-256 recorded, DINOv3 at a pinned commit); diff --git a/CHANGELOG.md b/CHANGELOG.md index fabfe53..3a0d41d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,12 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. are dropped by position (more than three are refused), and no diameter means the model's native scale, not an estimate (a blank diameter is recorded as the native scale, 0 is refused). The SHA-256 and file name of the weights, every effective setting and the DINOv3 commit - (`cpdino` models, installed only when ticked) go into the `SegmentationBatch`. 2D images only. + (`cpdino` models, installed only when ticked, `--no-deps`, at a pinned commit that is not + verified against `cpdino`) go into the `SegmentationBatch`, with the full normalisation, the + flow iterations, whether the weights were downloaded and from where, and a note that Cellpose may + run its flow-threshold step on the CPU (and the masks on the CPU on `mps`). The model's device is + verified on every parameter and buffer of the network. The batch ID is `new_batch_id()`. 2D + images only. - **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 diff --git a/docs/contract.md b/docs/contract.md index 95e8063..ade02e1 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1349,14 +1349,27 @@ imported only inside functions, so importing the brick and discovery stay inert) 4.2.1.1 is pinned and is not a dependency. Each of its silent behaviours is a refusal here: a model is one of `cpsam_v2`, `cpsam`, `cpdino`, `cpdino-vitb` or an existing file, checked before loading, and the weights file the loaded model reports must be the one asked for; a device -(`cuda`, `mps`, `cpu`) is always stated, an unavailable one is refused, and every weight must -sit on it after loading; uncached weights are downloaded only on an explicit request; more than +(`cuda`, `mps`, `cpu`) is always stated and an unavailable one is refused. After loading, **every parameter and every +buffer of the loaded network (`model.net`) must be on a device of the requested type** (`cuda:1` +counts as `cuda`; the index is not compared); a network that lists no tensors is refused. +Cellpose's own `model.device` is not evidence (it only repeats the device it was given), and +nothing beyond the network's tensors is verified. Cellpose may still move the flow-threshold +quality step to the CPU when GPU memory is short, and always computes the masks from the flows on +the CPU on `mps`; that is Cellpose's behaviour, **not refused**, and the batch records it as a +note. Uncached weights are downloaded only on an explicit request; more than three channels are refused (Cellpose reads the first three by position); a blank diameter is the model's native scale, never an estimate and never 0. The batch's `model` holds the model name, the weights file name (or the custom file's path) and its SHA-256, and its `parameters` -every effective setting (diameter in pixels or null with its meaning, thresholds, normalisation, -batch and tile size, `channel_axis` 0, device type, versions and, for a DINOv3 model, the DINOv3 -commit). Two-dimensional images only. +every effective setting (diameter in pixels or null with its meaning, thresholds, the **full** +normalisation dictionary given to Cellpose (its defaults read from its module at call time, with +the user's values applied) and the flow iterations `niter` (`int(200 / rescale)`, passed +explicitly), batch and tile size, `channel_axis` 0, device type, versions, `weights_downloaded` +and `weights_source` (the Hugging Face URL Cellpose uses; null for a model file), the device +`notes` and, for a DINOv3 model, the DINOv3 commit). The batch ID is the record's +`new_batch_id()`. The DINOv3 package is installed with `--no-deps` at a pinned commit, the head +of its default branch on 22 November 2026, which is **not verified against `cpdino`**; Cellpose +imports it only when first imported, so the runtime is restarted after installing it. +Two-dimensional images only. ## 16. Shared rules for other bricks (MorphoBricks D86) diff --git a/docs/user_guide.md b/docs/user_guide.md index 0308530..a4afd27 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -250,9 +250,12 @@ segment all images. Then: own. A name or file that does not exist is refused: Cellpose itself would silently use `cpsam_v2`. The weights of a built-in model are downloaded from Hugging Face on first use, only if you tick the download box. `cpdino` models also need DINOv3, installed at a pinned - commit only if you tick its box (restart the runtime after installing it). + commit (the head of its default branch on 22 November 2026, not verified against `cpdino`; installed without its dependencies) only if you tick its box. Restart the runtime after installing it, then run the cells again. - **Device.** You choose `cuda`, `mps` or `cpu`. A GPU that is not available is refused, never - replaced by the CPU. + replaced by the CPU, and after loading every parameter and buffer of the network must be on + the device you chose. Cellpose may still move its flow-threshold quality step to the CPU when + GPU memory is short, and always computes the masks on the CPU on `mps`; that is Cellpose's + behaviour, it is not refused, and the record notes it. - **Diameter** is in pixels. Blank means the model's own native scale (Cellpose 4.2.1.1 does not estimate a diameter); 0 is refused. - **2D only.** An image with more than one Z plane or time point fails with a message that @@ -260,7 +263,7 @@ segment all images. Then: - **Result.** One mask per image at `///.tif` (2D, `int32`, 0 is background, the image's width and height), never over an existing mask unless you tick overwrite, and `//segmentation_record.json` with the model's - file name and SHA-256, every setting, the channels, the device and each image as written, + file name and SHA-256, every setting (the full normalisation and the flow iterations included), whether the weights were downloaded now and from where, the channels, the device and each image as written, skipped or failed. The final table lists every image, with the error of a failed one. Afterwards declare the mask type in the experiment description (for example `[masks.Cells]` diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index a26221e..7782410 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -25,10 +25,10 @@ "- **2D images only for now.** An image with more than one Z plane or time point fails with a message that says so; it is never reduced to one plane.\n", "- **Channels by ID, at most three.** You choose channels by their ID (for example `DNA`, `ACTIN`). In a run where some images have a channel that others lack, only the channels every image has can be used; the notebook shows the refusal as it is. Cellpose reads at most three channels and drops the rest by position, so more than three are refused.\n", "- **Models:** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb`, or a model file of your own. A name or file Cellpose cannot find is **refused**; Cellpose itself would silently use `cpsam_v2` instead.\n", - "- **Downloads:** built-in weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. Nothing downloads unless you tick the download box in cell 5. The `cpdino` models also need DINOv3 (installed only if you tick its box, at a pinned commit).\n", - "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU.\n", + "- **Downloads:** built-in weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. Nothing downloads unless you tick the download box in cell 5. The `cpdino` models also need DINOv3 (installed only if you tick its box, at a pinned commit; see cell 5, which also says that the runtime must be restarted after that).\n", + "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU, and the notebook checks that every weight of the network sits on the device you chose. Cellpose itself may still move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's own behaviour, it is **not refused**, and it is written to the record as a note.\n", "- **Diameter:** in pixels. **Blank means the model's own native scale** (Cellpose 4.2.1.1 does not estimate a diameter). Zero is refused.\n", - "- Every setting that ran, the model's file name and its SHA-256 are written to the record.\n", + "- Every setting that ran (the full normalisation and the flow iterations included), the model's file name and its SHA-256, and whether the weights were downloaded in this session and from where, are written to the record.\n", "\n", "### How to run\n", "\n", @@ -44,7 +44,9 @@ "\n", "## **1. Install Cellpose and MorphoBricks preprocessing**\n", "\n", - "Installs Cellpose 4.2.1.1 and the preprocessing commit this notebook is made for. Nothing is installed when it is already there, so running the cell again is safe. It prints **Ready** with the versions. It never installs DINOv3: that is a choice in cell 5." + "Installs Cellpose 4.2.1.1 and the preprocessing commit this notebook is made for. Nothing is installed when it is already there, so running the cell again is safe. It prints **Ready** with the versions. It never installs DINOv3: that is a choice in cell 5.\n", + "\n", + "**Google Colab:** if the installation upgrades `numpy` or `opencv` while the runtime already has them loaded, the cell stops and tells you to restart the runtime (Runtime > Restart session). Do that, then run cell 1 again: it installs nothing more and prints **Ready**." ] }, { @@ -97,6 +99,8 @@ "# checkout): the cell then says so and installs no other preprocessing.\n", "DEVELOPMENT_OVERRIDE = False\n", "SETUP_RECORD: dict = {}\n", + "# Packages pip may upgrade under a running kernel; each maps to the module that stays loaded.\n", + "LOADED_BY_KERNEL = {\"numpy\": \"numpy\", \"opencv-python\": \"cv2\", \"opencv-python-headless\": \"cv2\"}\n", "\n", "\n", "def _version(name: str) -> str | None:\n", @@ -127,6 +131,7 @@ " if not preprocessing_ok:\n", " wanted.append(f\"morphobricks-preprocessing[{EXTRAS}] @ git+{REPOSITORY}@{RELEASE_REF}\")\n", " if wanted:\n", + " before = {name: _version(name) for name in LOADED_BY_KERNEL}\n", " print(\"Installing \" + \", \".join(wanted) + \"...\", flush=True)\n", " try:\n", " subprocess.run(\n", @@ -139,6 +144,17 @@ " \"then run this cell again.\"\n", " ) from exc\n", " invalidate_caches()\n", + " stale = [\n", + " f\"{name} {before[name]} -> {_version(name)}\"\n", + " for name, module in LOADED_BY_KERNEL.items()\n", + " if before[name] and _version(name) != before[name] and module in sys.modules\n", + " ]\n", + " if stale:\n", + " raise CellStop(\n", + " f\"The installation upgraded {', '.join(stale)} while the runtime already has it \"\n", + " \"loaded. Restart the runtime (Colab: Runtime > Restart session), then run this \"\n", + " \"cell again: it installs nothing more.\"\n", + " )\n", " if _version(\"cellpose\") != CELLPOSE_VERSION:\n", " raise CellStop(\n", " f\"Cellpose {CELLPOSE_VERSION} is not installed ({_version('cellpose')}). Restart \"\n", @@ -338,7 +354,11 @@ "\n", "## **5. Choose the model and the settings, then load the model**\n", "\n", - "Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box. The notebook loads the model, then checks that the weights file is the one you asked for and that the model is on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter is in pixels; blank is the model's native scale." + "Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box. The notebook loads the model, then checks that the weights file is the one you asked for and that the model is on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter is in pixels; blank is the model's native scale.\n", + "\n", + "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose may still move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and whether the weights were downloaded now and from where.\n", + "\n", + "**The `cpdino` models need DINOv3, and a restart.** Ticking the install box installs DINOv3 with `--no-deps` (so it cannot change your PyTorch) at commit `6876159a11b4`, **the head of its default branch on 22 November 2026, not verified against `cpdino`**. Cellpose imports DINOv3 only when it is first imported, so after installing DINOv3 **restart the runtime** (Colab: Runtime > Restart session), run cells 1 to 4 again and load a `cpdino` model; loading before the restart is refused with that instruction." ] }, { diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index 2d0a3a7..5d75e73 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -25,6 +25,7 @@ from . import segmentation_cellpose as cp from .notebook_progress import progress_html from .notebook_style import STYLE_CSS, status, table, tiles +from .preview_render import as_colour, display_panel, outline from .run_inputs import RunInputs, RunInputsError from .segmentation_handoff import SegmentationPlan, images_to_segment, resolve_segmentation from .segmentation_record import SegmentationError, check_mask_type @@ -119,6 +120,23 @@ def _changed(self, _change: object = None) -> None: ) self.message.value = note.value + def current_plan(self) -> SegmentationPlan: + """Resolve the dropdowns as they are now and return the plan, or refuse (once). + + The dropdowns may have changed since the model was loaded; every step that segments + calls this first, so a refused choice stops the cell with the resolver's message + before anything starts. + + Raises + ------ + SegmentationError + With the resolver's message, when the choice is refused. + """ + self._changed() + if self.plan is None: + raise SegmentationError(self.refusal) + return self.plan + def box(self) -> widgets.VBox: """Return the dropdowns and the message under them.""" return widgets.VBox([*self.dropdowns, self.message]) @@ -127,18 +145,19 @@ def box(self) -> widgets.VBox: def preview_figure(stack: np.ndarray, labels: np.ndarray, channel_ids: tuple[str, ...]) -> Figure: """Return the preview: each channel (display contrast only) and the outlines of the labels. - The contrast stretch is for the eye: the stack that was segmented, and the masks, are the - stored values and are never changed by it. + The contrast stretch (preprocessing's own display contrast, which also shows non-finite + pixels as such) is for the eye: the stack that was segmented, and the masks, are the stored + values and are never changed by it. """ - shown = cp.display_contrast(stack) - outlines = cp.label_outlines(labels) - figure = Figure(figsize=(4 * (len(shown) + 1), 4)) - axes = figure.subplots(1, len(shown) + 1, squeeze=False)[0] - for axis, channel, name in zip(axes, shown, channel_ids, strict=False): - axis.imshow(channel, cmap="gray", vmin=0, vmax=1) + panels = [display_panel(np.asarray(channel)).pixels for channel in stack] + edge = outline(np.asarray(labels)) + figure = Figure(figsize=(4 * (len(panels) + 1), 4)) + axes = figure.subplots(1, len(panels) + 1, squeeze=False)[0] + for axis, panel, name in zip(axes, panels, channel_ids, strict=False): + axis.imshow(panel, cmap="gray", vmin=0, vmax=255) axis.set_title(f"{name} (display contrast)") - overlay = np.repeat(shown[0][..., None], 3, axis=-1) - overlay[outlines] = (1.0, 0.85, 0.0) + overlay = as_colour(panels[0]).copy() + overlay[edge] = (255, 217, 0) axes[-1].imshow(overlay) axes[-1].set_title(f"Cellpose: {int(labels.max())} objects") for axis in axes: @@ -253,8 +272,7 @@ def load( ) -> None: """Say what loading does, then load the verified model (cell 5).""" self._need("channels", 4) - if self.picker.plan is None: - raise SegmentationError(self.picker.refusal) + self.picker.current_plan() if self.settings is None: raise SegmentationError("Set the settings first: run set_settings in cell 5.") chosen = custom_model_file.strip() or model @@ -268,6 +286,9 @@ def load( ( "Built-in weights are downloaded from Hugging Face on first use; they are " "downloaded only if the download box is ticked.", + "On a GPU Cellpose may move its flow-threshold quality step to the CPU " + "when GPU memory is short, and always computes the masks on the CPU on " + "mps. That is Cellpose's own behaviour; it is recorded as a note.", ), ) ) @@ -281,6 +302,11 @@ def load( f"Weights file: {loaded.file}", f"SHA-256: {loaded.sha256}", f"Network {loaded.backbone}, tile size {loaded.tile_size}", + ( + f"Weights downloaded now from {loaded.source}" + if loaded.downloaded + else "Weights were already on this computer (nothing downloaded)" + ), "Diameter: " + ( f"{diameter:g} pixels" @@ -295,6 +321,7 @@ def load( def preview(self, image: str = "") -> None: """Segment one image and show it with the outlines; nothing is written (cell 6).""" self._need("model", 5) + plan = self.picker.current_plan() fovs = self.inputs.fovs() todo = images_to_segment(self.inputs, self.mask_type, self.masks_root) by_path = {f.relative_path: f for f in fovs} @@ -304,10 +331,10 @@ def preview(self, image: str = "") -> None: f"such as {fovs[0].relative_path}." ) fov = by_path[image.strip()] if image.strip() else (todo or fovs)[0] - stack = self.picker.plan.read(fov) + stack = plan.read(fov) labels = cp.segment_image(self.loaded, self.settings, stack) self._show(_card("info", f"Preview of {fov.relative_path} (nothing is written)")) - display(preview_figure(stack, labels, self.picker.plan.channel_ids)) + display(preview_figure(stack, labels, plan.channel_ids)) @stops def run(self, overwrite: bool = False) -> cp.BatchResult: @@ -315,7 +342,7 @@ def run(self, overwrite: bool = False) -> cp.BatchResult: self._need("model", 5) job = cp.SegmentationJob( self.inputs, - self.picker.plan, + self.picker.current_plan(), self.loaded, self.settings, self.mask_type, diff --git a/src/morphobricks_preprocessing/preview_render.py b/src/morphobricks_preprocessing/preview_render.py index 4f3dc0f..be5a03d 100644 --- a/src/morphobricks_preprocessing/preview_render.py +++ b/src/morphobricks_preprocessing/preview_render.py @@ -189,7 +189,8 @@ def png_bytes(pixels: np.ndarray) -> bytes: ) -def _as_colour(pixels: np.ndarray) -> np.ndarray: +def as_colour(pixels: np.ndarray) -> np.ndarray: + """Return a grey (Y, X) panel as (Y, X, 3) colour; a colour panel unchanged.""" return pixels if pixels.ndim == 3 else np.repeat(pixels[..., None], 3, axis=2) @@ -207,14 +208,14 @@ def strip_png(panels: Sequence[Panel], gap: int = GAP) -> bytes: colour = any(p.pixels.ndim == 3 for p in panels) pieces = [] for index, panel in enumerate(panels): - shown = _as_colour(panel.pixels) if colour else panel.pixels + shown = as_colour(panel.pixels) if colour else panel.pixels if index: pieces.append(np.full((shown.shape[0], gap, *shown.shape[2:]), 255, np.uint8)) pieces.append(shown) return png_bytes(np.concatenate(pieces, axis=1)) -def _outline(labels: np.ndarray) -> np.ndarray: +def outline(labels: np.ndarray) -> np.ndarray: """Return the pixels of an object that touch another value in a 4-neighbourhood.""" edge = np.zeros(labels.shape, bool) for axis in (0, 1): @@ -252,13 +253,13 @@ def mask_overlay_png(panel: Panel, labels: np.ndarray, representation: str | Non raise OverlayRefused( f"the mask is {labels.shape} and the image {panel.pixels.shape[:2]}: not resampled" ) - shown = _as_colour(panel.pixels).copy() + shown = as_colour(panel.pixels).copy() if representation == BINARY: mark = labels != 0 blend = (1 - _TINT_SHARE) * shown[mark] + _TINT_SHARE * np.array(_TINT) shown[mark] = np.rint(blend).astype(np.uint8) else: - edge = _outline(labels) + edge = outline(labels) palette = np.array(_OUTLINES, np.uint8) shown[edge] = palette[labels[edge].astype(np.int64) % len(palette)] return png_bytes(shown) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index 2fab33f..c118f57 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -17,9 +17,13 @@ position, so more than three are refused (:func:`check_channel_count`). - **Diameter.** Blank means the model's native scale: Cellpose 4.2.1.1 does **not** estimate a diameter. A diameter is in pixels and never 0 (:class:`Settings`). +- **Device behaviour of Cellpose.** On a GPU, Cellpose may move the flow-threshold quality step + to the CPU when GPU memory is short and always computes the masks from the flows on the CPU + on ``mps``. That is Cellpose's own behaviour, not refused; it is recorded as a note. - **Record.** Every effective setting goes into the batch's parameters (:func:`inference_parameters`), every image into the batch with its outcome, written, skipped - or failed with the error (:func:`run_batch`); nothing is dropped. + or failed with the error (:func:`run_batch`); nothing is dropped. The full normalisation, + the flow iterations, and whether built-in weights were downloaded (and from where) are in it. Mask paths, pairing, the mask-type rules, writing, the folder rules and the record are the hand-off's own (:mod:`.segmentation_handoff`, :mod:`.segmentation_record`); nothing is repeated. @@ -31,7 +35,6 @@ import os from collections.abc import Callable, Sequence from dataclasses import dataclass -from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -44,6 +47,7 @@ BUILTIN_MODELS, CELLPOSE_VERSION, DEFAULT_MODEL, + DEVICE_NOTE, DINO_MODELS, DINOV3_COMMIT, DINOV3_URL, @@ -52,6 +56,7 @@ check_device, check_dinov3, choose_model, + default_normalization, dinov3_install_command, install_dinov3, installed_dinov3_commit, @@ -66,6 +71,7 @@ SegmentedImage, check_mask_type, mask_sha256, + new_batch_id, write_record, ) @@ -82,6 +88,7 @@ "check_device", "check_dinov3", "choose_model", + "default_normalization", "dinov3_install_command", "install_dinov3", "installed_dinov3_commit", @@ -96,6 +103,8 @@ TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 """Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" NORMALIZE_PERCENTILE = [1.0, 99.0] +FLOW_ITERATIONS = 200 +"""Cellpose's flow iterations at the native scale; it divides it by the rescale factor.""" NATIVE_SCALE = ( "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " "diameter means the model's own scale" @@ -193,24 +202,54 @@ def diameter_from_text(text: str) -> float | None: # --- one image -------------------------------------------------------------------------------- +def rescale_factor(settings: Settings) -> float: + """Return the factor Cellpose derives from the diameter: 30 / diameter, or 1 (native scale).""" + return 1.0 if settings.diameter is None else 30.0 / settings.diameter + + +def flow_iterations(settings: Settings) -> int: + """Return the flow iterations Cellpose 4.2.1.1 uses when none are given: 200 / rescale. + + Cellpose computes ``int(200 / rescale)`` (resampling is on); it is passed explicitly and + recorded, so what ran is not left to Cellpose's derivation. + """ + return max(1, int(FLOW_ITERATIONS / rescale_factor(settings))) + + +def normalization(settings: Settings) -> dict[str, Any]: + """Return the full normalisation given to Cellpose: its defaults now, with the user's values. + + The defaults (``tile_norm_blocksize``, ``sharpen_radius``, ``invert``, ``lowhigh``, ...) come + from Cellpose's module global at call time, copied; ``normalize`` and the percentiles are + then set from the settings. Nothing is left to Cellpose's defaults, so the record holds all. + """ + return { + **default_normalization(), + "normalize": settings.normalize, + "percentile": list(NORMALIZE_PERCENTILE), + } + + def eval_arguments(loaded: LoadedModel, settings: Settings) -> dict[str, Any]: """Return every argument given to ``model.eval``, the effective inference settings. ``channel_axis`` is 0: the stack from :meth:`.segmentation_handoff.SegmentationPlan.read` - is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size and the other - values Cellpose would default are given explicitly, so what is recorded is what ran. + is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size, the full + normalisation, the flow iterations and the other values Cellpose would default are given + explicitly, so what is recorded is what ran. """ return { "batch_size": settings.batch_size, "resample": True, "channel_axis": 0, - "normalize": {"normalize": settings.normalize, "percentile": list(NORMALIZE_PERCENTILE)}, + "normalize": normalization(settings), "diameter": settings.diameter, "flow_threshold": settings.flow_threshold, "cellprob_threshold": settings.cellprob_threshold, "do_3D": False, "min_size": MIN_SIZE, "max_size_fraction": MAX_SIZE_FRACTION, + "niter": flow_iterations(settings), "augment": False, "tile_overlap": TILE_OVERLAP, "bsize": loaded.tile_size, @@ -258,20 +297,27 @@ def inference_parameters( """Return the parameters of a batch for the record: every effective setting, plain JSON. The diameter is in pixels, or null with the statement that it is the model's native - scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). + scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). The + normalisation is the full dictionary given to Cellpose and ``niter`` the flow iterations + it derives from the rescale. ``weights_downloaded`` and ``weights_source`` say whether this + session downloaded the built-in weights and from where; ``notes`` holds Cellpose's device + behaviour (:data:`.segmentation_cellpose_model.DEVICE_NOTE`) for a GPU run. """ arguments = eval_arguments(loaded, settings) - scale = 1.0 if settings.diameter is None else 30.0 / settings.diameter + notes = [DEVICE_NOTE] if loaded.device != "cpu" else [] return { **arguments, "diameter_unit": "pixels" if settings.diameter is not None else NATIVE_SCALE, - "rescale": scale, + "rescale": rescale_factor(settings), "channel_ids_order": list(channel_ids), "device_type": loaded.device, "backbone": loaded.backbone, "use_bfloat16": True, "cellpose_version": CELLPOSE_VERSION, "dinov3_commit": loaded.dinov3_commit, + "weights_downloaded": loaded.downloaded, + "weights_source": loaded.source, + "notes": notes, } @@ -302,6 +348,11 @@ class SegmentationJob: masks_root: Path overwrite: bool = False + def __post_init__(self) -> None: + """Refuse a job without resolved channels, before anything is segmented.""" + if self.plan is None: + raise SegmentationError("No channels are resolved: choose channels the run has.") + @dataclass(frozen=True) class BatchResult: @@ -364,6 +415,14 @@ def _batch(job: SegmentationJob, batch_id: str, images: list[SegmentedImage]) -> ) +def _write_batch( + job: SegmentationJob, batch_id: str, entries: list[SegmentedImage] +) -> tuple[SegmentationBatch, Path | None]: + """Build the batch and write its record (none when no image was handled).""" + batch = _batch(job, batch_id, entries) + return batch, write_record(job.masks_root, job.mask_type, batch) if entries else None + + def run_batch( job: SegmentationJob, fovs: Sequence[Fov] | None = None, @@ -386,7 +445,7 @@ def run_batch( progress Called as ``progress(done, total, image)`` before each image and once at the end. batch_id - The record's batch ID; by default the start time (UTC, to the microsecond). + The record's batch ID; by default :func:`.segmentation_record.new_batch_id`. Raises ------ @@ -398,7 +457,7 @@ def run_batch( missing = { f.relative_path for f in images_to_segment(job.inputs, job.mask_type, job.masks_root) } - started = batch_id or datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + started = batch_id or new_batch_id() entries: list[SegmentedImage] = [] try: for done, fov in enumerate(chosen): @@ -410,9 +469,15 @@ def run_batch( entries.append(SegmentedImage(fov.relative_path, "skipped", IMAGE_SKIPPED)) if progress is not None: progress(len(chosen), len(chosen), "") - finally: - batch = _batch(job, started, entries) - record = write_record(job.masks_root, job.mask_type, batch) if entries else None + except BaseException as interrupted: + # The record of what was done is still written; if that fails too, the first error is + # the one raised (the second is attached to it), never one that hides it. + try: + _write_batch(job, started, entries) + except Exception as second: + interrupted.add_note(f"The record could not be written either: {second}") + raise + batch, record = _write_batch(job, started, entries) return BatchResult(batch, record) @@ -441,29 +506,6 @@ def channel_coverage(inputs: RunInputs) -> dict[str, tuple[int, int]]: return {c: (sum(c in (f.channel_ids or ()) for f in fovs), len(fovs)) for c in order} -def display_contrast(stack: np.ndarray, low: float = 1.0, high: float = 99.0) -> np.ndarray: - """Return ``stack`` as float32 in 0 to 1, each channel stretched between two percentiles. - - For **display only** (the preview): a new array, the stack is never changed, and nothing - of it is ever written. A channel with no spread shows as 0. - """ - shown = np.zeros(np.shape(stack), np.float32) - for index, channel in enumerate(np.asarray(stack, dtype=np.float64)): - lo, hi = np.percentile(channel, [low, high]) - if hi > lo: - shown[index] = np.clip((channel - lo) / (hi - lo), 0.0, 1.0) - return shown - - -def label_outlines(labels: np.ndarray) -> np.ndarray: - """Return a boolean image that is True on the boundary pixels of every label (display).""" - lab = np.asarray(labels) - edge = np.zeros(lab.shape, bool) - edge[:, :-1] |= lab[:, :-1] != lab[:, 1:] - edge[:-1, :] |= lab[:-1, :] != lab[1:, :] - return edge & (lab > 0) - - def next_steps_lines(mask_type: str, masks_root: str | os.PathLike) -> tuple[str, ...]: """Return what to do after the masks are made, as lines of text. diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py index f2d37bb..172dba9 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_model.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -7,9 +7,13 @@ Cellpose 4.2.1.1 replaces a model name or path it cannot find by ``cpsam_v2`` with a log warning, turns an unavailable GPU into the CPU, and downloads uncached built-in weights. Each is checked here: the model is one of :data:`BUILTIN_MODELS` or an existing file (validated -before loading); the weights file the loaded model reports must be the one asked for; every -weight must sit on the stated device (an unavailable one is refused up front); and uncached -weights are downloaded only with ``allow_download``. The weights file is hashed for the record. +before loading); the weights file the loaded model reports must be the one asked for; the +device is unavailable-refused up front, and after loading **every parameter and every buffer** +of the network (``model.net``) must sit on a device of the requested type (``cuda:1`` counts as +``cuda``; the index is not checked). ``model.device`` is not evidence: Cellpose 4.2.1.1 only +stores the device it was given. Uncached weights are downloaded only with ``allow_download``; +whether they were, and from where, goes into the record. The weights file is hashed for the +record. """ from __future__ import annotations @@ -37,8 +41,16 @@ """The built-in models that need the DINOv3 package (:data:`DINOV3_COMMIT`).""" DINOV3_URL = "https://github.com/facebookresearch/dinov3" DINOV3_COMMIT = "6876159a11b4df116f30f667f8c9888617df0751" -"""The DINOv3 commit installed for ``cpdino`` models (the head of its default branch on -22 November 2026); a model that needs DINOv3 runs only with exactly this commit installed.""" +"""The DINOv3 commit installed for ``cpdino`` models: the head of its default branch on +22 November 2026, **not verified against cpdino** (it is a pin, not a tested pairing). A model +that needs DINOv3 runs only with exactly this commit installed.""" +DEVICE_NOTE = ( + "Cellpose may move the flow-threshold quality step to the CPU when the GPU has too little " + "memory (images above 10000 x 10000 pixels on cuda), and always computes the masks from the " + "flows on the CPU on mps. This is Cellpose's own behaviour; it is not refused, and the " + "network itself ran on the device recorded." +) +"""Recorded with a batch that ran on a GPU (not refused: the network still runs on the device).""" SAM_TILE, DINO_TILE = 256, 384 """The tile size (``bsize``) of a SAM model and of a DINOv3 model.""" @@ -154,6 +166,16 @@ def weights_file(name: str) -> Path: return Path(os.fspath(_cellpose_models().MODEL_DIR)) / name +def default_normalization() -> dict: + """Return a copy of Cellpose's own normalisation defaults, read from its module right now. + + Cellpose 4.2.1.1 keeps them in ``cellpose.models.normalize_default`` (a module global that + its own ``eval`` writes to when ``normalize`` is a bool), so they are read at call time and + copied; the caller applies the user's values on the copy. + """ + return dict(_cellpose_models().normalize_default) + + def installed_dinov3_commit() -> str | None: """Return the Git commit the installed DINOv3 package came from, or None when unknown. @@ -172,9 +194,23 @@ def installed_dinov3_commit() -> str | None: def dinov3_install_command() -> list[str]: - """Return the ``pip`` command that installs DINOv3 at :data:`DINOV3_COMMIT`.""" + """Return the ``pip`` command that installs DINOv3 at :data:`DINOV3_COMMIT`, without deps. + + ``--no-deps``: DINOv3's requirements (``torch``, ``torchvision``, ``torchmetrics``, ...) are + unpinned and could replace the torch Cellpose runs on. Cellpose reaches DINOv3 only through + ``dinov3.hub.backbones``, which imports nothing but ``numpy`` and ``torch`` (read at the + pinned commit). + """ spec = f"git+{DINOV3_URL}@{DINOV3_COMMIT}" - return [sys.executable, "-m", "pip", "install", "--disable-pip-version-check", spec] + return [ + sys.executable, + "-m", + "pip", + "install", + "--disable-pip-version-check", + "--no-deps", + spec, + ] def install_dinov3() -> None: @@ -197,7 +233,7 @@ def check_dinov3(models: ModuleType) -> str: """Return the commit of the installed DINOv3 if it is the pinned one, else refuse. Cellpose imports DINOv3 when it is first imported, so DINOv3 installed after that needs a - restart of the runtime (the check says so). + restart of the runtime (the check says so): install it, restart, then load the model. """ command = " ".join(dinov3_install_command()[2:]) commit = installed_dinov3_commit() @@ -238,7 +274,13 @@ class LoadedModel: sha256 The SHA-256 of that file. device - ``cuda``, ``cpu`` or ``mps``: where the model sits, as verified after loading. + ``cuda``, ``cpu`` or ``mps``: the device type every parameter and buffer of the network + was verified to sit on after loading. + downloaded + True when this call downloaded the built-in weights (they were not on disk). + source + Where Cellpose downloads the built-in weights from (its URL on Hugging Face), or None + for a custom model file. backbone Cellpose's name of the network (``sam_vitl``, ``dino_vitl``, ...). tile_size @@ -256,24 +298,33 @@ class LoadedModel: backbone: str tile_size: int dinov3_commit: str | None = None + downloaded: bool = False + source: str | None = None -def _expected(models: ModuleType, choice: ModelChoice, allow_download: bool) -> tuple[Path, str]: - """Return the weights file this model must be, and what to hand to Cellpose to load it. +def _source(models: ModuleType, choice: ModelChoice) -> str | None: + """Return the URL Cellpose downloads built-in weights ``choice`` from, None for a file.""" + return None if choice.path is not None else f"{models._MODEL_URL}{choice.name}" + + +def _expected( + models: ModuleType, choice: ModelChoice, allow_download: bool +) -> tuple[Path, str, bool]: + """Return the weights file, what to hand to Cellpose to load it, and whether it downloads. A built-in model already on disk is handed over by its absolute path, so Cellpose looks nowhere else (not in the working folder, not in its list of user models) and cannot download. One that is not on disk is handed over by name only when ``allow_download``. """ if choice.path is not None: - return choice.path, os.fspath(choice.path) + return choice.path, os.fspath(choice.path), False expected = Path(os.fspath(models.MODEL_DIR)) / choice.name if expected.is_file(): - return expected, os.fspath(expected) + return expected, os.fspath(expected), False if not allow_download: raise SegmentationError( f"The weights of {choice.name} are not on this computer ({expected}). The built-in " - "weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. " + f"weights are downloaded from Hugging Face ({_source(models, choice)}) on first use. " "Allow the download on purpose (tick it in the notebook) and run the cell again." ) if os.path.lexists(choice.name): @@ -281,7 +332,7 @@ def _expected(models: ModuleType, choice: ModelChoice, allow_download: bool) -> f"A file or folder named {choice.name} is in the working folder, and Cellpose would " "load it instead of downloading the model. Change to another working folder." ) - return expected, choice.name + return expected, choice.name, True def _construct(models: ModuleType, request: str, device: str) -> object: @@ -300,14 +351,27 @@ def _construct(models: ModuleType, request: str, device: str) -> object: ) from exc -def _device_types(loaded: object) -> set[str]: - """Return the device types the loaded model reports (and its first weight, when it has one).""" - found = {str(loaded.device.type)} - parameters = getattr(getattr(loaded, "net", None), "parameters", None) - first = next(iter(parameters()), None) if callable(parameters) else None - if first is not None: - found.add(str(first.device.type)) - return found +def _weight_devices(loaded: object) -> tuple[int, set[str]]: + """Return how many tensors the network holds and the device types of all of them. + + Every parameter and every buffer of ``loaded.net`` counts. A model without a network that + lists its tensors, or one with none, proves nothing and is refused. + """ + net = getattr(loaded, "net", None) + tensors = [] + for listing in ("parameters", "buffers"): + method = getattr(net, listing, None) + if not callable(method): + raise SegmentationError( + "The loaded model's network does not list its weights, so the device they sit " + "on cannot be checked; refused." + ) + tensors.extend(method()) + if not tensors: + raise SegmentationError( + "The loaded model's network holds no weights, so the device cannot be checked; refused." + ) + return len(tensors), {str(t.device.type) for t in tensors} def _verify(loaded: object, expected: Path, device: str, choice: ModelChoice) -> None: @@ -318,10 +382,12 @@ def _verify(loaded: object, expected: Path, device: str, choice: ModelChoice) -> f"Cellpose loaded {got or 'an unknown file'} instead of {expected} for {choice.name}: " "it substituted another model. Nothing was segmented." ) - if _device_types(loaded) != {device}: + count, found = _weight_devices(loaded) + if found != {device}: raise SegmentationError( - f"The device {device} was asked for but the model sits on " - f"{', '.join(sorted(_device_types(loaded)))}. Nothing falls back to another device." + f"The device {device} was asked for but weights of the model sit on " + f"{', '.join(sorted(found))} ({count} parameters and buffers checked). Nothing " + "falls back to another device." ) @@ -333,7 +399,8 @@ def load_model( The order is: the model and device are validated, Cellpose's version is checked, the weights must be on disk (or the download allowed), a DINOv3 model needs the pinned DINOv3; then the model is loaded and **verified** (the weights file it reports is the one - asked for; every weight sits on the stated device), and the weights file is hashed. + asked for; every parameter and buffer of the network sits on the stated device type), and + the weights file is hashed. Raises ------ @@ -347,7 +414,7 @@ def load_model( models = _cellpose_models() dino = choice.name in DINO_MODELS commit = check_dinov3(models) if dino else None - expected, request = _expected(models, choice, allow_download) + expected, request, downloads = _expected(models, choice, allow_download) loaded = _construct(models, request, device) _verify(loaded, expected, device, choice) backbone = getattr(loaded, "backbone", None) @@ -365,4 +432,6 @@ def load_model( backbone=backbone, tile_size=SAM_TILE if backbone == "sam_vitl" else DINO_TILE, dinov3_commit=commit, + downloaded=downloads, + source=_source(models, choice), ) diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py index f341dbb..27d46b4 100644 --- a/tests/cellpose_stub.py +++ b/tests/cellpose_stub.py @@ -4,8 +4,10 @@ the real ``CellposeModel`` does that matters here, read from the 4.2.1.1 source: a name or path it cannot find is replaced by ``cpsam_v2`` (downloaded if absent), a built-in name is looked for in ``MODEL_DIR`` and fetched when missing, and ``pretrained_model`` / ``device`` / ``backbone`` -are set on the loaded model. Its ``eval`` records every call (the stack and the keywords) and -returns a fixed label image, so a test sees exactly what Cellpose was given. +are set on the loaded model. As in 4.2.1.1 ``device`` is only the device it was given; where +the weights sit is told by ``net`` (parameters and buffers with a ``device``). Its ``eval`` +records every call (the stack and the keywords) and returns a fixed label image, so a test sees +exactly what Cellpose was given. """ import sys @@ -39,6 +41,20 @@ def __init__(self, type): self.type = type +class Net: + """The network: parameters and buffers with a ``device`` (``state.params`` / ``buffers``).""" + + def __init__(self, state, device_type): + self._params = [Device(t) for t in state.params or [device_type] * 3] + self._buffers = [Device(t) for t in state.buffers or [device_type] * 2] + + def parameters(self): + return iter(SimpleNamespace(device=d) for d in self._params) + + def buffers(self): + return iter(SimpleNamespace(device=d) for d in self._buffers) + + def model_class(state): """Return the stand-in ``CellposeModel`` class bound to ``state``.""" @@ -48,7 +64,8 @@ def __init__(self, gpu=False, pretrained_model="cpsam_v2", device=None, **kwargs SimpleNamespace(gpu=gpu, pretrained_model=pretrained_model, device=device, **kwargs) ) self.pretrained_model = state.substitute or self._resolve(pretrained_model) - self.device = Device(state.device_type or device.type) + self.device = device # as in Cellpose: only what was passed in + self.net = None if state.no_net else Net(state, device.type) dino = "dino" in Path(self.pretrained_model).name self.backbone = "dino_vitl" if dino else "sam_vitl" @@ -77,6 +94,8 @@ def modules(state): """Return the fake ``cellpose``, ``cellpose.models`` and ``torch`` modules.""" models = types.ModuleType("cellpose.models") models.MODEL_DIR = state.models_dir + models._MODEL_URL = "https://huggingface.co/mouseland/cellpose-sam/resolve/main/" + models.normalize_default = dict(state.normalize_default) models.CellposeModel = model_class(state) if state.has_cpdino: models.CPDINO = object @@ -93,9 +112,10 @@ def install(monkeypatch, tmp_path, **options): """Install the stand-in; return its state (calls, constructed, and switches to flip). Switches (set on the returned state before loading): ``cuda`` / ``mps`` availability, - ``substitute`` (the path every loaded model reports, whatever was asked), ``device_type`` - (the device every loaded model reports), ``fail`` (a function of the stack that raises), - ``version`` and ``dinov3_commit``. + ``substitute`` (the path every loaded model reports, whatever was asked), ``params`` / + ``buffers`` (the device types of the network's tensors, when not the requested one), + ``no_net``, ``fail`` (a function of the stack that raises), ``version`` and + ``dinov3_commit``. """ models_dir = tmp_path / "cellpose_models" models_dir.mkdir(exist_ok=True) @@ -107,11 +127,24 @@ def install(monkeypatch, tmp_path, **options): cuda=False, mps=False, substitute=None, - device_type=None, + params=None, + buffers=None, + no_net=False, fail=None, version="4.2.1.1", dinov3_commit=model_module.DINOV3_COMMIT, has_cpdino=True, + normalize_default={ + "lowhigh": None, + "percentile": None, + "normalize": True, + "norm3D": True, + "sharpen_radius": 0, + "smooth_radius": 0, + "tile_norm_blocksize": 0, + "tile_norm_smooth3D": 1, + "invert": False, + }, ) for name, value in options.items(): setattr(state, name, value) diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index 678fae9..cd8d55b 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -13,6 +13,7 @@ import sys from pathlib import Path +import numpy as np import pytest import tifffile @@ -156,6 +157,7 @@ def installer(monkeypatch): state.versions = {"cellpose": "4.2.1.1", "morphobricks-preprocessing": "0.8.0"} state.commit = setting("RELEASE_REF") state.pip = [] + state.upgrades = {} # versions pip changes when it runs import importlib.metadata as metadata def fake_version(name): @@ -169,6 +171,7 @@ def read_text(self, name): def fake_run(command, check): state.pip.append(command) + state.versions.update(state.upgrades) state.versions["cellpose"] = "4.2.1.1" state.commit = setting("RELEASE_REF") @@ -201,6 +204,34 @@ def test_the_install_cell_installs_the_pinned_versions_when_they_differ(installe assert not any("dinov3" in a for a in command) +def test_an_install_that_upgrades_a_loaded_numpy_or_opencv_says_to_restart(installer): + assert "numpy" in sys.modules # loaded by the kernel, as in Colab + installer.versions.update(cellpose="4.0.0", numpy="1.26.4") + installer.upgrades = {"numpy": "2.1.0"} + with pytest.raises(RuntimeError, match=r"upgraded numpy 1.26.4 -> 2.1.0.*Restart the runtime"): + run_cell({}, INSTALL) + run_cell({}, INSTALL) # after the restart: nothing more is installed, and it is ready + assert len(installer.pip) == 1 + + +def test_an_upgrade_of_a_package_the_kernel_has_not_loaded_needs_no_restart(installer): + installer.versions.update(cellpose="4.0.0", **{"opencv-python": "4.9.0"}) + installer.upgrades = {"opencv-python": "4.10.0"} + assert "cv2" not in sys.modules + run_cell({}, INSTALL) + + +def test_the_text_warns_about_the_restarts_the_downloads_and_the_unverified_dinov3_pin(): + text = {n: "".join(c["source"]) for n, c in enumerate(notebook()["cells"])} + assert "Restart session" in text[1] and "numpy" in text[1] + assert "restart the runtime" in text[9] and "--no-deps" in text[9] + assert "not verified against `cpdino`" in text[9] and "22 November 2026" in text[9] + for number in (0, 9): # the introduction and cell 5 + assert "flow-threshold quality step to the CPU" in text[number] + assert "not refused" in text[number] or "is **not refused**" in text[number] + assert "every parameter and buffer" in text[9] + + # the cells run on a synthetic run ---------------------------------------------------------- @@ -307,6 +338,45 @@ def test_the_weights_download_needs_its_box_and_the_cell_says_where_from(cells): assert cells.stub.downloaded == ["cpsam_v2"] +def test_the_load_card_says_whether_the_weights_were_downloaded_and_from_where(cells): + open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + assert "nothing downloaded" in cells.ns["workflow"].shown[-1] + cells.stub.models_dir.joinpath("cpsam").unlink() + run_cell(cells.ns, MODEL, model="cpsam", device="cpu", download_weights=True) + assert "downloaded now from https://huggingface.co/" in cells.ns["workflow"].shown[-1] + run_cell(cells.ns, BATCH) + params = read_record(cells.run.masks, "Cells").batches[0].parameters + assert params["weights_downloaded"] is True and params["weights_source"].endswith("/cpsam") + + +@pytest.mark.parametrize("cell", [PREVIEW, BATCH]) +def test_a_channel_choice_refused_after_loading_stops_the_cell_once_and_starts_nothing(cells, cell): + picker = open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + picker.dropdowns[1].value = "EXTRA" # the dropdowns change after the model is loaded + assert picker.plan is None + with pytest.raises(notebook_cellpose.CellStop) as stopped: + run_cell(cells.ns, cell) + assert str(stopped.value) == picker.refusal and "A_SCOPE_INCOMPLETE" in str(stopped.value) + assert ( + stopped.value.__cause__ is not None and stopped.value.__context__ is stopped.value.__cause__ + ) + assert cells.stub.calls == [] and not cells.run.masks.exists() # no image, no record + picker.dropdowns[1].value = "DNA" # a valid choice again: the cell runs + run_cell(cells.ns, cell) + assert len(cells.stub.calls) >= 1 + + +def test_the_preview_figure_uses_the_display_contrast_and_shows_non_finite_pixels(): + stack = np.arange(32, dtype=np.float32).reshape(2, 4, 4) + stack[0, 0, 0] = np.nan + labels = np.zeros((4, 4), np.uint16) + labels[1:3, 1:3] = 1 + figure = notebook_cellpose.preview_figure(stack, labels, ("A", "B")) + assert len(figure.axes) == 3 and "1 objects" in figure.axes[-1].get_title() + + def test_failures_are_in_the_final_table_and_the_batch_goes_on(cells): open_and_choose(cells) run_cell(cells.ns, MODEL, device="cpu") diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py index 00027e8..d18d171 100644 --- a/tests/test_segmentation_cellpose.py +++ b/tests/test_segmentation_cellpose.py @@ -146,12 +146,35 @@ def test_a_gpu_that_is_not_available_is_refused_and_never_replaced_by_the_cpu(st assert stub.constructed == [] -def test_a_model_that_sits_on_another_device_than_asked_is_refused(stub): - stub.cuda, stub.device_type = True, "cpu" # Cellpose's silent GPU -> CPU fallback - with pytest.raises(SegmentationError, match="cuda was asked for but the model sits on cpu"): +@pytest.mark.parametrize( + "tensors", + [ + {"params": ["cuda", "cuda", "cpu"]}, # a parameter after the first sits elsewhere + {"buffers": ["cuda", "cpu"]}, # a buffer sits elsewhere + {"params": ["cpu", "cpu", "cpu"], "buffers": ["cpu"]}, # Cellpose's GPU -> CPU fallback + ], +) +def test_a_network_with_any_weight_on_another_device_than_asked_is_refused(stub, tensors): + # model.device is only what was passed in (Cellpose 4.2.1.1): the tensors are the evidence. + stub.cuda = True + for name, value in tensors.items(): + setattr(stub, name, value) + with pytest.raises(SegmentationError, match="cuda was asked for but weights of the model sit"): cp.load_model("cpsam_v2", "cuda") +def test_the_device_check_covers_every_parameter_and_buffer_of_a_cuda_index(stub): + stub.cuda = True + stub.params, stub.buffers = ["cuda", "cuda"], ["cuda"] # cuda:0 reports type cuda + assert cp.load_model("cpsam_v2", "cuda").device == "cuda" + + +def test_a_model_whose_weights_cannot_be_listed_is_refused(stub): + stub.no_net = True + with pytest.raises(SegmentationError, match="does not list its weights"): + cp.load_model("cpsam_v2", "cpu") + + def test_the_gpu_is_used_when_asked_and_present(stub): stub.cuda = True loaded = cp.load_model("cpsam_v2", "cuda") @@ -214,6 +237,7 @@ def test_the_dinov3_install_command_pins_the_commit(): command = model_module.dinov3_install_command() assert command[1:4] == ["-m", "pip", "install"] assert command[-1] == f"git+https://github.com/facebookresearch/dinov3@{cp.DINOV3_COMMIT}" + assert "--no-deps" in command # DINOv3's unpinned requirements must not replace torch assert len(cp.DINOV3_COMMIT) == 40 @@ -365,12 +389,24 @@ def test_every_effective_setting_is_in_the_record(run, stub): params = read_record(run.masks, "Cells").batches[0].parameters assert params == batch.parameters assert (params["flow_threshold"], params["cellprob_threshold"]) == (0.2, -1.5) - assert params["normalize"] == {"normalize": False, "percentile": [1.0, 99.0]} + assert params["normalize"] == { + **stub.normalize_default, + "normalize": False, + "percentile": [1.0, 99.0], + } + assert params["niter"] == 166 and params["rescale"] == 30 / 25 # 200 / rescale assert (params["batch_size"], params["bsize"], params["tile_overlap"]) == (4, 256, 0.1) assert (params["device_type"], params["cellpose_version"]) == ("cpu", "4.2.1.1") assert params["channel_axis"] == 0 and params["do_3D"] is False assert params["channel_ids_order"] == ["TUB", "DNA"] and batch.channel_ids == ("TUB", "DNA") - for key in ("flow_threshold", "cellprob_threshold", "batch_size", "bsize", "normalize"): + for key in ( + "flow_threshold", + "cellprob_threshold", + "batch_size", + "bsize", + "normalize", + "niter", + ): assert stub.calls[0].kwargs[key] == params[key] # what ran is what was recorded @@ -484,26 +520,6 @@ def test_masks_of_the_batch_pass_preprocessings_own_mask_checks_on_a_rerun(run, # what the preview shows, and the next steps --------------------------------------------------- -def test_the_display_contrast_is_per_channel_and_never_touches_the_stack(run): - fov = run.inputs.fovs()[0] - stack = resolve_segmentation(run.inputs, ("TUB", "DNA")).read(fov) - before = stack.copy() - shown = cp.display_contrast(stack) - np.testing.assert_array_equal(stack, before) - assert shown.dtype == np.float32 and shown.shape == stack.shape - assert shown.min() >= 0 and shown.max() <= 1 - assert shown[0].max() == 1.0 and shown[1].max() == 1.0 # each channel on its own range - assert cp.display_contrast(np.full((1, 4, 4), 7)).max() == 0 # no spread shows as 0 - - -def test_label_outlines_mark_the_boundary_of_every_label(): - labels = np.zeros((6, 6), np.uint16) - labels[1:5, 1:5] = 3 - edge = cp.label_outlines(labels) - assert edge.sum() > 0 and not edge[0].any() - assert not edge[labels == 0].any() # only inside a label - - def test_next_steps_tell_how_to_declare_the_mask_type(tmp_path): text = "\n".join(cp.next_steps_lines("Cells", tmp_path / "masks")) assert "[masks.Cells]" in text and 'representation = "instances"' in text diff --git a/tests/test_segmentation_cellpose_record.py b/tests/test_segmentation_cellpose_record.py new file mode 100644 index 0000000..023d8a1 --- /dev/null +++ b/tests/test_segmentation_cellpose_record.py @@ -0,0 +1,97 @@ +"""What the Cellpose batch records (full normalisation, flow iterations, downloads, notes, ID). + +Split from ``test_segmentation_cellpose.py``; the stand-in and the run are the same. +""" + +import dataclasses +import re +import sys + +import pytest + +from cellpose_stub import custom_model, install +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing.segmentation_record import SegmentationError +from test_segmentation_cellpose import make_job + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def test_the_record_says_whether_the_weights_were_downloaded_and_from_where(stub, tmp_path): + url = "https://huggingface.co/mouseland/cellpose-sam/resolve/main/" + on_disk = cp.load_model("cpsam", "cpu") + assert (on_disk.downloaded, on_disk.source) == (False, url + "cpsam") + (stub.models_dir / "cpsam").unlink() + fetched = cp.load_model("cpsam", "cpu", allow_download=True) + assert (fetched.downloaded, fetched.source) == (True, url + "cpsam") + params = cp.inference_parameters(fetched, cp.Settings(), ("DNA",)) + assert params["weights_downloaded"] is True and params["weights_source"] == url + "cpsam" + own = cp.load_model(str(custom_model(tmp_path)), "cpu") + assert (own.downloaded, own.source) == (False, None) + + +def test_the_full_normalisation_is_read_from_cellpose_now_copied_and_recorded(run, stub): + models = sys.modules["cellpose.models"] + models.normalize_default["tile_norm_blocksize"] = 100 # as set by another cell or session + models.normalize_default["normalize"] = False # Cellpose's eval writes this global itself + full = cp.eval_arguments(cp.load_model("cpsam_v2", "cpu"), cp.Settings())["normalize"] + assert full["tile_norm_blocksize"] == 100 and full["normalize"] is True # the user's wins + assert set(full) == set(stub.normalize_default) and full["percentile"] == [1.0, 99.0] + assert models.normalize_default["percentile"] is None # the global is not written to + cp.run_batch(make_job(run), batch_id="b1") + assert stub.calls[0].kwargs["normalize"] == full + + +def test_the_flow_iterations_are_cellpose_derivation_given_and_recorded(stub): + loaded = cp.load_model("cpsam_v2", "cpu") + assert cp.eval_arguments(loaded, cp.Settings())["niter"] == 200 + assert cp.eval_arguments(loaded, cp.Settings(diameter=60))["niter"] == 400 # int(200 / 0.5) + assert cp.eval_arguments(loaded, cp.Settings(diameter=1e-9))["niter"] == 1 # never 0 = derive + + +def test_a_gpu_batch_records_that_cellpose_may_use_the_cpu_for_post_processing(stub): + stub.cuda = True + on_gpu = cp.inference_parameters(cp.load_model("cpsam_v2", "cuda"), cp.Settings(), ("DNA",)) + assert on_gpu["notes"] == [model_module.DEVICE_NOTE] + assert "mps" in model_module.DEVICE_NOTE and "not refused" in model_module.DEVICE_NOTE + on_cpu = cp.inference_parameters(cp.load_model("cpsam_v2", "cpu"), cp.Settings(), ("DNA",)) + assert on_cpu["notes"] == [] + + +def test_the_default_batch_id_is_the_records_own_unique_id(run, stub): + first = cp.run_batch(make_job(run)).batch.batch_id + second = cp.run_batch(make_job(run, overwrite=True)).batch.batch_id + assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ-[0-9a-f]{8}", first) + assert first != second # two batches in the same second never clash + + +def test_a_job_without_resolved_channels_is_refused_before_anything_runs(run, stub): + with pytest.raises(SegmentationError, match="No channels are resolved"): + dataclasses.replace(make_job(run), plan=None) + assert stub.calls == [] + + +def test_an_error_while_writing_the_record_never_hides_the_error_that_interrupted( + run, stub, monkeypatch +): + def interrupt(stack): + if len(stub.calls) == 2: # one image is done, so there is a record to write + raise KeyboardInterrupt + + def broken(*args): + raise OSError("disk full") + + stub.fail = interrupt + monkeypatch.setattr(cp, "write_record", broken) + with pytest.raises(KeyboardInterrupt) as raised: + cp.run_batch(make_job(run)) + assert "disk full" in " ".join(raised.value.__notes__) From 52996b8f1d499735ae52c06c673d2435abf3b191 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:02:06 +0000 Subject: [PATCH 05/22] Pin the Cellpose notebook to the commit that holds its code (be8342f) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 7782410..f9eeec6 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"6a9765dd3dd343088d8b58b95ae1900bb53834c5\"\n", + "RELEASE_REF = \"be8342fd8fb9e7460550b9fba4e3d500224eedf4\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From 48643613c2f08cb202563f32b66631847ca5f77d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:15:25 +0000 Subject: [PATCH 06/22] Notebook tests: set form fields with a function, so Windows paths keep their backslashes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- tests/test_notebook_cellpose.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index cd8d55b..e2c686d 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -69,8 +69,9 @@ def with_params(number, params): """Return cell ``number`` with its Colab form fields set to ``params`` (each must exist).""" text = source(number) for name, value in params.items(): + line = f"{name} = {value!r}" # a function, so backslashes (Windows paths) stay as given text, count = re.subn( - rf"^{name} = .*?( # @param.*)$", rf"{name} = {value!r}\1", text, flags=re.M + rf"^{name} = .*?( # @param.*)$", lambda m, line=line: line + m[1], text, flags=re.M ) assert count == 1, f"cell {number + 1} has no form field {name}" return text From b70b1386f72c4cdbc70cd7bdee4477d8e65d7393 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:16:10 +0000 Subject: [PATCH 07/22] Pin the Cellpose notebook to 0a26163253dd, which holds its code after the merge of the base Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index f9eeec6..e27ed3d 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"be8342fd8fb9e7460550b9fba4e3d500224eedf4\"\n", + "RELEASE_REF = \"0a26163253ddf6268eb66165ca26da288a7aa083\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From 7045eceef439494d9c2e13f802b4697edc9410b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:10:02 +0000 Subject: [PATCH 08/22] Cellpose batch: record each mask before the next image, withdraw an unrecordable one A mask was published before it was hashed and the record was written only after all masks, so a failed hash left a "failed" image with a mask, and a failed final write left every mask without provenance (a retry then skipped them). Now each mask is hashed and recorded right after it is published; on a failure it is removed (only while still the file written), the image is failed, the rest are failed as not started and the batch stops. A retry reports a mask with no record entry as "exists without provenance". A diameter that gives fewer than one flow iteration is refused, not clamped to 1; the device wording separates the verified network placement from Cellpose's CPU post-processing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 9 + docs/contract.md | 24 +- notebooks/MorphoBricks_Cellpose.ipynb | 6 +- pyproject.toml | 1 + .../notebook_cellpose.py | 2 + .../segmentation_cellpose.py | 248 +++++++++--------- .../segmentation_cellpose_model.py | 12 +- .../segmentation_cellpose_settings.py | 124 +++++++++ tests/test_segmentation_cellpose_failsafe.py | 141 ++++++++++ tests/test_segmentation_cellpose_record.py | 8 +- 10 files changed, 440 insertions(+), 135 deletions(-) create mode 100644 src/morphobricks_preprocessing/segmentation_cellpose_settings.py create mode 100644 tests/test_segmentation_cellpose_failsafe.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e92a851..67ac226 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,15 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Cellpose notebook, failure-safe record (external audit C6).** A published mask is never left + without its record entry: each mask is hashed and recorded right after publication, before the + next image; if that fails the mask is removed (only if still the file written; otherwise a + `WITHOUT provenance` warning names it), the image is `failed`, the remaining images are + `failed` as not started and the batch stops. A retry reports a mask without a record entry + as `exists without provenance` instead of a plain skip. A diameter giving fewer than one flow + iteration is refused instead of clamped to 1; the docs and notebook say the verified device is + the network's placement, not Cellpose's CPU post-processing. `Settings` moved to + `segmentation_cellpose_settings` (re-exported). - **Cellpose notebook** (`notebooks/MorphoBricks_Cellpose.ipynb`, step 2 of the segmentation hand-off; owner request of 21 November 2026): opens a described run, chooses the mask type and the channels **by channel ID** (dropdowns; a channel only some images have is refused with diff --git a/docs/contract.md b/docs/contract.md index 210b320..86e1498 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1370,12 +1370,13 @@ loading, and the weights file the loaded model reports must be the one asked for buffer of the loaded network (`model.net`) must be on a device of the requested type** (`cuda:1` counts as `cuda`; the index is not compared); a network that lists no tensors is refused. Cellpose's own `model.device` is not evidence (it only repeats the device it was given), and -nothing beyond the network's tensors is verified. Cellpose may still move the flow-threshold -quality step to the CPU when GPU memory is short, and always computes the masks from the flows on -the CPU on `mps`; that is Cellpose's behaviour, **not refused**, and the batch records it as a -note. Uncached weights are downloaded only on an explicit request; more than +nothing beyond the network's tensors is verified. The device is the placement of the network's tensors; Cellpose's own post-processing is not +covered by it: Cellpose may move the flow-threshold quality step to the CPU when GPU memory is +short, and always computes the masks from the flows on the CPU on `mps`; that is Cellpose's +behaviour, **not refused**, and the batch records it as a note. Uncached weights are downloaded only on an explicit request; more than three channels are refused (Cellpose reads the first three by position); a blank diameter is -the model's native scale, never an estimate and never 0. The batch's `model` holds the model +the model's native scale, never an estimate and never 0, and a diameter that gives fewer than one +flow iteration (`int(200 / rescale)` is 0) is refused, never raised to 1. The batch's `model` holds the model name, the weights file name (or the custom file's path) and its SHA-256, and its `parameters` every effective setting (diameter in pixels or null with its meaning, thresholds, the **full** normalisation dictionary given to Cellpose (its defaults read from its module at call time, with @@ -1386,7 +1387,18 @@ and `weights_source` (the Hugging Face URL Cellpose uses; null for a model file) `new_batch_id()`. The DINOv3 package is installed with `--no-deps` at a pinned commit, the head of its default branch on 22 November 2026, which is **not verified against `cpdino`**; Cellpose imports it only when first imported, so the runtime is restarted after installing it. -Two-dimensional images only. +Two-dimensional images only. **A mask the batch publishes is never left without its record +entry**: each mask is hashed and the record (the batch so far, the same batch ID growing) is +written right after it is published, before the next image starts. If hashing or that write +fails, the mask is removed again, only while it is still the file the batch wrote (inode, +modification time and size taken right after publication, under the type's write lock), the image +is `failed` with the error and the statement that the mask was removed (with `overwrite`, the +earlier mask it replaced is gone), the images not yet started are `failed` as `not started`, and +the batch stops (`BatchResult.stopped`). If the mask cannot be removed or is no longer the batch's +file, the entry says so loudly (`WARNING: a mask exists WITHOUT provenance at `). A mask is +therefore never `failed` while left on disk. A retry without `overwrite` skips a mask that has a +`written` entry in the record and reports one that has none as `skipped` with `exists without +provenance (not made by a recorded batch)`; the model that made it is not guessed. ## 16. Shared rules for other bricks (MorphoBricks D86) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index e27ed3d..51fb5d6 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -26,7 +26,7 @@ "- **Channels by ID, at most three.** You choose channels by their ID (for example `DNA`, `ACTIN`). In a run where some images have a channel that others lack, only the channels every image has can be used; the notebook shows the refusal as it is. Cellpose reads at most three channels and drops the rest by position, so more than three are refused.\n", "- **Models:** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb`, or a model file of your own. A name or file Cellpose cannot find is **refused**; Cellpose itself would silently use `cpsam_v2` instead.\n", "- **Downloads:** built-in weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. Nothing downloads unless you tick the download box in cell 5. The `cpdino` models also need DINOv3 (installed only if you tick its box, at a pinned commit; see cell 5, which also says that the runtime must be restarted after that).\n", - "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU, and the notebook checks that every weight of the network sits on the device you chose. Cellpose itself may still move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's own behaviour, it is **not refused**, and it is written to the record as a note.\n", + "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU, and the notebook checks that every weight of the network sits on the device you chose (that is the network's placement only). Cellpose's own post-processing is not covered by that check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's own behaviour, it is **not refused**, and it is written to the record as a note.\n", "- **Diameter:** in pixels. **Blank means the model's own native scale** (Cellpose 4.2.1.1 does not estimate a diameter). Zero is refused.\n", "- Every setting that ran (the full normalisation and the flow iterations included), the model's file name and its SHA-256, and whether the weights were downloaded in this session and from where, are written to the record.\n", "\n", @@ -354,9 +354,9 @@ "\n", "## **5. Choose the model and the settings, then load the model**\n", "\n", - "Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box. The notebook loads the model, then checks that the weights file is the one you asked for and that the model is on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter is in pixels; blank is the model's native scale.\n", + "Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box. The notebook loads the model, then checks that the weights file is the one you asked for and that the network's weights are on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter is in pixels; blank is the model's native scale.\n", "\n", - "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose may still move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and whether the weights were downloaded now and from where.\n", + "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose's post-processing is outside this check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and whether the weights were downloaded now and from where.\n", "\n", "**The `cpdino` models need DINOv3, and a restart.** Ticking the install box installs DINOv3 with `--no-deps` (so it cannot change your PyTorch) at commit `6876159a11b4`, **the head of its default branch on 22 November 2026, not verified against `cpdino`**. Cellpose imports DINOv3 only when it is first imported, so after installing DINOv3 **restart the runtime** (Colab: Runtime > Restart session), run cells 1 to 4 again and load a `cpdino` model; loading before the restart is refused with that instruction." ] diff --git a/pyproject.toml b/pyproject.toml index 5d2af88..930cea0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -365,6 +365,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.mask_lineage" = "io" "morphobricks_preprocessing.segmentation_cellpose" = "io" "morphobricks_preprocessing.segmentation_cellpose_model" = "io" +"morphobricks_preprocessing.segmentation_cellpose_settings" = "pure" "morphobricks_preprocessing.segmentation_handoff" = "io" "morphobricks_preprocessing.segmentation_record" = "io" "morphobricks_preprocessing.lock_file" = "io" diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index 5d75e73..4b4ee78 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -360,6 +360,8 @@ def progress(done: int, total: int, item: str) -> None: counts = result.counts() rows = [["Image", "Status", "Message"], *map(list, result.rows())] failed = counts["failed"] + if result.stopped: + self._show(_card("error", "The batch stopped early", (result.stopped,))) self._show( widgets.HTML( "
" diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index c118f57..c9c57f1 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -31,7 +31,6 @@ from __future__ import annotations -import math import os from collections.abc import Callable, Sequence from dataclasses import dataclass @@ -64,14 +63,30 @@ load_model, weights_file, ) -from .segmentation_handoff import SegmentationPlan, images_to_segment, write_mask +from .segmentation_cellpose_settings import ( + FLOW_ITERATIONS, + Settings, + diameter_from_text, + flow_iterations, + rescale_factor, +) +from .segmentation_handoff import ( + WRITE_LOCK_FILENAME, + SegmentationPlan, + images_to_segment, + mask_path, + write_mask, +) from .segmentation_record import ( SegmentationBatch, SegmentationError, SegmentedImage, check_mask_type, + hold_lock, mask_sha256, new_batch_id, + read_record, + record_path, write_record, ) @@ -82,6 +97,7 @@ "DINOV3_COMMIT", "DINOV3_URL", "DINO_MODELS", + "FLOW_ITERATIONS", "LoadedModel", "ModelChoice", "Settings", @@ -89,6 +105,7 @@ "check_dinov3", "choose_model", "default_normalization", + "diameter_from_text", "dinov3_install_command", "install_dinov3", "installed_dinov3_commit", @@ -103,119 +120,19 @@ TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 """Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" NORMALIZE_PERCENTILE = [1.0, 99.0] -FLOW_ITERATIONS = 200 -"""Cellpose's flow iterations at the native scale; it divides it by the rescale factor.""" NATIVE_SCALE = ( "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " "diameter means the model's own scale" ) IMAGE_SKIPPED = "a mask of this type is already there; not replaced (overwrite is off)" - - -# --- settings and what is asked for ----------------------------------------------------------- - - -@dataclass(frozen=True) -class Settings: - """The inference settings the user chooses. - - Attributes - ---------- - diameter - Cell diameter in **pixels**, or None for the model's native scale (Cellpose 4.2.1.1 - does not estimate a diameter). Never 0. - flow_threshold - Flow error threshold, 0 or more (Cellpose's default 0.4). - cellprob_threshold - Cell probability threshold (Cellpose's default 0). - normalize - Cellpose's own normalisation: each channel to its 1st to 99th percentile. False - passes the stored values unchanged. - batch_size - Tiles run together on the device, 1 or more. - """ - - diameter: float | None = None - flow_threshold: float = 0.4 - cellprob_threshold: float = 0.0 - normalize: bool = True - batch_size: int = 8 - - def __post_init__(self) -> None: - """Refuse a value Cellpose would accept but this brick will not record as it is.""" - if self.diameter is not None and not _positive(self.diameter): - raise SegmentationError( - f"The diameter must be a positive number of pixels, or blank for the model's " - f"native scale; got {self.diameter!r}. Zero is refused: it would silently mean " - "the native scale." - ) - if not _finite(self.flow_threshold) or self.flow_threshold < 0: - raise SegmentationError( - f"The flow threshold must be 0 or more, not {self.flow_threshold!r}." - ) - if not _finite(self.cellprob_threshold): - raise SegmentationError( - f"The cell probability threshold must be a number, not {self.cellprob_threshold!r}." - ) - if not isinstance(self.normalize, bool): - raise SegmentationError("normalize is on or off.") - if ( - isinstance(self.batch_size, bool) - or not isinstance(self.batch_size, int) - or self.batch_size < 1 - ): - raise SegmentationError( - f"The batch size must be a whole number, 1 or more, not {self.batch_size!r}." - ) - - -def _finite(value: object) -> bool: - """Return True for a real number that is neither NaN nor infinite (a bool is not one).""" - return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) - - -def _positive(value: object) -> bool: - """Return True for a finite number above 0.""" - return _finite(value) and value > 0 # type: ignore[operator] - - -def diameter_from_text(text: str) -> float | None: - """Return the diameter typed in a text field: blank is None (native scale), else pixels. - - Raises - ------ - SegmentationError - For text that is not a positive number (0 included). - """ - if not text.strip(): - return None - try: - value = float(text) - except ValueError: - raise SegmentationError( - f"The diameter {text!r} is not a number. Type pixels (for example 30) or leave it " - "blank." - ) from None - return Settings(diameter=value).diameter +IMAGE_UNRECORDED = ( + "exists without provenance (not made by a recorded batch); not replaced (overwrite is off)" +) # --- one image -------------------------------------------------------------------------------- -def rescale_factor(settings: Settings) -> float: - """Return the factor Cellpose derives from the diameter: 30 / diameter, or 1 (native scale).""" - return 1.0 if settings.diameter is None else 30.0 / settings.diameter - - -def flow_iterations(settings: Settings) -> int: - """Return the flow iterations Cellpose 4.2.1.1 uses when none are given: 200 / rescale. - - Cellpose computes ``int(200 / rescale)`` (resampling is on); it is passed explicitly and - recorded, so what ran is not left to Cellpose's derivation. - """ - return max(1, int(FLOW_ITERATIONS / rescale_factor(settings))) - - def normalization(settings: Settings) -> dict[str, Any]: """Return the full normalisation given to Cellpose: its defaults now, with the user's values. @@ -364,10 +281,14 @@ class BatchResult: The batch as recorded (one entry per image handled). record The record file, or None when no image was handled. + stopped + Why the batch stopped early (a mask that could not be hashed or recorded was withdrawn), + or an empty string when every image was handled. """ batch: SegmentationBatch record: Path | None + stopped: str = "" def rows(self) -> tuple[tuple[str, str, str], ...]: """Return ``(image, status, message)`` for every image: nothing is left out.""" @@ -384,16 +305,76 @@ def non_2d_images(inputs: RunInputs) -> tuple[str, ...]: return tuple(f.relative_path for f in inputs.fovs() if f.z_count > 1 or f.t_count > 1) -def _segment_one(job: SegmentationJob, fov: Fov) -> SegmentedImage: - """Segment and write one image; any failure is returned as a ``failed`` entry.""" +def _segment_one( + job: SegmentationJob, fov: Fov, batch_id: str, entries: list[SegmentedImage] +) -> tuple[SegmentedImage, bool]: + """Segment, write, hash and record one image; return its entry and whether to stop. + + A mask this call published is recorded (the batch so far, with this image) before the next + image starts. If hashing it or that record write fails, the mask is withdrawn + (:func:`_withdraw`) and the batch stops: no mask of this batch is ever left unrecorded. + Any earlier failure (nothing was published) is a ``failed`` entry and the batch goes on. + """ try: labels = segment_image(job.loaded, job.settings, job.plan.read(fov)) + target = mask_path(job.masks_root, job.mask_type, fov) + replaced = target.exists() path = write_mask( job.masks_root, job.mask_type, fov, labels, job.inputs, overwrite=job.overwrite ) - return SegmentedImage(fov.relative_path, "written", mask_sha256=mask_sha256(path)) except Exception as exc: # per-image failures are reported in the table, never dropped - return SegmentedImage(fov.relative_path, "failed", f"{type(exc).__name__}: {exc}") + return SegmentedImage(fov.relative_path, "failed", f"{type(exc).__name__}: {exc}"), False + stamp = None + try: + stamp = _stamp(path) + entry = SegmentedImage(fov.relative_path, "written", mask_sha256=mask_sha256(path)) + if _stamp(path) != stamp: + raise SegmentationError(f"The mask {path} changed while it was being hashed.") + _write_batch(job, batch_id, [*entries, entry]) + except Exception as exc: + return _withdraw(job, fov, path, stamp, replaced, exc), True + return entry, False + + +def _stamp(path: Path) -> tuple[int, int, int]: + """Return the identity of the file at ``path``: inode, modification time (ns) and size.""" + found = path.stat() + return found.st_ino, found.st_mtime_ns, found.st_size + + +def _withdraw( + job: SegmentationJob, + fov: Fov, + path: Path, + stamp: tuple[int, int, int] | None, + replaced: bool, + error: Exception, +) -> SegmentedImage: + """Remove the mask this call published, if it is still that file; the entry says what. + + The file is removed only when its identity (:func:`_stamp`) is still the one taken right + after publication, under the type's write lock. When it cannot be removed, or is not shown + to be ours, the entry states loudly that a mask exists without provenance and where. + """ + what = f"{type(error).__name__}: {error}" + try: + with hold_lock( + path.parent / WRITE_LOCK_FILENAME, f"The {job.mask_type} masks in {job.masks_root}" + ): + ours = stamp is not None and path.exists() and _stamp(path) == stamp + if ours: + path.unlink() + if ours: + earlier = " It replaced an earlier mask, which is gone." if replaced else "" + note = f"The mask this batch wrote was removed, so none is left unrecorded.{earlier}" + else: + note = _UNRECORDED.format(path=path, why="it is not the file this batch wrote") + except (OSError, SegmentationError) as problem: + note = _UNRECORDED.format(path=path, why=f"it could not be removed ({problem})") + return SegmentedImage(fov.relative_path, "failed", f"{what}. {note}") + + +_UNRECORDED = "WARNING: a mask exists WITHOUT provenance at {path}; {why}. It was NOT recorded." def _batch(job: SegmentationJob, batch_id: str, images: list[SegmentedImage]) -> SegmentationBatch: @@ -423,6 +404,14 @@ def _write_batch( return batch, write_record(job.masks_root, job.mask_type, batch) if entries else None +def _recorded_images(job: SegmentationJob) -> set[str]: + """Return the images whose mask has an entry in the record (``written`` by some batch).""" + if not record_path(job.masks_root, job.mask_type).exists(): + return set() + record = read_record(job.masks_root, job.mask_type) + return {i.image for b in record.batches for i in b.images if i.status == "written"} + + def run_batch( job: SegmentationJob, fovs: Sequence[Fov] | None = None, @@ -432,9 +421,15 @@ def run_batch( ) -> BatchResult: """Segment images one at a time, write each mask and record every outcome. - Images that already have a mask of the type are ``skipped`` (never replaced) unless - ``job.overwrite``; an image that fails is ``failed`` with the error and the batch goes on. - The record is written even when the batch is interrupted, with the images done so far. + Each mask is hashed and recorded (the batch so far) right after it is published, before the + next image starts. If that fails the mask is removed again (only if it is still the file + written), the image is ``failed`` with the error, the images not yet started are ``failed`` + as not started, and the batch **stops** (``BatchResult.stopped`` says why): a mask is never + left without its record entry, and never reported ``failed`` while left on disk. Images that + already have a mask of the type are ``skipped`` (never replaced) unless ``job.overwrite``; + a mask with no entry in the record is skipped with a message saying it has no provenance. + Any other image that fails is ``failed`` with the error and the batch goes on. The record is + written even when the batch is interrupted, with the images done so far. Parameters ---------- @@ -450,23 +445,32 @@ def run_batch( Raises ------ SegmentationError - For a masks folder or mask type the hand-off refuses, or a record that cannot be - written (the masks written stay). + For a masks folder or mask type the hand-off refuses, or a record that is not valid. + A record that cannot be written at the end is raised too (every mask is recorded by then). """ chosen = tuple(job.inputs.fovs() if fovs is None else fovs) missing = { f.relative_path for f in images_to_segment(job.inputs, job.mask_type, job.masks_root) } + recorded = _recorded_images(job) started = batch_id or new_batch_id() entries: list[SegmentedImage] = [] + stopped = "" try: for done, fov in enumerate(chosen): if progress is not None: progress(done, len(chosen), fov.relative_path) - if job.overwrite or fov.relative_path in missing: - entries.append(_segment_one(job, fov)) + image = fov.relative_path + if not (job.overwrite or image in missing): + note = IMAGE_SKIPPED if image in recorded else IMAGE_UNRECORDED + entries.append(SegmentedImage(image, "skipped", note)) + elif stopped: + entries.append(SegmentedImage(image, "failed", f"not started: {stopped}")) else: - entries.append(SegmentedImage(fov.relative_path, "skipped", IMAGE_SKIPPED)) + entry, stop = _segment_one(job, fov, started, entries) + entries.append(entry) + if stop: + stopped = f"the batch stopped at {image}: {entry.message}" if progress is not None: progress(len(chosen), len(chosen), "") except BaseException as interrupted: @@ -477,8 +481,14 @@ def run_batch( except Exception as second: interrupted.add_note(f"The record could not be written either: {second}") raise - batch, record = _write_batch(job, started, entries) - return BatchResult(batch, record) + try: + batch, record = _write_batch(job, started, entries) + except Exception as exc: + if not stopped: + raise + stopped += f" The record could not be written either: {exc}" + return BatchResult(_batch(job, started, entries), None, stopped) + return BatchResult(batch, record, stopped) # --- the run, the channels and what is shown -------------------------------------------------- diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py index 172dba9..0f73334 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_model.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -45,10 +45,11 @@ 22 November 2026, **not verified against cpdino** (it is a pin, not a tested pairing). A model that needs DINOv3 runs only with exactly this commit installed.""" DEVICE_NOTE = ( - "Cellpose may move the flow-threshold quality step to the CPU when the GPU has too little " - "memory (images above 10000 x 10000 pixels on cuda), and always computes the masks from the " - "flows on the CPU on mps. This is Cellpose's own behaviour; it is not refused, and the " - "network itself ran on the device recorded." + "The device recorded is where the network's tensors were verified to sit; Cellpose's " + "post-processing is not covered by that check. Cellpose may move the flow-threshold quality " + "step to the CPU when the GPU has too little memory (images above 10000 x 10000 pixels on " + "cuda), and always computes the masks from the flows on the CPU on mps. This is Cellpose's " + "own behaviour; it is not refused." ) """Recorded with a batch that ran on a GPU (not refused: the network still runs on the device).""" SAM_TILE, DINO_TILE = 256, 384 @@ -275,7 +276,8 @@ class LoadedModel: The SHA-256 of that file. device ``cuda``, ``cpu`` or ``mps``: the device type every parameter and buffer of the network - was verified to sit on after loading. + was verified to sit on after loading (the network's placement only; Cellpose's CPU + post-processing, :data:`DEVICE_NOTE`, is not covered). downloaded True when this call downloaded the built-in weights (they were not on disk). source diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_settings.py b/src/morphobricks_preprocessing/segmentation_cellpose_settings.py new file mode 100644 index 0000000..8421658 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_settings.py @@ -0,0 +1,124 @@ +"""The Cellpose inference settings and what Cellpose derives from them (no Cellpose import). + +Split from :mod:`.segmentation_cellpose` to keep each file small; that module re-exports all of +it. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from .segmentation_record import SegmentationError + +FLOW_ITERATIONS = 200 +"""Cellpose's flow iterations at the native scale; it divides it by the rescale factor.""" + + +@dataclass(frozen=True) +class Settings: + """The inference settings the user chooses. + + Attributes + ---------- + diameter + Cell diameter in **pixels**, or None for the model's native scale (Cellpose 4.2.1.1 + does not estimate a diameter). Never 0. + flow_threshold + Flow error threshold, 0 or more (Cellpose's default 0.4). + cellprob_threshold + Cell probability threshold (Cellpose's default 0). + normalize + Cellpose's own normalisation: each channel to its 1st to 99th percentile. False + passes the stored values unchanged. + batch_size + Tiles run together on the device, 1 or more. + """ + + diameter: float | None = None + flow_threshold: float = 0.4 + cellprob_threshold: float = 0.0 + normalize: bool = True + batch_size: int = 8 + + def __post_init__(self) -> None: + """Refuse a value Cellpose would accept but this brick will not record as it is.""" + if self.diameter is not None and not _positive(self.diameter): + raise SegmentationError( + f"The diameter must be a positive number of pixels, or blank for the model's " + f"native scale; got {self.diameter!r}. Zero is refused: it would silently mean " + "the native scale." + ) + if flow_iterations(self) < 1: + raise SegmentationError( + f"A diameter of {self.diameter!r} pixels gives Cellpose less than one flow " + f"iteration (int({FLOW_ITERATIONS} / rescale) is 0 at a rescale of " + f"{rescale_factor(self):.4g}); Cellpose would run on a rescale it cannot use. " + "Give the diameter of the cells in pixels, or leave it blank." + ) + if not _finite(self.flow_threshold) or self.flow_threshold < 0: + raise SegmentationError( + f"The flow threshold must be 0 or more, not {self.flow_threshold!r}." + ) + if not _finite(self.cellprob_threshold): + raise SegmentationError( + f"The cell probability threshold must be a number, not {self.cellprob_threshold!r}." + ) + if not isinstance(self.normalize, bool): + raise SegmentationError("normalize is on or off.") + if ( + isinstance(self.batch_size, bool) + or not isinstance(self.batch_size, int) + or self.batch_size < 1 + ): + raise SegmentationError( + f"The batch size must be a whole number, 1 or more, not {self.batch_size!r}." + ) + + +def _finite(value: object) -> bool: + """Return True for a real number that is neither NaN nor infinite (a bool is not one).""" + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def _positive(value: object) -> bool: + """Return True for a finite number above 0.""" + return _finite(value) and value > 0 # type: ignore[operator] + + +def diameter_from_text(text: str) -> float | None: + """Return the diameter typed in a text field: blank is None (native scale), else pixels. + + Raises + ------ + SegmentationError + For text that is not a positive number (0 included). + """ + if not text.strip(): + return None + try: + value = float(text) + except ValueError: + raise SegmentationError( + f"The diameter {text!r} is not a number. Type pixels (for example 30) or leave it " + "blank." + ) from None + return Settings(diameter=value).diameter + + +def rescale_factor(settings: Settings) -> float: + """Return the factor Cellpose derives from the diameter: 30 / diameter, or 1 (native scale).""" + return 1.0 if settings.diameter is None else 30.0 / settings.diameter + + +def flow_iterations(settings: Settings) -> int: + """Return the flow iterations Cellpose 4.2.1.1 uses when none are given: 200 / rescale. + + Cellpose computes ``int(200 / rescale)`` (resampling is on); it is passed explicitly and + recorded, so what ran is not left to Cellpose's derivation. It is never raised to 1: a + diameter that gives 0 is refused by :class:`Settings`. + """ + try: + return int(FLOW_ITERATIONS / rescale_factor(settings)) + except (OverflowError, ZeroDivisionError): # a diameter so large its rescale rounds to 0 + return 0 diff --git a/tests/test_segmentation_cellpose_failsafe.py b/tests/test_segmentation_cellpose_failsafe.py new file mode 100644 index 0000000..20ec2c6 --- /dev/null +++ b/tests/test_segmentation_cellpose_failsafe.py @@ -0,0 +1,141 @@ +"""A mask the Cellpose batch publishes is never left without its record entry. + +Failures are injected right after publication (hashing), at the per-image record write and at +the final record write; each test checks the masks on disk against the record, the table, that +the batch stops, and what a retry reports. Same stand-in and run as ``test_segmentation_cellpose``. +""" + +import pytest + +from cellpose_stub import install +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing.segmentation_handoff import mask_path +from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record +from test_segmentation_cellpose import make_job + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def on_disk(run): + return {f.relative_path for f in run.inputs.fovs() if mask_path(run.masks, "Cells", f).exists()} + + +def recorded(run): + try: + record = read_record(run.masks, "Cells") + except SegmentationError: + return set() + return {i.image for b in record.batches for i in b.images if i.status == "written"} + + +def fail_from(monkeypatch, name, nth, error): + """Make ``cp.`` raise ``error`` from its ``nth`` call on (1 = the first).""" + real, calls = getattr(cp, name), [] + + def broken(*args, **kwargs): + calls.append(1) + if len(calls) >= nth: + raise error + return real(*args, **kwargs) + + monkeypatch.setattr(cp, name, broken) + return real + + +def test_a_hash_that_fails_withdraws_the_mask_and_stops_the_batch(run, stub, monkeypatch): + fovs = run.inputs.fovs() + fail_from(monkeypatch, "mask_sha256", 2, OSError("unreadable")) + result = cp.run_batch(make_job(run), batch_id="b1") + rows = {image: (status, message) for image, status, message in result.rows()} + assert sorted(rows) == sorted(f.relative_path for f in fovs) # every image accounted for + assert rows[fovs[0].relative_path][0] == "written" + status, message = rows[fovs[1].relative_path] + assert status == "failed" and "unreadable" in message and "was removed" in message + for later in fovs[2:]: + assert rows[later.relative_path] == ("failed", f"not started: {result.stopped}") + assert "stopped at " + fovs[1].relative_path in result.stopped + assert len(stub.calls) == 2 # the batch stopped: no third image was segmented + assert on_disk(run) == recorded(run) == {fovs[0].relative_path} # no unrecorded mask + assert read_record(run.masks, "Cells").batches[0] == result.batch + + +def test_a_record_write_that_fails_for_an_image_withdraws_that_mask_and_stops( + run, stub, monkeypatch +): + fovs = run.inputs.fovs() + fail_from(monkeypatch, "write_record", 2, OSError("disk full")) # the 2nd image's record + result = cp.run_batch(make_job(run), batch_id="b1") + assert result.counts()["written"] == 1 and result.counts()["failed"] == len(fovs) - 1 + assert "disk full" in result.rows()[1][2] and "was removed" in result.rows()[1][2] + assert on_disk(run) == recorded(run) == {fovs[0].relative_path} + assert result.stopped and len(stub.calls) == 2 + + +def test_a_mask_that_is_no_longer_the_one_written_is_not_removed_and_is_named( + run, stub, monkeypatch +): + fovs = run.inputs.fovs() + other = mask_path(run.masks, "Cells", fovs[0]) + + def replaced_meanwhile(*args): + other.write_bytes(b"someone else's mask") # another writer replaces our file + raise OSError("disk full") + + monkeypatch.setattr(cp, "write_record", replaced_meanwhile) + result = cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") + message = result.rows()[0][2] + assert other.read_bytes() == b"someone else's mask" # never removed + assert "WITHOUT provenance" in message and str(other) in message + assert result.stopped + + +def test_a_final_record_write_that_fails_leaves_only_recorded_masks(run, stub, monkeypatch): + fovs = run.inputs.fovs() + fail_from(monkeypatch, "write_record", len(fovs) + 1, OSError("disk full")) # the final one + with pytest.raises(OSError, match="disk full"): + cp.run_batch(make_job(run), batch_id="b1") + assert on_disk(run) == recorded(run) == {f.relative_path for f in fovs} # all recorded + + +def test_a_retry_reports_a_mask_without_provenance_instead_of_skipping_it(run, stub): + fovs = run.inputs.fovs() + cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") + path = mask_path(run.masks, "Cells", fovs[1]) # a mask no recorded batch made + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(mask_path(run.masks, "Cells", fovs[0]).read_bytes()) + rows = {i: (s, m) for i, s, m in cp.run_batch(make_job(run), batch_id="b2").rows()} + assert rows[fovs[0].relative_path] == ("skipped", cp.IMAGE_SKIPPED) + assert rows[fovs[1].relative_path][0] == "skipped" + assert rows[fovs[1].relative_path][1].startswith( + "exists without provenance (not made by a recorded batch)" + ) + + +def test_a_retry_after_a_stopped_batch_makes_the_missing_masks_and_skips_the_recorded( + run, stub, monkeypatch +): + fovs = run.inputs.fovs() + real = fail_from(monkeypatch, "mask_sha256", 2, OSError("unreadable")) + cp.run_batch(make_job(run), batch_id="b1") + monkeypatch.setattr(cp, "mask_sha256", real) + result = cp.run_batch(make_job(run), batch_id="b2") + rows = {i: s for i, s, _ in result.rows()} + assert rows[fovs[0].relative_path] == "skipped" and result.stopped == "" + assert result.counts() == {"written": len(fovs) - 1, "skipped": 1, "failed": 0} + assert on_disk(run) == recorded(run) == {f.relative_path for f in fovs} + + +def test_a_diameter_that_gives_no_flow_iteration_is_refused_not_raised_to_one(): + with pytest.raises(SegmentationError, match="less than one flow iteration"): + cp.Settings(diameter=0.1) # int(200 / (30 / 0.1)) is 0 + assert cp.flow_iterations(cp.Settings(diameter=0.15)) == 1 + with pytest.raises(SegmentationError, match="less than one flow iteration"): + cp.Settings(diameter=1e-300) diff --git a/tests/test_segmentation_cellpose_record.py b/tests/test_segmentation_cellpose_record.py index 023d8a1..6385539 100644 --- a/tests/test_segmentation_cellpose_record.py +++ b/tests/test_segmentation_cellpose_record.py @@ -55,7 +55,6 @@ def test_the_flow_iterations_are_cellpose_derivation_given_and_recorded(stub): loaded = cp.load_model("cpsam_v2", "cpu") assert cp.eval_arguments(loaded, cp.Settings())["niter"] == 200 assert cp.eval_arguments(loaded, cp.Settings(diameter=60))["niter"] == 400 # int(200 / 0.5) - assert cp.eval_arguments(loaded, cp.Settings(diameter=1e-9))["niter"] == 1 # never 0 = derive def test_a_gpu_batch_records_that_cellpose_may_use_the_cpu_for_post_processing(stub): @@ -87,8 +86,13 @@ def interrupt(stack): if len(stub.calls) == 2: # one image is done, so there is a record to write raise KeyboardInterrupt + real, calls = cp.write_record, [] + def broken(*args): - raise OSError("disk full") + calls.append(args) + if len(calls) > 1: # the record after the first image was written; the next one fails + raise OSError("disk full") + return real(*args) stub.fail = interrupt monkeypatch.setattr(cp, "write_record", broken) From a3789b27dd2b2786cfe57272f9705ab02d6bfd1d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:10:13 +0000 Subject: [PATCH 09/22] Pin the Cellpose notebook to 7045eceef439, which holds its code after the failure-safe record Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 51fb5d6..bd95d1f 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"0a26163253ddf6268eb66165ca26da288a7aa083\"\n", + "RELEASE_REF = \"7045eceef439494d9c2e13f802b4697edc9410b1\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From a2807f60d6915dd9772daa5b651fed9638d0304e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:16:42 +0000 Subject: [PATCH 10/22] Cellpose batch: withdraw on interrupt, stamp and hash under the write lock, retry checks the recorded hash Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 5 + .../segmentation_cellpose.py | 93 +++++++++++++------ tests/test_segmentation_cellpose_failsafe.py | 44 ++++++++- 3 files changed, 113 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbe6cc0..87b60ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,11 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Cellpose notebook, review fixes (PR #375)**: the per-image hash/record step now catches + `BaseException`, so a `KeyboardInterrupt` (stop button) between `write_mask` and the image's record + write withdraws the mask (identity-checked) and then re-raises; the identity stamp and SHA-256 are + taken under `write_mask`'s write lock (`on_published`, PR #367); a retry compares a recorded mask's + SHA-256 with its latest record entry and reports "exists, but differs from its recorded provenance". - **Cellpose notebook, failure-safe record (external audit C6).** A published mask is never left without its record entry: each mask is hashed and recorded right after publication, before the next image; if that fails the mask is removed (only if still the file written; otherwise a diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index c9c57f1..8d969a1 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -80,6 +80,7 @@ from .segmentation_record import ( SegmentationBatch, SegmentationError, + SegmentationRecord, SegmentedImage, check_mask_type, hold_lock, @@ -311,28 +312,47 @@ def _segment_one( """Segment, write, hash and record one image; return its entry and whether to stop. A mask this call published is recorded (the batch so far, with this image) before the next - image starts. If hashing it or that record write fails, the mask is withdrawn - (:func:`_withdraw`) and the batch stops: no mask of this batch is ever left unrecorded. - Any earlier failure (nothing was published) is a ``failed`` entry and the batch goes on. + image starts. Its identity stamp and SHA-256 are taken under ``write_mask``'s write lock + (``on_published``), so no other writer can replace the file in between. If hashing it or that + record write fails, even by an interrupt (``KeyboardInterrupt``: the notebook's stop button), + the mask is withdrawn (:func:`_withdraw`) and the batch stops (an interrupt is re-raised after + the withdrawal): no mask of this batch is ever left unrecorded. Any earlier failure (nothing + was published) is a ``failed`` entry and the batch goes on. """ + taken: dict[str, Any] = {} + + def take(path: Path) -> None: # under the write lock, right after the publish + taken["path"] = path + taken["stamp"] = _stamp(path) + taken["sha"] = mask_sha256(path) + if _stamp(path) != taken["stamp"]: + raise SegmentationError(f"The mask {path} changed while it was being hashed.") + + replaced = False try: labels = segment_image(job.loaded, job.settings, job.plan.read(fov)) - target = mask_path(job.masks_root, job.mask_type, fov) - replaced = target.exists() - path = write_mask( - job.masks_root, job.mask_type, fov, labels, job.inputs, overwrite=job.overwrite + replaced = mask_path(job.masks_root, job.mask_type, fov).exists() + write_mask( + job.masks_root, + job.mask_type, + fov, + labels, + job.inputs, + overwrite=job.overwrite, + on_published=take, ) - except Exception as exc: # per-image failures are reported in the table, never dropped - return SegmentedImage(fov.relative_path, "failed", f"{type(exc).__name__}: {exc}"), False - stamp = None - try: - stamp = _stamp(path) - entry = SegmentedImage(fov.relative_path, "written", mask_sha256=mask_sha256(path)) - if _stamp(path) != stamp: - raise SegmentationError(f"The mask {path} changed while it was being hashed.") + entry = SegmentedImage(fov.relative_path, "written", mask_sha256=taken["sha"]) _write_batch(job, batch_id, [*entries, entry]) - except Exception as exc: - return _withdraw(job, fov, path, stamp, replaced, exc), True + except BaseException as exc: + if "path" not in taken: # nothing was published + if isinstance(exc, Exception): # reported in the table, never dropped + message = f"{type(exc).__name__}: {exc}" + return SegmentedImage(fov.relative_path, "failed", message), False + raise + failed = _withdraw(job, fov, taken["path"], taken.get("stamp"), replaced, exc) + if not isinstance(exc, Exception): + raise + return failed, True return entry, False @@ -348,7 +368,7 @@ def _withdraw( path: Path, stamp: tuple[int, int, int] | None, replaced: bool, - error: Exception, + error: BaseException, ) -> SegmentedImage: """Remove the mask this call published, if it is still that file; the entry says what. @@ -404,12 +424,25 @@ def _write_batch( return batch, write_record(job.masks_root, job.mask_type, batch) if entries else None -def _recorded_images(job: SegmentationJob) -> set[str]: - """Return the images whose mask has an entry in the record (``written`` by some batch).""" - if not record_path(job.masks_root, job.mask_type).exists(): - return set() - record = read_record(job.masks_root, job.mask_type) - return {i.image for b in record.batches for i in b.images if i.status == "written"} +def _skip_note(job: SegmentationJob, fov: Fov, record: SegmentationRecord | None) -> str: + """Say why the mask of ``fov`` is not replaced: recorded, unrecorded, or changed since.""" + latest = record.latest(fov.relative_path) if record is not None else None + if latest is None: + return IMAGE_UNRECORDED + path = mask_path(job.masks_root, job.mask_type, fov) + if not path.is_file(): # a twin elsewhere pairs: the record says nothing about it + return IMAGE_SKIPPED + try: + found = mask_sha256(path) + except OSError as exc: + return f"exists, but could not be checked against its recorded provenance ({exc})" + expected = latest[1].mask_sha256 + if found != expected: + return ( + f"exists, but differs from its recorded provenance (sha256 {found}, " + f"recorded {expected})" + ) + return IMAGE_SKIPPED def run_batch( @@ -427,7 +460,8 @@ def run_batch( as not started, and the batch **stops** (``BatchResult.stopped`` says why): a mask is never left without its record entry, and never reported ``failed`` while left on disk. Images that already have a mask of the type are ``skipped`` (never replaced) unless ``job.overwrite``; - a mask with no entry in the record is skipped with a message saying it has no provenance. + a mask with no entry in the record is skipped with a message saying it has no provenance, and + one whose SHA-256 differs from its latest recorded entry with a message saying it differs. Any other image that fails is ``failed`` with the error and the batch goes on. The record is written even when the batch is interrupted, with the images done so far. @@ -452,7 +486,11 @@ def run_batch( missing = { f.relative_path for f in images_to_segment(job.inputs, job.mask_type, job.masks_root) } - recorded = _recorded_images(job) + record = ( + read_record(job.masks_root, job.mask_type) + if record_path(job.masks_root, job.mask_type).exists() + else None + ) started = batch_id or new_batch_id() entries: list[SegmentedImage] = [] stopped = "" @@ -462,8 +500,7 @@ def run_batch( progress(done, len(chosen), fov.relative_path) image = fov.relative_path if not (job.overwrite or image in missing): - note = IMAGE_SKIPPED if image in recorded else IMAGE_UNRECORDED - entries.append(SegmentedImage(image, "skipped", note)) + entries.append(SegmentedImage(image, "skipped", _skip_note(job, fov, record))) elif stopped: entries.append(SegmentedImage(image, "failed", f"not started: {stopped}")) else: diff --git a/tests/test_segmentation_cellpose_failsafe.py b/tests/test_segmentation_cellpose_failsafe.py index 20ec2c6..0a50435 100644 --- a/tests/test_segmentation_cellpose_failsafe.py +++ b/tests/test_segmentation_cellpose_failsafe.py @@ -9,7 +9,7 @@ from cellpose_stub import install from morphobricks_preprocessing import segmentation_cellpose as cp -from morphobricks_preprocessing.segmentation_handoff import mask_path +from morphobricks_preprocessing.segmentation_handoff import WRITE_LOCK_FILENAME, mask_path from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record from test_segmentation_cellpose import make_job @@ -139,3 +139,45 @@ def test_a_diameter_that_gives_no_flow_iteration_is_refused_not_raised_to_one(): assert cp.flow_iterations(cp.Settings(diameter=0.15)) == 1 with pytest.raises(SegmentationError, match="less than one flow iteration"): cp.Settings(diameter=1e-300) + + +def test_an_interrupt_between_publish_and_record_withdraws_the_mask_and_propagates( + run, stub, monkeypatch +): + fovs = run.inputs.fovs() + fail_from(monkeypatch, "mask_sha256", 2, KeyboardInterrupt()) # the stop button, image 2 + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run), batch_id="b1") + assert on_disk(run) == recorded(run) == {fovs[0].relative_path} # no unrecorded mask + + +def test_the_stamp_and_the_hash_are_taken_under_the_write_lock(run, stub, monkeypatch): + lock = run.masks / "Cells" / WRITE_LOCK_FILENAME + seen = [] + real_hash, real_stamp = cp.mask_sha256, cp._stamp + + def hashing(path): + seen.append(("hash", lock.exists())) + return real_hash(path) + + def stamping(path): + seen.append(("stamp", lock.exists())) + return real_stamp(path) + + monkeypatch.setattr(cp, "mask_sha256", hashing) + monkeypatch.setattr(cp, "_stamp", stamping) + cp.run_batch(make_job(run), fovs=run.inputs.fovs()[:1], batch_id="b1") + assert seen and all(held for _, held in seen) + + +def test_a_retry_reports_a_recorded_mask_that_differs_from_its_record(run, stub): + fovs = run.inputs.fovs() + cp.run_batch(make_job(run), fovs=fovs[:2], batch_id="b1") + changed = mask_path(run.masks, "Cells", fovs[1]) + changed.write_bytes(b"replaced after the batch") # recorded, but no longer that file + rows = {i: (s, m) for i, s, m in cp.run_batch(make_job(run), batch_id="b2").rows()} + assert rows[fovs[0].relative_path] == ("skipped", cp.IMAGE_SKIPPED) + status, message = rows[fovs[1].relative_path] + assert status == "skipped" + assert message.startswith("exists, but differs from its recorded provenance (sha256 ") + assert cp.mask_sha256(changed) in message From df6328182aa127136d130dcd84480d7730ed7024 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:16:42 +0000 Subject: [PATCH 11/22] Cellpose notebook: re-pin RELEASE_REF to the commit holding the final src Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index bd95d1f..882c373 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"7045eceef439494d9c2e13f802b4697edc9410b1\"\n", + "RELEASE_REF = \"a2807f60d6915dd9772daa5b651fed9638d0304e\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From ffdca160bb18665b2255782765a54f3883404f0e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:28:15 +0000 Subject: [PATCH 12/22] write_mask: roll back when the caller's provenance step fails Under the type's write lock, an overwrite first copies the earlier mask to a hidden ..previous. beside it. If on_published raises (any BaseException), the earlier mask is moved back byte for byte, or a new mask is removed, still under the lock, then the error propagates. A rollback that cannot restore or remove raises SegmentationError naming both files and keeps the copy. The record's duplicate-image check uses a seen-set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 8 ++ docs/contract.md | 2 +- .../segmentation_handoff.py | 110 +++++++++++--- .../segmentation_record.py | 7 +- tests/test_segmentation_rollback.py | 134 ++++++++++++++++++ tests/test_segmentation_write_lock.py | 14 -- 6 files changed, 238 insertions(+), 37 deletions(-) create mode 100644 tests/test_segmentation_rollback.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 52319cd..01642e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,14 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. 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. +- **`write_mask` rolls back when `on_published` fails** (external audit of #375, 22 November 2026). + The caller's provenance step now runs in the callback under the type's write lock; if it raises + (any exception, `KeyboardInterrupt` too), `write_mask` restores an overwritten mask byte for byte + from a hidden copy kept beside it (`..previous.`, skipped by the masks step, removed + on success) or removes a new mask, still under the lock, then re-raises. A rollback that cannot + restore or remove raises `SegmentationError` naming both files and keeps the copy. Before, a + failed overwrite left the new mask published and the earlier valid mask was lost. The record's + duplicate-image check is linear (a seen-set instead of `list.count` per entry). - **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 42fde9a..dd08adf 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1352,7 +1352,7 @@ links (a Google Drive mount) too. the image to the published file, **in both modes**: an overwriting writer and a default writer can never replace each other's mask. A held lock is refused at once, naming its holder, and never waited on; a killed writer leaves it, and the message says to delete it. Like the -record's lock it is a dot-file, skipped by the masks step. 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 +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 and write the provenance there; it is not called when the write is refused). If it raises (any exception, `KeyboardInterrupt` too), the write is **rolled back under the same lock** and the error propagates: with `overwrite=True` the earlier mask was first copied to a hidden file beside it (`..previous.`, a dot-file the masks step skips, removed once the callback returns) and is moved back over the new one byte for byte, with its mode; a new mask is removed. A rollback that cannot restore or remove is a `SegmentationError` naming both files, and the copy is kept. A lock holder carries a random token, so a lock deleted and retaken is never removed by its earlier holder. Limits: the lock protects the writers of one computer (not a Drive folder open in two Colab sessions); a reader may briefly see a **zero-byte placeholder** at the mask's name while a mask is being diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index 15bf9dd..5cc879d 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -23,6 +23,7 @@ from __future__ import annotations import os +import shutil import tempfile from collections.abc import Callable from dataclasses import dataclass @@ -241,8 +242,11 @@ def write_mask( 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. + here, and write its provenance). Not called when the write is refused. If it raises + (any exception, ``KeyboardInterrupt`` too), the write is rolled back under the lock: + an overwritten mask is restored byte for byte from a hidden copy kept beside it + (``..previous.``, removed once the callback returns), a new mask is + removed; then the error propagates. Returns ------- @@ -257,7 +261,7 @@ def write_mask( 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. + holder; or a rollback that could not restore or remove the mask (naming the files). """ target = mask_path(masks_root, mask_type, fov) _check_folders(inputs, masks_root) @@ -269,27 +273,93 @@ def write_mask( # 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) + what = f"The {mask_type} mask of {fov.relative_path}" + backup = _keep_backup(target) if overwrite and target.is_file() else None 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}" - ) + _write_and_publish(data, target, overwrite, what) except BaseException: - Path(temporary).unlink(missing_ok=True) + _drop_backup(backup, target) # nothing was replaced: the earlier mask is at the target raise if on_published is not None: - on_published(target) # still under the lock; an error propagates, the mask stays + try: + on_published(target) # still under the lock + except BaseException: + _roll_back(target, backup) # still under the lock; loud if it cannot + raise + _drop_backup(backup, target) + return target + + +def _write_and_publish(data: np.ndarray, target: Path, overwrite: bool, what: str) -> None: + """Write ``data`` to a temporary file beside ``target``, then publish it there.""" + 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, what) + except BaseException: + Path(temporary).unlink(missing_ok=True) + raise + + +def _keep_backup(target: Path) -> Path: + """Copy the mask at ``target`` to a hidden file beside it and return the copy's path. + + A copy, not a move, so the earlier mask stays at its name until the new one replaces it in + one move (a process killed meanwhile leaves the earlier mask and a stray dot-file, which + the masks step skips). ``..previous.``, the temporary-name pattern. + """ + handle, backup = tempfile.mkstemp(prefix=f".{target.name}.previous.", dir=target.parent) + os.close(handle) + try: + shutil.copyfile(target, backup) + give_output_mode(backup, target) # restored with the earlier mask's mode + except BaseException: + Path(backup).unlink(missing_ok=True) + raise + return Path(backup) + + +def _drop_backup(backup: Path | None, target: Path) -> None: + """Remove the hidden copy of the earlier mask once ``target`` holds a mask to keep.""" + if backup is None: + return + try: + backup.unlink(missing_ok=True) + except OSError as error: + raise SegmentationError( + f"{target} is in place, but the copy of the earlier mask, {backup}, could not be " + f"removed ({error}); delete it by hand." + ) from error + + +def _roll_back(target: Path, backup: Path | None) -> None: + """Undo a publish whose caller failed: put ``backup`` back at ``target``, or remove it. + + Called under the type's write lock. A failure is raised as a SegmentationError naming the + files, never ignored; the backup is then kept. + """ + try: + if backup is None: + target.unlink(missing_ok=True) + else: + os.replace(backup, target) + except OSError as error: + if backup is None: + raise SegmentationError( + f"The new mask {target} could not be removed after its caller failed ({error}); " + "delete it by hand: it has no provenance." + ) from error + raise SegmentationError( + f"The earlier mask could not be restored from {backup} to {target} after the " + f"caller failed ({error}); {target} holds the new mask, which has no provenance. " + f"Move {backup} to {target} by hand." + ) from error return target diff --git a/src/morphobricks_preprocessing/segmentation_record.py b/src/morphobricks_preprocessing/segmentation_record.py index ea92357..0f69dce 100644 --- a/src/morphobricks_preprocessing/segmentation_record.py +++ b/src/morphobricks_preprocessing/segmentation_record.py @@ -306,8 +306,11 @@ def _batch(data: object) -> dict[str, Any]: 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}) + seen: set[str] = set() + repeated: set[str] = set() + for entry in data["images"]: + (repeated if entry["image"] in seen else seen).add(entry["image"]) + twice = sorted(repeated) if twice: raise SegmentationError( f"The batch {data['batch_id']!r} has more than one entry for {', '.join(twice)}; " diff --git a/tests/test_segmentation_rollback.py b/tests/test_segmentation_rollback.py new file mode 100644 index 0000000..8ea5662 --- /dev/null +++ b/tests/test_segmentation_rollback.py @@ -0,0 +1,134 @@ +"""``write_mask`` rolls back when its ``on_published`` callback fails (audit of PR #375). + +The caller writes its provenance in the callback, under the type's write lock. If that fails, +an overwritten mask is restored byte for byte and a new mask is removed, still under the lock. +Fixtures and helpers are those of ``test_segmentation_handoff``. +""" + +import os + +import pytest + +from morphobricks_preprocessing import segmentation_handoff +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 + + +def _files(run): + return sorted(p.relative_to(run.masks).as_posix() for p in run.masks.rglob("*") if p.is_file()) + + +def _fail(error): + def callback(path): + assert (path.parent.parents[1] / WRITE_LOCK_FILENAME).exists() # under the type lock + raise error + + return callback + + +@pytest.mark.parametrize("error", [RuntimeError("record failed"), KeyboardInterrupt()]) +def test_a_failing_callback_removes_a_new_mask(run, error): + fov = run.inputs.fovs()[0] + with pytest.raises(type(error)): + write_mask( + run.masks, "Cells", fov, labels_like(run, fov), run.inputs, on_published=_fail(error) + ) + assert _files(run) == [] # no mask, no backup, no temporary file, no lock + assert fov in images_to_segment(run.inputs, "Cells", run.masks) + + +@pytest.mark.parametrize("error", [RuntimeError("record failed"), KeyboardInterrupt()]) +def test_a_failing_callback_restores_the_overwritten_mask_byte_for_byte(run, error): + fov = run.inputs.fovs()[0] + target = write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + before = target.read_bytes() + stat = os.stat(target) + new = labels_like(run, fov) + new[0, 0] = 7 # different bytes + with pytest.raises(type(error)): + write_mask( + run.masks, "Cells", fov, new, run.inputs, overwrite=True, on_published=_fail(error) + ) + assert target.read_bytes() == before + assert os.stat(target).st_mode == stat.st_mode + assert _files(run) == [target.relative_to(run.masks).as_posix()] # no backup left + + +def test_a_successful_overwrite_leaves_no_backup_and_the_backup_is_hidden(run): + fov = run.inputs.fovs()[0] + target = write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + seen = [] + + def callback(path): + seen.append(sorted(p.name for p in path.parent.iterdir())) + # the backup is a dot-file: the run's masks discovery skips it (no twin, no stray mask) + assert images_to_segment(run.inputs, "Cells", run.masks) == run.inputs.fovs()[1:] + + new = labels_like(run, fov) + new[0, 0] = 7 + write_mask(run.masks, "Cells", fov, new, run.inputs, overwrite=True, on_published=callback) + (names,) = seen + assert [n for n in names if n.startswith(f".{target.name}.previous.")] # kept meanwhile + assert _files(run) == [target.relative_to(run.masks).as_posix()] + + +def test_a_failed_restore_is_loud_names_both_files_and_keeps_the_backup(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + before = target.read_bytes() + real = os.replace + + def replace(source, destination): + if ".previous." in os.fspath(source): + raise OSError("disk gone") + return real(source, destination) + + monkeypatch.setattr(segmentation_handoff.os, "replace", replace) + new = labels_like(run, fov) + new[0, 0] = 7 + with pytest.raises(SegmentationError, match="could not be restored") as caught: + write_mask( + run.masks, + "Cells", + fov, + new, + run.inputs, + overwrite=True, + on_published=_fail(RuntimeError("record failed")), + ) + (backup,) = target.parent.glob(f".{target.name}.previous.*") + assert str(backup) in str(caught.value) and str(target) in str(caught.value) + assert backup.read_bytes() == before # the earlier mask is never lost + assert isinstance(caught.value.__cause__.__context__, RuntimeError) # caller's error kept + + +def test_a_failed_removal_of_a_new_mask_is_loud(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = mask_path(run.masks, "Cells", fov) + real = segmentation_handoff.Path.unlink + + def unlink(self, missing_ok=False): + if self == target: + raise OSError("read-only") + return real(self, missing_ok=missing_ok) + + monkeypatch.setattr(segmentation_handoff.Path, "unlink", unlink) + with pytest.raises(SegmentationError, match="could not be removed") as caught: + write_mask( + run.masks, + "Cells", + fov, + labels_like(run, fov), + run.inputs, + on_published=_fail(RuntimeError("record failed")), + ) + assert str(target) in str(caught.value) diff --git a/tests/test_segmentation_write_lock.py b/tests/test_segmentation_write_lock.py index 8eea726..55b991c 100644 --- a/tests/test_segmentation_write_lock.py +++ b/tests/test_segmentation_write_lock.py @@ -118,17 +118,3 @@ def test_on_published_is_not_called_when_the_write_is_refused(run): 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 From dcb6b83299103c453d06d755206e4700694331a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:34:56 +0000 Subject: [PATCH 13/22] Cellpose batch: hash and record each mask under the type's write lock; roll back via write_mask The SHA-256 and the record append now run in write_mask's on_published, under the type's write lock (then the record lock), so overlapping batches cannot leave a latest entry naming one batch while the bytes are another's. An entry that would not be the image's newest is refused. A failure there (an interrupt too) makes write_mask roll back: an overwritten mask is restored, a new one removed. _withdraw and its wrong-folder lock are gone. An existing mask not matching its latest entry is needs_attention in the table, not skipped. Fail-safe tests compare on-disk SHA-256 with the latest record entry; new orchestrated A/B interleaving tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 9 + docs/contract.md | 26 ++- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- .../notebook_cellpose.py | 1 + .../segmentation_cellpose.py | 200 ++++++++++-------- tests/test_notebook_cellpose.py | 21 +- tests/test_segmentation_cellpose.py | 14 +- tests/test_segmentation_cellpose_failsafe.py | 107 ++++++---- tests/test_segmentation_cellpose_race.py | 103 +++++++++ 9 files changed, 331 insertions(+), 152 deletions(-) create mode 100644 tests/test_segmentation_cellpose_race.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 06606ca..072db1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,15 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Cellpose notebook, provenance under the write lock (external audit of PR #375, 22 November + 2026).** Each mask's SHA-256 and its record append now run in `write_mask`'s `on_published`, + under the type's write lock (then the record's lock; never the reverse), so two overlapping + batches can no longer leave a latest record entry naming one batch while the bytes on disk are + the other's. A hash, newest-entry or record failure (an interrupt too) makes `write_mask` roll + back under that lock (#397): an overwritten mask is restored byte for byte, a new one removed. + `_withdraw`, its identity stamp and its own (wrong-folder) lock are gone. An existing mask not + shown to be its latest recorded one is `needs_attention` in the table and counts, not + `skipped`. The fail-safe tests compare on-disk SHA-256 with the latest record entry. - **Cellpose notebook, review fixes (PR #375)**: the per-image hash/record step now catches `BaseException`, so a `KeyboardInterrupt` (stop button) between `write_mask` and the image's record write withdraws the mask (identity-checked) and then re-raises; the identity stamp and SHA-256 are diff --git a/docs/contract.md b/docs/contract.md index 9e5bcac..43936e8 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1388,17 +1388,21 @@ and `weights_source` (the Hugging Face URL Cellpose uses; null for a model file) of its default branch on 22 November 2026, which is **not verified against `cpdino`**; Cellpose imports it only when first imported, so the runtime is restarted after installing it. Two-dimensional images only. **A mask the batch publishes is never left without its record -entry**: each mask is hashed and the record (the batch so far, the same batch ID growing) is -written right after it is published, before the next image starts. If hashing or that write -fails, the mask is removed again, only while it is still the file the batch wrote (inode, -modification time and size taken right after publication, under the type's write lock), the image -is `failed` with the error and the statement that the mask was removed (with `overwrite`, the -earlier mask it replaced is gone), the images not yet started are `failed` as `not started`, and -the batch stops (`BatchResult.stopped`). If the mask cannot be removed or is no longer the batch's -file, the entry says so loudly (`WARNING: a mask exists WITHOUT provenance at `). A mask is -therefore never `failed` while left on disk. A retry without `overwrite` skips a mask that has a -`written` entry in the record and reports one that has none as `skipped` with `exists without -provenance (not made by a recorded batch)`; the model that made it is not guessed. +entry**: each mask's SHA-256 and the record write (the batch so far, the same batch ID growing) +happen in `write_mask`'s `on_published`, **under the type's write lock**, before the next image +starts (lock order: the type's write lock, then the record's lock; never the reverse). So a +second batch cannot publish this type between a mask and its record entry, and the latest record +entry of an image always names the bytes on disk. An entry that would not be the image's newest +(a batch recorded after this one started already wrote the image) is refused. If hashing, +that check or the record write fails, even by an interrupt, `write_mask` rolls the write back under +the same lock (an overwritten mask restored byte for byte, a new one removed; a rollback that +cannot is a loud error naming the files), the image is `failed` with the error and `rolled back: +earlier mask restored` or `rolled back: the new mask was removed`, the images not yet started are +`failed` as `not started`, and the batch stops (`BatchResult.stopped`). A retry without +`overwrite` shows an existing mask as `skipped` only when its SHA-256 is that of its latest +`written` entry; otherwise (no entry: `exists without provenance (not made by a recorded batch)`, +another SHA-256, a twin elsewhere, or not readable) it is `needs_attention` in the table and the +counts (recorded as `skipped` with that reason); the model that made it is not guessed. ## 16. Shared rules for other bricks (MorphoBricks D86) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 882c373..3cc3a0b 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -470,7 +470,7 @@ "\n", "## **7. Segment all images**\n", "\n", - "Segments every image that has no mask of this type yet and writes each mask as a 2D integer image in the masks folder, then writes the record. A progress line shows how far it is. The table at the end lists **every** image as written, skipped or failed with the error: nothing is skipped silently, and one failed image does not stop the others." + "Segments every image that has no mask of this type yet and writes each mask as a 2D integer image in the masks folder, then writes the record. A progress line shows how far it is. The table at the end lists **every** image as written, skipped (its mask matches its record), needs attention (a mask with no record entry or other bytes; not replaced) or failed with the error: nothing is skipped silently, and one failed image does not stop the others. If a mask's record entry cannot be written, that mask is rolled back (an earlier mask restored) and the batch stops." ] }, { diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index 4b4ee78..4c75c03 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -369,6 +369,7 @@ def progress(done: int, total: int, item: str) -> None: [ ("✅", str(counts["written"]), "written"), ("⏩", str(counts["skipped"]), "skipped"), + ("⚠️", str(counts[cp.NEEDS_ATTENTION]), "need attention"), ("❌", str(failed), "failed"), ] ) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index 8d969a1..339947b 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -22,8 +22,10 @@ on ``mps``. That is Cellpose's own behaviour, not refused; it is recorded as a note. - **Record.** Every effective setting goes into the batch's parameters (:func:`inference_parameters`), every image into the batch with its outcome, written, skipped - or failed with the error (:func:`run_batch`); nothing is dropped. The full normalisation, - the flow iterations, and whether built-in weights were downloaded (and from where) are in it. + or failed with the error (:func:`run_batch`); nothing is dropped. Each mask's hash and record + entry are written under the type's write lock; a failure there rolls the mask back. The full + normalisation, the flow iterations, and whether built-in weights were downloaded (and from + where) are in it. Mask paths, pairing, the mask-type rules, writing, the folder rules and the record are the hand-off's own (:mod:`.segmentation_handoff`, :mod:`.segmentation_record`); nothing is repeated. @@ -71,7 +73,6 @@ rescale_factor, ) from .segmentation_handoff import ( - WRITE_LOCK_FILENAME, SegmentationPlan, images_to_segment, mask_path, @@ -83,7 +84,6 @@ SegmentationRecord, SegmentedImage, check_mask_type, - hold_lock, mask_sha256, new_batch_id, read_record, @@ -129,6 +129,11 @@ IMAGE_UNRECORDED = ( "exists without provenance (not made by a recorded batch); not replaced (overwrite is off)" ) +NEEDS_ATTENTION = "needs_attention" +"""The table's outcome for an existing mask that is not shown to be its latest recorded one +(recorded ``skipped`` with the reason: the record's statuses are the hand-off's).""" +ROLLED_BACK_RESTORED = "rolled back: earlier mask restored" +ROLLED_BACK_REMOVED = "rolled back: the new mask was removed" # --- one image -------------------------------------------------------------------------------- @@ -283,22 +288,29 @@ class BatchResult: record The record file, or None when no image was handled. stopped - Why the batch stopped early (a mask that could not be hashed or recorded was withdrawn), - or an empty string when every image was handled. + Why the batch stopped early (a mask that could not be hashed or recorded was rolled + back), or an empty string when every image was handled. + attention + The images whose existing mask was not replaced and is not shown to be its latest + recorded one (no entry, another SHA-256, not checked): ``needs_attention`` in the table. """ batch: SegmentationBatch record: Path | None stopped: str = "" + attention: frozenset[str] = frozenset() def rows(self) -> tuple[tuple[str, str, str], ...]: """Return ``(image, status, message)`` for every image: nothing is left out.""" - return tuple((i.image, i.status, i.message) for i in self.batch.images) + return tuple( + (i.image, NEEDS_ATTENTION if i.image in self.attention else i.status, i.message) + for i in self.batch.images + ) def counts(self) -> dict[str, int]: - """Return how many images were written, skipped and failed.""" - statuses = [i.status for i in self.batch.images] - return {s: statuses.count(s) for s in ("written", "skipped", "failed")} + """Return how many images were written, skipped (verified), need attention and failed.""" + statuses = [status for _, status, _ in self.rows()] + return {s: statuses.count(s) for s in ("written", "skipped", NEEDS_ATTENTION, "failed")} def non_2d_images(inputs: RunInputs) -> tuple[str, ...]: @@ -308,30 +320,35 @@ def non_2d_images(inputs: RunInputs) -> tuple[str, ...]: def _segment_one( job: SegmentationJob, fov: Fov, batch_id: str, entries: list[SegmentedImage] -) -> tuple[SegmentedImage, bool]: - """Segment, write, hash and record one image; return its entry and whether to stop. - - A mask this call published is recorded (the batch so far, with this image) before the next - image starts. Its identity stamp and SHA-256 are taken under ``write_mask``'s write lock - (``on_published``), so no other writer can replace the file in between. If hashing it or that - record write fails, even by an interrupt (``KeyboardInterrupt``: the notebook's stop button), - the mask is withdrawn (:func:`_withdraw`) and the batch stops (an interrupt is re-raised after - the withdrawal): no mask of this batch is ever left unrecorded. Any earlier failure (nothing - was published) is a ``failed`` entry and the batch goes on. +) -> tuple[SegmentedImage, str]: + """Segment, write, hash and record one image; return its entry and why to stop (or ""). + + The SHA-256 and the record write (the batch so far, with this image) happen in + ``write_mask``'s ``on_published``, under the type's write lock (lock order: the write lock, + then the record's lock inside :func:`.segmentation_record.write_record`; never the reverse), + so no other writer can publish this type between the mask and its record entry. If hashing + or recording fails, even by an interrupt (``KeyboardInterrupt``: the notebook's stop button), + ``write_mask`` rolls the write back under that lock (an overwritten mask restored, a new one + removed) and the batch stops; an interrupt is raised again. A failure before anything was + published is a ``failed`` entry and the batch goes on. """ - taken: dict[str, Any] = {} + image = fov.relative_path + state: dict[str, Any] = {} - def take(path: Path) -> None: # under the write lock, right after the publish - taken["path"] = path - taken["stamp"] = _stamp(path) - taken["sha"] = mask_sha256(path) - if _stamp(path) != taken["stamp"]: - raise SegmentationError(f"The mask {path} changed while it was being hashed.") + def commit(path: Path) -> None: # under the type's write lock, right after the publish + try: + entry = SegmentedImage(image, "written", mask_sha256=mask_sha256(path)) + _check_newest(job, batch_id, image) + _write_batch(job, batch_id, [*entries, entry]) + except BaseException as exc: + state["error"] = exc + raise + state["entry"] = entry replaced = False try: labels = segment_image(job.loaded, job.settings, job.plan.read(fov)) - replaced = mask_path(job.masks_root, job.mask_type, fov).exists() + replaced = job.overwrite and mask_path(job.masks_root, job.mask_type, fov).is_file() write_mask( job.masks_root, job.mask_type, @@ -339,62 +356,50 @@ def take(path: Path) -> None: # under the write lock, right after the publish labels, job.inputs, overwrite=job.overwrite, - on_published=take, + on_published=commit, ) - entry = SegmentedImage(fov.relative_path, "written", mask_sha256=taken["sha"]) - _write_batch(job, batch_id, [*entries, entry]) except BaseException as exc: - if "path" not in taken: # nothing was published + if "entry" in state: # written and recorded; only the earlier mask's copy is left over + return state["entry"], f"{type(exc).__name__}: {exc}" + if "error" not in state: # nothing was published if isinstance(exc, Exception): # reported in the table, never dropped - message = f"{type(exc).__name__}: {exc}" - return SegmentedImage(fov.relative_path, "failed", message), False + return SegmentedImage(image, "failed", f"{type(exc).__name__}: {exc}"), "" raise - failed = _withdraw(job, fov, taken["path"], taken.get("stamp"), replaced, exc) - if not isinstance(exc, Exception): + error = state["error"] + if exc is error: # write_mask rolled back + note = ROLLED_BACK_RESTORED if replaced else ROLLED_BACK_REMOVED + else: # the rollback failed: its error names the files + note = f"WARNING: the rollback failed and the mask has NO provenance: {exc}" + failed = SegmentedImage(image, "failed", f"{type(error).__name__}: {error}. {note}") + if not isinstance(error, Exception): raise - return failed, True - return entry, False + return failed, failed.message + return state["entry"], "" -def _stamp(path: Path) -> tuple[int, int, int]: - """Return the identity of the file at ``path``: inode, modification time (ns) and size.""" - found = path.stat() - return found.st_ino, found.st_mtime_ns, found.st_size +def _check_newest(job: SegmentationJob, batch_id: str, image: str) -> None: + """Refuse an entry for ``image`` that would not be its newest (a later batch wrote it). - -def _withdraw( - job: SegmentationJob, - fov: Fov, - path: Path, - stamp: tuple[int, int, int] | None, - replaced: bool, - error: BaseException, -) -> SegmentedImage: - """Remove the mask this call published, if it is still that file; the entry says what. - - The file is removed only when its identity (:func:`_stamp`) is still the one taken right - after publication, under the type's write lock. When it cannot be removed, or is not shown - to be ours, the entry states loudly that a mask exists without provenance and where. + ``SegmentationRecord.latest`` orders batches as recorded, and a batch keeps the place of its + first write. Called under the type's write lock, where no other cooperating batch records a + written mask. """ - what = f"{type(error).__name__}: {error}" - try: - with hold_lock( - path.parent / WRITE_LOCK_FILENAME, f"The {job.mask_type} masks in {job.masks_root}" - ): - ours = stamp is not None and path.exists() and _stamp(path) == stamp - if ours: - path.unlink() - if ours: - earlier = " It replaced an earlier mask, which is gone." if replaced else "" - note = f"The mask this batch wrote was removed, so none is left unrecorded.{earlier}" - else: - note = _UNRECORDED.format(path=path, why="it is not the file this batch wrote") - except (OSError, SegmentationError) as problem: - note = _UNRECORDED.format(path=path, why=f"it could not be removed ({problem})") - return SegmentedImage(fov.relative_path, "failed", f"{what}. {note}") - - -_UNRECORDED = "WARNING: a mask exists WITHOUT provenance at {path}; {why}. It was NOT recorded." + if not record_path(job.masks_root, job.mask_type).exists(): + return + batches = read_record(job.masks_root, job.mask_type).batches + ids = [b.batch_id for b in batches] + if batch_id not in ids: + return # appended: the newest + later = [ + b.batch_id + for b in batches[ids.index(batch_id) + 1 :] + if any(e.image == image and e.status == "written" for e in b.images) + ] + if later: + raise SegmentationError( + f"The batch {later[-1]!r}, recorded after the batch {batch_id!r} started, wrote " + f"{image}; an entry of this batch would not be the newest. Start a new batch." + ) def _batch(job: SegmentationJob, batch_id: str, images: list[SegmentedImage]) -> SegmentationBatch: @@ -424,25 +429,27 @@ def _write_batch( return batch, write_record(job.masks_root, job.mask_type, batch) if entries else None -def _skip_note(job: SegmentationJob, fov: Fov, record: SegmentationRecord | None) -> str: - """Say why the mask of ``fov`` is not replaced: recorded, unrecorded, or changed since.""" +def _skip_note( + job: SegmentationJob, fov: Fov, record: SegmentationRecord | None +) -> tuple[bool, str]: + """Say whether the existing mask of ``fov`` is its latest recorded one, and why not.""" latest = record.latest(fov.relative_path) if record is not None else None if latest is None: - return IMAGE_UNRECORDED + return False, IMAGE_UNRECORDED path = mask_path(job.masks_root, job.mask_type, fov) if not path.is_file(): # a twin elsewhere pairs: the record says nothing about it - return IMAGE_SKIPPED + return False, f"a mask of this image is paired, but not at {path}; not checked" try: found = mask_sha256(path) except OSError as exc: - return f"exists, but could not be checked against its recorded provenance ({exc})" + return False, f"exists, but could not be checked against its recorded provenance ({exc})" expected = latest[1].mask_sha256 if found != expected: - return ( + return False, ( f"exists, but differs from its recorded provenance (sha256 {found}, " f"recorded {expected})" ) - return IMAGE_SKIPPED + return True, IMAGE_SKIPPED def run_batch( @@ -454,14 +461,15 @@ def run_batch( ) -> BatchResult: """Segment images one at a time, write each mask and record every outcome. - Each mask is hashed and recorded (the batch so far) right after it is published, before the - next image starts. If that fails the mask is removed again (only if it is still the file - written), the image is ``failed`` with the error, the images not yet started are ``failed`` - as not started, and the batch **stops** (``BatchResult.stopped`` says why): a mask is never - left without its record entry, and never reported ``failed`` while left on disk. Images that - already have a mask of the type are ``skipped`` (never replaced) unless ``job.overwrite``; - a mask with no entry in the record is skipped with a message saying it has no provenance, and - one whose SHA-256 differs from its latest recorded entry with a message saying it differs. + Each mask is hashed and recorded (the batch so far) right after it is published, under the + type's write lock, before the next image starts. If that fails the write is rolled back + under the same lock (an overwritten mask restored byte for byte, a new one removed), the + image is ``failed`` with the error and what the rollback did, the images not yet started + are ``failed`` as not started, and the batch **stops** (``BatchResult.stopped`` says why): + a mask is never left without its record entry. Images that already have a mask of the type + are not replaced unless ``job.overwrite``: ``skipped`` when the file's SHA-256 is that of + its latest recorded entry, else ``needs_attention`` in the table (recorded ``skipped`` with + the reason: no provenance, another SHA-256, or not checked). Any other image that fails is ``failed`` with the error and the batch goes on. The record is written even when the batch is interrupted, with the images done so far. @@ -493,6 +501,7 @@ def run_batch( ) started = batch_id or new_batch_id() entries: list[SegmentedImage] = [] + attention: set[str] = set() stopped = "" try: for done, fov in enumerate(chosen): @@ -500,14 +509,17 @@ def run_batch( progress(done, len(chosen), fov.relative_path) image = fov.relative_path if not (job.overwrite or image in missing): - entries.append(SegmentedImage(image, "skipped", _skip_note(job, fov, record))) + verified, note = _skip_note(job, fov, record) + entries.append(SegmentedImage(image, "skipped", note)) + if not verified: + attention.add(image) elif stopped: entries.append(SegmentedImage(image, "failed", f"not started: {stopped}")) else: entry, stop = _segment_one(job, fov, started, entries) entries.append(entry) if stop: - stopped = f"the batch stopped at {image}: {entry.message}" + stopped = f"the batch stopped at {image}: {stop}" if progress is not None: progress(len(chosen), len(chosen), "") except BaseException as interrupted: @@ -524,8 +536,8 @@ def run_batch( if not stopped: raise stopped += f" The record could not be written either: {exc}" - return BatchResult(_batch(job, started, entries), None, stopped) - return BatchResult(batch, record, stopped) + return BatchResult(_batch(job, started, entries), None, stopped, frozenset(attention)) + return BatchResult(batch, record, stopped, frozenset(attention)) # --- the run, the channels and what is shown -------------------------------------------------- diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index e2c686d..3ac955c 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -266,7 +266,12 @@ def test_the_cells_segment_a_mixed_run_end_to_end(cells): run_cell(cells.ns, BATCH) result = cells.ns["result"] fovs = run.inputs.fovs() - assert result.counts() == {"written": len(fovs), "skipped": 0, "failed": 0} + assert result.counts() == { + "written": len(fovs), + "skipped": 0, + "needs_attention": 0, + "failed": 0, + } assert len(cells.stub.calls) == 1 + len(fovs) table = workflow.shown[-1] assert all(f.relative_path in table for f in fovs) and "written" in table @@ -389,11 +394,21 @@ def fail_third(stack): cells.stub.fail = fail_third run_cell(cells.ns, BATCH) result, fovs = cells.ns["result"], cells.run.inputs.fovs() - assert result.counts() == {"written": len(fovs) - 1, "skipped": 0, "failed": 1} + assert result.counts() == { + "written": len(fovs) - 1, + "skipped": 0, + "needs_attention": 0, + "failed": 1, + } table = cells.ns["workflow"].shown[-1] assert "RuntimeError: out of memory" in table and "failed" in table run_cell(cells.ns, BATCH) # again: the written images are skipped, the failed one is redone - assert cells.ns["result"].counts() == {"written": 1, "skipped": len(fovs) - 1, "failed": 0} + assert cells.ns["result"].counts() == { + "written": 1, + "skipped": len(fovs) - 1, + "needs_attention": 0, + "failed": 0, + } def test_a_preview_names_an_image_of_the_run_or_is_refused(cells): diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py index d18d171..0bd1b38 100644 --- a/tests/test_segmentation_cellpose.py +++ b/tests/test_segmentation_cellpose.py @@ -287,7 +287,12 @@ def test_channel_axis_is_0_and_the_stack_follows_the_requested_ids_on_a_mixed_ru job = make_job(run, ids=("TUB", "DNA")) result = cp.run_batch(job, batch_id="b1") fovs = run.inputs.fovs() - assert result.counts() == {"written": len(fovs), "skipped": 0, "failed": 0} + assert result.counts() == { + "written": len(fovs), + "skipped": 0, + "needs_attention": 0, + "failed": 0, + } assert {f.repeat_group for f in fovs} >= {REPEAT_2} # the repeat that stores EXTRA first assert len(stub.calls) == len(fovs) for call in stub.calls: @@ -428,7 +433,12 @@ def fail_second(stack): assert sorted(rows) == sorted(f.relative_path for f in fovs) # nothing left out assert rows[fovs[0].relative_path] == ("skipped", cp.IMAGE_SKIPPED) assert rows[fovs[2].relative_path] == ("failed", "RuntimeError: out of memory") - assert result.counts() == {"written": len(fovs) - 2, "skipped": 1, "failed": 1} + assert result.counts() == { + "written": len(fovs) - 2, + "skipped": 1, + "needs_attention": 0, + "failed": 1, + } assert len(stub.calls) == len(fovs) - 1 # the skipped image was never segmented assert not mask_path(run.masks, "Cells", fovs[2]).exists() record = read_record(run.masks, "Cells") diff --git a/tests/test_segmentation_cellpose_failsafe.py b/tests/test_segmentation_cellpose_failsafe.py index 0a50435..c4fbba7 100644 --- a/tests/test_segmentation_cellpose_failsafe.py +++ b/tests/test_segmentation_cellpose_failsafe.py @@ -1,8 +1,9 @@ """A mask the Cellpose batch publishes is never left without its record entry. Failures are injected right after publication (hashing), at the per-image record write and at -the final record write; each test checks the masks on disk against the record, the table, that -the batch stops, and what a retry reports. Same stand-in and run as ``test_segmentation_cellpose``. +the final record write; each test checks every mask's SHA-256 on disk against its **latest** +record entry, the table, that the batch stops, and what a retry reports. Same stand-in and run +as ``test_segmentation_cellpose``. """ import pytest @@ -10,7 +11,11 @@ from cellpose_stub import install from morphobricks_preprocessing import segmentation_cellpose as cp from morphobricks_preprocessing.segmentation_handoff import WRITE_LOCK_FILENAME, mask_path -from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record +from morphobricks_preprocessing.segmentation_record import ( + SegmentationError, + mask_sha256, + read_record, +) from test_segmentation_cellpose import make_job @@ -24,16 +29,28 @@ def stub(monkeypatch, tmp_path): return install(monkeypatch, tmp_path) -def on_disk(run): - return {f.relative_path for f in run.inputs.fovs() if mask_path(run.masks, "Cells", f).exists()} +def verified(run): + """Return the images with a mask, after checking each file against its latest entry. - -def recorded(run): + Every mask on disk has the SHA-256 of its latest record entry, and every image with a + latest written entry has that mask on disk: no unrecorded mask, no stale record. + """ try: record = read_record(run.masks, "Cells") except SegmentationError: - return set() - return {i.image for b in record.batches for i in b.images if i.status == "written"} + record = None + on_disk, latest = {}, {} + for fov in run.inputs.fovs(): + path = mask_path(run.masks, "Cells", fov) + if path.exists(): + on_disk[fov.relative_path] = mask_sha256(path) # never the patched one + found = record.latest(fov.relative_path) if record is not None else None + if found is not None: + latest[fov.relative_path] = found[1].mask_sha256 + assert on_disk == latest + hidden = [p for p in run.masks.rglob(".*") if p.is_file() and ".previous." in p.name] + assert hidden == [] # no backup of an earlier mask left behind + return set(on_disk) def fail_from(monkeypatch, name, nth, error): @@ -50,7 +67,7 @@ def broken(*args, **kwargs): return real -def test_a_hash_that_fails_withdraws_the_mask_and_stops_the_batch(run, stub, monkeypatch): +def test_a_hash_that_fails_rolls_the_mask_back_and_stops_the_batch(run, stub, monkeypatch): fovs = run.inputs.fovs() fail_from(monkeypatch, "mask_sha256", 2, OSError("unreadable")) result = cp.run_batch(make_job(run), batch_id="b1") @@ -58,42 +75,45 @@ def test_a_hash_that_fails_withdraws_the_mask_and_stops_the_batch(run, stub, mon assert sorted(rows) == sorted(f.relative_path for f in fovs) # every image accounted for assert rows[fovs[0].relative_path][0] == "written" status, message = rows[fovs[1].relative_path] - assert status == "failed" and "unreadable" in message and "was removed" in message + assert status == "failed" and "unreadable" in message and cp.ROLLED_BACK_REMOVED in message for later in fovs[2:]: assert rows[later.relative_path] == ("failed", f"not started: {result.stopped}") assert "stopped at " + fovs[1].relative_path in result.stopped assert len(stub.calls) == 2 # the batch stopped: no third image was segmented - assert on_disk(run) == recorded(run) == {fovs[0].relative_path} # no unrecorded mask + assert verified(run) == {fovs[0].relative_path} # no unrecorded mask assert read_record(run.masks, "Cells").batches[0] == result.batch -def test_a_record_write_that_fails_for_an_image_withdraws_that_mask_and_stops( +def test_a_record_write_that_fails_for_an_image_rolls_that_mask_back_and_stops( run, stub, monkeypatch ): fovs = run.inputs.fovs() fail_from(monkeypatch, "write_record", 2, OSError("disk full")) # the 2nd image's record result = cp.run_batch(make_job(run), batch_id="b1") assert result.counts()["written"] == 1 and result.counts()["failed"] == len(fovs) - 1 - assert "disk full" in result.rows()[1][2] and "was removed" in result.rows()[1][2] - assert on_disk(run) == recorded(run) == {fovs[0].relative_path} + assert "disk full" in result.rows()[1][2] and cp.ROLLED_BACK_REMOVED in result.rows()[1][2] + assert verified(run) == {fovs[0].relative_path} assert result.stopped and len(stub.calls) == 2 -def test_a_mask_that_is_no_longer_the_one_written_is_not_removed_and_is_named( +def test_a_failed_overwrite_after_earlier_images_restores_the_earlier_mask_and_record( run, stub, monkeypatch ): fovs = run.inputs.fovs() - other = mask_path(run.masks, "Cells", fovs[0]) - - def replaced_meanwhile(*args): - other.write_bytes(b"someone else's mask") # another writer replaces our file - raise OSError("disk full") - - monkeypatch.setattr(cp, "write_record", replaced_meanwhile) - result = cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") - message = result.rows()[0][2] - assert other.read_bytes() == b"someone else's mask" # never removed - assert "WITHOUT provenance" in message and str(other) in message + cp.run_batch(make_job(run), fovs=fovs[:3], batch_id="b1") + before = {f.relative_path: mask_path(run.masks, "Cells", f).read_bytes() for f in fovs[:3]} + real = cp.segment_image + monkeypatch.setattr(cp, "segment_image", lambda *a: real(*a) * 3) # other bytes + fail_from(monkeypatch, "write_record", 3, OSError("disk full")) # b2's 3rd image's record + result = cp.run_batch(make_job(run, overwrite=True), batch_id="b2") + rows = result.rows() + assert [s for _, s, _ in rows[:2]] == ["written", "written"] + assert rows[2][1] == "failed" and rows[2][2].endswith(cp.ROLLED_BACK_RESTORED) + assert mask_path(run.masks, "Cells", fovs[2]).read_bytes() == before[fovs[2].relative_path] + assert mask_path(run.masks, "Cells", fovs[0]).read_bytes() != before[fovs[0].relative_path] + latest = read_record(run.masks, "Cells").latest(fovs[2].relative_path) + assert latest[0].batch_id == "b1" # the earlier record entry is still the latest + assert verified(run) == {f.relative_path for f in fovs[:3]} assert result.stopped @@ -102,7 +122,7 @@ def test_a_final_record_write_that_fails_leaves_only_recorded_masks(run, stub, m fail_from(monkeypatch, "write_record", len(fovs) + 1, OSError("disk full")) # the final one with pytest.raises(OSError, match="disk full"): cp.run_batch(make_job(run), batch_id="b1") - assert on_disk(run) == recorded(run) == {f.relative_path for f in fovs} # all recorded + assert verified(run) == {f.relative_path for f in fovs} # all recorded def test_a_retry_reports_a_mask_without_provenance_instead_of_skipping_it(run, stub): @@ -113,7 +133,7 @@ def test_a_retry_reports_a_mask_without_provenance_instead_of_skipping_it(run, s path.write_bytes(mask_path(run.masks, "Cells", fovs[0]).read_bytes()) rows = {i: (s, m) for i, s, m in cp.run_batch(make_job(run), batch_id="b2").rows()} assert rows[fovs[0].relative_path] == ("skipped", cp.IMAGE_SKIPPED) - assert rows[fovs[1].relative_path][0] == "skipped" + assert rows[fovs[1].relative_path][0] == cp.NEEDS_ATTENTION # never counted as skipped assert rows[fovs[1].relative_path][1].startswith( "exists without provenance (not made by a recorded batch)" ) @@ -129,8 +149,13 @@ def test_a_retry_after_a_stopped_batch_makes_the_missing_masks_and_skips_the_rec result = cp.run_batch(make_job(run), batch_id="b2") rows = {i: s for i, s, _ in result.rows()} assert rows[fovs[0].relative_path] == "skipped" and result.stopped == "" - assert result.counts() == {"written": len(fovs) - 1, "skipped": 1, "failed": 0} - assert on_disk(run) == recorded(run) == {f.relative_path for f in fovs} + assert result.counts() == { + "written": len(fovs) - 1, + "skipped": 1, + "needs_attention": 0, + "failed": 0, + } + assert verified(run) == {f.relative_path for f in fovs} def test_a_diameter_that_gives_no_flow_iteration_is_refused_not_raised_to_one(): @@ -141,33 +166,33 @@ def test_a_diameter_that_gives_no_flow_iteration_is_refused_not_raised_to_one(): cp.Settings(diameter=1e-300) -def test_an_interrupt_between_publish_and_record_withdraws_the_mask_and_propagates( +def test_an_interrupt_between_publish_and_record_rolls_the_mask_back_and_propagates( run, stub, monkeypatch ): fovs = run.inputs.fovs() fail_from(monkeypatch, "mask_sha256", 2, KeyboardInterrupt()) # the stop button, image 2 with pytest.raises(KeyboardInterrupt): cp.run_batch(make_job(run), batch_id="b1") - assert on_disk(run) == recorded(run) == {fovs[0].relative_path} # no unrecorded mask + assert verified(run) == {fovs[0].relative_path} # no unrecorded mask -def test_the_stamp_and_the_hash_are_taken_under_the_write_lock(run, stub, monkeypatch): +def test_the_hash_and_the_record_write_happen_under_the_write_lock(run, stub, monkeypatch): lock = run.masks / "Cells" / WRITE_LOCK_FILENAME seen = [] - real_hash, real_stamp = cp.mask_sha256, cp._stamp + real_hash, real_record = cp.mask_sha256, cp.write_record def hashing(path): seen.append(("hash", lock.exists())) return real_hash(path) - def stamping(path): - seen.append(("stamp", lock.exists())) - return real_stamp(path) + def recording(*args): + seen.append(("record", lock.exists())) + return real_record(*args) monkeypatch.setattr(cp, "mask_sha256", hashing) - monkeypatch.setattr(cp, "_stamp", stamping) + monkeypatch.setattr(cp, "write_record", recording) cp.run_batch(make_job(run), fovs=run.inputs.fovs()[:1], batch_id="b1") - assert seen and all(held for _, held in seen) + assert seen[:2] == [("hash", True), ("record", True)] # the final rewrite comes after def test_a_retry_reports_a_recorded_mask_that_differs_from_its_record(run, stub): @@ -178,6 +203,6 @@ def test_a_retry_reports_a_recorded_mask_that_differs_from_its_record(run, stub) rows = {i: (s, m) for i, s, m in cp.run_batch(make_job(run), batch_id="b2").rows()} assert rows[fovs[0].relative_path] == ("skipped", cp.IMAGE_SKIPPED) status, message = rows[fovs[1].relative_path] - assert status == "skipped" + assert status == cp.NEEDS_ATTENTION assert message.startswith("exists, but differs from its recorded provenance (sha256 ") assert cp.mask_sha256(changed) in message diff --git a/tests/test_segmentation_cellpose_race.py b/tests/test_segmentation_cellpose_race.py new file mode 100644 index 0000000..77146c6 --- /dev/null +++ b/tests/test_segmentation_cellpose_race.py @@ -0,0 +1,103 @@ +"""Two overlapping Cellpose batches never leave a mask whose latest record entry is another's. + +The mask, its SHA-256 and its record entry are one step under the type's write lock: a second +batch is refused inside that window (audit of PR #375, blockers 1-3). Interleavings are +orchestrated in one process with the stand-in of ``test_segmentation_cellpose``. +""" + +import pytest + +from cellpose_stub import install +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing.segmentation_handoff import mask_path +from morphobricks_preprocessing.segmentation_record import mask_sha256, read_record +from test_segmentation_cellpose import make_job +from test_segmentation_cellpose_failsafe import verified + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def latest(run, fov): + found = read_record(run.masks, "Cells").latest(fov.relative_path) + return found[0].batch_id, found[1].mask_sha256 + + +def test_an_overwrite_in_the_window_after_publish_is_refused_until_the_record_is_written( + run, stub, monkeypatch +): + fov = run.inputs.fovs()[0] + path = mask_path(run.masks, "Cells", fov) + real_record, real_segment = cp.write_record, cp.segment_image + other = [] # B's result + + def b_in_the_window(*args): + if not other: # A has published and hashed; its record entry is not written yet + other.append(None) + monkeypatch.setattr(cp, "segment_image", lambda *a: real_segment(*a) * 5) + other[0] = cp.run_batch(make_job(run, overwrite=True), fovs=[fov], batch_id="B1") + monkeypatch.setattr(cp, "segment_image", real_segment) + return real_record(*args) + + monkeypatch.setattr(cp, "write_record", b_in_the_window) + cp.run_batch(make_job(run), fovs=[fov], batch_id="A") + ((_, status, message),) = other[0].rows() + assert status == "failed" and "is being written by process" in message # refused by the lock + assert latest(run, fov) == ("A", mask_sha256(path)) + monkeypatch.setattr(cp, "segment_image", lambda *a: real_segment(*a) * 5) + cp.run_batch(make_job(run, overwrite=True), fovs=[fov], batch_id="B2") # after A: allowed + assert latest(run, fov) == ("B2", mask_sha256(path)) + assert verified(run) == {fov.relative_path} + + +def test_a_batch_that_would_not_be_the_newest_entry_is_rolled_back(run, stub, monkeypatch): + fovs = run.inputs.fovs() + real_segment = cp.segment_image + calls = [] + + def b_between_two_images_of_a(loaded, settings, stack): + calls.append(1) + if len(calls) == 2: # A recorded image 0; B overwrites image 1 before A writes it + monkeypatch.setattr(cp, "segment_image", lambda *a: real_segment(*a) * 5) + cp.run_batch(make_job(run, overwrite=True), fovs=fovs[1:2], batch_id="B") + monkeypatch.setattr(cp, "segment_image", b_between_two_images_of_a) + return real_segment(loaded, settings, stack) + + monkeypatch.setattr(cp, "segment_image", b_between_two_images_of_a) + result = cp.run_batch(make_job(run, overwrite=True), fovs=fovs[:2], batch_id="A") + status, message = result.rows()[1][1:] + assert status == "failed" and "would not be the newest" in message + assert message.endswith(cp.ROLLED_BACK_RESTORED) + assert latest(run, fovs[1]) == ("B", mask_sha256(mask_path(run.masks, "Cells", fovs[1]))) + assert verified(run) == {f.relative_path for f in fovs[:2]} + + +@pytest.mark.parametrize("overwrite", [False, True]) +def test_an_interrupt_during_the_record_append_rolls_back(run, stub, monkeypatch, overwrite): + fovs = run.inputs.fovs() + if overwrite: + cp.run_batch(make_job(run), fovs=fovs[:2], batch_id="b0") + before = mask_path(run.masks, "Cells", fovs[1]).read_bytes() if overwrite else None + real_record, real_segment, calls = cp.write_record, cp.segment_image, [] + + def interrupted(*args): + calls.append(1) + if len(calls) == 2: # the stop button while image 1's record is being written + raise KeyboardInterrupt + return real_record(*args) + + monkeypatch.setattr(cp, "segment_image", lambda *a: real_segment(*a) * 3) + monkeypatch.setattr(cp, "write_record", interrupted) + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run, overwrite=overwrite), batch_id="b1") + path = mask_path(run.masks, "Cells", fovs[1]) + assert (path.read_bytes() == before) if overwrite else not path.exists() + expected = fovs[:2] if overwrite else fovs[:1] + assert verified(run) == {f.relative_path for f in expected} From 65be299f90f5597d158c173787f279c879bf3782 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:35:07 +0000 Subject: [PATCH 14/22] Cellpose notebook: re-pin RELEASE_REF to the commit holding the final src Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 3cc3a0b..af0f7f3 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"a2807f60d6915dd9772daa5b651fed9638d0304e\"\n", + "RELEASE_REF = \"dcb6b83299103c453d06d755206e4700694331a1\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From a585f599026f40a591046c1d8ec676183f2ce310 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:40:39 +0000 Subject: [PATCH 15/22] write_mask: decide the rollback from the file system; report stray backups An interrupt after os.replace but before _write_and_publish returned dropped the backup while the new mask stayed. The target's inode now decides whether the publish happened. stray_backups() reports leftover .previous copies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 5 +++ src/morphobricks_preprocessing/__init__.py | 2 + .../segmentation_handoff.py | 45 ++++++++++++++++--- tests/test_segmentation_rollback.py | 45 +++++++++++++++++++ 4 files changed, 90 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01642e3..d67bb35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,11 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. restore or remove raises `SegmentationError` naming both files and keeps the copy. Before, a failed overwrite left the new mask published and the earlier valid mask was lost. The record's duplicate-image check is linear (a seen-set instead of `list.count` per entry). +- **`write_mask` decides its rollback from the file system** (review of #397): an interrupt right + after the move but before `write_mask` returned used to delete the copy of the earlier mask, so the + new mask stayed and the earlier one was lost; now the target's inode says whether the move happened + and the earlier mask is restored (a new mask removed). New `stray_backups(masks_root, mask_type)` + lists `..previous.` copies left by killed processes; they are reported, never deleted. - **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/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index b7f512a..c70d7a3 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -247,6 +247,7 @@ mask_path, resolve_segmentation, segmentation_input, + stray_backups, write_mask, ) from .segmentation_record import ( @@ -502,6 +503,7 @@ "sample_planes", "scan_masks", "segmentation_input", + "stray_backups", "series_axes_from_metadata", "space_unit", "to_micrometers", diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index 5cc879d..09f8b6b 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -5,6 +5,8 @@ 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:`stray_backups`: hidden copies of earlier masks left by a killed overwrite (reported, + never deleted); - :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 @@ -275,11 +277,7 @@ def write_mask( target.parent.mkdir(parents=True, exist_ok=True) what = f"The {mask_type} mask of {fov.relative_path}" backup = _keep_backup(target) if overwrite and target.is_file() else None - try: - _write_and_publish(data, target, overwrite, what) - except BaseException: - _drop_backup(backup, target) # nothing was replaced: the earlier mask is at the target - raise + _write_and_publish(data, target, overwrite, what, backup) # rolls itself back on failure if on_published is not None: try: on_published(target) # still under the lock @@ -290,23 +288,56 @@ def write_mask( return target -def _write_and_publish(data: np.ndarray, target: Path, overwrite: bool, what: str) -> None: - """Write ``data`` to a temporary file beside ``target``, then publish it there.""" +def _write_and_publish( + data: np.ndarray, target: Path, overwrite: bool, what: str, backup: Path | None +) -> None: + """Write ``data`` to a temporary file beside ``target``, then publish it there. + + On any failure (``KeyboardInterrupt`` too) whether the publish happened is read from the + file system, not from whether the call returned: if ``target`` is now the temporary file + (same inode) the earlier mask is restored (or the new one removed); otherwise the backup + is dropped, the earlier mask never left. The backup is kept until that is decided. + """ handle, temporary = tempfile.mkstemp( prefix=f".{target.name}.", suffix=".tmp", dir=target.parent ) os.close(handle) + inode = None try: tifffile.imwrite( temporary, data, photometric="minisblack", compression="zlib", metadata={"axes": "YX"} ) give_output_mode(temporary, target) + inode = os.stat(temporary).st_ino _publish(Path(temporary), target, overwrite, what) except BaseException: Path(temporary).unlink(missing_ok=True) + if inode is not None and _is_inode(target, inode): + _roll_back(target, backup) # published, then interrupted before returning + else: + _drop_backup(backup, target) # nothing was replaced: the earlier mask is at the target raise +def _is_inode(path: Path, inode: int) -> bool: + """Whether ``path`` exists and is the file with this inode.""" + try: + return path.stat().st_ino == inode + except OSError: + return False + + +def stray_backups(masks_root: str | os.PathLike, mask_type: str) -> tuple[Path, ...]: + """Return the hidden ``..previous.`` copies left in the type's folder. + + A process killed while overwriting a mask leaves its copy of the earlier mask. They are + only reported, never deleted: the person decides (the earlier mask may be only there). + """ + check_mask_type(mask_type) + folder = Path(masks_root, mask_type) + return tuple(sorted(folder.rglob(".*.previous.*"))) if folder.is_dir() else () + + def _keep_backup(target: Path) -> Path: """Copy the mask at ``target`` to a hidden file beside it and return the copy's path. diff --git a/tests/test_segmentation_rollback.py b/tests/test_segmentation_rollback.py index 8ea5662..feb081c 100644 --- a/tests/test_segmentation_rollback.py +++ b/tests/test_segmentation_rollback.py @@ -132,3 +132,48 @@ def unlink(self, missing_ok=False): on_published=_fail(RuntimeError("record failed")), ) assert str(target) in str(caught.value) + + +def _interrupt_after_replace(monkeypatch): + real = os.replace + + def replace(source, destination): + real(source, destination) + if ".tmp" in os.path.basename(os.fspath(source)): + raise KeyboardInterrupt # after the move, before _write_and_publish returns + + monkeypatch.setattr(segmentation_handoff.os, "replace", replace) + + +def test_an_interrupt_right_after_the_publish_restores_the_earlier_mask(run, monkeypatch): + fov = run.inputs.fovs()[0] + target = write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + before = target.read_bytes() + new = labels_like(run, fov) + new[0, 0] = 7 + _interrupt_after_replace(monkeypatch) + with pytest.raises(KeyboardInterrupt): + write_mask(run.masks, "Cells", fov, new, run.inputs, overwrite=True) + assert target.read_bytes() == before # decided from the file system: it was replaced + assert _files(run) == [target.relative_to(run.masks).as_posix()] + + +def test_an_interrupt_right_after_the_publish_removes_a_new_mask(run, monkeypatch): + fov = run.inputs.fovs()[0] + _interrupt_after_replace(monkeypatch) + with pytest.raises(KeyboardInterrupt): + write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert _files(run) == [] + + +def test_stray_backups_are_reported_never_deleted(run): + from morphobricks_preprocessing.segmentation_handoff import stray_backups + + fov = run.inputs.fovs()[0] + target = write_mask(run.masks, "Cells", fov, labels_like(run, fov), run.inputs) + assert stray_backups(run.masks, "Cells") == () + stray = target.parent / f".{target.name}.previous.abc123" + stray.write_bytes(b"earlier") # a killed overwrite + assert stray_backups(run.masks, "Cells") == (stray,) + assert stray_backups(run.masks, "Nuclei") == () # no such type folder + assert stray.read_bytes() == b"earlier" From 425ca3ef646c0c897820ce1343b6d607ae3e9544 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:43:07 +0000 Subject: [PATCH 16/22] Cellpose batch: keep the mask when its record was saved; re-raise interrupts; report stray backups If write_record saved the file and then raised, the callback re-reads the record and, when the image's latest entry is this batch with this SHA-256, keeps the mask instead of rolling back. An interrupt after a successful commit is raised again. The replaced/removed note is read under the write lock. The batch summary lists stray backup copies. check_newest moves to segmentation_cellpose_commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 9 ++ pyproject.toml | 1 + .../notebook_cellpose.py | 10 +- .../segmentation_cellpose.py | 57 ++++---- .../segmentation_cellpose_commit.py | 70 ++++++++++ tests/test_notebook_cellpose.py | 13 ++ tests/test_segmentation_cellpose_commit.py | 129 ++++++++++++++++++ 7 files changed, 260 insertions(+), 29 deletions(-) create mode 100644 src/morphobricks_preprocessing/segmentation_cellpose_commit.py create mode 100644 tests/test_segmentation_cellpose_commit.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b2ac96..82d6a91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,6 +109,15 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. new mask stayed and the earlier one was lost; now the target's inode says whether the move happened and the earlier mask is restored (a new mask removed). New `stray_backups(masks_root, mask_type)` lists `..previous.` copies left by killed processes; they are reported, never deleted. +- **Cellpose batch: the mask and its record stay together when `write_record` fails after saving** + (review of #375). If the record file was saved and then the call raised (`OSError` releasing the + lock, `KeyboardInterrupt` after the replace, or an interrupt before the entry was noted), the + callback re-reads the record; when the image's latest entry is this batch with this SHA-256 the mask + is kept (not rolled back), an error stops the batch and an interrupt is raised again with the image + in the final record. An interrupt after a successful commit is no longer swallowed. Whether an + earlier mask was replaced (the table's "restored" or "removed" note) is read under the write lock. + The notebook's batch summary lists stray `.previous` copies (`stray_backups`), never deleting them. + New `segmentation_cellpose_commit` module (`check_newest` moved there). - **Channel-identity check after the run** (contract §14.1, design `channel-identity-check-2026-11-21` in MorphoFeature's `claude/restart-doc`): from the image summaries the intensity checks already make (no pixel read), every imaging unit's channel is diff --git a/pyproject.toml b/pyproject.toml index 930cea0..e213f4c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -364,6 +364,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.mask_rules" = "pure" "morphobricks_preprocessing.mask_lineage" = "io" "morphobricks_preprocessing.segmentation_cellpose" = "io" +"morphobricks_preprocessing.segmentation_cellpose_commit" = "io" "morphobricks_preprocessing.segmentation_cellpose_model" = "io" "morphobricks_preprocessing.segmentation_cellpose_settings" = "pure" "morphobricks_preprocessing.segmentation_handoff" = "io" diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index 4c75c03..6cc4fa0 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -27,7 +27,12 @@ from .notebook_style import STYLE_CSS, status, table, tiles from .preview_render import as_colour, display_panel, outline from .run_inputs import RunInputs, RunInputsError -from .segmentation_handoff import SegmentationPlan, images_to_segment, resolve_segmentation +from .segmentation_handoff import ( + SegmentationPlan, + images_to_segment, + resolve_segmentation, + stray_backups, +) from .segmentation_record import SegmentationError, check_mask_type NONE = "(none)" @@ -362,6 +367,9 @@ def progress(done: int, total: int, item: str) -> None: failed = counts["failed"] if result.stopped: self._show(_card("error", "The batch stopped early", (result.stopped,))) + if strays := stray_backups(self.masks_root, self.mask_type): # reported, never deleted + names = ", ".join(p.name for p in strays) + self._show(_card("warn", f"Copies of earlier masks left by a stopped run: {names}")) self._show( widgets.HTML( "
" diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index 339947b..54673a2 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -44,6 +44,7 @@ from ._io import file_sha256 from .manifest import MANIFEST_FILENAME from .run_inputs import Fov, RunInputs +from .segmentation_cellpose_commit import check_newest, is_recorded, replaced_earlier_mask from .segmentation_cellpose_model import ( BUILTIN_MODELS, CELLPOSE_VERSION, @@ -76,6 +77,7 @@ SegmentationPlan, images_to_segment, mask_path, + stray_backups, write_mask, ) from .segmentation_record import ( @@ -334,21 +336,29 @@ def _segment_one( """ image = fov.relative_path state: dict[str, Any] = {} + root, kind = job.masks_root, job.mask_type + strays = frozenset(stray_backups(root, kind)) def commit(path: Path) -> None: # under the type's write lock, right after the publish try: - entry = SegmentedImage(image, "written", mask_sha256=mask_sha256(path)) - _check_newest(job, batch_id, image) + entry = state["pending"] = SegmentedImage( + image, "written", mask_sha256=mask_sha256(path) + ) + state["replaced"] = replaced_earlier_mask(root, kind, strays) # exact, under the lock + check_newest(root, kind, batch_id, image) _write_batch(job, batch_id, [*entries, entry]) + state["entry"] = entry except BaseException as exc: + pending = state.get("pending") + if pending is not None and is_recorded(root, kind, batch_id, pending): + # write_record saved the file and then failed: mask and record agree, keep both + state["entry"], state["late"] = pending, exc + return state["error"] = exc raise - state["entry"] = entry - replaced = False try: labels = segment_image(job.loaded, job.settings, job.plan.read(fov)) - replaced = job.overwrite and mask_path(job.masks_root, job.mask_type, fov).is_file() write_mask( job.masks_root, job.mask_type, @@ -360,46 +370,37 @@ def commit(path: Path) -> None: # under the type's write lock, right after the ) except BaseException as exc: if "entry" in state: # written and recorded; only the earlier mask's copy is left over - return state["entry"], f"{type(exc).__name__}: {exc}" + return _after_commit(entries, state["entry"], exc) if "error" not in state: # nothing was published if isinstance(exc, Exception): # reported in the table, never dropped return SegmentedImage(image, "failed", f"{type(exc).__name__}: {exc}"), "" raise error = state["error"] if exc is error: # write_mask rolled back - note = ROLLED_BACK_RESTORED if replaced else ROLLED_BACK_REMOVED + note = ROLLED_BACK_RESTORED if state.get("replaced") else ROLLED_BACK_REMOVED else: # the rollback failed: its error names the files note = f"WARNING: the rollback failed and the mask has NO provenance: {exc}" failed = SegmentedImage(image, "failed", f"{type(error).__name__}: {error}. {note}") if not isinstance(error, Exception): raise return failed, failed.message + if "late" in state: # the record was saved, then something failed: stop, keep the mask + return _after_commit(entries, state["entry"], state["late"]) return state["entry"], "" -def _check_newest(job: SegmentationJob, batch_id: str, image: str) -> None: - """Refuse an entry for ``image`` that would not be its newest (a later batch wrote it). +def _after_commit( + entries: list[SegmentedImage], entry: SegmentedImage, exc: BaseException +) -> tuple[SegmentedImage, str]: + """Stop the batch after a failure that came once ``entry`` was recorded and its mask kept. - ``SegmentationRecord.latest`` orders batches as recorded, and a batch keeps the place of its - first write. Called under the type's write lock, where no other cooperating batch records a - written mask. + An error is reported in the table and stops the batch. An interrupt (``KeyboardInterrupt``) + is raised again, with the image in ``entries`` first so the final record keeps its entry. """ - if not record_path(job.masks_root, job.mask_type).exists(): - return - batches = read_record(job.masks_root, job.mask_type).batches - ids = [b.batch_id for b in batches] - if batch_id not in ids: - return # appended: the newest - later = [ - b.batch_id - for b in batches[ids.index(batch_id) + 1 :] - if any(e.image == image and e.status == "written" for e in b.images) - ] - if later: - raise SegmentationError( - f"The batch {later[-1]!r}, recorded after the batch {batch_id!r} started, wrote " - f"{image}; an entry of this batch would not be the newest. Start a new batch." - ) + if isinstance(exc, Exception): + return entry, f"{type(exc).__name__}: {exc}" + entries.append(entry) + raise exc def _batch(job: SegmentationJob, batch_id: str, images: list[SegmentedImage]) -> SegmentationBatch: diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_commit.py b/src/morphobricks_preprocessing/segmentation_cellpose_commit.py new file mode 100644 index 0000000..5d6a8ef --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_commit.py @@ -0,0 +1,70 @@ +"""What the Cellpose batch asks of the record while a mask is being committed. + +Both functions read the record under the type's write lock (called from ``write_mask``'s +``on_published``), with preprocessing's own reader; nothing here segments or writes. +""" + +from __future__ import annotations + +from pathlib import Path + +from .segmentation_handoff import stray_backups +from .segmentation_record import ( + SegmentationError, + SegmentedImage, + read_record, + record_path, +) + + +def check_newest(masks_root: str | Path, mask_type: str, batch_id: str, image: str) -> None: + """Refuse an entry for ``image`` that would not be its newest (a later batch wrote it). + + ``SegmentationRecord.latest`` orders batches as recorded, and a batch keeps the place of its + first write. Called under the type's write lock, where no other cooperating batch records a + written mask. + """ + if not record_path(masks_root, mask_type).exists(): + return + batches = read_record(masks_root, mask_type).batches + ids = [b.batch_id for b in batches] + if batch_id not in ids: + return # appended: the newest + later = [ + b.batch_id + for b in batches[ids.index(batch_id) + 1 :] + if any(e.image == image and e.status == "written" for e in b.images) + ] + if later: + raise SegmentationError( + f"The batch {later[-1]!r}, recorded after the batch {batch_id!r} started, wrote " + f"{image}; an entry of this batch would not be the newest. Start a new batch." + ) + + +def is_recorded( + masks_root: str | Path, mask_type: str, batch_id: str, entry: SegmentedImage +) -> bool: + """Say whether the record on disk already has ``entry`` as its image's latest, from this batch. + + ``write_record`` can save the file and then fail (releasing its lock, an interrupt after the + replace); the mask and the record then agree and the mask must not be rolled back. A record + that cannot be read is not shown to agree. + """ + try: + latest = read_record(masks_root, mask_type).latest(entry.image) + except (OSError, SegmentationError): + return False + return ( + latest is not None + and latest[0].batch_id == batch_id + and latest[1].mask_sha256 == entry.mask_sha256 + ) + + +def replaced_earlier_mask(masks_root: str | Path, mask_type: str, before: frozenset[Path]) -> bool: + """Say whether ``write_mask`` kept a copy of an earlier mask (a new backup). + + Read under the write lock, so it is exact; ``before`` is the strays seen before the write. + """ + return bool(set(stray_backups(masks_root, mask_type)) - before) diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index 3ac955c..65364b7 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -411,6 +411,19 @@ def fail_third(stack): } +def test_the_batch_summary_reports_stray_backups_and_deletes_none(cells): + open_and_choose(cells) + run_cell(cells.ns, MODEL, device="cpu") + folder = cells.run.masks / "Cells" + folder.mkdir(parents=True) + stray = folder / ".a.tif.previous.k3j2h1" # left by a killed overwrite + stray.write_bytes(b"earlier") + run_cell(cells.ns, BATCH) + shown = cells.ns["workflow"].shown + assert any("Copies of earlier masks" in card and stray.name in card for card in shown) + assert stray.read_bytes() == b"earlier" + + def test_a_preview_names_an_image_of_the_run_or_is_refused(cells): open_and_choose(cells) run_cell(cells.ns, MODEL, device="cpu") diff --git a/tests/test_segmentation_cellpose_commit.py b/tests/test_segmentation_cellpose_commit.py new file mode 100644 index 0000000..76070cf --- /dev/null +++ b/tests/test_segmentation_cellpose_commit.py @@ -0,0 +1,129 @@ +"""The record is saved, then something fails: the mask and its record entry stay together. + +``write_record`` can write the file and then raise (an ``OSError`` releasing the lock, an +interrupt after the replace). The callback re-reads the record: if the image's latest entry is +this batch with this SHA-256 the mask is kept, an error stops the batch and an interrupt is +raised again with the image in the final record. Same stand-in and helpers as +``test_segmentation_cellpose_failsafe``. +""" + +from contextlib import contextmanager + +import pytest + +from cellpose_stub import install +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_handoff, segmentation_record +from morphobricks_preprocessing.segmentation_handoff import mask_path +from morphobricks_preprocessing.segmentation_record import read_record +from test_segmentation_cellpose import make_job +from test_segmentation_cellpose_failsafe import verified + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def _fail_after_lock_release(monkeypatch, nth, error): + """Make the record lock raise ``error`` on release in its ``nth`` use: the file is saved.""" + real, calls = segmentation_record._record_lock, [] + + @contextmanager + def lock(path): + calls.append(1) + with real(path): + yield + if len(calls) == nth: + raise error + + monkeypatch.setattr(segmentation_record, "_record_lock", lock) + + +def test_an_error_after_the_record_was_saved_keeps_the_mask_and_stops_the_batch( + run, + stub, + monkeypatch, +): + fovs = run.inputs.fovs() + _fail_after_lock_release(monkeypatch, 2, OSError("lock gone")) # the 2nd image's record + result = cp.run_batch(make_job(run), batch_id="b1") + rows = result.rows() + assert rows[1][1] == "written" # kept + assert "lock gone" in result.stopped and rows[1][0] in result.stopped + assert result.stopped and "lock gone" in result.stopped + assert [s for _, s, _ in rows[2:]] == ["failed"] * (len(fovs) - 2) + assert verified(run) == {f.relative_path for f in fovs[:2]} # latest SHA == file SHA + assert read_record(run.masks, "Cells").batches[0] == result.batch + + +def test_an_interrupt_after_the_record_was_saved_keeps_the_mask_and_is_raised( + run, + stub, + monkeypatch, +): + fovs = run.inputs.fovs() + _fail_after_lock_release(monkeypatch, 2, KeyboardInterrupt()) + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run), batch_id="b1") + assert verified(run) == {f.relative_path for f in fovs[:2]} + entries = read_record(run.masks, "Cells").batches[0].images + assert [e.image for e in entries] == [f.relative_path for f in fovs[:2]] + + +def test_an_interrupt_between_the_record_write_and_the_entry_does_not_roll_back( + run, + stub, + monkeypatch, +): + fovs = run.inputs.fovs() + real, calls = cp._write_batch, [] + + def write_batch(*args): + result = real(*args) + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt # recorded, before the callback noted it + return result + + monkeypatch.setattr(cp, "_write_batch", write_batch) + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run), batch_id="b1") + assert verified(run) == {f.relative_path for f in fovs[:2]} + + +def test_an_interrupt_after_a_successful_commit_is_raised_again(run, stub, monkeypatch): + fovs = run.inputs.fovs() + real = segmentation_handoff._drop_backup + + def drop(backup, target): + real(backup, target) + if backup is not None: + raise KeyboardInterrupt # after the callback returned, before write_mask does + + cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") + monkeypatch.setattr(segmentation_handoff, "_drop_backup", drop) + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run, overwrite=True), fovs=fovs[:1], batch_id="b2") + assert verified(run) == {fovs[0].relative_path} + assert read_record(run.masks, "Cells").latest(fovs[0].relative_path)[0].batch_id == "b2" + + +def test_the_rollback_note_is_read_under_the_lock_not_before(run, stub, monkeypatch): + fovs = run.inputs.fovs() + cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") + real = cp.write_mask + + def write_mask(*args, **kwargs): + mask_path(run.masks, "Cells", fovs[0]).unlink() # gone just before the write + return real(*args, **kwargs) + + monkeypatch.setattr(cp, "write_mask", write_mask) + monkeypatch.setattr(cp, "write_record", lambda *a: (_ for _ in ()).throw(OSError("disk full"))) + result = cp.run_batch(make_job(run, overwrite=True), fovs=fovs[:1], batch_id="b2") + assert result.rows()[0][2].endswith(cp.ROLLED_BACK_REMOVED) # a new mask: nothing restored From fd87c7ec0edf1fd6f84ca169f2a5753f87465c66 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:43:07 +0000 Subject: [PATCH 17/22] Cellpose notebook: re-pin RELEASE_REF to the commit holding the final src Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index af0f7f3..ec7c3ad 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"dcb6b83299103c453d06d755206e4700694331a1\"\n", + "RELEASE_REF = \"425ca3ef646c0c897820ce1343b6d607ae3e9544\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From 1b7f4e518522a635a5f8ec167c3fba63dab78317 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:27:30 +0000 Subject: [PATCH 18/22] Docs: write_mask rolls back on every callback error; record is not fsynced The write_mask docstring and contract 15.5 now say that the rollback is unconditional (a callback that commits must reconcile its own post-commit failures) and that the record is replaced atomically but not fsynced. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 4 ++++ docs/contract.md | 2 +- src/morphobricks_preprocessing/segmentation_handoff.py | 6 +++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d67bb35..a8cae50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,10 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. restore or remove raises `SegmentationError` naming both files and keeps the copy. Before, a failed overwrite left the new mask published and the earlier valid mask was lost. The record's duplicate-image check is linear (a seen-set instead of `list.count` per entry). +- **Docs: `on_published` rollback and record durability** (external audit, 22 November 2026): the + `write_mask` docstring and contract §15.5 say that the rollback happens on every callback exception + even after the callback committed (it must reconcile its own post-commit failures), and that the + record is replaced atomically but not fsynced (not a power-loss guarantee). Behaviour unchanged. - **`write_mask` decides its rollback from the file system** (review of #397): an interrupt right after the move but before `write_mask` returned used to delete the copy of the earlier mask, so the new mask stayed and the earlier one was lost; now the target's inode says whether the move happened diff --git a/docs/contract.md b/docs/contract.md index dd08adf..3692c68 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1352,7 +1352,7 @@ links (a Google Drive mount) too. the image to the published file, **in both modes**: an overwriting writer and a default writer can never replace each other's mask. A held lock is refused at once, naming its holder, and never waited on; a killed writer leaves it, and the message says to delete it. Like the -record's lock it is a dot-file, skipped by the masks step. The optional `on_published(path)` callback runs right after the publish, still under the lock (take a hash and write the provenance there; it is not called when the write is refused). If it raises (any exception, `KeyboardInterrupt` too), the write is **rolled back under the same lock** and the error propagates: with `overwrite=True` the earlier mask was first copied to a hidden file beside it (`..previous.`, a dot-file the masks step skips, removed once the callback returns) and is moved back over the new one byte for byte, with its mode; a new mask is removed. A rollback that cannot restore or remove is a `SegmentationError` naming both files, and the copy is kept. A lock holder carries a random +record's lock it is a dot-file, skipped by the masks step. The optional `on_published(path)` callback runs right after the publish, still under the lock (take a hash and write the provenance there; it is not called when the write is refused). If it raises (any exception, `KeyboardInterrupt` too), the write is **rolled back under the same lock** and the error propagates: with `overwrite=True` the earlier mask was first copied to a hidden file beside it (`..previous.`, a dot-file the masks step skips, removed once the callback returns) and is moved back over the new one byte for byte, with its mode; a new mask is removed. A rollback that cannot restore or remove is a `SegmentationError` naming both files, and the copy is kept. The rollback is unconditional: it happens on **every** exception from the callback, even one raised after the callback had durably committed its provenance, so a callback that commits must reconcile its own post-commit failures (keep the mask and not raise, or undo its commit) before it raises; `write_mask` has no committed-state protocol. The provenance record is written atomically (a temporary file replaced into place) but **not fsynced**: that protects readers from a half-written record, not a power loss, after which a record or mask may be missing or stale. A lock holder carries a random token, so a lock deleted and retaken is never removed by its earlier holder. Limits: the lock protects the writers of one computer (not a Drive folder open in two Colab sessions); a reader may briefly see a **zero-byte placeholder** at the mask's name while a mask is being diff --git a/src/morphobricks_preprocessing/segmentation_handoff.py b/src/morphobricks_preprocessing/segmentation_handoff.py index 09f8b6b..f1b2091 100644 --- a/src/morphobricks_preprocessing/segmentation_handoff.py +++ b/src/morphobricks_preprocessing/segmentation_handoff.py @@ -248,7 +248,11 @@ def write_mask( (any exception, ``KeyboardInterrupt`` too), the write is rolled back under the lock: an overwritten mask is restored byte for byte from a hidden copy kept beside it (``..previous.``, removed once the callback returns), a new mask is - removed; then the error propagates. + removed; then the error propagates. The rollback happens on EVERY exception, even if the + callback had already durably committed its provenance: a callback that commits must + reconcile its own post-commit failures (and not raise) before returning or raising. + The provenance record is written atomically (replaced) but not fsynced, so a power + loss can lose it: this is not a durability guarantee. Returns ------- From c1977aa8f114f12d63ca5643939b1a2797d87d5c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:28:45 +0000 Subject: [PATCH 19/22] Cellpose batch: recover a failed record write only on the full batch provenance The recovery check compared the batch ID and mask SHA-256 alone, so a reused ID with another model or settings (refused by write_record) was reported written under the earlier batch's provenance. It now needs the expected batch's provenance (same_provenance) and the image's exact latest entry; otherwise write_mask rolls back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 9 +++ .../segmentation_cellpose.py | 25 ++++--- .../segmentation_cellpose_commit.py | 30 +++++--- tests/test_segmentation_cellpose_reuse.py | 72 +++++++++++++++++++ 4 files changed, 114 insertions(+), 22 deletions(-) create mode 100644 tests/test_segmentation_cellpose_reuse.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 69b7710..f3d96ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,15 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Cellpose notebook, a reused batch ID is not recovered as the old batch's (external audit B1, + 22 November 2026).** When the record write failed, the recovery check compared only the latest + entry's batch ID and mask SHA-256, so a reused ID with another model or settings and identical + mask bytes (refused by `write_record`) was reported `written` under the earlier batch's + provenance. The check now needs the record's batch of that ID to have the expected batch's + provenance (`SegmentationBatch.same_provenance`) and the image's latest entry to be exactly the + expected one; otherwise the error propagates and `write_mask` rolls back. The earlier-mask note + still comes from a `stray_backups` diff read under the lock (`on_published` is not told whether + its writer made a backup; changing its signature is outside this fix). - **Cellpose notebook, provenance under the write lock (external audit of PR #375, 22 November 2026).** Each mask's SHA-256 and its record append now run in `write_mask`'s `on_published`, under the type's write lock (then the record's lock; never the reverse), so two overlapping diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index 54673a2..0bfce73 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -341,18 +341,18 @@ def _segment_one( def commit(path: Path) -> None: # under the type's write lock, right after the publish try: - entry = state["pending"] = SegmentedImage( - image, "written", mask_sha256=mask_sha256(path) - ) + entry = SegmentedImage(image, "written", mask_sha256=mask_sha256(path)) state["replaced"] = replaced_earlier_mask(root, kind, strays) # exact, under the lock check_newest(root, kind, batch_id, image) - _write_batch(job, batch_id, [*entries, entry]) + state["expected"] = _batch(job, batch_id, [*entries, entry]) + _write_batch(job, batch_id, [*entries, entry], state["expected"]) state["entry"] = entry except BaseException as exc: - pending = state.get("pending") - if pending is not None and is_recorded(root, kind, batch_id, pending): - # write_record saved the file and then failed: mask and record agree, keep both - state["entry"], state["late"] = pending, exc + expected = state.get("expected") + if expected is not None and is_recorded(root, kind, expected): + # write_record saved the file and then failed: mask and record agree (the whole + # provenance of this batch, not just its ID), keep both + state["entry"], state["late"] = expected.images[-1], exc return state["error"] = exc raise @@ -423,10 +423,13 @@ def _batch(job: SegmentationJob, batch_id: str, images: list[SegmentedImage]) -> def _write_batch( - job: SegmentationJob, batch_id: str, entries: list[SegmentedImage] + job: SegmentationJob, + batch_id: str, + entries: list[SegmentedImage], + batch: SegmentationBatch | None = None, ) -> tuple[SegmentationBatch, Path | None]: - """Build the batch and write its record (none when no image was handled).""" - batch = _batch(job, batch_id, entries) + """Write the record of the batch (built here unless given; none when no image was handled).""" + batch = batch if batch is not None else _batch(job, batch_id, entries) return batch, write_record(job.masks_root, job.mask_type, batch) if entries else None diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_commit.py b/src/morphobricks_preprocessing/segmentation_cellpose_commit.py index 5d6a8ef..0314740 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_commit.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_commit.py @@ -10,8 +10,8 @@ from .segmentation_handoff import stray_backups from .segmentation_record import ( + SegmentationBatch, SegmentationError, - SegmentedImage, read_record, record_path, ) @@ -42,23 +42,31 @@ def check_newest(masks_root: str | Path, mask_type: str, batch_id: str, image: s ) -def is_recorded( - masks_root: str | Path, mask_type: str, batch_id: str, entry: SegmentedImage -) -> bool: - """Say whether the record on disk already has ``entry`` as its image's latest, from this batch. +def is_recorded(masks_root: str | Path, mask_type: str, expected: SegmentationBatch) -> bool: + """Say whether the record on disk is what writing ``expected`` would have left. - ``write_record`` can save the file and then fail (releasing its lock, an interrupt after the - replace); the mask and the record then agree and the mask must not be rolled back. A record - that cannot be read is not shown to agree. + ``expected`` is the batch passed to ``write_record``, its last image the entry being + committed. ``write_record`` can save the file and then fail (releasing its lock, an + interrupt after the replace); the mask and the record then agree and the mask must not be + rolled back. That needs the whole of it: the record's batch of this ID has the provenance + of ``expected`` (the record's own ``same_provenance``: a refused reuse of the ID with + another model or settings is not shown to agree) and the image's latest written entry is + exactly this one (image, status, SHA-256). A record that cannot be read is not shown to + agree. """ + entry = expected.images[-1] try: latest = read_record(masks_root, mask_type).latest(entry.image) except (OSError, SegmentationError): return False + if latest is None: + return False + batch, found = latest return ( - latest is not None - and latest[0].batch_id == batch_id - and latest[1].mask_sha256 == entry.mask_sha256 + batch.batch_id == expected.batch_id + and batch.same_provenance(expected) + and (found.image, found.status, found.mask_sha256) + == (entry.image, entry.status, entry.mask_sha256) ) diff --git a/tests/test_segmentation_cellpose_reuse.py b/tests/test_segmentation_cellpose_reuse.py new file mode 100644 index 0000000..4de25bb --- /dev/null +++ b/tests/test_segmentation_cellpose_reuse.py @@ -0,0 +1,72 @@ +"""A reused batch ID with other provenance is refused, never recorded as the old batch's. + +``write_record`` refuses an existing batch ID whose model or settings differ. The callback's +recovery (the record was saved, then something failed) must not read that refusal as success +because the ID and the mask bytes happen to match: it needs the whole provenance of the batch. +Same stand-in and helpers as ``test_segmentation_cellpose_failsafe``. +""" + +import pytest + +from cellpose_stub import install +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing.segmentation_handoff import mask_path +from morphobricks_preprocessing.segmentation_record import read_record +from test_segmentation_cellpose import make_job +from test_segmentation_cellpose_commit import _fail_after_lock_release +from test_segmentation_cellpose_failsafe import verified + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def test_a_reused_batch_id_with_other_settings_is_refused_and_the_mask_restored(run, stub): + first = run.inputs.fovs()[0] + cp.run_batch(make_job(run), fovs=[first], batch_id="same") + path = mask_path(run.masks, "Cells", first) + before_mask, before_record = path.read_bytes(), read_record(run.masks, "Cells") + other = make_job(run, overwrite=True, settings=cp.Settings(batch_size=3)) + result = cp.run_batch(other, fovs=[first], batch_id="same") + image, status, message = result.rows()[0] + assert status == "failed" and cp.ROLLED_BACK_RESTORED in message + assert result.stopped + assert path.read_bytes() == before_mask # the earlier mask, byte for byte + assert read_record(run.masks, "Cells") == before_record # latest entry unchanged + assert verified(run) == {first.relative_path} + + +def test_a_reused_batch_id_with_another_model_is_refused_and_the_mask_restored(run, stub): + first = run.inputs.fovs()[0] + cp.run_batch(make_job(run), fovs=[first], batch_id="same") + path = mask_path(run.masks, "Cells", first) + before_mask, before_record = path.read_bytes(), read_record(run.masks, "Cells") + other = make_job(run, overwrite=True, model="cpsam") + result = cp.run_batch(other, fovs=[first], batch_id="same") + assert result.rows()[0][1] == "failed" and result.stopped + assert path.read_bytes() == before_mask + assert read_record(run.masks, "Cells") == before_record + + +def test_a_post_commit_error_with_the_complete_batch_keeps_the_mask(run, stub, monkeypatch): + fovs = run.inputs.fovs() + cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") + _fail_after_lock_release(monkeypatch, 1, OSError("lock gone")) + result = cp.run_batch(make_job(run, overwrite=True), fovs=fovs[:1], batch_id="b2") + assert result.rows()[0][1] == "written" and "lock gone" in result.stopped + assert read_record(run.masks, "Cells").latest(fovs[0].relative_path)[0].batch_id == "b2" + assert verified(run) == {fovs[0].relative_path} # latest SHA == file SHA + + +def test_a_post_commit_interrupt_with_the_complete_batch_keeps_the_mask(run, stub, monkeypatch): + fovs = run.inputs.fovs() + _fail_after_lock_release(monkeypatch, 1, KeyboardInterrupt()) + with pytest.raises(KeyboardInterrupt): + cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") + assert verified(run) == {fovs[0].relative_path} From ee388ffe64f97f633cad7edc1c454f4046f6abcd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:28:49 +0000 Subject: [PATCH 20/22] Cellpose notebook: re-pin RELEASE_REF to the commit holding the final src Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index ec7c3ad..5da944d 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"425ca3ef646c0c897820ce1343b6d607ae3e9544\"\n", + "RELEASE_REF = \"c1977aa8f114f12d63ca5643939b1a2797d87d5c\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n", From cc649def101e7d2d1a3b9255352ea2dc84d494dc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:35:45 +0000 Subject: [PATCH 21/22] Cellpose recovery: require the batch's whole image list (a shortened reuse of the ID is refused) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- CHANGELOG.md | 2 ++ .../segmentation_cellpose_commit.py | 6 ++++-- tests/test_segmentation_cellpose_reuse.py | 12 ++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3d96ae..504e09a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- Cellpose batch recovery after a failed record write also requires the batch's whole image list to be the one written (a reused batch ID that leaves out earlier images is refused and the mask restored; ChatGPT al FILE 1). + **One header-name rule (#368).** Whether a raw header name is a confirmed name of a channel is now decided by one function, `description_identity.header_name_matches` (equal after NFC, never trimmed, never case-folded), used by the notebook's channel matrix, the fast layout, the physical check and diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_commit.py b/src/morphobricks_preprocessing/segmentation_cellpose_commit.py index 0314740..32250b2 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_commit.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_commit.py @@ -51,8 +51,9 @@ def is_recorded(masks_root: str | Path, mask_type: str, expected: SegmentationBa rolled back. That needs the whole of it: the record's batch of this ID has the provenance of ``expected`` (the record's own ``same_provenance``: a refused reuse of the ID with another model or settings is not shown to agree) and the image's latest written entry is - exactly this one (image, status, SHA-256). A record that cannot be read is not shown to - agree. + exactly this one (image, status, SHA-256), and the batch's whole image list is the one + written (a reuse of the ID that leaves out earlier images is refused by ``write_record`` + and must not read as success). A record that cannot be read is not shown to agree. """ entry = expected.images[-1] try: @@ -65,6 +66,7 @@ def is_recorded(masks_root: str | Path, mask_type: str, expected: SegmentationBa return ( batch.batch_id == expected.batch_id and batch.same_provenance(expected) + and batch.images == expected.images and (found.image, found.status, found.mask_sha256) == (entry.image, entry.status, entry.mask_sha256) ) diff --git a/tests/test_segmentation_cellpose_reuse.py b/tests/test_segmentation_cellpose_reuse.py index 4de25bb..5c46958 100644 --- a/tests/test_segmentation_cellpose_reuse.py +++ b/tests/test_segmentation_cellpose_reuse.py @@ -54,6 +54,18 @@ def test_a_reused_batch_id_with_another_model_is_refused_and_the_mask_restored(r assert read_record(run.masks, "Cells") == before_record +def test_a_reused_batch_id_that_leaves_out_earlier_images_is_refused(run, stub): + fovs = run.inputs.fovs() + cp.run_batch(make_job(run), fovs=fovs[:2], batch_id="same") + path = mask_path(run.masks, "Cells", fovs[1]) + before_mask, before_record = path.read_bytes(), read_record(run.masks, "Cells") + shorter = make_job(run, overwrite=True) # same provenance, identical mask bytes + result = cp.run_batch(shorter, fovs=fovs[1:2], batch_id="same") + assert result.rows()[0][1] == "failed" and result.stopped + assert path.read_bytes() == before_mask + assert read_record(run.masks, "Cells") == before_record + + def test_a_post_commit_error_with_the_complete_batch_keeps_the_mask(run, stub, monkeypatch): fovs = run.inputs.fovs() cp.run_batch(make_job(run), fovs=fovs[:1], batch_id="b1") From ae3347e3c723e6e48823d4b55a62095187a84d9a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:36:16 +0000 Subject: [PATCH 22/22] Pin the Cellpose notebook to cc649def101e, which holds its code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Scma6W3LC11s3qjXHZuGDm --- notebooks/MorphoBricks_Cellpose.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 5da944d..b963e64 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -91,7 +91,7 @@ "# Both are pinned: Cellpose to the release this notebook is made for, preprocessing to the\n", "# immutable source revision that holds this notebook's code.\n", "CELLPOSE_VERSION = \"4.2.1.1\"\n", - "RELEASE_REF = \"c1977aa8f114f12d63ca5643939b1a2797d87d5c\"\n", + "RELEASE_REF = \"cc649def101e7d2d1a3b9255352ea2dc84d494dc\"\n", "REPOSITORY = \"https://github.com/CellMigrationLab/morphobricks-preprocessing.git\"\n", "EXTRAS = \"notebook,zarr\" if \"google.colab\" in sys.modules else \"notebook\"\n", "\n",