From ffdca160bb18665b2255782765a54f3883404f0e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:28:15 +0000 Subject: [PATCH 1/3] 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 a585f599026f40a591046c1d8ec676183f2ce310 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:40:39 +0000 Subject: [PATCH 2/3] 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 1b7f4e518522a635a5f8ec167c3fba63dab78317 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:27:30 +0000 Subject: [PATCH 3/3] 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 -------