From 04d761eacce20b600bfacb63d32014d7b757fe68 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:06:57 +0000 Subject: [PATCH] Pass a stopped preprocessing run's refusal on, from RunStoppedError (#126) On an output folder where preprocessing stopped on purpose without writing a run (Spec v29: RGB units beside fluorescence units, R_HETEROGENEOUS_LAYOUT_NOT_ENABLED), CellPatcher refused with preprocessing_run_refused and advised running preprocessing again, which stops the same way. Preprocessing's RunInputs.open now raises RunStoppedError (RUN_FOLDER_STOPPED, preprocessing #322, merged in #324) there. CellPatcher passes its issues on first, unchanged and in order (code, message, paths, suggested action; Spec ADR 0005, construction and propagation), then preprocessing_run_refused naming the folder ("holds no run_manifest.json") with no re-run advice. A report preprocessing cannot read (RunReportUnreadableError) is refused with its code, RUN_FOLDER_REPORT_UNREADABLE, naming the report. CellPatcher reads no discovery_report.json. A folder with no run and no stopped run's report says to give a written run or run preprocessing first; a stale written run keeps the advice to run preprocessing again. TODO(tag): preprocessing (core and zarr extra) is pinned to its main commit b24371abe0a728995f44b2f8f1dd6d36b4a4addc until its next release is tagged, and test_preprocessing_is_pinned_to_a_release_tag_not_a_commit accepts that one commit. Both go back to a tag before this is merged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- docs/normalization.md | 2 +- notebooks/CellPatcher/CHANGELOG.md | 23 ++++- setup.py | 10 +- src/cellpatcher/run_open.py | 52 +++++++++- tests/test_dependency_pins.py | 8 +- tests/test_stopped_run.py | 152 +++++++++++++++++++++++++++++ 6 files changed, 239 insertions(+), 8 deletions(-) create mode 100644 tests/test_stopped_run.py diff --git a/docs/normalization.md b/docs/normalization.md index 8dc348b9..ec8ae7e3 100644 --- a/docs/normalization.md +++ b/docs/normalization.md @@ -193,7 +193,7 @@ planes and what to do: |---|---| | *The preprocessing run in ... cannot be used: The experiment holds ... that the preprocessing run did not record* (`unrecorded_files`) | Since preprocessing v0.4.0rc2: images or masks were added to the experiment (or masks folder) after the run. None is left out: run preprocessing again on the experiment as it is, or exclude the images there. | | *... the zarr package is not installed* (`zarr_extra_missing`) | The run holds OME-Zarr images: `pip install "cellpatcher[zarr]"`. | -| *The preprocessing run in ... cannot be used* (`preprocessing_run_refused`) | The preprocessing brick's `RunInputs` refuses the run (since v0.2.0): no `run_manifest.json` next to the table, a run written before preprocessing v0.4.0, a table or description changed since the run, or an image or mask changed or missing since the run where CellPatcher reads it. Run preprocessing v0.5 on the experiment as it is now; an experiment only moved or copied (times kept) since its run is read where it is now when CellPatcher is given that folder and its masks folder (since CP-2a). | +| *The preprocessing run in ... cannot be used* (`preprocessing_run_refused`) | The preprocessing brick's `RunInputs` refuses the run (since v0.2.0): no `run_manifest.json` next to the table, a run written before preprocessing v0.4.0, a table or description changed since the run, or an image or mask changed or missing since the run where CellPatcher reads it. Run preprocessing v0.5 on the experiment as it is now; an experiment only moved or copied (times kept) since its run is read where it is now when CellPatcher is given that folder and its masks folder (since CP-2a). A folder where preprocessing **stopped** without writing a run (for example Spec `v29`, RGB units beside fluorescence units, `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`) is refused with preprocessing's own errors first, in order, their codes, messages, paths and suggested actions unchanged (from preprocessing's `RunInputs.open`, `RunStoppedError`, `RUN_FOLDER_STOPPED`; CellPatcher reads no `discovery_report.json`), and no advice to run preprocessing again, which would stop the same way (issue #126). A run report preprocessing cannot read there is refused with its code, `RUN_FOLDER_REPORT_UNREADABLE`, naming the report. | | *The preprocessing run in ... has no published experiment description* (`A_DESCRIPTION_REQUIRED`) | Every run needs one (Spec ADR 0002 AR10): describe the experiment and publish its description in the preprocessing notebook, run preprocessing again and give CellPatcher that run. | | *normalization.plane_histograms/manifest names ...* (`not_the_run_output`) | Only the run's own files, unrenamed in its output folder, are read. Give that folder's `plane_histograms.csv` (and leave `manifest` empty). | | *... these images of the run have no repeat group* (`missing_repeat_group`) / *... several repeat groups to the images of one condition and biological-repeat folder* (`repeat_group_conflict`) | The `biological_repeat` scope pools the repeat groups of the run's description: run preprocessing again with its published description. `normalization.experiment_design` was removed (the derived `experiment_design.csv` is never read). | diff --git a/notebooks/CellPatcher/CHANGELOG.md b/notebooks/CellPatcher/CHANGELOG.md index 8840fa89..1cc50a41 100644 --- a/notebooks/CellPatcher/CHANGELOG.md +++ b/notebooks/CellPatcher/CHANGELOG.md @@ -74,11 +74,26 @@ Release v0.3.0 Pin preprocessing v0.4.0rc4; prepare v0.2.0rc2 --- -## [Unreleased] - Channel IDs on every patch (#125) +## [Unreleased] - Channel IDs on every patch (#125); a stopped preprocessing run's refusal passed on (#126) -For v0.7.2. Found by the S3.4 adversarial suite (MorphoFeature draft PR #240, gate G3). +For v0.7.2. Found by the S3.4 adversarial suite (MorphoFeature draft PR #240, gate G3 (#125) and row A07 (#126)). +#126 needs the preprocessing release after v0.6.1 (preprocessing #322, merged in #324); until it is tagged, +draft PR #128 pins preprocessing's main commit b24371a, and it is not merged before that release. ### Fixed +- **#126: a run preprocessing stopped on purpose is refused with preprocessing's own errors, without re-run + advice.** On an output folder where preprocessing stopped without writing a run (Spec `v29`: RGB units beside + fluorescence units, `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`), v0.7.1 refused with `preprocessing_run_refused` + ("holds no run_manifest.json") and advised running preprocessing again, which stops the same way. Preprocessing's + `RunInputs.open` now raises `RunStoppedError` (`RUN_FOLDER_STOPPED`) there, carrying the stopped run's error + issues; CellPatcher passes them on first, in order, with their codes, messages, paths and suggested actions + unchanged (Spec ADR 0005, construction and propagation), then `preprocessing_run_refused` naming the folder, + still "holds no run_manifest.json", whose action is to follow preprocessing's, with no re-run advice. A run + report preprocessing cannot read (`RunReportUnreadableError`) is refused with its code, + `RUN_FOLDER_REPORT_UNREADABLE`, naming the report. CellPatcher reads no `discovery_report.json` itself. A folder + with neither a run nor a stopped run's report still says to give a written run or run preprocessing first, and a + run that was written but is stale (an image changed since, an older manifest) keeps the advice to run + preprocessing again, which fixes it. `tests/test_stopped_run.py`. - **#125: every patch of a described run records its channel IDs, in its C order.** Without normalization and without channel splitting, v0.7.1 recorded no channel ID at all (`c`, `channel_id` and `normalization_channels` empty, on the patch and in `patches.csv`), so the patches of two units storing DNA, ACTIN and ACTIN, DNA could @@ -108,6 +123,10 @@ For v0.7.2. Found by the S3.4 adversarial suite (MorphoFeature draft PR #240, ga without the `channel_ids` column, like any table missing a column CellPatcher writes (nothing is defaulted): a table written by v0.7.1 or earlier must be written again by running CellPatcher again. A `channel_ids` cell is read as a tuple and checked with the normalization brick's `check_channel_ids`. +- **Dependencies (draft only, `TODO(tag)`):** preprocessing (core and `zarr` extra) is pinned to its main commit + `b24371abe0a728995f44b2f8f1dd6d36b4a4addc` (`RunStoppedError`, #324), not a release tag, so + `test_preprocessing_is_pinned_to_a_release_tag_not_a_commit` accepts that one commit until the next preprocessing + release is tagged; the pin and the test go back to a tag before #126 is merged. Normalization stays `v0.7.0`. ## [0.7.1] - 2026-11-16 - Fixes from the external audit of v0.7.0 (CP1, CP2, CP3, F3, F4); preprocessing v0.6.1 diff --git a/setup.py b/setup.py index 40f150c5..7b669415 100644 --- a/setup.py +++ b/setup.py @@ -18,8 +18,13 @@ # below adds its OME-Zarr reader at the same tag. v0.6.0 is Spec ADR 0005 # steps 2 and 2b (resolver contract v3, RunInputs.read_objects, the # conversion helpers); v0.6.1 fixes the checked-fingerprint race. + # TODO(tag): draft PR #128 only. RunStoppedError (preprocessing #322, merged + # in #324) is on preprocessing's main, not yet in a release: pinned to that + # commit until the next preprocessing release is tagged, then back to its + # tag (here, in the zarr extra and in tests/test_dependency_pins.py) before + # #128 is merged. "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/" - "morphobricks-preprocessing@v0.6.1", + "morphobricks-preprocessing@b24371abe0a728995f44b2f8f1dd6d36b4a4addc", # CellPatcher imports the normalization brick directly (plane histograms, # the plane table, pooling, normalization parameters, SINGLE), so it # declares it, at the tag the preprocessing tag above pins (owner @@ -62,8 +67,9 @@ # name of this extra, ``preprocessing``, is gone: the preprocessing brick # is a core dependency. "zarr": [ + # TODO(tag): the commit of the core pin above until the preprocessing release. "morphobricks-preprocessing[zarr] @ git+https://github.com/CellMigrationLab/" - "morphobricks-preprocessing@v0.6.1", + "morphobricks-preprocessing@b24371abe0a728995f44b2f8f1dd6d36b4a4addc", ], }, ) diff --git a/src/cellpatcher/run_open.py b/src/cellpatcher/run_open.py index 04d460c1..421c285d 100644 --- a/src/cellpatcher/run_open.py +++ b/src/cellpatcher/run_open.py @@ -169,7 +169,10 @@ def open_run( ``unrecorded_files`` (images or masks the run did not record), ``zarr_extra_missing`` or ``preprocessing_run_refused``, with the brick's reason, when ``RunInputs`` refuses the run, or - ``unreadable_plane_histograms`` when its table cannot be read. + ``unreadable_plane_histograms`` when its table cannot be read. For a folder + where preprocessing stopped without writing a run (``RunStoppedError``), + preprocessing's own errors come first, unchanged (:func:`_refusal_issues`, + issue #126); ``RUN_FOLDER_REPORT_UNREADABLE`` when its report cannot be read. """ from morphobricks_normalization.csv_io import CsvFormatError from morphobricks_preprocessing.manifest import ManifestFormatError @@ -190,7 +193,7 @@ def open_run( except (RunInputsError, ManifestFormatError) as exc: # ManifestFormatError: a manifest of another version (preprocessing v0.5.1 reads version 4 only, # older runs are refused, never converted) or not a manifest at all. - raise PreprocessingCheckError([_refusal_issue(exc, folder)]) from exc + raise PreprocessingCheckError(_refusal_issues(exc, folder)) from exc except CsvFormatError as exc: raise PreprocessingCheckError([ error( @@ -208,6 +211,51 @@ def open_run( """The code of a run without a published experiment description (Spec ADR 0002 AR10, AR11 (1)).""" +def _refusal_issues(exc: Exception, folder: Path) -> list[ValidationIssue]: + """Return the issues for ``RunInputs.open`` refusing the run in *folder*. + + Where preprocessing stopped on purpose without writing a run (Spec ``v29``: + ``R_HETEROGENEOUS_LAYOUT_NOT_ENABLED``), ``RunInputs.open`` raises ``RunStoppedError`` + (``RUN_FOLDER_STOPPED``, preprocessing contract §9.1) with the stopped run's error issues. A run + of the same experiment stops the same way, so "run preprocessing again" would loop (issue #126): + those issues are passed on first, unchanged and in order (Spec ADR 0005, construction and + propagation), followed by CellPatcher's ``preprocessing_run_refused`` naming the folder, which + gives no re-run advice. A report preprocessing cannot read (``RunReportUnreadableError``) is + refused with its code, ``RUN_FOLDER_REPORT_UNREADABLE``. CellPatcher never reads the report. + """ + from morphobricks_preprocessing import MANIFEST_FILENAME, RunReportUnreadableError, RunStoppedError + from morphobricks_preprocessing.validation import error + + if isinstance(exc, RunStoppedError): + return [*exc.issues, error( + "preprocessing_run_refused", + f"The preprocessing run in {folder} cannot be used: it holds no run_manifest.json, because " + f"preprocessing stopped there without writing a run ({RunStoppedError.code}), for the errors " + "listed above.", + [str(folder)], + "Do what preprocessing's suggested actions above say; the run is written only once preprocessing " + "no longer stops there. Then give CellPatcher that run.", + )] + if isinstance(exc, RunReportUnreadableError): + return [error( + RunReportUnreadableError.code, + f"The preprocessing run in {folder} cannot be used: {exc}", + [str(exc.path)], + "Run preprocessing again into that folder with the preprocessing CellPatcher installs, which " + "writes a report it can read, then give CellPatcher that run.", + )] + if (folder / MANIFEST_FILENAME).exists(): # a written run: stale, older or changed since + return [_refusal_issue(exc, folder)] + return [error( + "preprocessing_run_refused", + f"The preprocessing run in {folder} cannot be used: {exc}", + [str(folder)], + "Give CellPatcher the output folder of a preprocessing run that was written (it holds " + "run_manifest.json), or run preprocessing on the experiment first. If preprocessing stopped in " + "that folder, its discovery_report.txt there says why and what to fix.", + )] + + def _refusal_issue(exc: Exception, folder: Path) -> ValidationIssue: """Return the issue for ``RunInputs.open`` refusing the run in *folder*, by its reason. diff --git a/tests/test_dependency_pins.py b/tests/test_dependency_pins.py index 1c0dc6bf..78178326 100644 --- a/tests/test_dependency_pins.py +++ b/tests/test_dependency_pins.py @@ -125,14 +125,20 @@ def test_the_zarr_extra_installs_the_core_preprocessing_tag(): assert _url(zarr) == _url(_by_name(core)["morphobricks-preprocessing"]) +PREPROCESSING_MAIN_COMMIT = "b24371abe0a728995f44b2f8f1dd6d36b4a4addc" +"""TODO(tag): draft PR #128 only. Preprocessing's main with RunStoppedError (#322, merged in #324), +not yet released. Remove it, and pin the release tag, before #128 is merged.""" + + def test_preprocessing_is_pinned_to_a_release_tag_not_a_commit(): # Stage 2 CP-1 pinned the v0.5.0 release-candidate commit until the tag existed; a commit pin # is not a release, and every brick must spell the same URL (pip refuses two for one package). + # TODO(tag): on draft PR #128 the one accepted commit is PREPROCESSING_MAIN_COMMIT, until the tag. core, extras = _setup_requirements() for requirement in (_by_name(core)["morphobricks-preprocessing"], *extras["zarr"]): repository, ref = _url(requirement).rsplit("@", 1) assert repository == "git+https://github.com/CellMigrationLab/morphobricks-preprocessing", requirement - assert re.fullmatch(r"v\d+\.\d+\.\d+", ref), ( + assert re.fullmatch(r"v\d+\.\d+\.\d+", ref) or ref == PREPROCESSING_MAIN_COMMIT, ( f"{requirement}: pin a release tag, not {ref!r}" ) diff --git a/tests/test_stopped_run.py b/tests/test_stopped_run.py new file mode 100644 index 00000000..6324a2b4 --- /dev/null +++ b/tests/test_stopped_run.py @@ -0,0 +1,152 @@ +"""A run preprocessing refused on purpose is refused with preprocessing's code and fix (issue #126). + +Found by the S3.4 adversarial suite (MorphoFeature draft PR #240). Spec fixture ``v29`` puts RGB units +beside fluorescence units; preprocessing refuses it on purpose (``R_HETEROGENEOUS_LAYOUT_NOT_ENABLED``) +and writes no run, only its report. CellPatcher said "Run preprocessing again", which stops the same +way: the advice looped. Spec ADR 0005 (construction and propagation): a refusal is passed on with its +code, message and fix unchanged, and CellPatcher advises a re-run only where one can help (a stale run). +CellPatcher gets the stopped run's issues from preprocessing's ``RunInputs.open`` (``RunStoppedError``, +``RUN_FOLDER_STOPPED``, preprocessing contract §9.1) and never reads ``discovery_report.json`` itself. +""" + +import json +from pathlib import Path + +import pytest +import tifffile + +from cellpatcher.config import CellPatcherConfig, GridConfig +from cellpatcher.orchestration import run_patching_condition_repeat_tree +from cellpatcher.run_open import open_run +from cellpatcher.statistics import PreprocessingCheckError + +VALID = Path(__file__).parent / "spec_fixtures" / "fixtures" / "valid" + + +def _v29_stopped(tmp_path): + """Run preprocessing on Spec v29, as the G4 suite does; return (experiment, output, its issues).""" + from morphobricks_preprocessing import run_experiment + from morphobricks_preprocessing.axes import prefill_mapping + from morphobricks_preprocessing.testing_described import description_of, write_described_tree + + (fixture,) = VALID.glob("v29_*.toml") + parsed, data = description_of(fixture.read_bytes()) + experiment, output = tmp_path / "experiment", tmp_path / "output" + write_described_tree(experiment, None, parsed) + output.mkdir() + (output / "morphobricks.toml").write_bytes(data) + result = run_experiment(experiment, prefill_mapping("CYX"), output_folder=output) + assert not result.written and not (output / "run_manifest.json").exists() + return experiment, output, [issue for issue in result.issues if issue.is_error] + + +def _tree_run(experiment, output, target): + config = CellPatcherConfig(mode="grid", grid=GridConfig(tile_size=4)) + config.common.preprocessing_run, config.common.output_dir = str(output), str(target) + config.export.enabled = True + return run_patching_condition_repeat_tree(experiment, config=config, combine_metadata=True) + + +def test_v29_refusal_carries_preprocessings_code_message_and_fix_and_no_rerun_advice(tmp_path): + experiment, output, refused = _v29_stopped(tmp_path) + assert refused[0].code == "R_HETEROGENEOUS_LAYOUT_NOT_ENABLED" + + with pytest.raises(PreprocessingCheckError) as raised: + _tree_run(experiment, output, tmp_path / "patches") + issues = raised.value.issues + # preprocessing's errors first, unchanged (code, message, paths, fix), then CellPatcher's naming the folder + assert [(i.code, i.message, i.paths, i.action) for i in issues[:-1]] == [ + (i.code, i.message, i.paths, i.action) for i in refused + ] + assert issues[0].code == "R_HETEROGENEOUS_LAYOUT_NOT_ENABLED" + from morphobricks_preprocessing import RunInputs, RunStoppedError + + with pytest.raises(RunStoppedError) as stopped: # what CellPatcher passes on, equal and in order + RunInputs.open(output) + assert tuple(issues[:-1]) == stopped.value.issues + assert issues[-1].code == "preprocessing_run_refused" and str(output) in issues[-1].message + text = str(raised.value) + assert "no run_manifest.json" in text # what the G4 suite's A07 matches + assert "preprocessing again" not in text.lower() # the issue's acceptance: no re-run advice + assert "again" not in issues[-1].action.lower() and "run preprocessing" not in issues[-1].action.lower() + assert not (tmp_path / "patches").exists() + + +def test_a_folder_without_a_run_or_report_says_to_run_preprocessing_first_not_again(tmp_path): + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + assert [issue.code for issue in raised.value.issues] == ["preprocessing_run_refused"] + assert "holds no run_manifest.json" in str(raised.value) + assert "again" not in raised.value.issues[0].action.lower() + assert "discovery_report.txt" in raised.value.issues[0].action + + +def test_the_issues_come_from_run_stopped_error_not_from_reading_the_report(tmp_path, monkeypatch): + # The issues passed on are RunStoppedError's, in its order and unchanged (paths not re-sorted), and + # CellPatcher opens no discovery_report.json of its own. + from morphobricks_preprocessing import RunInputs, RunStoppedError + from morphobricks_preprocessing.validation import Severity, ValidationIssue + + raised_issues = ( + ValidationIssue(Severity.ERROR, "B_SECOND", "second, listed first.", ("z.tif", "a.tif"), "Fix B."), + ValidationIssue(Severity.ERROR, "A_FIRST", "first, listed second.", (), ""), + ) + + def stopped(*_args, **_kwargs): + raise RunStoppedError("RUN_FOLDER_STOPPED: stopped.", raised_issues) + + monkeypatch.setattr(RunInputs, "open", stopped) + (tmp_path / "discovery_report.json").write_text("this is not read", encoding="utf-8") + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + issues = raised.value.issues + assert tuple(issues[:-1]) == raised_issues + assert issues[-1].code == "preprocessing_run_refused" and "RUN_FOLDER_STOPPED" in issues[-1].message + + +@pytest.mark.parametrize( + "report", + [ + "not json", + json.dumps({"report_version": "2", "status": "stopped", "issues": [{"code": "X", "severity": "error"}]}), + json.dumps({"report_version": "1", "step": "run", "status": "stopped", "provisional": False, "issues": []}), + ], +) +def test_an_unreadable_report_gives_preprocessings_coded_refusal(tmp_path, report): + # Nothing is guessed from a report preprocessing cannot read: its code, naming the report. + path = tmp_path / "discovery_report.json" + path.write_text(report, encoding="utf-8") + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + (issue,) = raised.value.issues + assert issue.code == "RUN_FOLDER_REPORT_UNREADABLE" + assert issue.paths == (str(path),) + assert "RUN_FOLDER_REPORT_UNREADABLE" in issue.message and str(tmp_path) in issue.message + + +@pytest.mark.parametrize("step, status, provisional", [("run", "written", False), ("check", "stopped", False), + ("run", "stopped", True)]) +def test_a_report_of_no_stopped_run_gives_the_plain_missing_run_refusal(tmp_path, step, status, provisional): + # A written, check or provisional report names no stopped run: the plain refusal of a folder without a run. + report = {"report_version": "1", "step": step, "status": status, "provisional": provisional, "issues": [ + {"code": "X", "severity": "error", "message": "m", "paths": [], "action": "a"}]} + (tmp_path / "discovery_report.json").write_text(json.dumps(report), encoding="utf-8") + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + assert [issue.code for issue in raised.value.issues] == ["preprocessing_run_refused"] + assert "holds no run_manifest.json" in str(raised.value) + assert "again" not in raised.value.issues[0].action.lower() + + +def test_a_stale_run_still_advises_running_preprocessing_again(tmp_path): + # A run whose image changed since it was written is one a re-run fixes: that advice stays. + from morphobricks_preprocessing.testing_described import make_described_run + + (fixture,) = VALID.glob("v13_*.toml") + run = make_described_run(tmp_path / "run", fixture.read_bytes()) + image = next(run.experiment.rglob("*.tif")) + tifffile.imwrite(image, tifffile.imread(image)[:, :4, :4], photometric="minisblack", metadata={"axes": "CYX"}) + with pytest.raises(PreprocessingCheckError) as raised: + open_run(run.output) + assert [issue.code for issue in raised.value.issues] == ["preprocessing_run_refused"] + assert "Run preprocessing again" in raised.value.issues[0].action