From fe922977b167c40d87389b2b4f466db90feb51db Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 22:57:55 -0400 Subject: [PATCH 01/11] Reconcile completed plate metadata from one admitted transaction --- openhcs/core/source_projection.py | 31 ++--- openhcs/core/steps/function_outputs.py | 45 +++++-- openhcs/core/virtual_workspace_metadata.py | 113 ++++++++++++++---- openhcs/microscopes/openhcs.py | 21 +++- .../unit/test_persisted_semantic_metadata.py | 35 ++++++ 5 files changed, 195 insertions(+), 50 deletions(-) diff --git a/openhcs/core/source_projection.py b/openhcs/core/source_projection.py index 1349e94927..f089f8cca1 100644 --- a/openhcs/core/source_projection.py +++ b/openhcs/core/source_projection.py @@ -9,7 +9,7 @@ from pathlib import Path, PurePosixPath from types import MappingProxyType from functools import lru_cache -from typing import Any, ClassVar, Mapping, cast, get_type_hints +from typing import Any, ClassVar, Mapping, cast, get_args, get_type_hints from urllib.parse import quote from polystore.virtual_workspace import SourcePixelRef @@ -704,6 +704,17 @@ def extend_source_metadata( def extend_serialized_payload(self, payload: dict[str, Any]) -> None: """Add projection-specific fields to the nominal wire payload.""" + def persisted_image_metadata(self) -> ImagePayloadMetadata | None: + """Restore pixel metadata when a consumer needs physical image semantics. + + Publication uses the same coordinates while retaining opaque serialized + provenance. Durable image readers still admit the complete payload. + """ + return ( + ImagePayloadMetadata.from_mapping(self.image_metadata) + if isinstance(self.image_metadata, Mapping) else self.image_metadata + ) + def matches_binding(self, binding: NamedSourceBinding) -> bool: """Return whether this projection represents one exact source binding.""" @@ -720,7 +731,7 @@ def belongs_to_execution_axis(self, axis_id: str) -> bool: def declared_optional_payload_field(cls, payload_type: type) -> str: - """Derive the one declared field carrying ``payload_type | None``. + """Derive the one optional declared field carrying ``payload_type``. Class-level derivation: the wire field is owned by the projection's dataclass declaration, so it is computed once per (class, payload type) @@ -731,7 +742,8 @@ def declared_optional_payload_field(cls, payload_type: type) -> str: matches = tuple( declared.name for declared in fields(cls) - if annotations[declared.name] == payload_type | None + if payload_type in get_args(annotations[declared.name]) + and type(None) in get_args(annotations[declared.name]) ) if len(matches) != 1: raise ValueError( @@ -762,7 +774,7 @@ class SourcePlaneProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) - image_metadata: ImagePayloadMetadata | None = None + image_metadata: ImagePayloadMetadata | Mapping[str, object] | None = None def __post_init__(self) -> None: _normalize_projection(self) @@ -777,9 +789,6 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: if self.image_metadata is not None: payload[self.image_metadata_wire_field()] = to_jsonable(self.image_metadata) - def persisted_image_metadata(self) -> ImagePayloadMetadata | None: - return self.image_metadata - @property def payload_composition_alias(self) -> str | None: """Return this plane's alias for source-binding bundle composition.""" @@ -805,7 +814,7 @@ class SourceArtifactProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) - image_metadata: ImagePayloadMetadata | None = None + image_metadata: ImagePayloadMetadata | Mapping[str, object] | None = None execution_scope: RuntimeExecutionAxisScope | None = None def artifact_result_directory( @@ -939,12 +948,6 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: self.image_metadata ) - def persisted_image_metadata(self) -> ImagePayloadMetadata | None: - """Return pixel metadata when this artifact is independently loadable.""" - - return self.image_metadata - - @dataclass(frozen=True, slots=True) class SourceProjectionSet: """Validated source projection set for one OpenHCS source workspace.""" diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index f87d19772a..e85706c2de 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -82,6 +82,7 @@ from openhcs.core.virtual_workspace_metadata import ( METADATA_CONFIG, AtomicMetadataWriter, + OpenHCSMetadataSubdirectories, VirtualWorkspaceSourceProjectionEntries, ) from openhcs.microscopes.microscope_interfaces import FilenameParser @@ -701,7 +702,11 @@ def production_targets( return (self,) def reconciliation_targets( - self, context: ProcessingContext + self, + context: ProcessingContext, + *, + document: OpenHCSMetadataSubdirectories | None = None, + admitted_entries: Mapping[str, VirtualWorkspaceSourceProjectionEntries] | None = None, ) -> tuple[OpenHCSMetadataTarget, ...]: """Resolve destinations after runtime values have been released.""" return (self,) @@ -749,7 +754,10 @@ def write( context: ProcessingContext, *, produced_plan: CompiledStepPlan | None = None, - ) -> None: + metadata_writer: AtomicMetadataWriter | None = None, + metadata_document: dict[str, Any] | None = None, + admitted_entries: VirtualWorkspaceSourceProjectionEntries | None = None, + ) -> VirtualWorkspaceSourceProjectionEntries: """Project the target's current storage state into plate metadata.""" if context.filemanager is None: @@ -770,7 +778,7 @@ def write( str(self.output_dir), self.backend ) ) - AtomicMetadataWriter().publish_source_projection_metadata( + return (metadata_writer or AtomicMetadataWriter()).publish_source_projection_metadata( METADATA_CONFIG.metadata_path(self.plate_root), self.sub_dir, projection_entries, @@ -786,6 +794,8 @@ def write( if self.results_dir is not None else None ), + metadata_document=metadata_document, + admitted_entries=admitted_entries, ) def produced_projection_entries( @@ -1051,10 +1061,15 @@ def finalize_completed_plate( for target in cls.for_plan(plan): target_contexts.setdefault(target, context) + targets_by_document: dict[ + Path, dict[OpenHCSMetadataTarget, ProcessingContext] + ] = {} for owner, context in target_contexts.items(): - for target in owner.reconciliation_targets(context): - if target.contains_outputs(context): - target.write(context) + targets_by_document.setdefault( + METADATA_CONFIG.metadata_path(owner.plate_root), {} + )[owner] = context + for metadata_path, targets in targets_by_document.items(): + AtomicMetadataWriter().reconcile_completed_plate(metadata_path, targets) class ProducedImageMetadataCapability: @@ -1157,14 +1172,24 @@ def production_targets( ) def reconciliation_targets( - self, context: ProcessingContext + self, + context: ProcessingContext, + *, + document: OpenHCSMetadataSubdirectories | None = None, + admitted_entries: Mapping[str, VirtualWorkspaceSourceProjectionEntries] | None = None, ) -> tuple[RuntimeArtifactMetadataTarget, ...]: """Use durable typed projections, without reloading cleaned artifact values.""" from openhcs.microscopes.openhcs import OpenHCSMetadataHandler - directories = OpenHCSMetadataHandler( - context.filemanager - ).reconciliation_directories(self.plate_root, self.backend) + if (document is None) != (admitted_entries is None): + raise ValueError("Reconciliation requires one document and its admitted entries.") + handler = OpenHCSMetadataHandler(context.filemanager) + directories = ( + handler.reconciliation_directories(self.plate_root, self.backend) + if document is None else handler.reconciliation_directories_from_document( + self.plate_root, self.backend, document, admitted_entries + ) + ) return tuple( self.for_directory(directory) for directory in dict.fromkeys( diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index 9356ff5a70..75add98866 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -9,7 +9,7 @@ from dataclasses import dataclass, field from pathlib import Path from types import MappingProxyType -from typing import Any, Callable, TypeAlias +from typing import TYPE_CHECKING, Any, Callable, TypeAlias from polystore.atomic import FileLockError, atomic_update_json from polystore.metadata_writer import MetadataConfig @@ -36,6 +36,10 @@ ) from openhcs.core.source_tile_geometry import SourceTileLayout +if TYPE_CHECKING: + from openhcs.core.context.processing_context import ProcessingContext + from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget + @dataclass(frozen=True) class OpenHCSMetadataConfig(MetadataConfig): @@ -166,7 +170,9 @@ def publish_source_projection_metadata( backend: str, is_main: bool, results_dir: str | None, - ) -> None: + metadata_document: dict[str, Any] | None = None, + admitted_entries: VirtualWorkspaceSourceProjectionEntries | None = None, + ) -> VirtualWorkspaceSourceProjectionEntries: """Publish saved inventory from retained addresses, never generated names. Final reconciliation uses the same durable typed projections after step @@ -174,13 +180,15 @@ def publish_source_projection_metadata( inventing coordinates from filenames or the input label cache. """ saved_paths = tuple(saved_image_paths) + published_entries = None def update(data): + nonlocal published_entries data = self._ensure_subdirectories_structure(data) subdirectory = data[METADATA_CONFIG.SUBDIRECTORIES_KEY].setdefault( subdirectory_name, {} ) - entries = ( + published_entries = ( VirtualWorkspaceSourceProjectionEntries(MappingProxyType({})) if projection_entries is None else projection_entries ).publish_into_subdirectory( @@ -189,7 +197,9 @@ def update(data): reconcile_directory=( subdirectory_name if projection_entries is None else None ), - ).entries + admitted_entries=admitted_entries, + ) + entries = published_entries.entries # Concurrent axes may persist their pixels before publishing their # own producer records. A step publishes known saved addresses only; # completed-plate reconciliation requires the entire saved inventory. @@ -220,6 +230,47 @@ def update(data): ) return data + if metadata_document is None: + self._execute_update(metadata_path, update) + else: + update(metadata_document) + return published_entries + + def reconcile_completed_plate( + self, + metadata_path: str | Path, + target_contexts: Mapping[OpenHCSMetadataTarget, ProcessingContext], + ) -> None: + """Admit and reconcile all targets from one locked plate document.""" + if not Path(metadata_path).is_file() and not any( + target.contains_outputs(context) + for target, context in target_contexts.items() + ): + return + + def update(data): + data = self._ensure_subdirectories_structure(data) + document = OpenHCSMetadataSubdirectories(data) + admitted = { + name: VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + for name, subdirectory in document.items() + } + for owner, context in target_contexts.items(): + for target in owner.reconciliation_targets( + context, document=document, admitted_entries=admitted + ): + if target.contains_outputs(context): + admitted[target.sub_dir] = target.write( + context, + metadata_writer=self, + metadata_document=data, + admitted_entries=admitted.get( + target.sub_dir, + VirtualWorkspaceSourceProjectionEntries(MappingProxyType({})), + ), + ) + return data + self._execute_update(metadata_path, update) @staticmethod @@ -431,6 +482,12 @@ def from_projection_paths( cls, projection_paths: Sequence[tuple[SourceProjection, str]], ) -> "VirtualWorkspaceSourceProjectionEntries": + """Admit full physical metadata unless only publication views are needed. + + Publication retains the exact serialized image metadata; it never feeds + that view into a physical image reader. Canonical durable readers restore + and validate all nested provenance by default. + """ """Admit a producer's typed updates in persisted path order.""" SourceProjectionSet( tuple(projection for projection, _path in projection_paths) @@ -466,12 +523,16 @@ def merged_with_subdirectory( def _admit_retained_records( self, records: Mapping[str, JsonValue], + *, + restore_image_metadata: bool = True, ) -> "VirtualWorkspaceSourceProjectionEntries": entries: dict[str, SourceProjection] = {} for path, record in records.items(): virtual_path, projection = ( (path, self.entries[path]) - if path in self.entries else self._projection_record(record) + if path in self.entries else self._projection_record( + record, restore_image_metadata=restore_image_metadata + ) ) if virtual_path in entries: raise RuntimeError( @@ -495,7 +556,7 @@ def merge_into_subdirectory( ) -> "VirtualWorkspaceSourceProjectionEntries": """Merge producer fields without normalizing opaque retained wire fields.""" records = self._records_by_path(subdirectory) - admitted = self._admit_retained_records(records) + admitted = self._admit_retained_records(records, restore_image_metadata=False) fields = SourceProjectionMetadataSerializer.projection_fields( self.projection_paths ) @@ -514,6 +575,7 @@ def publish_into_subdirectory( *, saved_image_paths: Sequence[str], reconcile_directory: str | None, + admitted_entries: VirtualWorkspaceSourceProjectionEntries | None = None, ) -> "VirtualWorkspaceSourceProjectionEntries": """Publish current path views while retaining admitted durable records. @@ -523,7 +585,10 @@ def publish_into_subdirectory( workspace maps are independently derived normalized views. """ records = self._records_by_path(subdirectory) - admitted = self._admit_retained_records(records) + admitted = ( + self._admit_retained_records(records, restore_image_metadata=False) + if admitted_entries is None else admitted_entries + ) saved_set = frozenset(saved_image_paths) missing = saved_set.difference(admitted.entries) if missing and reconcile_directory is not None: @@ -576,6 +641,8 @@ def publish_into_subdirectory( def from_subdirectory( cls, subdirectory: OpenHCSSubdirectoryPayload, + *, + restore_image_metadata: bool = True, ) -> "VirtualWorkspaceSourceProjectionEntries": records = subdirectory.get("source_projection") if records is None: @@ -584,7 +651,9 @@ def from_subdirectory( raise RuntimeError("virtual_workspace source_projection must be a list.") entries: dict[str, SourceProjection] = {} for record in records: - virtual_path, projection = cls._projection_record(record) + virtual_path, projection = cls._projection_record( + record, restore_image_metadata=restore_image_metadata + ) if virtual_path in entries: raise RuntimeError( "virtual_workspace source_projection contains duplicate path " @@ -597,6 +666,8 @@ def from_subdirectory( def _projection_record( cls, record: JsonValue, + *, + restore_image_metadata: bool = True, ) -> tuple[str, SourceProjection]: if not isinstance(record, Mapping): raise RuntimeError( @@ -636,21 +707,22 @@ def _projection_record( source_metadata = cls._optional_metadata(record, "source_metadata") component_labels = cls._optional_component_labels(record) source_alias = cls._optional_text(record, "source_alias") + image_metadata_value = record.get(SourcePlaneProjection.image_metadata_wire_field()) + if image_metadata_value is not None and not isinstance(image_metadata_value, Mapping): + raise TypeError("Persisted image metadata must be a mapping.") + image_metadata = ( + None if image_metadata_value is None else + ImagePayloadMetadata.from_mapping(image_metadata_value) + if restore_image_metadata else MappingProxyType(image_metadata_value) + ) if projection_role is SourceProjectionRole.PRIMARY_PLANE: - image_metadata_value = record.get( - SourcePlaneProjection.image_metadata_wire_field() - ) projection: SourceProjection = SourcePlaneProjection( address=address, ref=ref, source_alias=source_alias, source_metadata=source_metadata, component_labels=component_labels, - image_metadata=( - None - if image_metadata_value is None - else ImagePayloadMetadata.from_mapping(image_metadata_value) - ), + image_metadata=image_metadata, ) else: if source_alias is None: @@ -658,9 +730,6 @@ def _projection_record( "Source-artifact projection records require source_alias." ) artifact_kind = cls._required_text(record, "artifact_kind") - image_metadata_value = record.get( - SourcePlaneProjection.image_metadata_wire_field() - ) projection = SourceArtifactProjection( address=address, ref=ref, @@ -668,11 +737,7 @@ def _projection_record( artifact_kind=ArtifactType.coerce(artifact_kind), source_metadata=source_metadata, component_labels=component_labels, - image_metadata=( - None - if image_metadata_value is None - else ImagePayloadMetadata.from_mapping(image_metadata_value) - ), + image_metadata=image_metadata, execution_scope=cls._optional_execution_scope(record), ) return virtual_path, projection diff --git a/openhcs/microscopes/openhcs.py b/openhcs/microscopes/openhcs.py index 4af2a07d22..367e05bc5b 100644 --- a/openhcs/microscopes/openhcs.py +++ b/openhcs/microscopes/openhcs.py @@ -407,12 +407,29 @@ def reconciliation_directories( for directory in self.analysis_result_directories(plate_root) ) document = OpenHCSMetadataSubdirectories.from_path(metadata_path) + admitted_entries = { + name: VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + for name, subdirectory in document.items() + } + return self.reconciliation_directories_from_document( + plate_root, backend, document, admitted_entries + ) + + def reconciliation_directories_from_document( + self, + plate_path: Union[str, Path], + backend: str, + document: OpenHCSMetadataSubdirectories, + admitted_entries: Mapping[str, VirtualWorkspaceSourceProjectionEntries], + ) -> tuple[Path, ...]: + """Select destinations from the current transaction's admitted entries.""" + plate_root = Path(plate_path) admitted = tuple( ( subdirectory, - VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory), + admitted_entries[name], ) - for _name, subdirectory in document.items() + for name, subdirectory in document.items() ) directories = tuple( plate_root / directory diff --git a/tests/unit/test_persisted_semantic_metadata.py b/tests/unit/test_persisted_semantic_metadata.py index 6f9535c173..308c079487 100644 --- a/tests/unit/test_persisted_semantic_metadata.py +++ b/tests/unit/test_persisted_semantic_metadata.py @@ -7,6 +7,7 @@ from pathlib import Path import numpy as np +import pytest from polystore.virtual_workspace import SourcePixelRef from openhcs.constants.constants import AllComponents @@ -32,6 +33,7 @@ VirtualWorkspacePathLookup, VirtualWorkspaceSourceProjection, ) +from openhcs.core.virtual_workspace_metadata import VirtualWorkspaceSourceProjectionEntries from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.serialization.json import to_jsonable @@ -129,6 +131,39 @@ def test_source_projection_serialization_decodes_typed_image_metadata() -> None: assert projection.image_metadata == _collapsed_metadata() +def test_publication_retains_provenance_without_reconstructing_physical_payload() -> None: + subdirectory = _serialized_metadata(_collapsed_metadata())["subdirectories"]["."] + original = json.dumps(subdirectory) + retained = VirtualWorkspaceSourceProjectionEntries({}).publish_into_subdirectory( + subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory="." + ) + projection = retained.entries[VIRTUAL_PATH] + + assert isinstance(projection.image_metadata, Mapping) + assert projection.persisted_image_metadata() == _collapsed_metadata() + assert json.dumps(subdirectory) == original + assert VirtualWorkspaceSourceProjectionEntries.from_subdirectory( + subdirectory + ).entries[VIRTUAL_PATH].image_metadata == _collapsed_metadata() + + +def test_retained_corrupt_provenance_still_fails_at_physical_admission() -> None: + subdirectory = _serialized_metadata(_collapsed_metadata())["subdirectories"]["."] + subdirectory["source_projection"][0]["image_metadata"]["source_provenance"][ + "source_image_provenance_planes" + ][0]["undeclared_field"] = "corrupt" + original = json.dumps(subdirectory) + retained = VirtualWorkspaceSourceProjectionEntries({}).publish_into_subdirectory( + subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory="." + ) + + assert json.dumps(subdirectory) == original + with pytest.raises(ValueError, match="undeclared field"): + retained.entries[VIRTUAL_PATH].persisted_image_metadata() + with pytest.raises(ValueError, match="undeclared field"): + VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + + def test_image_artifact_projection_round_trips_typed_pixel_metadata() -> None: metadata = ImagePayloadMetadata( source_component_metadata={ From 5580938250bd79b6edb9670f5db7714d7820c4c9 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 22:59:36 -0400 Subject: [PATCH 02/11] Trace publication admission with its declared metadata restoration scope --- tests/unit/test_persisted_image_metadata.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_persisted_image_metadata.py b/tests/unit/test_persisted_image_metadata.py index eb95e7d4a2..6d485bd65c 100644 --- a/tests/unit/test_persisted_image_metadata.py +++ b/tests/unit/test_persisted_image_metadata.py @@ -333,9 +333,9 @@ def test_typed_projection_update_admits_only_retained_wire_records( decode = VirtualWorkspaceSourceProjectionEntries._projection_record encode = SourceProjectionMetadataSerializer._source_projection_payload - def record(cls, wire): + def record(cls, wire, **kwargs): admitted_paths.append(wire["virtual_path"]) - return decode(wire) + return decode(wire, **kwargs) def payload(cls, projection, virtual_path): serialized_paths.append(virtual_path) From 524ff501015c2b75224b4a9a3c662baee4c81d71 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:13:43 -0400 Subject: [PATCH 03/11] Retain persisted projection facts in completed output observations --- openhcs/core/steps/abstract.py | 60 ++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/openhcs/core/steps/abstract.py b/openhcs/core/steps/abstract.py index 9aa4c6f695..4c024ce05d 100644 --- a/openhcs/core/steps/abstract.py +++ b/openhcs/core/steps/abstract.py @@ -39,6 +39,10 @@ # ProcessingContext is used in type hints if TYPE_CHECKING: + from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget + from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, + ) from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.orchestrator.analysis_consolidation import ( RuntimeAnalysisConsolidationInputs, @@ -60,6 +64,46 @@ class StepExecutionObservation: default_factory=dict ) + source_projection_entries_by_target: Mapping[ + "OpenHCSMetadataTarget", "VirtualWorkspaceSourceProjectionEntries" + ] = field(default_factory=dict) + + def __post_init__(self) -> None: + projections = dict(self.source_projection_entries_by_target) + if projections: + from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget + from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, + ) + + for target, entries in projections.items(): + if not isinstance(target, OpenHCSMetadataTarget): + raise TypeError( + "Persisted source projection observations require declared metadata targets." + ) + if target.artifact_materializations: + raise ValueError( + "Persisted source projection observations cannot retain image materializations." + ) + if not isinstance(entries, VirtualWorkspaceSourceProjectionEntries): + raise TypeError( + "Persisted source projection observations require typed projection entries." + ) + object.__setattr__( + self, "source_projection_entries_by_target", MappingProxyType(projections) + ) + + @property + def is_empty(self) -> bool: + """Whether this completed output carrier has no facts to transport.""" + return not ( + self.materialized_locations_by_address + or self.runtime_export_paths + or self.analysis_inputs is not None + or self.image_numbers_by_export_path + or self.source_projection_entries_by_target + ) + @classmethod def empty(cls) -> "StepExecutionObservation": return cls(MappingProxyType({})) @@ -84,6 +128,7 @@ def combine( paths = [] analysis_inputs = [] image_numbers = {} + source_projections = {} for observation in observations: for ( address, @@ -100,11 +145,26 @@ def combine( f"Export {path} has conflicting execution image-number owners." ) image_numbers[path] = numbers + for ( + target, + entries, + ) in observation.source_projection_entries_by_target.items(): + source_projections.setdefault(target, []).append(entries) + from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, + ) + return cls( MappingProxyType(locations), tuple(dict.fromkeys(paths)), RuntimeAnalysisConsolidationInputs.combine(analysis_inputs), MappingProxyType(image_numbers), + MappingProxyType( + { + target: VirtualWorkspaceSourceProjectionEntries.combine(entries) + for target, entries in source_projections.items() + } + ), ) From 2ea5e891f64857d363273810e64bbe04feafc1c3 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:13:43 -0400 Subject: [PATCH 04/11] Retain persisted projection facts in completed output observations --- openhcs/core/steps/abstract.py | 60 ++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/openhcs/core/steps/abstract.py b/openhcs/core/steps/abstract.py index 9aa4c6f695..4c024ce05d 100644 --- a/openhcs/core/steps/abstract.py +++ b/openhcs/core/steps/abstract.py @@ -39,6 +39,10 @@ # ProcessingContext is used in type hints if TYPE_CHECKING: + from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget + from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, + ) from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.orchestrator.analysis_consolidation import ( RuntimeAnalysisConsolidationInputs, @@ -60,6 +64,46 @@ class StepExecutionObservation: default_factory=dict ) + source_projection_entries_by_target: Mapping[ + "OpenHCSMetadataTarget", "VirtualWorkspaceSourceProjectionEntries" + ] = field(default_factory=dict) + + def __post_init__(self) -> None: + projections = dict(self.source_projection_entries_by_target) + if projections: + from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget + from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, + ) + + for target, entries in projections.items(): + if not isinstance(target, OpenHCSMetadataTarget): + raise TypeError( + "Persisted source projection observations require declared metadata targets." + ) + if target.artifact_materializations: + raise ValueError( + "Persisted source projection observations cannot retain image materializations." + ) + if not isinstance(entries, VirtualWorkspaceSourceProjectionEntries): + raise TypeError( + "Persisted source projection observations require typed projection entries." + ) + object.__setattr__( + self, "source_projection_entries_by_target", MappingProxyType(projections) + ) + + @property + def is_empty(self) -> bool: + """Whether this completed output carrier has no facts to transport.""" + return not ( + self.materialized_locations_by_address + or self.runtime_export_paths + or self.analysis_inputs is not None + or self.image_numbers_by_export_path + or self.source_projection_entries_by_target + ) + @classmethod def empty(cls) -> "StepExecutionObservation": return cls(MappingProxyType({})) @@ -84,6 +128,7 @@ def combine( paths = [] analysis_inputs = [] image_numbers = {} + source_projections = {} for observation in observations: for ( address, @@ -100,11 +145,26 @@ def combine( f"Export {path} has conflicting execution image-number owners." ) image_numbers[path] = numbers + for ( + target, + entries, + ) in observation.source_projection_entries_by_target.items(): + source_projections.setdefault(target, []).append(entries) + from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, + ) + return cls( MappingProxyType(locations), tuple(dict.fromkeys(paths)), RuntimeAnalysisConsolidationInputs.combine(analysis_inputs), MappingProxyType(image_numbers), + MappingProxyType( + { + target: VirtualWorkspaceSourceProjectionEntries.combine(entries) + for target, entries in source_projections.items() + } + ), ) From 1f1525046b7477eb7d9856e278bef07e43b4c1d2 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:15:47 -0400 Subject: [PATCH 05/11] Publish held producer metadata once at the plate receiving boundary --- openhcs/core/source_projection.py | 31 ++++--- openhcs/core/steps/function_outputs.py | 82 ++++++++++++------- openhcs/core/virtual_workspace_metadata.py | 66 +++++++++------ tests/unit/test_function_outputs.py | 70 +++++++++++----- .../unit/test_named_checkpoint_publication.py | 11 ++- .../test_persisted_roi_only_publication.py | 37 +++++++-- .../unit/test_persisted_semantic_metadata.py | 25 ++---- 7 files changed, 198 insertions(+), 124 deletions(-) diff --git a/openhcs/core/source_projection.py b/openhcs/core/source_projection.py index f089f8cca1..1349e94927 100644 --- a/openhcs/core/source_projection.py +++ b/openhcs/core/source_projection.py @@ -9,7 +9,7 @@ from pathlib import Path, PurePosixPath from types import MappingProxyType from functools import lru_cache -from typing import Any, ClassVar, Mapping, cast, get_args, get_type_hints +from typing import Any, ClassVar, Mapping, cast, get_type_hints from urllib.parse import quote from polystore.virtual_workspace import SourcePixelRef @@ -704,17 +704,6 @@ def extend_source_metadata( def extend_serialized_payload(self, payload: dict[str, Any]) -> None: """Add projection-specific fields to the nominal wire payload.""" - def persisted_image_metadata(self) -> ImagePayloadMetadata | None: - """Restore pixel metadata when a consumer needs physical image semantics. - - Publication uses the same coordinates while retaining opaque serialized - provenance. Durable image readers still admit the complete payload. - """ - return ( - ImagePayloadMetadata.from_mapping(self.image_metadata) - if isinstance(self.image_metadata, Mapping) else self.image_metadata - ) - def matches_binding(self, binding: NamedSourceBinding) -> bool: """Return whether this projection represents one exact source binding.""" @@ -731,7 +720,7 @@ def belongs_to_execution_axis(self, axis_id: str) -> bool: def declared_optional_payload_field(cls, payload_type: type) -> str: - """Derive the one optional declared field carrying ``payload_type``. + """Derive the one declared field carrying ``payload_type | None``. Class-level derivation: the wire field is owned by the projection's dataclass declaration, so it is computed once per (class, payload type) @@ -742,8 +731,7 @@ def declared_optional_payload_field(cls, payload_type: type) -> str: matches = tuple( declared.name for declared in fields(cls) - if payload_type in get_args(annotations[declared.name]) - and type(None) in get_args(annotations[declared.name]) + if annotations[declared.name] == payload_type | None ) if len(matches) != 1: raise ValueError( @@ -774,7 +762,7 @@ class SourcePlaneProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) - image_metadata: ImagePayloadMetadata | Mapping[str, object] | None = None + image_metadata: ImagePayloadMetadata | None = None def __post_init__(self) -> None: _normalize_projection(self) @@ -789,6 +777,9 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: if self.image_metadata is not None: payload[self.image_metadata_wire_field()] = to_jsonable(self.image_metadata) + def persisted_image_metadata(self) -> ImagePayloadMetadata | None: + return self.image_metadata + @property def payload_composition_alias(self) -> str | None: """Return this plane's alias for source-binding bundle composition.""" @@ -814,7 +805,7 @@ class SourceArtifactProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) - image_metadata: ImagePayloadMetadata | Mapping[str, object] | None = None + image_metadata: ImagePayloadMetadata | None = None execution_scope: RuntimeExecutionAxisScope | None = None def artifact_result_directory( @@ -948,6 +939,12 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: self.image_metadata ) + def persisted_image_metadata(self) -> ImagePayloadMetadata | None: + """Return pixel metadata when this artifact is independently loadable.""" + + return self.image_metadata + + @dataclass(frozen=True, slots=True) class SourceProjectionSet: """Validated source projection set for one OpenHCS source workspace.""" diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index e85706c2de..c06b5e2723 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -5,11 +5,11 @@ import logging import time from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace from pathlib import Path from types import MappingProxyType -from typing import ClassVar, TypeVar +from typing import TYPE_CHECKING, ClassVar, TypeVar import numpy as np from metaclass_registry import ( @@ -87,6 +87,9 @@ ) from openhcs.microscopes.microscope_interfaces import FilenameParser +if TYPE_CHECKING: + from openhcs.core.orchestrator.execution_result import RuntimeExecutionObservation + logger = logging.getLogger(__name__) StreamPayload = RuntimeArrayData @@ -117,7 +120,7 @@ def finalize_function_step_outputs( MaterializedImageOutputWriter.write_if_needed(context, plan) StreamOutputsAuthority.stream_outputs(context, plan) materializations = ArtifactMaterializationTargetPlan.materialize(context, plan) - OpenHCSMetadataTarget.write_for_step( + projection_entries = OpenHCSMetadataTarget.observe_for_step( context, plan, artifact_materializations=materializations ) else: @@ -141,15 +144,18 @@ def finalize_function_step_outputs( lambda: ArtifactMaterializationTargetPlan.materialize(context, plan), plan, ) - _profile_finalization_phase( + projection_entries = _profile_finalization_phase( "finalize_openhcs_metadata", - lambda: OpenHCSMetadataTarget.write_for_step( + lambda: OpenHCSMetadataTarget.observe_for_step( context, plan, artifact_materializations=materializations ), plan, ) - return StepExecutionObservation.combine( - item.observation(plan, context) for item in materializations + return replace( + StepExecutionObservation.combine( + item.observation(plan, context) for item in materializations + ), + source_projection_entries_by_target=projection_entries, ) @@ -645,6 +651,7 @@ class OpenHCSMetadataTarget(ABC, metaclass=AutoRegisterMeta): __key_extractor__ = staticmethod(extract_key_from_class_name) declaration_key: ClassVar[str | None] = None is_main: ClassVar[bool] = False + create_openhcs_metadata: bool = field(default=True, kw_only=True) output_dir: Path backend: str @@ -689,7 +696,8 @@ def for_execution( for declaration in cls.__registry__.values() if (owner := declaration.from_execution(context, plan)) is not None for target in replace( - owner, artifact_materializations=artifact_materializations + owner, artifact_materializations=artifact_materializations, + create_openhcs_metadata=plan.create_openhcs_metadata, ).production_targets(context, plan) ) @@ -812,7 +820,8 @@ def produced_projection_entries( raise ValueError("OpenHCS metadata requires a file manager.") target = type(self).from_plan(plan) if target is None or self not in replace( - target, artifact_materializations=self.artifact_materializations + target, artifact_materializations=self.artifact_materializations, + create_openhcs_metadata=self.create_openhcs_metadata, ).production_targets(context, plan): raise ValueError("Produced metadata plan does not own this output target.") records = self.produced_records(context, plan) @@ -1024,34 +1033,31 @@ def persisted_image_metadata( ) @classmethod - def write_for_step( + def observe_for_step( cls, context: ProcessingContext, plan: CompiledStepPlan, *, artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = (), - ) -> None: + ) -> Mapping[OpenHCSMetadataTarget, VirtualWorkspaceSourceProjectionEntries]: + """Retain exact saved-image facts before payload release, without JSON I/O.""" + observations = {} for target in cls.for_execution( context, plan, artifact_materializations=artifact_materializations ): - if not plan.create_openhcs_metadata: - projection_entries = target.produced_projection_entries(context, plan) - if projection_entries.is_empty: - continue - AtomicMetadataWriter().merge_source_projection_metadata( - METADATA_CONFIG.metadata_path(target.plate_root), - target.sub_dir, - projection_entries, - ) - else: - target.write(context, produced_plan=plan) + entries = target.produced_projection_entries(context, plan) + if target.create_openhcs_metadata or not entries.is_empty: + observations[replace(target, artifact_materializations=())] = entries + return MappingProxyType(observations) @classmethod def finalize_completed_plate( cls, compiled_contexts: Mapping[str, ProcessingContext], + *, + runtime_observations: Iterable[RuntimeExecutionObservation] = (), ) -> None: - """Write each populated metadata target after all axis outputs exist.""" + """Publish completed or partial saved outputs once at the receiving boundary.""" target_contexts: dict[OpenHCSMetadataTarget, ProcessingContext] = {} for context in compiled_contexts.values(): @@ -1061,6 +1067,17 @@ def finalize_completed_plate( for target in cls.for_plan(plan): target_contexts.setdefault(target, context) + produced_by_document: dict[Path, dict[OpenHCSMetadataTarget, list[VirtualWorkspaceSourceProjectionEntries]]] = {} + for observation in runtime_observations: + for context_observation in observation.contexts: + context = compiled_contexts[context_observation.context_key] + for target, entries in context_observation.outputs.source_projection_entries_by_target.items(): + produced_by_document.setdefault( + METADATA_CONFIG.metadata_path(target.plate_root), {} + ).setdefault(target, []).append(entries) + if target.create_openhcs_metadata: + target_contexts.setdefault(target, context) + targets_by_document: dict[ Path, dict[OpenHCSMetadataTarget, ProcessingContext] ] = {} @@ -1068,8 +1085,15 @@ def finalize_completed_plate( targets_by_document.setdefault( METADATA_CONFIG.metadata_path(owner.plate_root), {} )[owner] = context - for metadata_path, targets in targets_by_document.items(): - AtomicMetadataWriter().reconcile_completed_plate(metadata_path, targets) + for metadata_path in dict.fromkeys((*targets_by_document, *produced_by_document)): + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, + targets_by_document.get(metadata_path, {}), + produced_entries_by_target={ + target: VirtualWorkspaceSourceProjectionEntries.combine(entries) + for target, entries in produced_by_document.get(metadata_path, {}).items() + }, + ) class ProducedImageMetadataCapability: @@ -1163,13 +1187,9 @@ def production_targets( Path(output.path).parent for materialization in self.artifact_materializations for output in materialization.outputs_for_backend(self.backend) + if context.filemanager.exists(output.path, self.backend) ) - return tuple( - target - for directory in directories - for target in (self.for_directory(directory),) - if target.contains_outputs(context) - ) + return tuple(self.for_directory(directory) for directory in directories) def reconciliation_targets( self, diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index 75add98866..f95cb7e1dd 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -240,9 +240,13 @@ def reconcile_completed_plate( self, metadata_path: str | Path, target_contexts: Mapping[OpenHCSMetadataTarget, ProcessingContext], + *, + produced_entries_by_target: Mapping[ + OpenHCSMetadataTarget, VirtualWorkspaceSourceProjectionEntries + ] = MappingProxyType({}), ) -> None: """Admit and reconcile all targets from one locked plate document.""" - if not Path(metadata_path).is_file() and not any( + if not produced_entries_by_target and not Path(metadata_path).is_file() and not any( target.contains_outputs(context) for target, context in target_contexts.items() ): @@ -250,11 +254,24 @@ def reconcile_completed_plate( def update(data): data = self._ensure_subdirectories_structure(data) + subdirectories = data[METADATA_CONFIG.SUBDIRECTORIES_KEY] + updates_by_directory: dict[str, list[VirtualWorkspaceSourceProjectionEntries]] = {} + for target, entries in produced_entries_by_target.items(): + updates_by_directory.setdefault(target.sub_dir, []).append(entries) + admitted = {} + for name, updates in updates_by_directory.items(): + subdirectory = subdirectories.setdefault(name, {}) + admitted[name] = VirtualWorkspaceSourceProjectionEntries.combine( + updates + ).merge_into_subdirectory(subdirectory) document = OpenHCSMetadataSubdirectories(data) - admitted = { - name: VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) - for name, subdirectory in document.items() - } + for name, subdirectory in document.items(): + if name not in admitted: + admitted[name] = VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + for name in updates_by_directory: + self._update_projection_geometry( + subdirectories[name], admitted[name].entries.values() + ) for owner, context in target_contexts.items(): for target in owner.reconciliation_targets( context, document=document, admitted_entries=admitted @@ -477,17 +494,25 @@ def projection_paths(self) -> tuple[tuple[SourceProjection, str], ...]: """Expose serialization order directly from the admitted path owner.""" return tuple((projection, path) for path, projection in self.entries.items()) + @classmethod + def combine( + cls, observations: Iterable[VirtualWorkspaceSourceProjectionEntries] + ) -> VirtualWorkspaceSourceProjectionEntries: + """Combine exact producer paths in execution order, retaining typed facts.""" + entries = {} + for observation in observations: + entries.update(observation.entries) + if not entries: + return cls(MappingProxyType({})) + return cls.from_projection_paths( + tuple((projection, path) for path, projection in entries.items()) + ) + @classmethod def from_projection_paths( cls, projection_paths: Sequence[tuple[SourceProjection, str]], ) -> "VirtualWorkspaceSourceProjectionEntries": - """Admit full physical metadata unless only publication views are needed. - - Publication retains the exact serialized image metadata; it never feeds - that view into a physical image reader. Canonical durable readers restore - and validate all nested provenance by default. - """ """Admit a producer's typed updates in persisted path order.""" SourceProjectionSet( tuple(projection for projection, _path in projection_paths) @@ -523,16 +548,12 @@ def merged_with_subdirectory( def _admit_retained_records( self, records: Mapping[str, JsonValue], - *, - restore_image_metadata: bool = True, ) -> "VirtualWorkspaceSourceProjectionEntries": entries: dict[str, SourceProjection] = {} for path, record in records.items(): virtual_path, projection = ( (path, self.entries[path]) - if path in self.entries else self._projection_record( - record, restore_image_metadata=restore_image_metadata - ) + if path in self.entries else self._projection_record(record) ) if virtual_path in entries: raise RuntimeError( @@ -556,7 +577,7 @@ def merge_into_subdirectory( ) -> "VirtualWorkspaceSourceProjectionEntries": """Merge producer fields without normalizing opaque retained wire fields.""" records = self._records_by_path(subdirectory) - admitted = self._admit_retained_records(records, restore_image_metadata=False) + admitted = self._admit_retained_records(records) fields = SourceProjectionMetadataSerializer.projection_fields( self.projection_paths ) @@ -586,7 +607,7 @@ def publish_into_subdirectory( """ records = self._records_by_path(subdirectory) admitted = ( - self._admit_retained_records(records, restore_image_metadata=False) + self._admit_retained_records(records) if admitted_entries is None else admitted_entries ) saved_set = frozenset(saved_image_paths) @@ -641,8 +662,6 @@ def publish_into_subdirectory( def from_subdirectory( cls, subdirectory: OpenHCSSubdirectoryPayload, - *, - restore_image_metadata: bool = True, ) -> "VirtualWorkspaceSourceProjectionEntries": records = subdirectory.get("source_projection") if records is None: @@ -651,9 +670,7 @@ def from_subdirectory( raise RuntimeError("virtual_workspace source_projection must be a list.") entries: dict[str, SourceProjection] = {} for record in records: - virtual_path, projection = cls._projection_record( - record, restore_image_metadata=restore_image_metadata - ) + virtual_path, projection = cls._projection_record(record) if virtual_path in entries: raise RuntimeError( "virtual_workspace source_projection contains duplicate path " @@ -666,8 +683,6 @@ def from_subdirectory( def _projection_record( cls, record: JsonValue, - *, - restore_image_metadata: bool = True, ) -> tuple[str, SourceProjection]: if not isinstance(record, Mapping): raise RuntimeError( @@ -713,7 +728,6 @@ def _projection_record( image_metadata = ( None if image_metadata_value is None else ImagePayloadMetadata.from_mapping(image_metadata_value) - if restore_image_metadata else MappingProxyType(image_metadata_value) ) if projection_role is SourceProjectionRole.PRIMARY_PLANE: projection: SourceProjection = SourcePlaneProjection( diff --git a/tests/unit/test_function_outputs.py b/tests/unit/test_function_outputs.py index 0a0e005248..8ac348c55e 100644 --- a/tests/unit/test_function_outputs.py +++ b/tests/unit/test_function_outputs.py @@ -88,6 +88,8 @@ StreamingViewerSurface, ) from openhcs.core.virtual_workspace_metadata import ( + AtomicMetadataWriter, + METADATA_CONFIG, FIELDS, MetadataWriteError, VirtualWorkspaceSourceProjectionEntries, @@ -104,6 +106,25 @@ ) +def _publish_saved_step(context, plan, *, artifact_materializations=()): + """Exercise the receiving transaction with this step's actual saved facts.""" + facts = OpenHCSMetadataTarget.observe_for_step( + context, plan, artifact_materializations=artifact_materializations + ) + for metadata_path in dict.fromkeys( + METADATA_CONFIG.metadata_path(target.plate_root) for target in facts + ): + entries = { + target: value for target, value in facts.items() + if METADATA_CONFIG.metadata_path(target.plate_root) == metadata_path + } + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, + {target: context for target in entries if target.create_openhcs_metadata}, + produced_entries_by_target=entries, + ) + + @pytest.mark.parametrize("backend", [Backend.ZARR.value, "custom-array-store"]) def test_memory_output_writer_projects_runtime_image_payload_for_array_storage( backend, @@ -139,14 +160,14 @@ def test_function_step_metadata_follows_runtime_artifact_persistence( "materialize", "runtime_artifacts", ), - (OpenHCSMetadataTarget, "write_for_step", "metadata"), + (OpenHCSMetadataTarget, "observe_for_step", "metadata"), ): monkeypatch.setattr( authority, method_name, - lambda _context, _plan, event=event, **_kwargs: (events.append(event), ())[ - 1 - ], + lambda _context, _plan, event=event, **_kwargs: ( + events.append(event), {} if event == "metadata" else () + )[1], ) finalize_function_step_outputs(context, plan) @@ -1457,7 +1478,7 @@ def from_plan(cls, plan): (target,) = OpenHCSMetadataTarget.for_plan(plan) assert type(target) is SupplementalImageMetadataTarget assert OpenHCSMetadataTarget.for_execution(context, plan) == ( - target, + replace(target, create_openhcs_metadata=plan.create_openhcs_metadata), ) assert target.produced_projection_entries(context, plan).entries == {} finally: @@ -1482,7 +1503,7 @@ def test_metadata_writer_skips_owner_without_image_outputs(): ), ) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifact( @@ -1526,7 +1547,7 @@ def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifac plan.create_openhcs_metadata = True record_output_path(context, plan, output_path) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -1619,7 +1640,7 @@ def test_produced_projection_metadata_persists_typed_collapsed_semantics( str(path), Backend.MEMORY.value, ) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) subdirectory = json.loads( @@ -1982,7 +2003,7 @@ def test_produced_projection_derives_artifact_alias_for_same_address_outputs( ), ) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -2090,7 +2111,7 @@ def reject_generated_path_parse(_filename): raise AssertionError("Publication must consume the typed produced address.") monkeypatch.setattr(parser, "parse_filename", reject_generated_path_parse) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) # Step memory is unavailable at final reconciliation. Durable projections # must supply the same addresses, calibration and exact saved coverage. for record in records: @@ -2212,11 +2233,8 @@ def test_completed_plate_metadata_includes_outputs_written_after_owner_axis( owner_context.step_plans = {owner_plan.step_index: owner_plan} record_output_path(owner_context, owner_plan, str(first_image)) - OpenHCSMetadataTarget.write_for_step(owner_context, owner_plan) - initial_metadata = json.loads( - (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") - )["subdirectories"]["images"] - assert initial_metadata["wells"] == {"A01": None} + first_facts = OpenHCSMetadataTarget.observe_for_step(owner_context, owner_plan) + assert not (plate_root / "openhcs_metadata.json").exists() follower_context = context_stub(filemanager) follower_context.metadata_cache = owner_context.metadata_cache @@ -2231,7 +2249,19 @@ def test_completed_plate_metadata_includes_outputs_written_after_owner_axis( follower_plan.create_openhcs_metadata = True filemanager.save(first_pixels, str(later_image), Backend.MEMORY.value) record_output_path(follower_context, follower_plan, str(later_image)) - OpenHCSMetadataTarget.write_for_step(follower_context, follower_plan) + later_facts = OpenHCSMetadataTarget.observe_for_step(follower_context, follower_plan) + combined_facts = { + target: VirtualWorkspaceSourceProjectionEntries.combine( + (first_facts.get(target, VirtualWorkspaceSourceProjectionEntries({})), + later_facts.get(target, VirtualWorkspaceSourceProjectionEntries({}))) + ) + for target in dict.fromkeys((*first_facts, *later_facts)) + } + AtomicMetadataWriter().reconcile_completed_plate( + plate_root / "openhcs_metadata.json", + {target: owner_context for target in combined_facts}, + produced_entries_by_target=combined_facts, + ) OpenHCSMetadataTarget.finalize_completed_plate( {"A01": owner_context, "B03": follower_context} @@ -2350,11 +2380,11 @@ def test_runtime_image_metadata_target_requires_persisted_images(tmp_path, conte context, plan, artifact_materializations=saved_artifacts ) if contents == "images": - assert selected == (target,) + assert selected == (replace(target, create_openhcs_metadata=plan.create_openhcs_metadata),) else: assert selected == () plan.create_openhcs_metadata = True - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) assert not (tmp_path / "openhcs_metadata.json").exists() assert directory.exists() == (contents != "absent") @@ -2423,7 +2453,7 @@ def test_declared_image_destinations_publish_and_reconcile_after_value_cleanup( materializations = ArtifactMaterializationTargetPlan.materialize( context, plan ) - OpenHCSMetadataTarget.write_for_step( + _publish_saved_step( context, plan, artifact_materializations=materializations ) context.runtime_value_store.clear() @@ -2543,7 +2573,7 @@ def test_actual_array_exports_only_publish_declared_raster_inventory( ) assert {Path(location.path) for location in observed_locations} == expected_paths - OpenHCSMetadataTarget.write_for_step( + _publish_saved_step( context, plan, artifact_materializations=materializations ) context.runtime_value_store.clear() diff --git a/tests/unit/test_named_checkpoint_publication.py b/tests/unit/test_named_checkpoint_publication.py index 8251ebbfb9..bc08805e40 100644 --- a/tests/unit/test_named_checkpoint_publication.py +++ b/tests/unit/test_named_checkpoint_publication.py @@ -23,6 +23,7 @@ ) from openhcs.core.memory import numpy as numpy_decorator from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator +from openhcs.core.orchestrator.execution_result import RuntimeContextObservation, RuntimeExecutionObservation from openhcs.core.pipeline.function_contracts import ( artifact_outputs, required_variable_components, ) @@ -93,9 +94,13 @@ def test_named_and_ordinary_checkpoint_inventory_owns_every_address(tmp_path, ma step_materialization_config=LazyStepMaterializationConfig(enabled=True), ) bundle = orchestrator.compile_pipelines([step]) - for context in bundle.runtime_contexts.values(): - step.process(context, 0) - OpenHCSMetadataTarget.finalize_completed_plate(bundle.runtime_contexts) + observations = RuntimeExecutionObservation(contexts=tuple( + RuntimeContextObservation(context_key=key, records=(), outputs=step.process(context, 0)) + for key, context in bundle.runtime_contexts.items() + )) + OpenHCSMetadataTarget.finalize_completed_plate( + bundle.runtime_contexts, runtime_observations=(observations,) + ) root = tmp_path / "source_out" metadata = json.loads((root / "openhcs_metadata.json").read_text()) reopened = VirtualWorkspaceSourceProjection.from_openhcs_metadata(root, metadata) diff --git a/tests/unit/test_persisted_roi_only_publication.py b/tests/unit/test_persisted_roi_only_publication.py index 195afa5ad7..12db9ff1b2 100644 --- a/tests/unit/test_persisted_roi_only_publication.py +++ b/tests/unit/test_persisted_roi_only_publication.py @@ -36,7 +36,7 @@ ProducedImageMetadataCapability, RuntimeArtifactMetadataTarget, ) -from openhcs.core.virtual_workspace_metadata import METADATA_CONFIG, MetadataWriteError +from openhcs.core.virtual_workspace_metadata import AtomicMetadataWriter, METADATA_CONFIG, MetadataWriteError from openhcs.processing.materialization.core import ( MaterializationSpec, _WRITERS_BY_OPTIONS, @@ -45,6 +45,25 @@ from openhcs.processing.materialization.options import FileBundleOptions +def _publish_saved_step(context, plan, *, artifact_materializations=()): + """Exercise the receiving transaction with this step's actual saved facts.""" + facts = OpenHCSMetadataTarget.observe_for_step( + context, plan, artifact_materializations=artifact_materializations + ) + for metadata_path in dict.fromkeys( + METADATA_CONFIG.metadata_path(target.plate_root) for target in facts + ): + entries = { + target: value for target, value in facts.items() + if METADATA_CONFIG.metadata_path(target.plate_root) == metadata_path + } + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, + {target: context for target in entries if target.create_openhcs_metadata}, + produced_entries_by_target=entries, + ) + + @pytest.fixture def publication_context(tmp_path): filemanager = FileManager({Backend.DISK.value: DiskStorageBackend()}) @@ -205,7 +224,7 @@ def test_saved_roi_only_batch_publishes_and_reconciles_without_rendering( artifact_materializations=(outcome,), ) assert tuple(target.output_dir for target in targets) == (plate / destination,) - OpenHCSMetadataTarget.write_for_step( + _publish_saved_step( publication_context, plan, artifact_materializations=(outcome,) ) assert result_paths(plate, publication_context) == (output.path,) @@ -274,19 +293,19 @@ def test_measurement_only_step_does_not_reconcile_pending_image_producer( publication_context, plan, artifact_materializations=(outcome,), ) assert target.produced_projection_entries(publication_context, plan).entries == {} - OpenHCSMetadataTarget.write_for_step( + staged = OpenHCSMetadataTarget.observe_for_step( publication_context, plan, artifact_materializations=(outcome,), ) metadata_path = METADATA_CONFIG.metadata_path(plate) - snapshot = json.loads(metadata_path.read_text())[FIELDS.SUBDIRECTORIES][destination] - assert snapshot[FIELDS.IMAGE_FILES] == [] - assert snapshot[FIELDS.SOURCE_PROJECTION] == [] + assert not metadata_path.exists() assert table_output.path == str(plate / destination / "measurements.csv") assert (plate / destination / "measurements.csv").read_bytes() == b"ObjectNumber,Area\n1,6\n" - before = metadata_path.read_bytes() with pytest.raises(MetadataWriteError, match="lack typed produced addresses"): - target.write(publication_context) # Actual final reconciliation remains strict. - assert metadata_path.read_bytes() == before + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, {target: publication_context}, + produced_entries_by_target=staged, + ) + assert not metadata_path.exists() virtual_path = str(pending.relative_to(plate)) projection = SourceArtifactProjection( diff --git a/tests/unit/test_persisted_semantic_metadata.py b/tests/unit/test_persisted_semantic_metadata.py index 308c079487..8b965cecd9 100644 --- a/tests/unit/test_persisted_semantic_metadata.py +++ b/tests/unit/test_persisted_semantic_metadata.py @@ -131,35 +131,24 @@ def test_source_projection_serialization_decodes_typed_image_metadata() -> None: assert projection.image_metadata == _collapsed_metadata() -def test_publication_retains_provenance_without_reconstructing_physical_payload() -> None: +def test_publication_retains_typed_provenance_and_exact_wire_document() -> None: subdirectory = _serialized_metadata(_collapsed_metadata())["subdirectories"]["."] original = json.dumps(subdirectory) - retained = VirtualWorkspaceSourceProjectionEntries({}).publish_into_subdirectory( - subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory="." + typed = VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + retained = typed.publish_into_subdirectory( + subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory=".", + admitted_entries=typed, ) - projection = retained.entries[VIRTUAL_PATH] - assert isinstance(projection.image_metadata, Mapping) - assert projection.persisted_image_metadata() == _collapsed_metadata() + assert retained.entries[VIRTUAL_PATH].image_metadata == _collapsed_metadata() assert json.dumps(subdirectory) == original - assert VirtualWorkspaceSourceProjectionEntries.from_subdirectory( - subdirectory - ).entries[VIRTUAL_PATH].image_metadata == _collapsed_metadata() -def test_retained_corrupt_provenance_still_fails_at_physical_admission() -> None: +def test_retained_corrupt_provenance_fails_at_admission() -> None: subdirectory = _serialized_metadata(_collapsed_metadata())["subdirectories"]["."] subdirectory["source_projection"][0]["image_metadata"]["source_provenance"][ "source_image_provenance_planes" ][0]["undeclared_field"] = "corrupt" - original = json.dumps(subdirectory) - retained = VirtualWorkspaceSourceProjectionEntries({}).publish_into_subdirectory( - subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory="." - ) - - assert json.dumps(subdirectory) == original - with pytest.raises(ValueError, match="undeclared field"): - retained.entries[VIRTUAL_PATH].persisted_image_metadata() with pytest.raises(ValueError, match="undeclared field"): VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) From e5d10eda2322357be355266495360bd95e02cc59 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:15:47 -0400 Subject: [PATCH 06/11] Publish held producer metadata once at the plate receiving boundary --- openhcs/core/source_projection.py | 31 ++++--- openhcs/core/steps/function_outputs.py | 82 ++++++++++++------- openhcs/core/virtual_workspace_metadata.py | 66 +++++++++------ tests/unit/test_function_outputs.py | 70 +++++++++++----- .../unit/test_named_checkpoint_publication.py | 11 ++- .../test_persisted_roi_only_publication.py | 37 +++++++-- .../unit/test_persisted_semantic_metadata.py | 25 ++---- 7 files changed, 198 insertions(+), 124 deletions(-) diff --git a/openhcs/core/source_projection.py b/openhcs/core/source_projection.py index f089f8cca1..1349e94927 100644 --- a/openhcs/core/source_projection.py +++ b/openhcs/core/source_projection.py @@ -9,7 +9,7 @@ from pathlib import Path, PurePosixPath from types import MappingProxyType from functools import lru_cache -from typing import Any, ClassVar, Mapping, cast, get_args, get_type_hints +from typing import Any, ClassVar, Mapping, cast, get_type_hints from urllib.parse import quote from polystore.virtual_workspace import SourcePixelRef @@ -704,17 +704,6 @@ def extend_source_metadata( def extend_serialized_payload(self, payload: dict[str, Any]) -> None: """Add projection-specific fields to the nominal wire payload.""" - def persisted_image_metadata(self) -> ImagePayloadMetadata | None: - """Restore pixel metadata when a consumer needs physical image semantics. - - Publication uses the same coordinates while retaining opaque serialized - provenance. Durable image readers still admit the complete payload. - """ - return ( - ImagePayloadMetadata.from_mapping(self.image_metadata) - if isinstance(self.image_metadata, Mapping) else self.image_metadata - ) - def matches_binding(self, binding: NamedSourceBinding) -> bool: """Return whether this projection represents one exact source binding.""" @@ -731,7 +720,7 @@ def belongs_to_execution_axis(self, axis_id: str) -> bool: def declared_optional_payload_field(cls, payload_type: type) -> str: - """Derive the one optional declared field carrying ``payload_type``. + """Derive the one declared field carrying ``payload_type | None``. Class-level derivation: the wire field is owned by the projection's dataclass declaration, so it is computed once per (class, payload type) @@ -742,8 +731,7 @@ def declared_optional_payload_field(cls, payload_type: type) -> str: matches = tuple( declared.name for declared in fields(cls) - if payload_type in get_args(annotations[declared.name]) - and type(None) in get_args(annotations[declared.name]) + if annotations[declared.name] == payload_type | None ) if len(matches) != 1: raise ValueError( @@ -774,7 +762,7 @@ class SourcePlaneProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) - image_metadata: ImagePayloadMetadata | Mapping[str, object] | None = None + image_metadata: ImagePayloadMetadata | None = None def __post_init__(self) -> None: _normalize_projection(self) @@ -789,6 +777,9 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: if self.image_metadata is not None: payload[self.image_metadata_wire_field()] = to_jsonable(self.image_metadata) + def persisted_image_metadata(self) -> ImagePayloadMetadata | None: + return self.image_metadata + @property def payload_composition_alias(self) -> str | None: """Return this plane's alias for source-binding bundle composition.""" @@ -814,7 +805,7 @@ class SourceArtifactProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) - image_metadata: ImagePayloadMetadata | Mapping[str, object] | None = None + image_metadata: ImagePayloadMetadata | None = None execution_scope: RuntimeExecutionAxisScope | None = None def artifact_result_directory( @@ -948,6 +939,12 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: self.image_metadata ) + def persisted_image_metadata(self) -> ImagePayloadMetadata | None: + """Return pixel metadata when this artifact is independently loadable.""" + + return self.image_metadata + + @dataclass(frozen=True, slots=True) class SourceProjectionSet: """Validated source projection set for one OpenHCS source workspace.""" diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index e85706c2de..c06b5e2723 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -5,11 +5,11 @@ import logging import time from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace from pathlib import Path from types import MappingProxyType -from typing import ClassVar, TypeVar +from typing import TYPE_CHECKING, ClassVar, TypeVar import numpy as np from metaclass_registry import ( @@ -87,6 +87,9 @@ ) from openhcs.microscopes.microscope_interfaces import FilenameParser +if TYPE_CHECKING: + from openhcs.core.orchestrator.execution_result import RuntimeExecutionObservation + logger = logging.getLogger(__name__) StreamPayload = RuntimeArrayData @@ -117,7 +120,7 @@ def finalize_function_step_outputs( MaterializedImageOutputWriter.write_if_needed(context, plan) StreamOutputsAuthority.stream_outputs(context, plan) materializations = ArtifactMaterializationTargetPlan.materialize(context, plan) - OpenHCSMetadataTarget.write_for_step( + projection_entries = OpenHCSMetadataTarget.observe_for_step( context, plan, artifact_materializations=materializations ) else: @@ -141,15 +144,18 @@ def finalize_function_step_outputs( lambda: ArtifactMaterializationTargetPlan.materialize(context, plan), plan, ) - _profile_finalization_phase( + projection_entries = _profile_finalization_phase( "finalize_openhcs_metadata", - lambda: OpenHCSMetadataTarget.write_for_step( + lambda: OpenHCSMetadataTarget.observe_for_step( context, plan, artifact_materializations=materializations ), plan, ) - return StepExecutionObservation.combine( - item.observation(plan, context) for item in materializations + return replace( + StepExecutionObservation.combine( + item.observation(plan, context) for item in materializations + ), + source_projection_entries_by_target=projection_entries, ) @@ -645,6 +651,7 @@ class OpenHCSMetadataTarget(ABC, metaclass=AutoRegisterMeta): __key_extractor__ = staticmethod(extract_key_from_class_name) declaration_key: ClassVar[str | None] = None is_main: ClassVar[bool] = False + create_openhcs_metadata: bool = field(default=True, kw_only=True) output_dir: Path backend: str @@ -689,7 +696,8 @@ def for_execution( for declaration in cls.__registry__.values() if (owner := declaration.from_execution(context, plan)) is not None for target in replace( - owner, artifact_materializations=artifact_materializations + owner, artifact_materializations=artifact_materializations, + create_openhcs_metadata=plan.create_openhcs_metadata, ).production_targets(context, plan) ) @@ -812,7 +820,8 @@ def produced_projection_entries( raise ValueError("OpenHCS metadata requires a file manager.") target = type(self).from_plan(plan) if target is None or self not in replace( - target, artifact_materializations=self.artifact_materializations + target, artifact_materializations=self.artifact_materializations, + create_openhcs_metadata=self.create_openhcs_metadata, ).production_targets(context, plan): raise ValueError("Produced metadata plan does not own this output target.") records = self.produced_records(context, plan) @@ -1024,34 +1033,31 @@ def persisted_image_metadata( ) @classmethod - def write_for_step( + def observe_for_step( cls, context: ProcessingContext, plan: CompiledStepPlan, *, artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = (), - ) -> None: + ) -> Mapping[OpenHCSMetadataTarget, VirtualWorkspaceSourceProjectionEntries]: + """Retain exact saved-image facts before payload release, without JSON I/O.""" + observations = {} for target in cls.for_execution( context, plan, artifact_materializations=artifact_materializations ): - if not plan.create_openhcs_metadata: - projection_entries = target.produced_projection_entries(context, plan) - if projection_entries.is_empty: - continue - AtomicMetadataWriter().merge_source_projection_metadata( - METADATA_CONFIG.metadata_path(target.plate_root), - target.sub_dir, - projection_entries, - ) - else: - target.write(context, produced_plan=plan) + entries = target.produced_projection_entries(context, plan) + if target.create_openhcs_metadata or not entries.is_empty: + observations[replace(target, artifact_materializations=())] = entries + return MappingProxyType(observations) @classmethod def finalize_completed_plate( cls, compiled_contexts: Mapping[str, ProcessingContext], + *, + runtime_observations: Iterable[RuntimeExecutionObservation] = (), ) -> None: - """Write each populated metadata target after all axis outputs exist.""" + """Publish completed or partial saved outputs once at the receiving boundary.""" target_contexts: dict[OpenHCSMetadataTarget, ProcessingContext] = {} for context in compiled_contexts.values(): @@ -1061,6 +1067,17 @@ def finalize_completed_plate( for target in cls.for_plan(plan): target_contexts.setdefault(target, context) + produced_by_document: dict[Path, dict[OpenHCSMetadataTarget, list[VirtualWorkspaceSourceProjectionEntries]]] = {} + for observation in runtime_observations: + for context_observation in observation.contexts: + context = compiled_contexts[context_observation.context_key] + for target, entries in context_observation.outputs.source_projection_entries_by_target.items(): + produced_by_document.setdefault( + METADATA_CONFIG.metadata_path(target.plate_root), {} + ).setdefault(target, []).append(entries) + if target.create_openhcs_metadata: + target_contexts.setdefault(target, context) + targets_by_document: dict[ Path, dict[OpenHCSMetadataTarget, ProcessingContext] ] = {} @@ -1068,8 +1085,15 @@ def finalize_completed_plate( targets_by_document.setdefault( METADATA_CONFIG.metadata_path(owner.plate_root), {} )[owner] = context - for metadata_path, targets in targets_by_document.items(): - AtomicMetadataWriter().reconcile_completed_plate(metadata_path, targets) + for metadata_path in dict.fromkeys((*targets_by_document, *produced_by_document)): + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, + targets_by_document.get(metadata_path, {}), + produced_entries_by_target={ + target: VirtualWorkspaceSourceProjectionEntries.combine(entries) + for target, entries in produced_by_document.get(metadata_path, {}).items() + }, + ) class ProducedImageMetadataCapability: @@ -1163,13 +1187,9 @@ def production_targets( Path(output.path).parent for materialization in self.artifact_materializations for output in materialization.outputs_for_backend(self.backend) + if context.filemanager.exists(output.path, self.backend) ) - return tuple( - target - for directory in directories - for target in (self.for_directory(directory),) - if target.contains_outputs(context) - ) + return tuple(self.for_directory(directory) for directory in directories) def reconciliation_targets( self, diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index 75add98866..f95cb7e1dd 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -240,9 +240,13 @@ def reconcile_completed_plate( self, metadata_path: str | Path, target_contexts: Mapping[OpenHCSMetadataTarget, ProcessingContext], + *, + produced_entries_by_target: Mapping[ + OpenHCSMetadataTarget, VirtualWorkspaceSourceProjectionEntries + ] = MappingProxyType({}), ) -> None: """Admit and reconcile all targets from one locked plate document.""" - if not Path(metadata_path).is_file() and not any( + if not produced_entries_by_target and not Path(metadata_path).is_file() and not any( target.contains_outputs(context) for target, context in target_contexts.items() ): @@ -250,11 +254,24 @@ def reconcile_completed_plate( def update(data): data = self._ensure_subdirectories_structure(data) + subdirectories = data[METADATA_CONFIG.SUBDIRECTORIES_KEY] + updates_by_directory: dict[str, list[VirtualWorkspaceSourceProjectionEntries]] = {} + for target, entries in produced_entries_by_target.items(): + updates_by_directory.setdefault(target.sub_dir, []).append(entries) + admitted = {} + for name, updates in updates_by_directory.items(): + subdirectory = subdirectories.setdefault(name, {}) + admitted[name] = VirtualWorkspaceSourceProjectionEntries.combine( + updates + ).merge_into_subdirectory(subdirectory) document = OpenHCSMetadataSubdirectories(data) - admitted = { - name: VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) - for name, subdirectory in document.items() - } + for name, subdirectory in document.items(): + if name not in admitted: + admitted[name] = VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + for name in updates_by_directory: + self._update_projection_geometry( + subdirectories[name], admitted[name].entries.values() + ) for owner, context in target_contexts.items(): for target in owner.reconciliation_targets( context, document=document, admitted_entries=admitted @@ -477,17 +494,25 @@ def projection_paths(self) -> tuple[tuple[SourceProjection, str], ...]: """Expose serialization order directly from the admitted path owner.""" return tuple((projection, path) for path, projection in self.entries.items()) + @classmethod + def combine( + cls, observations: Iterable[VirtualWorkspaceSourceProjectionEntries] + ) -> VirtualWorkspaceSourceProjectionEntries: + """Combine exact producer paths in execution order, retaining typed facts.""" + entries = {} + for observation in observations: + entries.update(observation.entries) + if not entries: + return cls(MappingProxyType({})) + return cls.from_projection_paths( + tuple((projection, path) for path, projection in entries.items()) + ) + @classmethod def from_projection_paths( cls, projection_paths: Sequence[tuple[SourceProjection, str]], ) -> "VirtualWorkspaceSourceProjectionEntries": - """Admit full physical metadata unless only publication views are needed. - - Publication retains the exact serialized image metadata; it never feeds - that view into a physical image reader. Canonical durable readers restore - and validate all nested provenance by default. - """ """Admit a producer's typed updates in persisted path order.""" SourceProjectionSet( tuple(projection for projection, _path in projection_paths) @@ -523,16 +548,12 @@ def merged_with_subdirectory( def _admit_retained_records( self, records: Mapping[str, JsonValue], - *, - restore_image_metadata: bool = True, ) -> "VirtualWorkspaceSourceProjectionEntries": entries: dict[str, SourceProjection] = {} for path, record in records.items(): virtual_path, projection = ( (path, self.entries[path]) - if path in self.entries else self._projection_record( - record, restore_image_metadata=restore_image_metadata - ) + if path in self.entries else self._projection_record(record) ) if virtual_path in entries: raise RuntimeError( @@ -556,7 +577,7 @@ def merge_into_subdirectory( ) -> "VirtualWorkspaceSourceProjectionEntries": """Merge producer fields without normalizing opaque retained wire fields.""" records = self._records_by_path(subdirectory) - admitted = self._admit_retained_records(records, restore_image_metadata=False) + admitted = self._admit_retained_records(records) fields = SourceProjectionMetadataSerializer.projection_fields( self.projection_paths ) @@ -586,7 +607,7 @@ def publish_into_subdirectory( """ records = self._records_by_path(subdirectory) admitted = ( - self._admit_retained_records(records, restore_image_metadata=False) + self._admit_retained_records(records) if admitted_entries is None else admitted_entries ) saved_set = frozenset(saved_image_paths) @@ -641,8 +662,6 @@ def publish_into_subdirectory( def from_subdirectory( cls, subdirectory: OpenHCSSubdirectoryPayload, - *, - restore_image_metadata: bool = True, ) -> "VirtualWorkspaceSourceProjectionEntries": records = subdirectory.get("source_projection") if records is None: @@ -651,9 +670,7 @@ def from_subdirectory( raise RuntimeError("virtual_workspace source_projection must be a list.") entries: dict[str, SourceProjection] = {} for record in records: - virtual_path, projection = cls._projection_record( - record, restore_image_metadata=restore_image_metadata - ) + virtual_path, projection = cls._projection_record(record) if virtual_path in entries: raise RuntimeError( "virtual_workspace source_projection contains duplicate path " @@ -666,8 +683,6 @@ def from_subdirectory( def _projection_record( cls, record: JsonValue, - *, - restore_image_metadata: bool = True, ) -> tuple[str, SourceProjection]: if not isinstance(record, Mapping): raise RuntimeError( @@ -713,7 +728,6 @@ def _projection_record( image_metadata = ( None if image_metadata_value is None else ImagePayloadMetadata.from_mapping(image_metadata_value) - if restore_image_metadata else MappingProxyType(image_metadata_value) ) if projection_role is SourceProjectionRole.PRIMARY_PLANE: projection: SourceProjection = SourcePlaneProjection( diff --git a/tests/unit/test_function_outputs.py b/tests/unit/test_function_outputs.py index 0a0e005248..8ac348c55e 100644 --- a/tests/unit/test_function_outputs.py +++ b/tests/unit/test_function_outputs.py @@ -88,6 +88,8 @@ StreamingViewerSurface, ) from openhcs.core.virtual_workspace_metadata import ( + AtomicMetadataWriter, + METADATA_CONFIG, FIELDS, MetadataWriteError, VirtualWorkspaceSourceProjectionEntries, @@ -104,6 +106,25 @@ ) +def _publish_saved_step(context, plan, *, artifact_materializations=()): + """Exercise the receiving transaction with this step's actual saved facts.""" + facts = OpenHCSMetadataTarget.observe_for_step( + context, plan, artifact_materializations=artifact_materializations + ) + for metadata_path in dict.fromkeys( + METADATA_CONFIG.metadata_path(target.plate_root) for target in facts + ): + entries = { + target: value for target, value in facts.items() + if METADATA_CONFIG.metadata_path(target.plate_root) == metadata_path + } + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, + {target: context for target in entries if target.create_openhcs_metadata}, + produced_entries_by_target=entries, + ) + + @pytest.mark.parametrize("backend", [Backend.ZARR.value, "custom-array-store"]) def test_memory_output_writer_projects_runtime_image_payload_for_array_storage( backend, @@ -139,14 +160,14 @@ def test_function_step_metadata_follows_runtime_artifact_persistence( "materialize", "runtime_artifacts", ), - (OpenHCSMetadataTarget, "write_for_step", "metadata"), + (OpenHCSMetadataTarget, "observe_for_step", "metadata"), ): monkeypatch.setattr( authority, method_name, - lambda _context, _plan, event=event, **_kwargs: (events.append(event), ())[ - 1 - ], + lambda _context, _plan, event=event, **_kwargs: ( + events.append(event), {} if event == "metadata" else () + )[1], ) finalize_function_step_outputs(context, plan) @@ -1457,7 +1478,7 @@ def from_plan(cls, plan): (target,) = OpenHCSMetadataTarget.for_plan(plan) assert type(target) is SupplementalImageMetadataTarget assert OpenHCSMetadataTarget.for_execution(context, plan) == ( - target, + replace(target, create_openhcs_metadata=plan.create_openhcs_metadata), ) assert target.produced_projection_entries(context, plan).entries == {} finally: @@ -1482,7 +1503,7 @@ def test_metadata_writer_skips_owner_without_image_outputs(): ), ) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifact( @@ -1526,7 +1547,7 @@ def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifac plan.create_openhcs_metadata = True record_output_path(context, plan, output_path) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -1619,7 +1640,7 @@ def test_produced_projection_metadata_persists_typed_collapsed_semantics( str(path), Backend.MEMORY.value, ) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) subdirectory = json.loads( @@ -1982,7 +2003,7 @@ def test_produced_projection_derives_artifact_alias_for_same_address_outputs( ), ) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -2090,7 +2111,7 @@ def reject_generated_path_parse(_filename): raise AssertionError("Publication must consume the typed produced address.") monkeypatch.setattr(parser, "parse_filename", reject_generated_path_parse) - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) # Step memory is unavailable at final reconciliation. Durable projections # must supply the same addresses, calibration and exact saved coverage. for record in records: @@ -2212,11 +2233,8 @@ def test_completed_plate_metadata_includes_outputs_written_after_owner_axis( owner_context.step_plans = {owner_plan.step_index: owner_plan} record_output_path(owner_context, owner_plan, str(first_image)) - OpenHCSMetadataTarget.write_for_step(owner_context, owner_plan) - initial_metadata = json.loads( - (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") - )["subdirectories"]["images"] - assert initial_metadata["wells"] == {"A01": None} + first_facts = OpenHCSMetadataTarget.observe_for_step(owner_context, owner_plan) + assert not (plate_root / "openhcs_metadata.json").exists() follower_context = context_stub(filemanager) follower_context.metadata_cache = owner_context.metadata_cache @@ -2231,7 +2249,19 @@ def test_completed_plate_metadata_includes_outputs_written_after_owner_axis( follower_plan.create_openhcs_metadata = True filemanager.save(first_pixels, str(later_image), Backend.MEMORY.value) record_output_path(follower_context, follower_plan, str(later_image)) - OpenHCSMetadataTarget.write_for_step(follower_context, follower_plan) + later_facts = OpenHCSMetadataTarget.observe_for_step(follower_context, follower_plan) + combined_facts = { + target: VirtualWorkspaceSourceProjectionEntries.combine( + (first_facts.get(target, VirtualWorkspaceSourceProjectionEntries({})), + later_facts.get(target, VirtualWorkspaceSourceProjectionEntries({}))) + ) + for target in dict.fromkeys((*first_facts, *later_facts)) + } + AtomicMetadataWriter().reconcile_completed_plate( + plate_root / "openhcs_metadata.json", + {target: owner_context for target in combined_facts}, + produced_entries_by_target=combined_facts, + ) OpenHCSMetadataTarget.finalize_completed_plate( {"A01": owner_context, "B03": follower_context} @@ -2350,11 +2380,11 @@ def test_runtime_image_metadata_target_requires_persisted_images(tmp_path, conte context, plan, artifact_materializations=saved_artifacts ) if contents == "images": - assert selected == (target,) + assert selected == (replace(target, create_openhcs_metadata=plan.create_openhcs_metadata),) else: assert selected == () plan.create_openhcs_metadata = True - OpenHCSMetadataTarget.write_for_step(context, plan) + _publish_saved_step(context, plan) assert not (tmp_path / "openhcs_metadata.json").exists() assert directory.exists() == (contents != "absent") @@ -2423,7 +2453,7 @@ def test_declared_image_destinations_publish_and_reconcile_after_value_cleanup( materializations = ArtifactMaterializationTargetPlan.materialize( context, plan ) - OpenHCSMetadataTarget.write_for_step( + _publish_saved_step( context, plan, artifact_materializations=materializations ) context.runtime_value_store.clear() @@ -2543,7 +2573,7 @@ def test_actual_array_exports_only_publish_declared_raster_inventory( ) assert {Path(location.path) for location in observed_locations} == expected_paths - OpenHCSMetadataTarget.write_for_step( + _publish_saved_step( context, plan, artifact_materializations=materializations ) context.runtime_value_store.clear() diff --git a/tests/unit/test_named_checkpoint_publication.py b/tests/unit/test_named_checkpoint_publication.py index 8251ebbfb9..bc08805e40 100644 --- a/tests/unit/test_named_checkpoint_publication.py +++ b/tests/unit/test_named_checkpoint_publication.py @@ -23,6 +23,7 @@ ) from openhcs.core.memory import numpy as numpy_decorator from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator +from openhcs.core.orchestrator.execution_result import RuntimeContextObservation, RuntimeExecutionObservation from openhcs.core.pipeline.function_contracts import ( artifact_outputs, required_variable_components, ) @@ -93,9 +94,13 @@ def test_named_and_ordinary_checkpoint_inventory_owns_every_address(tmp_path, ma step_materialization_config=LazyStepMaterializationConfig(enabled=True), ) bundle = orchestrator.compile_pipelines([step]) - for context in bundle.runtime_contexts.values(): - step.process(context, 0) - OpenHCSMetadataTarget.finalize_completed_plate(bundle.runtime_contexts) + observations = RuntimeExecutionObservation(contexts=tuple( + RuntimeContextObservation(context_key=key, records=(), outputs=step.process(context, 0)) + for key, context in bundle.runtime_contexts.items() + )) + OpenHCSMetadataTarget.finalize_completed_plate( + bundle.runtime_contexts, runtime_observations=(observations,) + ) root = tmp_path / "source_out" metadata = json.loads((root / "openhcs_metadata.json").read_text()) reopened = VirtualWorkspaceSourceProjection.from_openhcs_metadata(root, metadata) diff --git a/tests/unit/test_persisted_roi_only_publication.py b/tests/unit/test_persisted_roi_only_publication.py index 195afa5ad7..12db9ff1b2 100644 --- a/tests/unit/test_persisted_roi_only_publication.py +++ b/tests/unit/test_persisted_roi_only_publication.py @@ -36,7 +36,7 @@ ProducedImageMetadataCapability, RuntimeArtifactMetadataTarget, ) -from openhcs.core.virtual_workspace_metadata import METADATA_CONFIG, MetadataWriteError +from openhcs.core.virtual_workspace_metadata import AtomicMetadataWriter, METADATA_CONFIG, MetadataWriteError from openhcs.processing.materialization.core import ( MaterializationSpec, _WRITERS_BY_OPTIONS, @@ -45,6 +45,25 @@ from openhcs.processing.materialization.options import FileBundleOptions +def _publish_saved_step(context, plan, *, artifact_materializations=()): + """Exercise the receiving transaction with this step's actual saved facts.""" + facts = OpenHCSMetadataTarget.observe_for_step( + context, plan, artifact_materializations=artifact_materializations + ) + for metadata_path in dict.fromkeys( + METADATA_CONFIG.metadata_path(target.plate_root) for target in facts + ): + entries = { + target: value for target, value in facts.items() + if METADATA_CONFIG.metadata_path(target.plate_root) == metadata_path + } + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, + {target: context for target in entries if target.create_openhcs_metadata}, + produced_entries_by_target=entries, + ) + + @pytest.fixture def publication_context(tmp_path): filemanager = FileManager({Backend.DISK.value: DiskStorageBackend()}) @@ -205,7 +224,7 @@ def test_saved_roi_only_batch_publishes_and_reconciles_without_rendering( artifact_materializations=(outcome,), ) assert tuple(target.output_dir for target in targets) == (plate / destination,) - OpenHCSMetadataTarget.write_for_step( + _publish_saved_step( publication_context, plan, artifact_materializations=(outcome,) ) assert result_paths(plate, publication_context) == (output.path,) @@ -274,19 +293,19 @@ def test_measurement_only_step_does_not_reconcile_pending_image_producer( publication_context, plan, artifact_materializations=(outcome,), ) assert target.produced_projection_entries(publication_context, plan).entries == {} - OpenHCSMetadataTarget.write_for_step( + staged = OpenHCSMetadataTarget.observe_for_step( publication_context, plan, artifact_materializations=(outcome,), ) metadata_path = METADATA_CONFIG.metadata_path(plate) - snapshot = json.loads(metadata_path.read_text())[FIELDS.SUBDIRECTORIES][destination] - assert snapshot[FIELDS.IMAGE_FILES] == [] - assert snapshot[FIELDS.SOURCE_PROJECTION] == [] + assert not metadata_path.exists() assert table_output.path == str(plate / destination / "measurements.csv") assert (plate / destination / "measurements.csv").read_bytes() == b"ObjectNumber,Area\n1,6\n" - before = metadata_path.read_bytes() with pytest.raises(MetadataWriteError, match="lack typed produced addresses"): - target.write(publication_context) # Actual final reconciliation remains strict. - assert metadata_path.read_bytes() == before + AtomicMetadataWriter().reconcile_completed_plate( + metadata_path, {target: publication_context}, + produced_entries_by_target=staged, + ) + assert not metadata_path.exists() virtual_path = str(pending.relative_to(plate)) projection = SourceArtifactProjection( diff --git a/tests/unit/test_persisted_semantic_metadata.py b/tests/unit/test_persisted_semantic_metadata.py index 308c079487..8b965cecd9 100644 --- a/tests/unit/test_persisted_semantic_metadata.py +++ b/tests/unit/test_persisted_semantic_metadata.py @@ -131,35 +131,24 @@ def test_source_projection_serialization_decodes_typed_image_metadata() -> None: assert projection.image_metadata == _collapsed_metadata() -def test_publication_retains_provenance_without_reconstructing_physical_payload() -> None: +def test_publication_retains_typed_provenance_and_exact_wire_document() -> None: subdirectory = _serialized_metadata(_collapsed_metadata())["subdirectories"]["."] original = json.dumps(subdirectory) - retained = VirtualWorkspaceSourceProjectionEntries({}).publish_into_subdirectory( - subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory="." + typed = VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) + retained = typed.publish_into_subdirectory( + subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory=".", + admitted_entries=typed, ) - projection = retained.entries[VIRTUAL_PATH] - assert isinstance(projection.image_metadata, Mapping) - assert projection.persisted_image_metadata() == _collapsed_metadata() + assert retained.entries[VIRTUAL_PATH].image_metadata == _collapsed_metadata() assert json.dumps(subdirectory) == original - assert VirtualWorkspaceSourceProjectionEntries.from_subdirectory( - subdirectory - ).entries[VIRTUAL_PATH].image_metadata == _collapsed_metadata() -def test_retained_corrupt_provenance_still_fails_at_physical_admission() -> None: +def test_retained_corrupt_provenance_fails_at_admission() -> None: subdirectory = _serialized_metadata(_collapsed_metadata())["subdirectories"]["."] subdirectory["source_projection"][0]["image_metadata"]["source_provenance"][ "source_image_provenance_planes" ][0]["undeclared_field"] = "corrupt" - original = json.dumps(subdirectory) - retained = VirtualWorkspaceSourceProjectionEntries({}).publish_into_subdirectory( - subdirectory, saved_image_paths=(VIRTUAL_PATH,), reconcile_directory="." - ) - - assert json.dumps(subdirectory) == original - with pytest.raises(ValueError, match="undeclared field"): - retained.entries[VIRTUAL_PATH].persisted_image_metadata() with pytest.raises(ValueError, match="undeclared field"): VirtualWorkspaceSourceProjectionEntries.from_subdirectory(subdirectory) From f15fe5c04375d5e313263110051d27e50cfcb1f5 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:17:05 -0400 Subject: [PATCH 07/11] Reconcile each compatible output target once in its metadata transaction --- openhcs/core/virtual_workspace_metadata.py | 23 ++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index f95cb7e1dd..d1e977034a 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -272,20 +272,23 @@ def update(data): self._update_projection_geometry( subdirectories[name], admitted[name].entries.values() ) + reconciliation_contexts = {} for owner, context in target_contexts.items(): for target in owner.reconciliation_targets( context, document=document, admitted_entries=admitted ): - if target.contains_outputs(context): - admitted[target.sub_dir] = target.write( - context, - metadata_writer=self, - metadata_document=data, - admitted_entries=admitted.get( - target.sub_dir, - VirtualWorkspaceSourceProjectionEntries(MappingProxyType({})), - ), - ) + reconciliation_contexts.setdefault(target, context) + for target, context in reconciliation_contexts.items(): + if target.contains_outputs(context): + admitted[target.sub_dir] = target.write( + context, + metadata_writer=self, + metadata_document=data, + admitted_entries=admitted.get( + target.sub_dir, + VirtualWorkspaceSourceProjectionEntries(MappingProxyType({})), + ), + ) return data self._execute_update(metadata_path, update) From fe92d2522210b873a86e656e0f3447f447f428b4 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:17:05 -0400 Subject: [PATCH 08/11] Reconcile each compatible output target once in its metadata transaction --- openhcs/core/virtual_workspace_metadata.py | 23 ++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index f95cb7e1dd..d1e977034a 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -272,20 +272,23 @@ def update(data): self._update_projection_geometry( subdirectories[name], admitted[name].entries.values() ) + reconciliation_contexts = {} for owner, context in target_contexts.items(): for target in owner.reconciliation_targets( context, document=document, admitted_entries=admitted ): - if target.contains_outputs(context): - admitted[target.sub_dir] = target.write( - context, - metadata_writer=self, - metadata_document=data, - admitted_entries=admitted.get( - target.sub_dir, - VirtualWorkspaceSourceProjectionEntries(MappingProxyType({})), - ), - ) + reconciliation_contexts.setdefault(target, context) + for target, context in reconciliation_contexts.items(): + if target.contains_outputs(context): + admitted[target.sub_dir] = target.write( + context, + metadata_writer=self, + metadata_document=data, + admitted_entries=admitted.get( + target.sub_dir, + VirtualWorkspaceSourceProjectionEntries(MappingProxyType({})), + ), + ) return data self._execute_update(metadata_path, update) From 0657716c7c97eb9faf4532dc03c7ad7b8bef4f81 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:18:27 -0400 Subject: [PATCH 09/11] Remove obsolete per-step source-projection JSON transaction API --- openhcs/core/virtual_workspace_metadata.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index d1e977034a..e3bfaed0ea 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -134,28 +134,6 @@ def update(data: dict[str, Any] | None) -> dict[str, Any]: {METADATA_CONFIG.SUBDIRECTORIES_KEY: {}}, ) - def merge_source_projection_metadata( - self, - metadata_path: str | Path, - subdirectory_name: str, - projection_entries: VirtualWorkspaceSourceProjectionEntries, - ) -> None: - """Merge exact produced paths under one lock, preserving other wells.""" - - def update(data): - data = self._ensure_subdirectories_structure(data) - subdirectory = data[METADATA_CONFIG.SUBDIRECTORIES_KEY].setdefault( - subdirectory_name, {} - ) - entries = projection_entries.merge_into_subdirectory(subdirectory) - self._update_projection_geometry( - subdirectory, - entries.entries.values(), - ) - return data - - self._execute_update(metadata_path, update) - def publish_source_projection_metadata( self, metadata_path: str | Path, From 6362e651e66285180c163bac9c592a81057161a1 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:22:49 -0400 Subject: [PATCH 10/11] Migrate retained-projection controls to the receiving transaction owner --- tests/unit/test_persisted_image_metadata.py | 27 ++++++++++++++----- .../test_persisted_roi_only_publication.py | 5 ++-- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/tests/unit/test_persisted_image_metadata.py b/tests/unit/test_persisted_image_metadata.py index 6d485bd65c..249cf5f74f 100644 --- a/tests/unit/test_persisted_image_metadata.py +++ b/tests/unit/test_persisted_image_metadata.py @@ -3,6 +3,8 @@ import json from concurrent.futures import ThreadPoolExecutor from dataclasses import fields +from pathlib import Path +from openhcs.core.steps.function_outputs import RuntimeArtifactMetadataTarget import numpy as np import pytest @@ -158,6 +160,17 @@ def test_saved_two_channel_planes_keep_runtime_axis_not_contributor_axis( ) +def receive_projection_entries(writer, metadata_path, subdirectory, entries): + target = RuntimeArtifactMetadataTarget( + output_dir=Path(metadata_path).parent / subdirectory, + plate_root=str(Path(metadata_path).parent), sub_dir=subdirectory, + backend="disk", results_dir=None, create_openhcs_metadata=False, + ) + writer.reconcile_completed_plate( + metadata_path, {}, produced_entries_by_target={target: entries} + ) + + def test_atomic_perwell_projection_merge_preserves_all_records(tmp_path): path = tmp_path / "openhcs_metadata.json" writer = AtomicMetadataWriter() @@ -170,7 +183,7 @@ def merge(well): SourcePixelRef("disk", virtual_path), image_metadata=metadata_fixture(), ) - writer.merge_source_projection_metadata( + receive_projection_entries(writer, path, ".", VirtualWorkspaceSourceProjectionEntries.from_projection_paths( @@ -216,7 +229,7 @@ def publish_projection_inventory(writer, path, projection_metadata, saved_paths) @pytest.mark.parametrize( - "merge_method", ("merge_subdirectory_metadata", "merge_source_projection_metadata") + "merge_method", ("merge_subdirectory_metadata", "reconcile_completed_plate") ) def test_atomic_projection_merge_refreshes_geometry_from_current_document( tmp_path, merge_method @@ -234,7 +247,7 @@ def test_atomic_projection_merge_refreshes_geometry_from_current_document( writer.merge_subdirectory_metadata(path, {"images": second_fields}) expected_pixel_size = 2.0 else: - writer.merge_source_projection_metadata( + receive_projection_entries(writer, path, "images", VirtualWorkspaceSourceProjectionEntries.from_projection_paths( ((second, "images/second.tif"),) @@ -257,7 +270,7 @@ def test_final_publication_prunes_geometry_and_preserves_other_directories(tmp_p (deleted, "images/deleted.tif"), (elsewhere, "other/retained.tif"), ) - writer.merge_source_projection_metadata( + receive_projection_entries(writer, path, "images", VirtualWorkspaceSourceProjectionEntries.from_projection_paths(projection_paths) ) @@ -360,7 +373,7 @@ def payload(cls, projection, virtual_path): writer, path, updates, ("images/retained.tif", "images/replaced.tif") ) else: - writer.merge_source_projection_metadata(path, "images", updates) + receive_projection_entries(writer, path, "images", updates) assert admitted_paths == ["images/retained.tif"] assert serialized_paths == ["images/replaced.tif"] subdir = json.loads(path.read_text())[FIELDS.SUBDIRECTORIES]["images"] @@ -388,7 +401,7 @@ def test_invalid_unreplaced_projection_aborts_typed_transaction(tmp_path, publis if publish: publish_projection_inventory(writer, path, updates, ("images/new.tif",)) else: - writer.merge_source_projection_metadata(path, "images", updates) + receive_projection_entries(writer, path, "images", updates) assert path.read_bytes() == before @@ -418,7 +431,7 @@ def test_typed_transaction_retains_wire_fields_and_derives_workspace_views( writer, path, updates, ("images/original.tif", "images/new.tif") ) else: - writer.merge_source_projection_metadata(path, "images", updates) + receive_projection_entries(writer, path, "images", updates) subdir = json.loads(path.read_text())[FIELDS.SUBDIRECTORIES]["images"] assert subdir[FIELDS.SOURCE_PROJECTION][0]["external_annotation"] == {"version": 7} if publish: diff --git a/tests/unit/test_persisted_roi_only_publication.py b/tests/unit/test_persisted_roi_only_publication.py index 12db9ff1b2..7cbdf7f17b 100644 --- a/tests/unit/test_persisted_roi_only_publication.py +++ b/tests/unit/test_persisted_roi_only_publication.py @@ -313,9 +313,10 @@ def test_measurement_only_step_does_not_reconcile_pending_image_producer( ref=SourcePixelRef(Backend.DISK.value, virtual_path), source_alias="declared_image", artifact_kind=ImageArtifactType, ) - AtomicMetadataWriter().merge_source_projection_metadata( + from openhcs.core.source_projection import SourceProjectionMetadataSerializer + AtomicMetadataWriter().replace_subdirectory_metadata( metadata_path, destination, - VirtualWorkspaceSourceProjectionEntries.from_projection_paths(((projection, virtual_path),)), + SourceProjectionMetadataSerializer.projection_fields(((projection, virtual_path),)), ) publication_context.step_plans = {0: plan} OpenHCSMetadataTarget.finalize_completed_plate({"A01": publication_context}) From 53d708b166ebd72558624be9fcd248e2efc725d7 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 5 Oct 2026 23:26:40 -0400 Subject: [PATCH 11/11] Preserve completed metadata facts through runtime cleanup and plate receiving Retain completed output facts in the existing context observation under OMIT, errors and cooperative cancellation; finalize durable metadata once at the parent receiving boundary. Derive same-plate runtime source views from those nominal facts before durable publication. Carry forward the exact shared plate-input selection from PR964, preserving source-only alias exclusion and parent required-input admission. Supports the structural publication fix for issue962; disk metadata visibility moves to receiving/error/cancel boundaries. --- openhcs/core/context/processing_context.py | 22 ++ .../orchestrator/compiled_plate_execution.py | 136 +++---- openhcs/core/orchestrator/execution_result.py | 80 +++- openhcs/core/orchestrator/worker_execution.py | 344 ++++++++++-------- openhcs/core/runtime_stores.py | 29 ++ openhcs/core/source_workspace_projection.py | 59 ++- tests/unit/test_compiled_execution.py | 33 +- ..._completed_output_publication_lifecycle.py | 145 ++++++++ ...test_function_runtime_source_projection.py | 4 + .../test_function_step_execution_scope.py | 160 +++++++- tests/unit/test_orchestrator_lane_planning.py | 20 +- .../test_runtime_adapter_source_artifacts.py | 3 + tests/unit/test_runtime_value_store.py | 106 ++++++ 13 files changed, 869 insertions(+), 272 deletions(-) create mode 100644 tests/unit/test_completed_output_publication_lifecycle.py diff --git a/openhcs/core/context/processing_context.py b/openhcs/core/context/processing_context.py index 5c41f5c52d..910eb8a75a 100644 --- a/openhcs/core/context/processing_context.py +++ b/openhcs/core/context/processing_context.py @@ -133,6 +133,9 @@ def __init__( self.runtime_pattern_discovery_cache = RuntimePatternDiscoveryCache() self.runtime_source_binding_context_cache = RuntimeSourceBindingContextCache() self._runtime_step_values: dict[type[object], object] | None = None + from openhcs.core.steps.abstract import StepExecutionObservation + + self.completed_step_outputs = StepExecutionObservation.empty() self.runtime_source_workspace_projection_cache = ( VirtualWorkspaceSourceProjectionCache() ) @@ -194,6 +197,25 @@ def bind_execution_runtime( """Bind worker-owned execution identity after compilation freeze.""" self.execution_runtime = runtime + self.reset_completed_step_outputs() + + def reset_completed_step_outputs(self) -> None: + """Start an execution's saved-output facts without retaining old payloads.""" + from openhcs.core.steps.abstract import StepExecutionObservation + + self.completed_step_outputs = StepExecutionObservation.empty() + + def record_completed_step_outputs( + self, observation: "StepExecutionObservation" + ) -> None: + """Own completed persisted facts across step cleanup and worker transfer.""" + from openhcs.core.steps.abstract import StepExecutionObservation + + if observation is self.completed_step_outputs: + return + self.completed_step_outputs = StepExecutionObservation.combine( + (self.completed_step_outputs, observation) + ) def release_execution_image_cache(self) -> None: """Release image reuse storage without discarding runtime observations.""" diff --git a/openhcs/core/orchestrator/compiled_plate_execution.py b/openhcs/core/orchestrator/compiled_plate_execution.py index 7c4ac64db2..e530455c7f 100644 --- a/openhcs/core/orchestrator/compiled_plate_execution.py +++ b/openhcs/core/orchestrator/compiled_plate_execution.py @@ -210,6 +210,8 @@ def execute_compiled_plate_request( raise set_progress_queue(validated.progress_queue) + for context in validated.compiled_contexts.values(): + context.reset_completed_step_outputs() try: orchestrator._state = OrchestratorState.EXECUTING logger.info( @@ -229,53 +231,63 @@ def execute_compiled_plate_request( execution_bundle = request.execution_bundle worker_assignments = request.worker_assignments_for() - executor_resources.install_execution_bundle(execution_bundle) - orchestrator._executor = executor_resources.executor execution_results: Dict[str, ExecutionResult] = {} + plate_runtime_observation = RuntimeExecutionObservation() try: - with executor_resources.execution_context(): - worker_assignment_plan = executor_resources.plan_worker_lanes( - actual_max_workers=validated.actual_max_workers, - execution_bundle=execution_bundle, - worker_assignments=worker_assignments, + executor_resources.install_execution_bundle(execution_bundle) + orchestrator._executor = executor_resources.executor + try: + with executor_resources.execution_context(): + worker_assignment_plan = executor_resources.plan_worker_lanes( + actual_max_workers=validated.actual_max_workers, + execution_bundle=execution_bundle, + worker_assignments=worker_assignments, + ) + worker_lane_execution_plan = validated.worker_lane_execution_plan( + request=request, + worker_assignment_plan=worker_assignment_plan, + ) + execution_results = executor_resources.run_worker_lanes( + pipeline_definition=validated.pipeline_definition, + worker_lane_execution_plan=worker_lane_execution_plan, + parent_contexts=validated.compiled_contexts, + ) + if any(result.is_cancelled() for result in execution_results.values()): + raise ExecutionCancelledError("Execution cancelled during worker execution") + cancellation.raise_if_requested("after worker execution") + executor_resources.shutdown_executor() + except BrokenProcessPool as exc: + logger.warning( + "ORCHESTRATOR: Executor context exit failed due to broken process " + f"pool (workers were killed externally): {exc}" ) - worker_lane_execution_plan = validated.worker_lane_execution_plan( - request=request, - worker_assignment_plan=worker_assignment_plan, + if not execution_results: + raise + finally: + executor_resources.clear_execution_bundle() + executor_resources.release_parent_runtime_resources(execution_bundle) + + if all(result.is_success() for result in execution_results.values()): + plate_runtime_observation = execute_plate_scoped_steps( + validated.compiled_contexts, + progress_queue=validated.progress_queue, + progress_context=validated, ) - execution_results = executor_resources.run_worker_lanes( - pipeline_definition=validated.pipeline_definition, - worker_lane_execution_plan=worker_lane_execution_plan, - parent_contexts=validated.compiled_contexts, + consolidate_analysis_outputs( + validated.compiled_contexts, + execution_results, + plate_runtime_observation=plate_runtime_observation, ) - cancellation.raise_if_requested("after worker execution") - executor_resources.shutdown_executor() - except BrokenProcessPool as exc: - logger.warning( - "ORCHESTRATOR: Executor context exit failed due to broken process " - f"pool (workers were killed externally): {exc}" - ) - if not execution_results: - raise finally: - executor_resources.clear_execution_bundle() - executor_resources.release_parent_runtime_resources(execution_bundle) - - plate_runtime_observation = RuntimeExecutionObservation() - if all(result.is_success() for result in execution_results.values()): - plate_runtime_observation = execute_plate_scoped_steps( - validated.compiled_contexts, - progress_queue=validated.progress_queue, - progress_context=validated, - ) - consolidate_analysis_outputs( - validated.compiled_contexts, - execution_results, - plate_runtime_observation=plate_runtime_observation, - ) OpenHCSMetadataTarget.finalize_completed_plate( validated.compiled_contexts, + runtime_observations=( + RuntimeExecutionObservation.from_completed_outputs( + validated.compiled_contexts + ), + ), ) + if all(result.is_success() for result in execution_results.values()): viewer_states_by_port = settle_viewer_state( visualizers, progress_queue=validated.progress_queue, @@ -545,7 +557,7 @@ def execute_plate_scoped_steps( owner_context, owner_plan.require_function_execution_ready(), ) - OpenHCSMetadataTarget.write_for_step( + projection_entries = OpenHCSMetadataTarget.observe_for_step( owner_context, owner_plan.require_function_execution_ready(), artifact_materializations=materializations, @@ -555,12 +567,18 @@ def execute_plate_scoped_steps( for key, context in compiled_contexts.items() if context is owner_context ) - observations_by_context[owner_context_key].append( + observation = StepExecutionObservation.combine(( StepExecutionObservation.combine( item.observation(owner_plan, owner_context) for item in materializations - ) - ) + ), + StepExecutionObservation( + materialized_locations_by_address=MappingProxyType({}), + source_projection_entries_by_target=projection_entries, + ), + )) + owner_context.record_completed_step_outputs(observation) + observations_by_context[owner_context_key].append(observation) _emit_execution_progress( progress_queue=progress_queue, progress_context=progress_context, @@ -813,30 +831,18 @@ def _plate_artifact_batch( if input_ref not in selected_input_edges: continue input_edge = selected_input_edges[input_ref] - input_plan = input_edge.storage_plan - projection = input_edge.projection - if input_plan is None or projection is None: - raise RuntimeError( - "Selected plate artifact input lost its storage plan." - ) - for group_key in projection.producer_selection_scope.keys: - query = RuntimeArtifactQuery.from_input_plan( - input_plan, - axis_id=axis_id, - backend=Backend.MEMORY.value, - group_key=group_key, - ) - matches = tuple( - record - for record in records_by_axis.get(axis_id, ()) - if query.matches(record) + matches = RuntimeArtifactQuery.records_for_input_edge( + input_edge, + records_by_axis.get(axis_id, ()), + axis_id=axis_id, + backend=Backend.MEMORY.value, + ) + for record in matches: + selected[axis_id].setdefault( + (record.key, record.location), + record, ) - for record in matches: - selected[axis_id].setdefault( - (record.key, record.location), - record, - ) - selected_for_spec += len(matches) + selected_for_spec += len(matches) if input_spec.required and selected_for_spec == 0: raise ValueError( f"Plate-scoped callable {contract.function_name!r} is missing required " diff --git a/openhcs/core/orchestrator/execution_result.py b/openhcs/core/orchestrator/execution_result.py index a3a9273c79..a9cf794731 100644 --- a/openhcs/core/orchestrator/execution_result.py +++ b/openhcs/core/orchestrator/execution_result.py @@ -11,8 +11,9 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Mapping, Optional +from openhcs.constants.constants import Backend from openhcs.core.context.processing_context import ProcessingContext -from openhcs.core.runtime_stores import StoredRuntimeValue +from openhcs.core.runtime_stores import RuntimeArtifactQuery, StoredRuntimeValue from openhcs.core.steps.abstract import StepExecutionObservation if TYPE_CHECKING: @@ -86,12 +87,28 @@ class RuntimeExecutionObservation: contexts: tuple[RuntimeContextObservation, ...] = field(default_factory=tuple) + @classmethod + def from_completed_outputs( + cls, contexts: Mapping[str, ProcessingContext] + ) -> "RuntimeExecutionObservation": + """Project saved facts independently of retained runtime pixel records.""" + return cls(contexts=tuple( + RuntimeContextObservation( + context_key=context_key, + records=(), + outputs=context.completed_step_outputs, + ) + for context_key, context in contexts.items() + if not context.completed_step_outputs.is_empty + )) + def merge_into(self, execution_contexts: Mapping[str, ProcessingContext]) -> None: """Merge returned runtime records into parent-owned compiled contexts.""" for context_observation in self.contexts: context = execution_contexts[context_observation.context_key] store = context.runtime_value_store store.merge_observed_values(context_observation.records) + context.record_completed_step_outputs(context_observation.outputs) class RuntimeObservationMode(Enum): @@ -140,15 +157,33 @@ def retain_records( return () if self is RuntimeObservationMode.MERGE_INTO_PARENT: return records - required_types = { - spec.artifact_type - for plan in context.step_plans.values() - if plan.execution_scope.requires_parent_runtime_observation - for invocation in plan.compiled_function_pattern.default_group.invocations - for spec in invocation.contract.artifact_inputs - } + selected_addresses = set() + for plan in context.step_plans.values(): + if not plan.execution_scope.requires_parent_runtime_observation: + continue + for invocation in plan.compiled_function_pattern.default_group.invocations: + input_edges = { + edge.spec.ref(): edge + for edge in invocation.select_inputs(plan.artifact_inputs).values() + if edge.storage_plan is not None + } + for spec in invocation.contract.artifact_inputs: + edge = input_edges.get(spec.ref()) + if edge is None: + continue + selected_addresses.update( + (record.key, record.location) + for record in RuntimeArtifactQuery.records_for_input_edge( + edge, + records, + axis_id=context.require_axis_id(), + backend=Backend.MEMORY.value, + ) + ) return tuple( - record for record in records if record.key.artifact_type in required_types + record + for record in records + if (record.key, record.location) in selected_addresses ) @@ -183,6 +218,9 @@ def is_error(self) -> bool: """Check if execution failed.""" return self.status == ExecutionStatus.ERROR + def is_cancelled(self) -> bool: + return self.status == ExecutionStatus.CANCELLED + @classmethod def success( cls, @@ -202,6 +240,7 @@ def error( axis_id: str, failed_combination: Optional[str] = None, error_message: Optional[str] = None, + runtime_observation: RuntimeExecutionObservation | None = None, ) -> "ExecutionResult": """Create an error execution result.""" return cls( @@ -209,4 +248,27 @@ def error( axis_id=axis_id, failed_combination=failed_combination, error_message=error_message, + runtime_observation=( + RuntimeExecutionObservation() + if runtime_observation is None else runtime_observation + ), + ) + + @classmethod + def cancelled( + cls, + axis_id: str, + *, + error_message: str, + runtime_observation: RuntimeExecutionObservation | None = None, + ) -> "ExecutionResult": + """Return completed outputs from a cooperative cancellation boundary.""" + return cls( + status=ExecutionStatus.CANCELLED, + axis_id=axis_id, + error_message=error_message, + runtime_observation=( + RuntimeExecutionObservation() + if runtime_observation is None else runtime_observation + ), ) diff --git a/openhcs/core/orchestrator/worker_execution.py b/openhcs/core/orchestrator/worker_execution.py index aa4736ac71..e077a1cc1a 100644 --- a/openhcs/core/orchestrator/worker_execution.py +++ b/openhcs/core/orchestrator/worker_execution.py @@ -7,7 +7,7 @@ import logging import multiprocessing from abc import ABC, abstractmethod -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import Any, Dict, Iterable, List, Mapping from openhcs.core.compiled_execution import ( @@ -30,7 +30,9 @@ RuntimeExecutionObservation, RuntimeObservationMode, ) -from openhcs.core.orchestrator.cancellation import ExecutionCancellationSignal +from openhcs.core.orchestrator.cancellation import ( + ExecutionCancellationSignal, ExecutionCancelledError, +) from openhcs.core.orchestrator.worker_lanes import ( CompiledContextLanePlanner, ForkInheritedWorkerExecutionState, @@ -179,9 +181,8 @@ def run_worker_lanes( pipeline_definition, worker_lane_execution_plan, ) - if worker_lane_execution_plan.runtime_observation_mode.collects_records: - for result in lane_results.values(): - result.runtime_observation.merge_into(parent_contexts) + for result in lane_results.values(): + result.runtime_observation.merge_into(parent_contexts) return lane_results @@ -508,47 +509,52 @@ def run( result_writer.close() processes.append((worker_slot, owned_wells, process, result_reader)) + lane_errors: list[Exception] = [] for worker_slot, owned_wells, process, result_reader in processes: try: - message_kind, payload, *rest = result_reader.recv() - except EOFError as exc: + try: + message_kind, payload, *rest = result_reader.recv() + except EOFError as exc: + process.join() + raise RuntimeError( + f"Fork worker lane {worker_slot} exited without returning " + f"a result; exitcode={process.exitcode}." + ) from exc + finally: + result_reader.close() + process.join() - raise RuntimeError( - f"Fork worker lane {worker_slot} exited without returning " - f"a result; exitcode={process.exitcode}." - ) from exc - finally: - result_reader.close() - - process.join() - if process.exitcode != 0: - raise RuntimeError( - f"Fork worker lane {worker_slot} exited with " - f"exitcode={process.exitcode}." - ) - if message_kind == "error": - if not rest: + if process.exitcode != 0: raise RuntimeError( - f"Fork worker lane {worker_slot} returned an error without traceback." + f"Fork worker lane {worker_slot} exited with " + f"exitcode={process.exitcode}." + ) + if message_kind == "error": + if not rest: + raise RuntimeError( + f"Fork worker lane {worker_slot} returned an error without traceback." + ) + traceback_text = rest[0] + raise RuntimeError( + f"Fork worker lane {worker_slot} generated an exception: " + f"{payload}\n{traceback_text}" + ) + if message_kind != "result": + raise RuntimeError( + f"Fork worker lane {worker_slot} returned unknown message " + f"{message_kind!r}." ) - traceback_text = rest[0] - raise RuntimeError( - f"Fork worker lane {worker_slot} generated an exception: " - f"{payload}\n{traceback_text}" - ) - if message_kind != "result": - raise RuntimeError( - f"Fork worker lane {worker_slot} returned unknown message " - f"{message_kind!r}." - ) - lane_results = payload - execution_results.update(lane_results) - if execution_plan.runtime_observation_mode.collects_records: + lane_results = payload + execution_results.update(lane_results) for result in lane_results.values(): result.runtime_observation.merge_into( ForkInheritedWorkerExecutionState.require_current().runtime_contexts ) + except Exception as exc: + lane_errors.append(exc) + if lane_errors: + raise lane_errors[0] return execution_results @@ -687,20 +693,16 @@ def _collect_results( parent_contexts: Mapping[str, ProcessingContext], ) -> Dict[str, ExecutionResult]: execution_results: Dict[str, ExecutionResult] = {} + lane_errors: list[Exception] = [] for future in concurrent.futures.as_completed(future_to_worker_slot): worker_slot, owned_wells = future_to_worker_slot[future] try: lane_results = future.result() execution_results.update(lane_results) - if execution_plan.runtime_observation_mode.collects_records: - for result in lane_results.values(): - result.runtime_observation.merge_into(parent_contexts) + for result in lane_results.values(): + result.runtime_observation.merge_into(parent_contexts) except Exception as exc: - if self._cancellation is not None: - self._cancellation.raise_if_requested( - f"while collecting worker lane {worker_slot}" - ) self._emit_lane_error( exc, worker_slot=worker_slot, @@ -708,7 +710,11 @@ def _collect_results( pipeline_definition=pipeline_definition, execution_plan=execution_plan, ) - raise + lane_errors.append(exc) + if lane_errors: + if self._cancellation is not None: + self._cancellation.raise_if_requested("after collecting worker lanes") + raise lane_errors[0] return execution_results def _emit_lane_error( @@ -789,7 +795,16 @@ def _execute_axis_with_sequential_combinations( runtime_observations: list[RuntimeContextObservation] = [] for context_key, frozen_context in axis_contexts: if cancellation is not None: - cancellation.raise_if_requested(f"before context {context_key}") + try: + cancellation.raise_if_requested(f"before context {context_key}") + except ExecutionCancelledError as exc: + return ExecutionResult.cancelled( + axis_id=axis_id, + error_message=str(exc), + runtime_observation=RuntimeExecutionObservation( + contexts=tuple(runtime_observations), + ), + ) runtime_store = frozen_context.runtime_value_store execution_observation_cursor = runtime_store.observation_cursor() try: @@ -819,11 +834,7 @@ def _execute_axis_with_sequential_combinations( if release_axis_resources: _release_runtime_resources((frozen_context,), owner=f"axis {axis_id}") frozen_context.runtime_value_store.clear() - if ( - observation.records - or observation.outputs.runtime_export_paths - or observation.outputs.analysis_inputs - ): + if observation.records or not observation.outputs.is_empty: runtime_observations.append(observation) del observed_records @@ -836,8 +847,14 @@ def _execute_axis_with_sequential_combinations( plate_id=lane_context.plate_id, axis_id=axis_id, step_name=PIPELINE_PROGRESS_STEP_NAME, - phase=ProgressPhase.AXIS_ERROR, - status=ProgressStatus.ERROR, + phase=( + ProgressPhase.CANCELLED if result.is_cancelled() + else ProgressPhase.AXIS_ERROR + ), + status=( + ProgressStatus.CANCELLED if result.is_cancelled() + else ProgressStatus.ERROR + ), completed=0, total=total_steps, percent=0.0, @@ -845,10 +862,12 @@ def _execute_axis_with_sequential_combinations( worker_slot=lane_context.worker_slot, owned_wells=list(lane_context.owned_wells), ) - return ExecutionResult.error( - axis_id=axis_id, + return replace( + result, failed_combination=context_key, - error_message=result.error_message, + runtime_observation=RuntimeExecutionObservation( + contexts=tuple(runtime_observations), + ), ) emit( @@ -948,112 +967,125 @@ def _execute_single_axis_static( frozen_context.bind_execution_runtime(lane_context) lane_context.install_debug_sink(frozen_context) runtime_value_store = frozen_context.runtime_value_store - step_observations = [] - for step_index, step in enumerate(pipeline_definition): - if cancellation is not None: - cancellation.raise_if_requested(f"before step {step_index + 1}") - step_plan = frozen_context.step_plans[step_index] - compiled_pattern = step_plan.compiled_function_pattern - if ( - compiled_pattern is not None - and compiled_pattern.execution_scope is FunctionStepExecutionScope.PLATE - ): - continue - step_name = step_plan.step_name - if not lane_context.debug_execution_policy.should_execute_step(step_index): - if lane_context.debug_execution_policy.should_reuse_step_outputs( - step_index + try: + for step_index, step in enumerate(pipeline_definition): + if cancellation is not None: + cancellation.raise_if_requested(f"before step {step_index + 1}") + step_plan = frozen_context.step_plans[step_index] + compiled_pattern = step_plan.compiled_function_pattern + if ( + compiled_pattern is not None + and compiled_pattern.execution_scope is FunctionStepExecutionScope.PLATE ): - observation_cursor = runtime_value_store.observation_cursor() - lane_context.debug_execution_policy.prepare_reused_step_outputs( - step_index=step_index, - step_name=step_name, - step_scope_id=step_plan.step_scope_id, - context=frozen_context, - artifact_outputs=step_plan.artifact_outputs, - ) - observed_records = runtime_value_store.observed_values_after( - observation_cursor - ) - reused_outputs = preview_reused_step_outputs( - step_plan, frozen_context, observed_records, - ) - runtime_progress_context = _runtime_observation_progress_context( - observed_records, - materialized_locations_by_address=reused_outputs.materialized_locations_by_address, - ) - step_observations.append(reused_outputs) - emit( - execution_id=lane_context.execution_id, - plate_id=lane_context.plate_id, - axis_id=axis_id, - step_name=step_name, - phase=ProgressPhase.STEP_COMPLETED, - status=ProgressStatus.SUCCESS, - completed=step_index + 1, - total=total_steps, - percent=((step_index + 1) / total_steps) * 100.0, - worker_slot=lane_context.worker_slot, - owned_wells=list(lane_context.owned_wells), - message="Reused warm debug artifacts", - context=runtime_progress_context, - ) - continue + continue + step_name = step_plan.step_name + if not lane_context.debug_execution_policy.should_execute_step(step_index): + if lane_context.debug_execution_policy.should_reuse_step_outputs( + step_index + ): + observation_cursor = runtime_value_store.observation_cursor() + lane_context.debug_execution_policy.prepare_reused_step_outputs( + step_index=step_index, + step_name=step_name, + step_scope_id=step_plan.step_scope_id, + context=frozen_context, + artifact_outputs=step_plan.artifact_outputs, + ) + observed_records = runtime_value_store.observed_values_after( + observation_cursor + ) + reused_outputs = preview_reused_step_outputs( + step_plan, frozen_context, observed_records, + ) + runtime_progress_context = _runtime_observation_progress_context( + observed_records, + materialized_locations_by_address=reused_outputs.materialized_locations_by_address, + ) + frozen_context.record_completed_step_outputs(reused_outputs) + emit( + execution_id=lane_context.execution_id, + plate_id=lane_context.plate_id, + axis_id=axis_id, + step_name=step_name, + phase=ProgressPhase.STEP_COMPLETED, + status=ProgressStatus.SUCCESS, + completed=step_index + 1, + total=total_steps, + percent=((step_index + 1) / total_steps) * 100.0, + worker_slot=lane_context.worker_slot, + owned_wells=list(lane_context.owned_wells), + message="Reused warm debug artifacts", + context=runtime_progress_context, + ) + continue - emit( - execution_id=lane_context.execution_id, - plate_id=lane_context.plate_id, - axis_id=axis_id, - step_name=step_name, - phase=ProgressPhase.STEP_STARTED, - status=ProgressStatus.STARTED, - completed=step_index, - total=total_steps, - percent=(step_index / total_steps) * 100.0, - worker_slot=lane_context.worker_slot, - owned_wells=list(lane_context.owned_wells), - ) + emit( + execution_id=lane_context.execution_id, + plate_id=lane_context.plate_id, + axis_id=axis_id, + step_name=step_name, + phase=ProgressPhase.STEP_STARTED, + status=ProgressStatus.STARTED, + completed=step_index, + total=total_steps, + percent=(step_index / total_steps) * 100.0, + worker_slot=lane_context.worker_slot, + owned_wells=list(lane_context.owned_wells), + ) - observation_cursor = runtime_value_store.observation_cursor() - step_observation = step.process(frozen_context, step_index) - step_observations.append(step_observation) - observed_records = runtime_value_store.observed_values_after(observation_cursor) - runtime_progress_context = _runtime_observation_progress_context( - observed_records, - materialized_locations_by_address=step_observation.materialized_locations_by_address, - ) + observation_cursor = runtime_value_store.observation_cursor() + step_observation = step.process(frozen_context, step_index) + frozen_context.record_completed_step_outputs(step_observation) + observed_records = runtime_value_store.observed_values_after(observation_cursor) + runtime_progress_context = _runtime_observation_progress_context( + observed_records, + materialized_locations_by_address=step_observation.materialized_locations_by_address, + ) - emit( - execution_id=lane_context.execution_id, - plate_id=lane_context.plate_id, + emit( + execution_id=lane_context.execution_id, + plate_id=lane_context.plate_id, + axis_id=axis_id, + step_name=step_name, + phase=ProgressPhase.STEP_COMPLETED, + status=ProgressStatus.SUCCESS, + completed=step_index + 1, + total=total_steps, + percent=((step_index + 1) / total_steps) * 100.0, + worker_slot=lane_context.worker_slot, + owned_wells=list(lane_context.owned_wells), + context=runtime_progress_context, + ) + if lane_context.debug_execution_policy.step_stop_strategy().should_stop_after_step( + step_index=step_index, + step_name=step_name, + ): + break + + except ExecutionCancelledError as exc: + return ExecutionResult.cancelled( axis_id=axis_id, - step_name=step_name, - phase=ProgressPhase.STEP_COMPLETED, - status=ProgressStatus.SUCCESS, - completed=step_index + 1, - total=total_steps, - percent=((step_index + 1) / total_steps) * 100.0, - worker_slot=lane_context.worker_slot, - owned_wells=list(lane_context.owned_wells), - context=runtime_progress_context, + error_message=str(exc), + runtime_observation=RuntimeExecutionObservation.from_completed_outputs( + {context_key: frozen_context} + ), + ) + except Exception as exc: + logger.exception("Axis %s failed while retaining completed output facts", axis_id) + return ExecutionResult.error( + axis_id=axis_id, + failed_combination=context_key, + error_message=str(exc), + runtime_observation=RuntimeExecutionObservation.from_completed_outputs( + {context_key: frozen_context} + ), ) - if lane_context.debug_execution_policy.step_stop_strategy().should_stop_after_step( - step_index=step_index, - step_name=step_name, - ): - break return ExecutionResult.success( axis_id=axis_id, - runtime_observation=RuntimeExecutionObservation( - contexts=( - RuntimeContextObservation( - context_key=context_key, - records=(), - outputs=StepExecutionObservation.combine(step_observations), - ), - ) + runtime_observation=RuntimeExecutionObservation.from_completed_outputs( + {context_key: frozen_context} ), ) @@ -1076,7 +1108,13 @@ def execute_worker_lane( lane_results: Dict[str, ExecutionResult] = {} for axis_id, axis_contexts in lane_axis_contexts: if cancellation is not None: - cancellation.raise_if_requested(f"before axis {axis_id}") + try: + cancellation.raise_if_requested(f"before axis {axis_id}") + except ExecutionCancelledError as exc: + lane_results[axis_id] = ExecutionResult.cancelled( + axis_id=axis_id, error_message=str(exc), + ) + break lane_results[axis_id] = _execute_axis_with_sequential_combinations( pipeline_definition=pipeline_definition, axis_contexts=axis_contexts, @@ -1085,6 +1123,8 @@ def execute_worker_lane( cancellation=cancellation, release_axis_resources=release_axis_resources, ) + if lane_results[axis_id].is_cancelled(): + break return lane_results diff --git a/openhcs/core/runtime_stores.py b/openhcs/core/runtime_stores.py index bbf9b69b16..2304ce7bca 100644 --- a/openhcs/core/runtime_stores.py +++ b/openhcs/core/runtime_stores.py @@ -162,6 +162,35 @@ class RuntimeArtifactQuery: axis_id: str target: RuntimeArtifactQueryTarget + @classmethod + def records_for_input_edge( + cls, + edge: InvocationArtifactInputEdgePlan, + records: tuple["StoredRuntimeValue", ...], + *, + axis_id: str, + backend: str, + ) -> tuple["StoredRuntimeValue", ...]: + """Select observed records in the compiled producer-group order. + + Unstored sources have no runtime records. Missing records remain empty; + the consuming invocation owns required-input admission across axes. + """ + if edge.storage_plan is None: + return () + queries = ( + cls.from_input_plan( + edge.storage_plan, + axis_id=axis_id, + backend=backend, + group_key=group_key, + ) + for group_key in edge.projection.producer_selection_scope.keys + ) + return tuple( + record for query in queries for record in records if query.matches(record) + ) + @classmethod def from_input_plan( cls, diff --git a/openhcs/core/source_workspace_projection.py b/openhcs/core/source_workspace_projection.py index 78770d9772..7b392d9458 100644 --- a/openhcs/core/source_workspace_projection.py +++ b/openhcs/core/source_workspace_projection.py @@ -34,7 +34,7 @@ source_metadata_values_equal, ) from openhcs.core.source_path_identity import source_path_identity_key -from openhcs.core.source_projection import SourceProjection +from openhcs.core.source_projection import SourceProjection, SourceProjectionMetadataSerializer from openhcs.core.virtual_workspace_metadata import ( OpenHCSMetadataPayload, OpenHCSMetadataSubdirectories, @@ -775,11 +775,12 @@ def from_context( *, cache: VirtualWorkspaceSourceProjectionCache | None = None, ) -> "VirtualWorkspaceSourceProjectionAuthority": - return cls.from_plate_metadata( + return RuntimeVirtualWorkspaceSourceProjectionAuthority( plate_path=Path(context.plate_path), metadata_handler=context.microscope_handler.metadata_handler, filemanager=context.filemanager, - cache=cache, + cache=DEFAULT_SOURCE_PROJECTION_CACHE if cache is None else cache, + context=context, ) @classmethod @@ -858,6 +859,58 @@ def projection_or_empty(self) -> VirtualWorkspaceSourceProjection: return VirtualWorkspaceSourceProjection.empty(self.plate_path) +@dataclass(frozen=True, slots=True) +class RuntimeVirtualWorkspaceSourceProjectionAuthority( + VirtualWorkspaceSourceProjectionAuthority +): + """Read completed same-plate outputs from their execution observation owner.""" + + context: "ProcessingContext" = field(kw_only=True, compare=False, repr=False) + + def is_bound_to_context(self, context: "ProcessingContext") -> bool: + return self.context is context and super( + RuntimeVirtualWorkspaceSourceProjectionAuthority, self + ).is_bound_to_context(context) + + def projection_if_available(self) -> VirtualWorkspaceSourceProjection | None: + projection = super( + RuntimeVirtualWorkspaceSourceProjectionAuthority, self + ).projection_if_available() + produced_entries = tuple( + entries + for target, entries in ( + self.context.completed_step_outputs.source_projection_entries_by_target.items() + ) + if source_path_identity_key(target.plate_root) + == source_path_identity_key(self.plate_path) + and not entries.is_empty + ) + if not produced_entries: + return projection + builder = VirtualWorkspaceSourceProjectionBuilder(self.plate_path) + if projection is not None: + builder.ingest_workspace_mapping( + VirtualWorkspaceMapping(projection.source_refs_by_virtual_path) + ) + builder.ingest_source_projections( + VirtualWorkspaceSourceProjectionEntries( + projection.source_projections_by_virtual_path + ) + ) + builder.ingest_source_metadata( + VirtualWorkspaceSourceMetadataEntries(projection.source_metadata_by_path) + ) + for entries in produced_entries: + fields = SourceProjectionMetadataSerializer.workspace_fields( + entries.projection_paths + ) + builder.ingest_workspace_mapping( + VirtualWorkspaceMapping.from_subdirectory(fields) + ) + builder.ingest_admitted_subdirectory(fields, entries) + return builder.projection() + + @dataclass(slots=True) class VirtualWorkspaceSourceProjectionBuilder: """Build source-binding projection data from OpenHCS virtual-workspace metadata.""" diff --git a/tests/unit/test_compiled_execution.py b/tests/unit/test_compiled_execution.py index c95e7277d1..a77f58fd6d 100644 --- a/tests/unit/test_compiled_execution.py +++ b/tests/unit/test_compiled_execution.py @@ -194,37 +194,6 @@ def test_consolidation_does_not_require_parent_payload_records( assert RuntimeObservationMode.for_compiled_bundle(bundle) is RuntimeObservationMode.OMIT -def test_plate_input_retention_uses_compiled_consumer_types() -> None: - plate_input = SimpleNamespace(artifact_type=MeasurementsArtifactType) - plate_plan = SimpleNamespace( - execution_scope=FunctionStepExecutionScope.PLATE, - compiled_function_pattern=SimpleNamespace( - default_group=SimpleNamespace( - invocations=( - SimpleNamespace( - contract=SimpleNamespace(artifact_inputs=(plate_input,)) - ), - ) - ) - ), - ) - context = ProcessingContext(axis_id="A01", step_plans={0: plate_plan}) - image_record = SimpleNamespace(key=SimpleNamespace(artifact_type=ImageArtifactType)) - measurement_record = SimpleNamespace( - key=SimpleNamespace(artifact_type=MeasurementsArtifactType) - ) - records = (image_record, measurement_record) - - assert RuntimeObservationMode.MERGE_PLATE_INPUTS.retain_records( - records, context - ) == (measurement_record,) - assert ( - RuntimeObservationMode.MERGE_INTO_PARENT.retain_records(records, context) - == records - ) - assert RuntimeObservationMode.OMIT.retain_records(records, context) == () - - def test_runtime_observation_mode_can_only_be_strengthened() -> None: assert ( RuntimeObservationMode.OMIT.including_parent_requirement(True) @@ -316,7 +285,7 @@ def test_runtime_execution_observation_merges_into_parent_contexts(): path="/memory/measurements.pkl", backend="memory", ) - parent_context = SimpleNamespace(runtime_value_store=RuntimeValueStore()) + parent_context = ProcessingContext(axis_id="A01") RuntimeExecutionObservation( contexts=( diff --git a/tests/unit/test_completed_output_publication_lifecycle.py b/tests/unit/test_completed_output_publication_lifecycle.py new file mode 100644 index 0000000000..61a6601e83 --- /dev/null +++ b/tests/unit/test_completed_output_publication_lifecycle.py @@ -0,0 +1,145 @@ +"""Completed persisted facts survive cleanup, failure and deferred publication.""" +from pathlib import Path +import pickle +from types import MappingProxyType, SimpleNamespace +import weakref + +import numpy as np +import pytest +from polystore.virtual_workspace import SourcePixelRef + +from openhcs.core.callable_contract import FunctionStepExecutionScope +from openhcs.core.context.processing_context import ProcessingContext +from openhcs.core.debug import NoOpDebugExecutionPolicy +from openhcs.core.orchestrator.cancellation import ExecutionCancellationSignal +from openhcs.core.orchestrator import worker_execution +from openhcs.core.orchestrator.execution_result import RuntimeObservationMode +from openhcs.core.orchestrator.worker_lanes import WorkerLaneExecutionContext +from openhcs.core.runtime_image_values import ImagePayloadMetadata +from openhcs.core.source_projection import OpenHCSPlaneAddress, SourcePlaneProjection +from openhcs.core.source_workspace_projection import ( + RuntimeVirtualWorkspaceSourceProjectionAuthority, + VirtualWorkspacePathLookup, + VirtualWorkspaceSourceProjectionAuthority, +) +from openhcs.core.steps.abstract import StepExecutionObservation +from openhcs.core.steps.function_outputs import PrimaryImageMetadataTarget +from openhcs.core.virtual_workspace_metadata import VirtualWorkspaceSourceProjectionEntries +from openhcs.microscopes.source_schema import SourceSchemaFilenameParser + + +def _facts(plate_root: Path) -> StepExecutionObservation: + target = PrimaryImageMetadataTarget( + output_dir=plate_root / "images", backend="disk", plate_root=str(plate_root), + sub_dir="images", results_dir=None, + ) + projection = SourcePlaneProjection( + address=OpenHCSPlaneAddress.from_values("A01", 1, 0, 1, 1), + ref=SourcePixelRef("disk", "images/saved.tif"), source_alias="saved", + image_metadata=ImagePayloadMetadata(source_dtype="uint16"), + ) + return StepExecutionObservation( + MappingProxyType({}), source_projection_entries_by_target=MappingProxyType({ + target: VirtualWorkspaceSourceProjectionEntries.from_projection_paths( + ((projection, "images/saved.tif"),) + ) + }), + ) + + +def _context(plate_root: Path, count: int) -> ProcessingContext: + context = ProcessingContext( + axis_id="A01", filemanager=SimpleNamespace(exists=lambda *_args: False), + step_plans={index: SimpleNamespace( + compiled_function_pattern=None, execution_scope=FunctionStepExecutionScope.AXIS, + step_name=str(index), + ) for index in range(count)}, + ) + context.plate_path = plate_root + context.microscope_handler = SimpleNamespace( + parser=SourceSchemaFilenameParser(), + metadata_handler=SimpleNamespace(source_workspace_metadata_document=lambda _p: None), + ) + context.freeze() + return context + + +def _lane() -> WorkerLaneExecutionContext: + return WorkerLaneExecutionContext( + execution_id="output-facts", plate_id="plate", worker_slot="worker_0", + debug_execution_policy=NoOpDebugExecutionPolicy(), + worker_assignments={"worker_0": ["A01"]}, + ) + + +@pytest.mark.parametrize("cancel", [False, True]) +def test_completed_projection_facts_survive_error_or_cancel_and_omit(tmp_path, monkeypatch, cancel): + monkeypatch.setattr(worker_execution, "emit", lambda **_kwargs: None) + facts = _facts(tmp_path) + signal = ExecutionCancellationSignal() + pixel_refs = [] + + class Save: + def process(self, context, index): + pixels = np.ones((8, 8), dtype=np.float32) + pixel_refs.append(weakref.ref(pixels)) + context.runtime_image_stack_cache.store( + ("temporary-image",), memory_type="numpy", stack=pixels, + ) + if cancel: + signal.request() + return facts + + class Fail: + def process(self, context, index): + raise RuntimeError("later callable failed") + + context = _context(tmp_path, 2) + result = worker_execution._execute_axis_with_sequential_combinations( + [Save(), Fail()], [("A01", context)], _lane(), RuntimeObservationMode.OMIT, + cancellation=signal, release_axis_resources=False, + ) + assert result.is_cancelled() if cancel else result.is_error() + assert not context.runtime_value_store.observed_values + assert pixel_refs[0]() is None + assert len(result.runtime_observation.contexts) == 1 + observation = result.runtime_observation.contexts[0] + assert not observation.records + assert observation.outputs.source_projection_entries_by_target == facts.source_projection_entries_by_target + restored = pickle.loads(pickle.dumps(result)) + assert restored.runtime_observation.contexts[0].outputs.source_projection_entries_by_target == facts.source_projection_entries_by_target + parent = ProcessingContext(axis_id="A01") + restored.runtime_observation.merge_into({"A01": parent}) + assert parent.completed_step_outputs.source_projection_entries_by_target == facts.source_projection_entries_by_target + + +def test_same_plate_reader_uses_completed_facts_before_durable_publication(tmp_path): + context = _context(tmp_path, 1) + authority = context.runtime_source_workspace_projection_authority + assert isinstance(authority, RuntimeVirtualWorkspaceSourceProjectionAuthority) + assert authority.projection_if_available() is None + context.record_completed_step_outputs(_facts(tmp_path)) + projection = authority.projection_or_empty() + lookup = VirtualWorkspacePathLookup.from_paths("images/saved.tif", str(tmp_path / "images/saved.tif")) + assert projection.source_projection_for(lookup).image_metadata.source_dtype == "uint16" + assert projection.source_metadata_for(lookup)["source_alias"] == "saved" + # A direct durable reader retains its published-boundary contract. + direct = VirtualWorkspaceSourceProjectionAuthority.from_plate_metadata( + plate_path=tmp_path, metadata_handler=context.microscope_handler.metadata_handler, + filemanager=context.filemanager, + ) + assert direct.projection_if_available() is None + context.bind_execution_runtime(_lane()) + assert authority.projection_if_available() is None + + +def test_runtime_overlay_excludes_another_output_plate_and_other_context(tmp_path): + context = _context(tmp_path, 1) + context.record_completed_step_outputs(_facts(tmp_path / "other-plate")) + authority = context.runtime_source_workspace_projection_authority + assert authority.projection_if_available() is None + other = _context(tmp_path, 1) + other.microscope_handler = context.microscope_handler + other.filemanager = context.filemanager + assert authority.is_bound_to_context(context) + assert not authority.is_bound_to_context(other) diff --git a/tests/unit/test_function_runtime_source_projection.py b/tests/unit/test_function_runtime_source_projection.py index 907eb3a624..7c7d7a7797 100644 --- a/tests/unit/test_function_runtime_source_projection.py +++ b/tests/unit/test_function_runtime_source_projection.py @@ -1,3 +1,4 @@ +from openhcs.core.steps.abstract import StepExecutionObservation from openhcs.core.steps.function_runtime import ( PatternGroupExecutionRequest, PatternGroupExecutionScope, @@ -130,6 +131,7 @@ def _anchor_executor( executor = object.__new__(FunctionStepExecutor) executor.plan = plan executor.context = Mock( + completed_step_outputs=StepExecutionObservation.empty(), plate_path=Path("."), microscope_handler=SimpleNamespace( parser=parser, @@ -4266,6 +4268,7 @@ def load_batch(self, paths, backend): ), ) context = SimpleNamespace( + source_image_set_identity_policy=SourceImageSetIdentityPolicy(), microscope_handler=SimpleNamespace(parser=SourceSchemaFilenameParser()), filemanager=MemoryFileManager(), runtime_image_stack_cache=RuntimeImageStackCache(), @@ -5911,6 +5914,7 @@ def get(self, *_args, **_kwargs): pytest.fail("Ambiguous producer admission must precede cached pixels") context = SimpleNamespace( + source_image_set_identity_policy=SourceImageSetIdentityPolicy(), microscope_handler=SimpleNamespace(parser=SourceSchemaFilenameParser()), runtime_image_stack_cache=RejectImageCache(), ) diff --git a/tests/unit/test_function_step_execution_scope.py b/tests/unit/test_function_step_execution_scope.py index d26feb22dd..14d3e85eb8 100644 --- a/tests/unit/test_function_step_execution_scope.py +++ b/tests/unit/test_function_step_execution_scope.py @@ -44,6 +44,7 @@ execute_plate_scoped_steps, validate_plate_scoped_contexts, ) +from openhcs.core.orchestrator.execution_result import RuntimeObservationMode from openhcs.core.progress import ( ProgressEvent, ProgressExecutionContext, @@ -225,6 +226,8 @@ def test_plate_scope_drives_no_main_flow_paths() -> None: } output_dir = Path("/data/plate_processed/images") planner.paths = SimpleNamespace(build_output_path=lambda: output_dir) + planner.artifact_context = ArtifactDeclarationStepContext.empty() + planner.declared = {} planner.steps = PathPlannerStepAssemblyStage(planner) snapshot = FunctionStep(func=lambda image: image, name="export") @@ -607,6 +610,159 @@ def export(*, artifact_batch: RuntimeArtifactBatch): assert batch.records(source_spec.ref())["A01"] == () +@pytest.mark.parametrize("stored_image", (False, True)) +def test_plate_retention_uses_exact_edges_instead_of_requested_types( + stored_image: bool, +) -> None: + source_spec = ArtifactSpec.input("raw", ImageArtifactType, required=False) + measurement_spec = ArtifactSpec.input("Measurements", MeasurementsArtifactType) + output_spec = ArtifactSpec.output("Export", SpecialArtifactType) + + @execution_scope(FunctionStepExecutionScope.PLATE) + @runtime_bound_parameters(RuntimeArtifactBatch) + @artifact_inputs(source_spec, measurement_spec) + @artifact_outputs(output_spec) + def export(*, artifact_batch: RuntimeArtifactBatch): + return artifact_batch + + inputs = ( + ArtifactInputPlan( + name="Measurements", + path="/memory/measurements", + artifact_type=MeasurementsArtifactType, + ), + ) + if stored_image: + inputs += ( + ArtifactInputPlan( + name="raw", + path="/memory/raw", + artifact_type=ImageArtifactType, + ), + ) + plan = _plate_step_plan( + axis_id="A01", + step_index=1, + func=export, + artifact_inputs=inputs, + artifact_output=ArtifactOutputPlan( + name="Export", + path="/memory/export", + artifact_type=SpecialArtifactType, + ), + metadata_writer=True, + ) + context = _plate_context("A01", (plan,)) + for name in ("RGB", "raw"): + image = RuntimeValue.normalize( + ArtifactOutputPlan( + name=name, + path=f"/memory/{name}", + artifact_type=ImageArtifactType, + ), + np.ones((2, 2, 3)), + axis_id="A01", + ) + context.runtime_value_store.replace( + image, + path=f"/memory/{name}", + backend=Backend.MEMORY.value, + ) + _record_measurements(context, name="Other", path="/memory/other", count=1) + _record_measurements( + context, + name="Measurements", + path="/memory/measurements", + count=2, + ) + _record_measurements( + context, + name="Measurements", + path="/memory/measurements", + count=3, + ) + observations = context.runtime_value_store.observed_values + retained = RuntimeObservationMode.MERGE_PLATE_INPUTS.retain_records( + observations, + context, + ) + assert [record.key.name for record in retained] == ( + (["raw"] if stored_image else []) + ["Measurements", "Measurements"] + ) + assert ( + RuntimeObservationMode.MERGE_INTO_PARENT.retain_records( + observations, + context, + ) + is observations + ) + assert RuntimeObservationMode.OMIT.retain_records(observations, context) == () + + full_store = type(context.runtime_value_store)() + full_store.merge_observed_values(observations) + retained_store = type(context.runtime_value_store)() + retained_store.merge_observed_values(retained) + batches = tuple( + _plate_artifact_batch( + compiled_contexts={"A01": context}, + step_index=1, + invocation_position=0, + contract=CallableContract.from_callable(export), + records_by_axis={"A01": store.values()}, + source_binding_plan=plan.source_binding_plan, + source_image_set_identity_policy=SourceImageSetIdentityPolicy(frozenset()), + ) + for store in (full_store, retained_store) + ) + assert batches[0].records_by_axis == batches[1].records_by_axis + assert ( + batches[1].records(measurement_spec.ref())["A01"][0].data.rows[0]["count"] == 3 + ) + + +def test_plate_retention_defers_required_missing_admission_to_parent() -> None: + measurement_spec = ArtifactSpec.input("Missing", MeasurementsArtifactType) + output_spec = ArtifactSpec.output("Export", SpecialArtifactType) + + @execution_scope(FunctionStepExecutionScope.PLATE) + @runtime_bound_parameters(RuntimeArtifactBatch) + @artifact_inputs(measurement_spec) + @artifact_outputs(output_spec) + def export(*, artifact_batch: RuntimeArtifactBatch): + return artifact_batch + + plan = _plate_step_plan( + axis_id="A01", + step_index=1, + func=export, + artifact_inputs=( + ArtifactInputPlan( + name="Missing", + path="/memory/missing", + artifact_type=MeasurementsArtifactType, + ), + ), + artifact_output=ArtifactOutputPlan( + name="Export", + path="/memory/export", + artifact_type=SpecialArtifactType, + ), + metadata_writer=True, + ) + context = _plate_context("A01", (plan,)) + assert RuntimeObservationMode.MERGE_PLATE_INPUTS.retain_records((), context) == () + with pytest.raises(ValueError, match="missing required input"): + _plate_artifact_batch( + compiled_contexts={"A01": context}, + step_index=1, + invocation_position=0, + contract=CallableContract.from_callable(export), + records_by_axis={"A01": ()}, + source_binding_plan=plan.source_binding_plan, + source_image_set_identity_policy=SourceImageSetIdentityPolicy(frozenset()), + ) + + def test_plate_scope_runs_once_from_exact_contract_selected_records() -> None: measurement_spec = ArtifactSpec.input( "Measurements", @@ -786,7 +942,7 @@ def export(*, artifact_batch: RuntimeArtifactBatch): assert {record.key.name for record in observation.contexts[0].records} == { output_spec.name } - analysis_inputs = observation.contexts[0].analysis_inputs + analysis_inputs = observation.contexts[0].outputs.analysis_inputs assert analysis_inputs is not None assert analysis_inputs.destination.backend == Backend.MEMORY.value (table,) = tuple( @@ -795,7 +951,7 @@ def export(*, artifact_batch: RuntimeArtifactBatch): ) assert table.csv_content == "ImageNumber,Count\r\n1,7\r\n" assert table.well_id == "A01" - assert observation.contexts[0].runtime_export_paths == (table.path,) + assert observation.contexts[0].outputs.runtime_export_paths == (table.path,) events = [ProgressEvent.from_dict(event) for event in progress_queue.events] assert events[-1].phase is ProgressPhase.STEP_COMPLETED diff --git a/tests/unit/test_orchestrator_lane_planning.py b/tests/unit/test_orchestrator_lane_planning.py index 629fb430c5..e3ef381fc1 100644 --- a/tests/unit/test_orchestrator_lane_planning.py +++ b/tests/unit/test_orchestrator_lane_planning.py @@ -674,16 +674,18 @@ def execute_axis( ("B01", [("B01", SimpleNamespace(axis_id="B01"))]), ] - with pytest.raises(ExecutionCancelledError, match="before axis B01"): - worker_execution_module.execute_worker_lane( - pipeline_definition=[], - lane_axis_contexts=lane_axis_contexts, - lane_context=lane_context, - runtime_observation_mode=RuntimeObservationMode.OMIT, - cancellation=cancellation, - ) + results = worker_execution_module.execute_worker_lane( + pipeline_definition=[], + lane_axis_contexts=lane_axis_contexts, + lane_context=lane_context, + runtime_observation_mode=RuntimeObservationMode.OMIT, + cancellation=cancellation, + ) assert visited == ["A01"] + assert results["A01"].is_success() + assert results["B01"].is_cancelled() + assert "before axis B01" in results["B01"].error_message def test_cancellation_authority_preserves_pre_entry_request_for_exact_scope(): @@ -1134,7 +1136,7 @@ def test_compiled_execution_returns_settled_nonpersistent_viewer_state_before_cl monkeypatch.setattr( compiled_plate_execution_module.OpenHCSMetadataTarget, "finalize_completed_plate", - lambda _contexts: events.append("metadata"), + lambda _contexts, *, runtime_observations: events.append("metadata"), ) response = ViewerControlResponse( payload={ diff --git a/tests/unit/test_runtime_adapter_source_artifacts.py b/tests/unit/test_runtime_adapter_source_artifacts.py index 21c1ca8695..eb7b41d393 100644 --- a/tests/unit/test_runtime_adapter_source_artifacts.py +++ b/tests/unit/test_runtime_adapter_source_artifacts.py @@ -1,3 +1,4 @@ +from openhcs.core.steps.abstract import StepExecutionObservation from pathlib import Path from types import SimpleNamespace @@ -138,6 +139,7 @@ def binding( microscope_handler.initialize_workspace(workspace_root, filemanager) projection_cache = VirtualWorkspaceSourceProjectionCache() context = SimpleNamespace( + completed_step_outputs=StepExecutionObservation.empty(), plate_path=workspace_root, filemanager=filemanager, microscope_handler=microscope_handler, @@ -297,6 +299,7 @@ def test_workspace_materialization_preserves_declared_source_pixels(tmp_path, mo microscope.initialize_workspace(workspace_root, filemanager) cache = VirtualWorkspaceSourceProjectionCache() context = SimpleNamespace( + completed_step_outputs=StepExecutionObservation.empty(), plate_path=workspace_root, filemanager=filemanager, microscope_handler=microscope, runtime_source_workspace_projection_cache=cache, ) diff --git a/tests/unit/test_runtime_value_store.py b/tests/unit/test_runtime_value_store.py index 316d551850..1f3664b895 100644 --- a/tests/unit/test_runtime_value_store.py +++ b/tests/unit/test_runtime_value_store.py @@ -35,6 +35,7 @@ from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.component_set import ComponentSet +from openhcs.core.equivalence import RuntimeMeasurementDialect from openhcs.core.callable_contract import CallableContract from openhcs.core.runtime_equivalence import ( RuntimeMeasurementObservationAxis, @@ -588,6 +589,111 @@ def test_runtime_artifact_query_from_dynamic_input_plan_matches_discovered_group ) +@pytest.mark.parametrize("dynamic", (False, True)) +def test_observed_input_selection_preserves_groups_axis_backend_and_locations( + dynamic: bool, +) -> None: + storage_plan = ArtifactInputPlan( + name="RGB", + path="/memory/RGB.pkl", + artifact_type=ImageArtifactType, + group_keys=(None,) if dynamic else ("1", "2", "3"), + group_component=AllComponents.SITE, + paths_by_group=( + {None: "/memory/RGB.pkl"} + if dynamic + else {key: f"/memory/RGB_s{key}.pkl" for key in ("1", "2", "3")} + ), + ) + selection = ( + ComponentGroupScope.dynamic(AllComponents.SITE) + if dynamic + else ComponentGroupScope.from_raw(("2", "1"), component=AllComponents.SITE) + ) + edge = _runtime_input_edge( + storage_plan, + invocation_scope=ComponentGroupScope.ungrouped(), + producer_selection_scope=selection, + component_scopes=(selection,), + consumer_variable_components=(AllComponents.SITE,), + ) + records = tuple( + StoredRuntimeValue( + key=ArtifactKey( + name="RGB", + artifact_type=ImageArtifactType, + scope=RuntimeExecutionAxisScope.from_raw( + "A01", + component=AllComponents.SITE, + value=key, + ), + ), + data=np.full((2, 2, 3), int(key), dtype=np.float32), + location=RuntimeArtifactLocation( + storage_plan.path_for_runtime_query(key), + "memory", + ), + ) + for key in ("1", "2", "3") + ) + first = records[0] + unrelated = ( + replace(first, location=RuntimeArtifactLocation(first.location.path, "disk")), + replace(first, location=RuntimeArtifactLocation("/memory/wrong.pkl", "memory")), + replace( + first, + key=replace( + first.key, + scope=RuntimeExecutionAxisScope.from_raw( + "B01", + component=AllComponents.SITE, + value="1", + ), + ), + ), + replace(first, key=replace(first.key, name="Other")), + ) + selected = RuntimeArtifactQuery.records_for_input_edge( + edge, + (*records, *unrelated), + axis_id="A01", + backend="memory", + ) + expected = records if dynamic else (records[1], records[0]) + assert tuple(id(record) for record in selected) == tuple( + id(record) for record in expected + ) + + +def test_unstored_source_input_does_not_select_same_named_runtime_record() -> None: + spec = ArtifactSpec.input("raw", ImageArtifactType, required=False) + key = FunctionInvocationKey("source_test", DEFAULT_GROUP_KEY, 0) + edge = InvocationArtifactInputEdgePlan( + key=InvocationArtifactInputProjectionKey(key, 0), + spec=spec, + storage_plan=None, + projection=None, + ) + record = StoredRuntimeValue( + key=ArtifactKey( + name="raw", + artifact_type=ImageArtifactType, + scope=RuntimeExecutionAxisScope.from_raw("A01", component=None, value=None), + ), + data=np.ones((2, 2)), + location=RuntimeArtifactLocation("/memory/raw", "memory"), + ) + assert ( + RuntimeArtifactQuery.records_for_input_edge( + edge, + (record,), + axis_id="A01", + backend="memory", + ) + == () + ) + + def test_runtime_artifact_query_from_dynamic_output_plan_uses_runtime_group_path(): query = RuntimeArtifactQuery.from_output_plan( ArtifactOutputPlan(