Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion openhcs/core/image_file_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from abc import abstractmethod
from dataclasses import dataclass, replace
from functools import lru_cache
from hashlib import md5
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Sequence

Expand Down Expand Up @@ -193,7 +194,7 @@ def project_image_metadata(

@dataclass(frozen=True, slots=True)
class ImageFileRevision:
"""Physical file identity and timestamps determining header reuse."""
"""Physical file identity and timestamps determining source-fact reuse."""

path: Path
device: int
Expand All @@ -214,6 +215,26 @@ def from_path(cls, path: Path) -> "ImageFileRevision":
changed_ns=stat.st_ctime_ns,
)

@lru_cache(maxsize=4096)
def md5_digest(self) -> str:
"""Derive a bounded, lazy content fact for this exact physical revision.

A first read must still belong to the captured revision. Failed or
changing reads are not cached; an already observed digest remains a
fact about its immutable revision. Current-file consumers construct a
fresh revision before querying it.
"""
if ImageFileRevision.from_path(self.path) != self:
raise ValueError(
f"Image file revision changed before reading content digest: {self.path}."
)
content = self.path.read_bytes()
if ImageFileRevision.from_path(self.path) != self:
raise ValueError(
f"Image file revision changed while reading content digest: {self.path}."
)
return md5(content, usedforsecurity=False).hexdigest()


class ImageFileFormat(CompilerPreparedAutoRegisterFamily, metaclass=AutoRegisterMeta):
"""Nominal owner of image-file source and serialization semantics."""
Expand Down
10 changes: 4 additions & 6 deletions openhcs/interop/cellprofiler/analyst_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from collections.abc import Callable, Iterator, Mapping, Sequence
from dataclasses import dataclass, fields, replace
from enum import Enum
from hashlib import md5
from io import BytesIO
from itertools import chain
from numbers import Integral, Real
Expand All @@ -38,7 +37,7 @@
)
from openhcs.core.component_group_scope import RuntimeExecutionAxisScope
from openhcs.core.context.processing_context import ProcessingContext
from openhcs.core.image_file_serialization import ImageFileFormat
from openhcs.core.image_file_serialization import ImageFileFormat, ImageFileRevision
from openhcs.core.measurement_row_materialization import (
WideMeasurementRowAccumulator,
ConcatenatedColumnarRows,
Expand Down Expand Up @@ -222,10 +221,9 @@ def _source_image_projection_values(
source_axis_indices
),
CellProfilerSourceImageProjectionField.HEIGHT: height,
CellProfilerSourceImageProjectionField.MD5_DIGEST: md5(
source_path.read_bytes(),
usedforsecurity=False,
).hexdigest(),
CellProfilerSourceImageProjectionField.MD5_DIGEST: (
ImageFileRevision.from_path(source_path).md5_digest()
),
CellProfilerSourceImageProjectionField.SCALING: scaling,
CellProfilerSourceImageProjectionField.SERIES: 0,
CellProfilerSourceImageProjectionField.URL: source_path.resolve().as_uri(),
Expand Down
75 changes: 75 additions & 0 deletions tests/unit/test_cellprofiler_analyst_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,7 @@ def _borrowed_source_export_fixture(
context.microscope_handler = SimpleNamespace(
source_admission_config=lambda: None,
metadata_handler=SimpleNamespace(
source_workspace_root=lambda _plate_path: tmp_path,
source_workspace_metadata_document=lambda _plate_path: document,
)
)
Expand Down Expand Up @@ -1990,6 +1991,80 @@ def test_database_projection_includes_derived_grid_measurements() -> None:
}


def test_source_digest_is_shared_across_image_numbers_and_channel_aliases(
tmp_path, monkeypatch,
):
from collections import defaultdict
from hashlib import md5
from openhcs.core.component_group_scope import RuntimeExecutionAxisScope
from openhcs.core.image_file_serialization import ImageFileRevision
from openhcs.core.source_image_provenance import SourceImageProvenance
import tifffile

source = tmp_path / "source.tif"
tifffile.imwrite(source, np.arange(64, dtype=np.uint16).reshape(8, 8))
expected = md5(source.read_bytes(), usedforsecurity=False).hexdigest()
original = Path.read_bytes
reads = []

def read_bytes(self):
reads.append(self)
return original(self)

ImageFileRevision.md5_digest.cache_clear()
monkeypatch.setattr(Path, "read_bytes", read_bytes)
owner = CPATableRowProjection(
CellProfilerDatabaseColumnDialect(),
CellProfilerImageSetNumbering(SourceImageSetIdentityPolicy()),
)
rows, metadata = {}, defaultdict(list)
for axis_id in ("W001", "W002"):
for alias in ("DNA", "Tubulin"):
owner.collect_image_provenance(
SourceImageProvenance(
source_path=str(source),
source_component_metadata={"well": "A01", "site": "1"},
source_image_names=(alias,),
),
scope=RuntimeExecutionAxisScope(axis_id),
source_image_name=alias,
image_rows_by_number=rows,
source_metadata_by_image_number=metadata,
)
assert tuple(rows) == (1, 2)
for image_number, row in rows.items():
assert row["ImageNumber"] == image_number
assert row["Image_MD5Digest_DNA"] == expected
assert row["Image_MD5Digest_Tubulin"] == expected
assert row["Image_Height_DNA"] == row["Image_Height_Tubulin"] == 8
assert len(metadata[image_number]) == 2
assert reads == [source]


def test_source_projection_frame_error_precedes_digest_read(tmp_path, monkeypatch):
import tifffile
import openhcs.interop.cellprofiler.analyst_export as export
from openhcs.core.image_file_serialization import ImageFileRevision

source = tmp_path / "source.tif"
tifffile.imwrite(
source, np.zeros((3, 4, 5), dtype=np.uint16),
photometric="minisblack", metadata={"axes": "ZYX"},
)

def forbidden_read(self):
raise AssertionError("Content digest read before frame validation")

ImageFileRevision.md5_digest.cache_clear()
monkeypatch.setattr(Path, "read_bytes", forbidden_read)
with pytest.raises(ValueError, match="Source frame index True"):
export._source_image_projection_values(
source, "DNA", CellProfilerDatabaseColumnDialect(),
source_axis_indices=(True,),
)
assert ImageFileRevision.md5_digest.cache_info().currsize == 0


def test_repeated_source_contributors_share_physical_projection(tmp_path, monkeypatch):
from collections import defaultdict
import openhcs.interop.cellprofiler.analyst_export as export
Expand Down
126 changes: 126 additions & 0 deletions tests/unit/test_image_file_serialization.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import os
from hashlib import md5
from pathlib import Path
from contextlib import nullcontext
from dataclasses import replace

Expand All @@ -9,6 +11,7 @@
from openhcs.core.image_file_serialization import (
ImageFileFormat,
ImageFileSourceMetadata,
ImageFileRevision,
NumpyImageFileFormat,
PngImageFileFormat,
SourceImagePixelSemantics,
Expand All @@ -18,13 +21,136 @@
prepare_disk_image_payloads,
require_image_file_source_metadata,
)


from openhcs.core.runtime_image_values import (
ImageMetadataPayload,
ImagePayloadMetadata,
)
from openhcs.core.runtime_plane_projection import RuntimePlaneAxis


def test_content_digest_is_lazy_shared_and_bounded(tmp_path, monkeypatch) -> None:
path = tmp_path / "digest.tif"
tifffile.imwrite(path, np.arange(20, dtype=np.uint16).reshape(4, 5))
expected = md5(path.read_bytes(), usedforsecurity=False).hexdigest()
original = Path.read_bytes
reads = []

def read_bytes(self):
reads.append(self)
return original(self)

ImageFileRevision.md5_digest.cache_clear()
monkeypatch.setattr(Path, "read_bytes", read_bytes)
require_image_file_source_metadata(path)
assert reads == []
for _ in range(3):
assert ImageFileRevision.from_path(path).md5_digest() == expected
assert reads == [path]
assert ImageFileRevision.md5_digest.cache_parameters() == {
"maxsize": 4096, "typed": False,
}


def test_content_digest_detects_same_size_rewrite_with_restored_mtime(tmp_path) -> None:
path = tmp_path / "digest.tif"
path.write_bytes(b"old source")
before_stat = path.stat()
before = ImageFileRevision.from_path(path)
first = before.md5_digest()
path.write_bytes(b"new source")
os.utime(path, ns=(before_stat.st_atime_ns, before_stat.st_mtime_ns))
after = ImageFileRevision.from_path(path)
assert after.size == before.size
assert after.modified_ns == before.modified_ns
assert after.changed_ns != before.changed_ns
assert after.md5_digest() == md5(b"new source", usedforsecurity=False).hexdigest()
assert after.md5_digest() != first
assert before.md5_digest() == first # An observed revision retains its own fact.


def test_content_digest_refuses_stale_first_read_without_caching(tmp_path) -> None:
path = tmp_path / "digest.tif"
path.write_bytes(b"old")
before = ImageFileRevision.from_path(path)
path.write_bytes(b"new")
ImageFileRevision.md5_digest.cache_clear()
for _ in range(2):
with pytest.raises(ValueError, match="changed before reading content digest"):
before.md5_digest()
assert ImageFileRevision.md5_digest.cache_info().currsize == 0
assert ImageFileRevision.from_path(path).md5_digest() == md5(
b"new", usedforsecurity=False,
).hexdigest()


def test_content_digest_refuses_mutation_during_read_without_caching(
tmp_path, monkeypatch,
) -> None:
path = tmp_path / "digest.tif"
path.write_bytes(b"old")
before = ImageFileRevision.from_path(path)
original = Path.read_bytes

def read_then_change(self):
content = original(self)
self.write_bytes(b"new")
return content

ImageFileRevision.md5_digest.cache_clear()
with monkeypatch.context() as patch:
patch.setattr(Path, "read_bytes", read_then_change)
with pytest.raises(ValueError, match="changed while reading content digest"):
before.md5_digest()
assert ImageFileRevision.md5_digest.cache_info().currsize == 0
assert ImageFileRevision.from_path(path).md5_digest() == md5(
b"new", usedforsecurity=False,
).hexdigest()


def test_content_digest_does_not_cache_read_errors(tmp_path, monkeypatch) -> None:
path = tmp_path / "digest.tif"
path.write_bytes(b"source")
revision = ImageFileRevision.from_path(path)
original = Path.read_bytes
reads = []

def fail_once(self):
reads.append(self)
if len(reads) == 1:
raise PermissionError("original content read refused")
return original(self)

ImageFileRevision.md5_digest.cache_clear()
monkeypatch.setattr(Path, "read_bytes", fail_once)
with pytest.raises(PermissionError, match="original content read refused"):
revision.md5_digest()
assert ImageFileRevision.md5_digest.cache_info().currsize == 0
assert revision.md5_digest() == md5(b"source", usedforsecurity=False).hexdigest()
assert reads == [path, path]


def test_content_digest_detects_replacement_deletion_and_recreation(tmp_path) -> None:
path = tmp_path / "digest.tif"
path.write_bytes(b"old")
before = ImageFileRevision.from_path(path)
old_digest = before.md5_digest()
replacement = tmp_path / "replacement.tif"
replacement.write_bytes(b"new")
os.utime(replacement, ns=(path.stat().st_atime_ns, before.modified_ns))
replacement.replace(path)
after = ImageFileRevision.from_path(path)
assert after.size == before.size
assert after.modified_ns == before.modified_ns
assert after.inode != before.inode
assert after.md5_digest() != old_digest
path.unlink()
with pytest.raises(FileNotFoundError):
ImageFileRevision.from_path(path)
path.write_bytes(b"old")
assert ImageFileRevision.from_path(path).md5_digest() == old_digest

def test_jpeg_disk_serialization_scales_unit_float_image_to_uint8() -> None:
image = np.array([[0.0, 0.5, 1.0]], dtype=np.float32)

Expand Down
Loading