diff --git a/openhcs/core/artifacts.py b/openhcs/core/artifacts.py index b5b1552315..d7b96622c3 100644 --- a/openhcs/core/artifacts.py +++ b/openhcs/core/artifacts.py @@ -43,6 +43,9 @@ MeasurementTable, RuntimeMeasurementFeatureOwner, ) + from openhcs.core.runtime_stores import StoredRuntimeValue + from openhcs.core.source_projection import OpenHCSPlaneAddress + from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.runtime_slice_alignment import RuntimeSliceAlignedValueSet @@ -430,6 +433,70 @@ def publishes_to_main_flow( return cls.participates_in_main_flow_output and sidecar_role is None + @classmethod + def reduce_materialization_records( + cls, + *, + records: tuple[StoredRuntimeValue, ...], + output_plan: ArtifactOutputPlan, + ) -> tuple[StoredRuntimeValue, ...]: + """Reduce records across every compiled group of one artifact output.""" + + del output_plan + return records + + @classmethod + def reduce_materialization_scopes( + cls, + *, + records: tuple[StoredRuntimeValue, ...], + output_plan: ArtifactOutputPlan, + group_key: str | None, + ) -> tuple[StoredRuntimeValue, ...]: + """Partition records by exact scope before artifact-specific reduction.""" + + records_by_scope: dict[ + RuntimeExecutionAxisScope, + list[StoredRuntimeValue], + ] = {} + for record in records: + records_by_scope.setdefault(record.key.scope, []).append(record) + return tuple( + reduced_record + for scoped_records in records_by_scope.values() + for reduced_record in cls.reduce_materialization_scope( + records=tuple(scoped_records), + output_plan=output_plan, + group_key=group_key, + ) + ) + + @classmethod + def reduce_materialization_scope( + cls, + *, + records: tuple[StoredRuntimeValue, ...], + output_plan: ArtifactOutputPlan, + group_key: str | None, + ) -> tuple[StoredRuntimeValue, ...]: + del output_plan, group_key + if len(records) <= 1: + return records + record_locations = tuple( + ( + record.key.semantic_id, + record.location.path, + ) + for record in records + ) + raise RuntimeError( + f"Ambiguous RuntimeValueStore records for planned artifact " + f"materialization '{records[0].key.name}' " + f"({records[0].key.artifact_type.value}) on axis " + f"'{records[0].key.scope.axis_id}' group " + f"{records[0].key.scope.value_text!r}: {record_locations!r}." + ) + ArtifactTypeValue = type[ArtifactType] | str @@ -814,7 +881,9 @@ def compose_runtime_values( payloads = tuple(value.data for value in values) arrays = tuple(image_payload_data(payload) for payload in payloads) return stack_image_payloads( - payloads, memory_type=detect_memory_type(arrays[0]), device_id=0, + payloads, + memory_type=detect_memory_type(arrays[0]), + device_id=0, metadata_mode=ImagePayloadMetadataCompositionMode.for_plane_axis( RuntimePlaneAxis.RUNTIME_SLICE ), @@ -850,6 +919,110 @@ def normalize_group_scoped_payload( projection.selected_plane(0), ) + @classmethod + def reduce_materialization_records( + cls, + *, + records: tuple[StoredRuntimeValue, ...], + output_plan: ArtifactOutputPlan, + ) -> tuple[StoredRuntimeValue, ...]: + from openhcs.core.runtime_image_values import image_payload_metadata + from openhcs.core.source_projection import OpenHCSPlaneAddress + + if not output_plan.materialization_uses_source_identity_filename(): + return records + + addressed_records: list[ + tuple[StoredRuntimeValue, OpenHCSPlaneAddress | None] + ] = [] + records_by_address: dict[ + OpenHCSPlaneAddress, + list[StoredRuntimeValue], + ] = {} + for record in records: + payload = output_plan.materialization_payload(record) + metadata = image_payload_metadata(payload) + address = OpenHCSPlaneAddress.from_complete_source_metadata( + metadata.source_component_metadata + ) + addressed_records.append((record, address)) + if address is not None: + records_by_address.setdefault(address, []).append(record) + + reduced_records: list[StoredRuntimeValue] = [] + emitted_addresses: set[OpenHCSPlaneAddress] = set() + for record, address in addressed_records: + if address is None: + reduced_records.append(record) + continue + if address in emitted_addresses: + continue + emitted_addresses.add(address) + reduced_records.append( + cls._materialization_record_for_scalar_address( + output_plan, + address, + tuple(records_by_address[address]), + ) + ) + return tuple(reduced_records) + + @classmethod + def _materialization_record_for_scalar_address( + cls, + output_plan: ArtifactOutputPlan, + address: OpenHCSPlaneAddress, + records: tuple[StoredRuntimeValue, ...], + ) -> StoredRuntimeValue: + if len(records) == 1: + return records[0] + + owner_records = tuple( + record + for record in records + if all( + address.value_for(component) == value + for component, value in record.key.scope.source_component_values + ) + ) + if len(owner_records) != 1: + raise ValueError( + "Scalar image materialization requires one execution scope matching " + f"source address {address!r} for artifact {output_plan.name!r}; " + f"found {len(owner_records)} among " + f"{tuple(record.key.scope for record in records)!r}." + ) + + owner_record = owner_records[0] + owner_payload = output_plan.materialization_payload(owner_record) + for record in records: + payload = output_plan.materialization_payload(record) + if not cls._materialization_payloads_are_equivalent(owner_payload, payload): + raise ValueError( + "Conflicting scalar image materialization payloads for source " + f"address {address!r} and artifact {output_plan.name!r}: " + f"{owner_record.key.scope!r} != {record.key.scope!r}." + ) + return owner_record + + @staticmethod + def _materialization_payloads_are_equivalent(left: object, right: object) -> bool: + import numpy as np + from openhcs.core.runtime_image_values import ( + image_payload_data, + image_payload_metadata, + ) + + left_metadata = image_payload_metadata(left) + right_metadata = image_payload_metadata(right) + if left_metadata != right_metadata: + return False + left_data = np.asarray(image_payload_data(left)) + right_data = np.asarray(image_payload_data(right)) + return left_data.dtype == right_data.dtype and np.array_equal( + left_data, right_data, equal_nan=True + ) + class ObjectLabelsArtifactType(ArtifactType): """Object-label array artifact type.""" @@ -1254,6 +1427,44 @@ def uses_aggregate_materialization_identity(cls, data: object) -> bool: or len(provenance.represented_source_identities) > 1 ) + @classmethod + def reduce_materialization_scope( + cls, + *, + records: tuple[StoredRuntimeValue, ...], + output_plan: ArtifactOutputPlan, + group_key: str | None, + ) -> tuple[StoredRuntimeValue, ...]: + from openhcs.constants.constants import Backend + from openhcs.core.runtime_artifact_values import RuntimeValue + from openhcs.core.runtime_measurements import MeasurementTable + from openhcs.core.runtime_stores import ( + RuntimeArtifactLocation, + StoredRuntimeValue, + ) + + if len(records) <= 1: + return records + group_plan = output_plan.for_group(group_key) + tables = tuple(cast(MeasurementTable, record.data) for record in records) + table = MeasurementTable.join_artifact(output_plan.name, tables) + value = RuntimeValue.normalize_for_execution_scope( + group_plan, + table, + execution_scope=records[0].key.scope, + ) + return ( + StoredRuntimeValue( + key=value.key, + data=value.data, + materialization_source_metadata=value.materialization_source_metadata, + location=RuntimeArtifactLocation( + path=group_plan.path, + backend=Backend.MEMORY.value, + ), + ), + ) + class ObjectLineageArtifactType(ArtifactType): """Internal directed object lineage used to project object measurements.""" diff --git a/openhcs/core/orchestrator/compiled_plate_execution.py b/openhcs/core/orchestrator/compiled_plate_execution.py index 5e2cb76fcf..585269ac31 100644 --- a/openhcs/core/orchestrator/compiled_plate_execution.py +++ b/openhcs/core/orchestrator/compiled_plate_execution.py @@ -79,9 +79,11 @@ ) from openhcs.core.source_bindings import CompiledSourceBindingPlan from openhcs.core.steps.abstract import AbstractStep, StepExecutionObservation +from openhcs.core.steps.function_artifact_materialization import ( + ArtifactMaterializationTargetPlan, +) from openhcs.core.steps.function_outputs import ( - OpenHCSMetadataWriter, - RuntimeArtifactMaterializationAuthority, + OpenHCSMetadataTarget, ) if TYPE_CHECKING: @@ -272,7 +274,7 @@ def execute_compiled_plate_request( execution_results, plate_runtime_observation=plate_runtime_observation, ) - OpenHCSMetadataWriter.finalize_completed_plate( + OpenHCSMetadataTarget.finalize_completed_plate( validated.compiled_contexts, ) viewer_states_by_port = settle_viewer_state( @@ -537,11 +539,11 @@ def execute_plate_scoped_steps( ) records_by_axis = _records_with_output(records_by_axis, record) - materializations = RuntimeArtifactMaterializationAuthority.materialize( + materializations = ArtifactMaterializationTargetPlan.materialize( owner_context, owner_plan.require_function_execution_ready(), ) - OpenHCSMetadataWriter.write( + OpenHCSMetadataTarget.write_for_step( owner_context, owner_plan.require_function_execution_ready(), artifact_materializations=materializations, @@ -553,7 +555,8 @@ def execute_plate_scoped_steps( ) observations_by_context[owner_context_key].append( StepExecutionObservation.combine( - item.observation(owner_plan, owner_context) for item in materializations + item.observation(owner_plan, owner_context) + for item in materializations ) ) _emit_execution_progress( @@ -575,13 +578,15 @@ def execute_plate_scoped_steps( records=records, runtime_export_paths=tuple( dict.fromkeys( - path for item in observations_by_context[context_key] + path + for item in observations_by_context[context_key] for path in item.runtime_export_paths ) ), runtime_observation_mode=RuntimeObservationMode.MERGE_INTO_PARENT, analysis_inputs=RuntimeAnalysisConsolidationInputs.combine( - item.analysis_inputs for item in observations_by_context[context_key] + item.analysis_inputs + for item in observations_by_context[context_key] ), ) for context_key, context in compiled_contexts.items() diff --git a/openhcs/core/projected_image_output.py b/openhcs/core/projected_image_output.py index 76965d4494..6dc45b5e2f 100644 --- a/openhcs/core/projected_image_output.py +++ b/openhcs/core/projected_image_output.py @@ -28,7 +28,9 @@ ObjectLabelValue, object_label_dense_array, ) -from openhcs.core.runtime_object_label_building import SourceImageObjectLabelBuildRequest +from openhcs.core.runtime_object_label_building import ( + SourceImageObjectLabelBuildRequest, +) from openhcs.core.runtime_plane_projection import ( RuntimePlaneAxis, RuntimePlaneAxisValueProjection, diff --git a/openhcs/core/runtime_object_labels.py b/openhcs/core/runtime_object_labels.py index 396e677ae6..7d528736a1 100644 --- a/openhcs/core/runtime_object_labels.py +++ b/openhcs/core/runtime_object_labels.py @@ -215,6 +215,39 @@ def project( ), ) + def validate_representation( + self, + *, + representation: ObjectLabelRepresentation, + value_label: str, + ) -> None: + """Validate final and optional variants before admitting a label carrier.""" + label_data = self.labels + final_authority = ObjectLabelStorageStrategy.for_value(label_data) + final_authority.validate_representation( + label_data, + representation=representation, + value_label=value_label, + ) + for variant_name, variant in ( + ("unedited_labels", self.unedited_labels), + ("small_removed_labels", self.small_removed_labels), + ): + if variant is None: + continue + variant_authority = ObjectLabelStorageStrategy.for_value(variant) + variant_authority.validate_representation( + variant, + representation=representation, + value_label=f"{value_label} {variant_name}", + ) + if variant_authority.matching_variant(variant, variant, label_data) is None: + raise ValueError( + f"{value_label} {variant_name} shape " + f"{variant_authority.label_shape(variant)!r} does not match " + f"final labels shape {final_authority.label_shape(label_data)!r}." + ) + def in_representation( self, representation: ObjectLabelRepresentation, @@ -976,21 +1009,64 @@ def from_payload( *, dimensions: tuple[str, ...] = (), source_image_name: str | None = None, + source_image_payload: runtime_array_values.RuntimeArrayData | None = None, + parent_image_payload: runtime_array_values.RuntimeArrayData | None = None, + source_image_names: tuple[str, ...] = (), ) -> Self: - """Bind artifact identity to an already nominal object-label payload.""" + """Admit a named label value with its resolved source and parent context.""" + variants = payload.variant_data + provenance = payload.source_provenance + spatial_domain = payload.source_spatial_domain + plane_axis = payload.plane_axis + if source_image_payload is not None: + metadata = runtime_image_values.image_payload_metadata(source_image_payload) + provenance = object_label_source_context_provenance( + payload, source_image_payload + ) + spatial_domain = ( + payload.object_label_source_spatial_domain().with_missing_from( + metadata.object_label_source_spatial_domain() + ) + ) + plane_axis = ObjectLabelPlaneDomainStrategy.for_enum_member( + payload.domain.scope + ).value_plane_axis(payload.plane_axis) + variants = variants.in_representation(payload.representation) + if isinstance(payload, ObjectLabelSet): + payload.validate_artifact_name() + if payload.source_image_name == "": + raise ValueError("ObjectLabelSet.source_image_name cannot be empty.") + variants.validate_representation( + representation=ObjectLabelRepresentation(payload.representation), + value_label=type(payload).__name__, + ) + spacing = payload.parent_image_source_voxel_spacing + if parent_image_payload is not None: + spacing = spacing.with_missing_from( + runtime_image_values.image_payload_metadata( + parent_image_payload + ).source_voxel_spacing + ) + fallback_names = source_image_names + if not fallback_names and source_image_payload is not None: + fallback_names = runtime_image_values.image_payload_metadata( + source_image_payload + ).source_image_names + if fallback_names: + provenance = provenance.with_source_image_names( + provenance.source_image_names or fallback_names + ) return cls( name=name, dimensions=dimensions, source_image_name=source_image_name, - variant_data=payload.variant_data, + variant_data=variants, representation=payload.representation, domain=payload.domain, - plane_axis=payload.plane_axis, - source_spatial_domain=payload.source_spatial_domain, - parent_image_source_voxel_spacing=( - payload.parent_image_source_voxel_spacing - ), - source_provenance=payload.source_provenance, + plane_axis=plane_axis, + source_spatial_domain=spatial_domain, + parent_image_source_voxel_spacing=spacing, + source_provenance=provenance, ) def __post_init__(self, *source_provenance_values: object) -> None: @@ -1503,31 +1579,11 @@ def validate_representation( value_label: str, ) -> None: label_value = cast(ObjectLabelValue, labels) - label_data = self.label_data(label_value) - final_authority = ObjectLabelStorageStrategy.for_value(label_data) - final_authority.validate_representation( - label_data, + self.label_data(label_value) + label_value.variant_data.validate_representation( representation=representation, value_label=value_label, ) - for variant_name, variant in ( - ("unedited_labels", label_value.unedited_labels), - ("small_removed_labels", label_value.small_removed_labels), - ): - if variant is None: - continue - variant_authority = ObjectLabelStorageStrategy.for_value(variant) - variant_authority.validate_representation( - variant, - representation=representation, - value_label=f"{value_label} {variant_name}", - ) - if variant_authority.matching_variant(variant, variant, label_data) is None: - raise ValueError( - f"{value_label} {variant_name} shape " - f"{variant_authority.label_shape(variant)!r} does not match " - f"final labels shape {final_authority.label_shape(label_data)!r}." - ) def validate_plane_count( self, diff --git a/openhcs/core/steps/function_artifact_materialization.py b/openhcs/core/steps/function_artifact_materialization.py index 5d67e6a6ab..f0adf8f429 100644 --- a/openhcs/core/steps/function_artifact_materialization.py +++ b/openhcs/core/steps/function_artifact_materialization.py @@ -7,9 +7,9 @@ from dataclasses import dataclass from pathlib import Path from types import MappingProxyType -from typing import TYPE_CHECKING, ClassVar, cast +from typing import TYPE_CHECKING, ClassVar -import numpy as np +import logging from metaclass_registry import AutoRegisterMeta from polystore.streaming.identity import StreamProducerIdentity from polystore.streaming.viewer_transport import ViewerStreamProducer @@ -17,25 +17,19 @@ from openhcs.constants.constants import AllComponents, Backend, VariableComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, - ArtifactType, - ArtifactTypeStrategyMatchMixin, - ImageArtifactType, - MeasurementsArtifactType, ) from openhcs.core.axis_filter import step_axis_allows_config -from openhcs.core.compiled_step_plan import CompiledStepPlan +from openhcs.microscopes.microscope_interfaces import FilenameParser +from openhcs.core.compiled_step_plan import ( + CompiledStepPlan, + RuntimeArtifactMaterializationPlan, +) from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.component_set import ComponentSet -from openhcs.core.registry_strategies import MostDerivedContextStrategyMixin -from openhcs.core.runtime_artifact_values import RuntimeValue from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, - image_payload_data, image_payload_metadata, ) -from openhcs.core.runtime_measurements import ( - MeasurementTable, -) from openhcs.core.runtime_stores import ( RuntimeArtifactAddress, RuntimeArtifactLocation, @@ -54,7 +48,6 @@ from openhcs.core.steps.abstract import StepExecutionObservation from openhcs.core.steps.function_output_identity import ( FunctionOutputIdentity, - FunctionOutputParserContext, IncompleteFunctionOutputFilenameIdentityError, ) from openhcs.core.steps.stream_component_semantics import ( @@ -80,302 +73,186 @@ from openhcs.core.context.processing_context import ProcessingContext -class ArtifactMaterializationRecordReducer( - ArtifactTypeStrategyMatchMixin, - MostDerivedContextStrategyMixin[type[ArtifactType]], -): - """Registered reducer from runtime store records to materialization records.""" - - artifact_type: ClassVar[type[ArtifactType] | None] = ArtifactType +logger = logging.getLogger(__name__) - def records_for_output( - self, - *, - records: tuple[StoredRuntimeValue, ...], - output_plan: ArtifactOutputPlan, - ) -> tuple[StoredRuntimeValue, ...]: - """Reduce records across every compiled group of one artifact output.""" - del output_plan - return records +class ArtifactMaterializationTargetPlan(ABC, metaclass=AutoRegisterMeta): + """Nominal target policy for artifact materialization destinations.""" - def records_for_exact_scopes( - self, - *, - records: tuple[StoredRuntimeValue, ...], - output_plan: ArtifactOutputPlan, - axis_id: str, - group_key: str | None, - ) -> tuple[StoredRuntimeValue, ...]: - """Partition records by exact scope before artifact-specific reduction.""" - - records_by_scope: dict[ - RuntimeExecutionAxisScope, - list[StoredRuntimeValue], - ] = {} - for record in records: - records_by_scope.setdefault(record.key.scope, []).append(record) - return tuple( - reduced_record - for scoped_records in records_by_scope.values() - for reduced_record in self.records_for_group( - records=tuple(scoped_records), - output_plan=output_plan, - axis_id=axis_id, - group_key=group_key, - ) - ) + __registry_key__ = "target_key" + __skip_if_no_key__ = True + target_key: ClassVar[str | None] = None - def records_for_group( - self, - *, - records: tuple[StoredRuntimeValue, ...], - output_plan: ArtifactOutputPlan, - axis_id: str, - group_key: str | None, - ) -> tuple[StoredRuntimeValue, ...]: - del output_plan, axis_id, group_key - if len(records) <= 1: - return records - record_locations = tuple( - ( - record.key.semantic_id, - record.location.path, - ) - for record in records - ) - raise RuntimeError( - f"Ambiguous RuntimeValueStore records for planned artifact " - f"materialization '{records[0].key.name}' " - f"({records[0].key.artifact_type.value}) on axis " - f"'{records[0].key.scope.axis_id}' group " - f"{records[0].key.scope.value_text!r}: {record_locations!r}." + @classmethod + def materialize( + cls, + context: ProcessingContext, + plan: CompiledStepPlan, + ) -> tuple[MaterializedRuntimeArtifact, ...]: + if not plan.artifact_outputs: + return () + materialization_plan = plan.runtime_artifact_materialization + has_persistent_target = materialization_plan.has_persistent_target + has_streaming_target = bool(plan.streaming_configs) + if not has_persistent_target and not has_streaming_target: + logger.info("Skipping runtime artifact materialization and streaming") + return () + + logger.info( + "Starting materialization for %s artifact outputs", + len(plan.artifact_outputs), ) + filemanager = context.filemanager + target = cls.from_config(materialization_plan) + materializations = target.materialize_outputs(filemanager, plan, context) + logger.info("Completed artifact materialization") + return materializations + @classmethod + def from_config( + cls, + materialization_plan: RuntimeArtifactMaterializationPlan, + ) -> ( + PersistentArtifactMaterializationTargetPlan + | StreamingOnlyArtifactMaterializationTargetPlan + ): + if not materialization_plan.has_persistent_target: + logger.info("Skipping persistent runtime artifact materialization") + return StreamingOnlyArtifactMaterializationTargetPlan() -class ImageArtifactMaterializationRecordReducer(ArtifactMaterializationRecordReducer): - """Reduce redundant scalar image records to their source-address owner.""" - - artifact_type = ImageArtifactType + return PersistentArtifactMaterializationTargetPlan( + materialization_plan.require_persistent_backend() + ) - def records_for_output( + def materialize_outputs( self, - *, - records: tuple[StoredRuntimeValue, ...], - output_plan: ArtifactOutputPlan, - ) -> tuple[StoredRuntimeValue, ...]: - if not output_plan.materialization_uses_source_identity_filename(): - return records - - addressed_records: list[ - tuple[StoredRuntimeValue, OpenHCSPlaneAddress | None] - ] = [] - records_by_address: dict[ - OpenHCSPlaneAddress, - list[StoredRuntimeValue], - ] = {} - for record in records: - payload = output_plan.materialization_payload(record) - metadata = image_payload_metadata(payload) - address = OpenHCSPlaneAddress.from_complete_source_metadata( - metadata.source_component_metadata + filemanager: "FileManager", + plan: CompiledStepPlan, + context: "ProcessingContext", + ) -> tuple[MaterializedRuntimeArtifact, ...]: + """Save each exact artifact batch once and return its successful outputs.""" + saved_materializations = [] + images_dir = plan.artifact_images_dir + + for materialization in runtime_artifact_materializations(plan, context): + persistent_backend_kwargs = self.persistent_backend_kwargs(context) + streaming_viewer_surfaces = self.streaming_viewer_surfaces( + plan, + context, + materialization, ) - addressed_records.append((record, address)) - if address is not None: - records_by_address.setdefault(address, []).append(record) - - reduced_records: list[StoredRuntimeValue] = [] - emitted_addresses: set[OpenHCSPlaneAddress] = set() - for record, address in addressed_records: - if address is None: - reduced_records.append(record) - continue - if address in emitted_addresses: - continue - emitted_addresses.add(address) - reduced_records.append( - self._record_for_scalar_address( - output_plan, - address, - tuple(records_by_address[address]), - ) + record = materialization.record + data = materialization.data + filemanager.ensure_directory( + Path(record.location.path).parent, record.location.backend ) - return tuple(reduced_records) - - @classmethod - def _record_for_scalar_address( - cls, - output_plan: ArtifactOutputPlan, - address: OpenHCSPlaneAddress, - records: tuple[StoredRuntimeValue, ...], - ) -> StoredRuntimeValue: - if len(records) == 1: - return records[0] - - owner_records = tuple( - record - for record in records - if all( - address.value_for(component) == value - for component, value in record.key.scope.source_component_values + stream_output_paths = materialization.spec.candidate_paths( + str(materialization.base_path) ) - ) - if len(owner_records) != 1: - raise ValueError( - "Scalar image materialization requires one execution scope matching " - f"source address {address!r} for artifact {output_plan.name!r}; " - f"found {len(owner_records)} among " - f"{tuple(record.key.scope for record in records)!r}." + backends = [ + *( + persistent_backend_kwargs + if materialization.spec.participates_in_persistent_materialization() + else () + ), + *self.streamable_viewer_surfaces( + filemanager=filemanager, + streaming_viewer_surfaces=streaming_viewer_surfaces, + stream_output_paths=stream_output_paths, + ), + ] + if not backends: + continue + batch = prepare_materialization( + materialization.spec, + data, + str(materialization.base_path), + filemanager, + backends, + self.backend_kwargs( + materialization=materialization, + persistent_backend_kwargs=persistent_backend_kwargs, + streaming_viewer_surfaces=streaming_viewer_surfaces, + fallback_source_identity=( + materialization.filename_source_identity + if materialization.spec.uses_filename_source_identity(data) + else materialization.source_identity + ), + producer_identity=( + plan.producer_identity_for_artifact(materialization.output_plan) + ), + context=context, + filemanager=filemanager, + images_dir=images_dir, + stream_output_paths=stream_output_paths, + ), + context=context, + artifact_source_identity=materialization.source_identity, + artifact_filename_identity=materialization.filename_source_identity, + variable_components=materialization.output_plan.variable_components, + pipeline_position=plan.pipeline_position, + output_plan=materialization.output_plan, ) - - owner_record = owner_records[0] - owner_payload = output_plan.materialization_payload(owner_record) - for record in records: - payload = output_plan.materialization_payload(record) - if not cls._payloads_are_equivalent(owner_payload, payload): - raise ValueError( - "Conflicting scalar image materialization payloads for source " - f"address {address!r} and artifact {output_plan.name!r}: " - f"{owner_record.key.scope!r} != {record.key.scope!r}." + saved_materializations.append( + MaterializedRuntimeArtifact( + outputs_by_backend=MappingProxyType( + dict(batch.save().outputs_by_backend) + ), + materialization=materialization, ) - return owner_record - - @staticmethod - def _payloads_are_equivalent(left: object, right: object) -> bool: - left_metadata = image_payload_metadata(left) - right_metadata = image_payload_metadata(right) - if left_metadata != right_metadata: - return False - left_data = np.asarray(image_payload_data(left)) - right_data = np.asarray(image_payload_data(right)) - return left_data.dtype == right_data.dtype and np.array_equal( - left_data, right_data, equal_nan=True - ) - - -class MeasurementArtifactMaterializationRecordReducer( - ArtifactMaterializationRecordReducer -): - """Union same-artifact measurement subject records before materialization.""" - - artifact_type = MeasurementsArtifactType + ) + return tuple(saved_materializations) - def records_for_group( + def streaming_viewer_surfaces( self, - *, - records: tuple[StoredRuntimeValue, ...], - output_plan: ArtifactOutputPlan, - axis_id: str, - group_key: str | None, - ) -> tuple[StoredRuntimeValue, ...]: - if len(records) <= 1: - return records - group_plan = output_plan.for_group(group_key) - tables = tuple(cast(MeasurementTable, record.data) for record in records) - table = MeasurementTable.join_artifact(output_plan.name, tables) - value = RuntimeValue.normalize_for_execution_scope( - group_plan, - table, - execution_scope=records[0].key.scope, + plan: CompiledStepPlan, + context: "ProcessingContext", + materialization: "RuntimeArtifactMaterialization", + ) -> Mapping[str, StreamingViewerSurface]: + """Capture enabled destinations for this artifact at the write boundary.""" + streams_artifact = ( + not plan.compiled_function_pattern.publishes_output_to_main_flow( + materialization.output_plan, + materialization.record.key.scope.value_text, + ) ) return ( - StoredRuntimeValue( - key=value.key, - data=value.data, - materialization_source_metadata=value.materialization_source_metadata, - location=RuntimeArtifactLocation( - path=group_plan.path, - backend=Backend.MEMORY.value, - ), - ), + { + config.backend.value: config.streaming_viewer_surface(context) + for config in plan.streaming_configs.values() + if step_axis_allows_config( + context.step_axis_filters, + step_index=plan.step_index, + config=config, + axis_id=context.axis_id, + ) + } + if streams_artifact + else {} ) - -@dataclass(frozen=True, slots=True) -class ArtifactMaterializationBackendPlan: - """Persistent backends and streaming payload builders for artifact output.""" - - persistent_backend_kwargs: BackendKwargs - streaming_viewer_surfaces: Mapping[str, StreamingViewerSurface] - - def backends_for( - self, - *, - materialization_spec: MaterializationSpec, - filemanager: "FileManager", - stream_output_paths: tuple[str, ...], - ) -> list[str]: - return [ - *( - self.persistent_backend_kwargs - if materialization_spec.participates_in_persistent_materialization() - else () - ), - *self.streamable_viewer_surfaces( - filemanager=filemanager, - stream_output_paths=stream_output_paths, - ), - ] - + @staticmethod def streamable_viewer_surfaces( - self, *, filemanager: "FileManager", + streaming_viewer_surfaces: Mapping[str, StreamingViewerSurface], stream_output_paths: tuple[str, ...], ) -> Mapping[str, StreamingViewerSurface]: return { - backend: viewer_surface - for backend, viewer_surface in self.streaming_viewer_surfaces.items() + backend: surface + for backend, surface in streaming_viewer_surfaces.items() if any( - self.stream_backend_supports_output_path( - filemanager, - backend, - path, - ) + filemanager._get_backend(backend).supports_file_path(path) for path in stream_output_paths ) } - @staticmethod - def stream_backend_supports_output_path( - filemanager: "FileManager", - backend: str, - path: str, - ) -> bool: - """Return whether one exact viewer backend accepts this output path.""" - return filemanager._get_backend(backend).supports_file_path(path) - - def supports_stream_output_path( - self, - filemanager: "FileManager", - path: str, - ) -> bool: - """Return whether an enabled viewer backend accepts this exact output.""" - return any( - self.stream_backend_supports_output_path(filemanager, backend, path) - for backend in self.streaming_viewer_surfaces - ) - - def supports_stream_output( - self, - filemanager: "FileManager", - output: Output, - ) -> bool: - """Return whether an enabled viewer accepts one concrete writer output.""" - - return any( - filemanager._get_backend(backend).accepts_payload( - output.content, - output.path, - ) - for backend in self.streaming_viewer_surfaces - ) - def backend_kwargs( self, *, - materialization_spec: MaterializationSpec, - data: MaterializationValue, + materialization: "RuntimeArtifactMaterialization", + persistent_backend_kwargs: BackendKwargs, + streaming_viewer_surfaces: Mapping[str, StreamingViewerSurface], fallback_source_identity: SourceImageIdentity | None, producer_identity: StreamProducerIdentity, context: "ProcessingContext", @@ -385,8 +262,8 @@ def backend_kwargs( ) -> BackendKwargs: result: BackendKwargs = {} persistent_backend_kwargs = ( - self.persistent_backend_kwargs - if materialization_spec.participates_in_persistent_materialization() + persistent_backend_kwargs + if materialization.spec.participates_in_persistent_materialization() else {} ) for backend, kwargs in persistent_backend_kwargs.items(): @@ -414,15 +291,14 @@ def backend_kwargs( streamable_viewer_surfaces = self.streamable_viewer_surfaces( filemanager=filemanager, + streaming_viewer_surfaces=streaming_viewer_surfaces, stream_output_paths=stream_output_paths, ) if not streamable_viewer_surfaces: return result - source_metadata_items = ArtifactStreamSourceMetadataAuthority.metadata_items( - materialization_spec=materialization_spec, - data=data, - fallback_source_identity=fallback_source_identity, + source_metadata_items = materialization.stream_source_metadata_items( + fallback_source_identity ) producer = ViewerStreamProducer.from_identity(producer_identity) for backend, viewer_surface in streamable_viewer_surfaces.items(): @@ -439,85 +315,6 @@ def backend_kwargs( ) return result - -class ArtifactStreamSourceMetadataAuthority: - """Choose source metadata for the viewer request that starts artifact streaming.""" - - @staticmethod - def metadata_items( - *, - materialization_spec: MaterializationSpec, - data: MaterializationValue, - fallback_source_identity: SourceImageIdentity | None, - ) -> StreamSourceComponentMetadataItems: - fallback_source_identity = ( - fallback_source_identity - or ArtifactStreamSourceMetadataAuthority.payload_source_identity(data) - ) - emitted_identities = materialization_spec.emitted_source_identities(data) - if emitted_identities: - return StreamSourceComponentMetadataItems.from_source_identities( - emitted_identities, - fallback_source_identity=fallback_source_identity, - ) - return StreamSourceComponentMetadataItems.from_values( - ( - ( - fallback_source_identity.component_metadata - if fallback_source_identity is not None - else None - ), - ) - ) - - @staticmethod - def payload_source_identity( - data: MaterializationValue, - ) -> SourceImageIdentity | None: - metadata = image_payload_metadata(data) - source_identity = metadata.source_provenance.scalar_source_identity - if source_identity.addressable: - return source_identity - return None - - -class ArtifactMaterializationTargetPlan(ABC, metaclass=AutoRegisterMeta): - """Nominal target policy for artifact materialization destinations.""" - - __registry_key__ = "target_key" - __skip_if_no_key__ = True - target_key: ClassVar[str | None] = None - - def backend_plan( - self, - plan: CompiledStepPlan, - context: "ProcessingContext", - materialization: "RuntimeArtifactMaterialization", - ) -> ArtifactMaterializationBackendPlan: - streams_artifact = ( - not plan.compiled_function_pattern.publishes_output_to_main_flow( - materialization.output_plan, - materialization.record.key.scope.value_text, - ) - ) - return ArtifactMaterializationBackendPlan( - persistent_backend_kwargs=self.persistent_backend_kwargs(context), - streaming_viewer_surfaces=( - { - config.backend.value: config.streaming_viewer_surface(context) - for config in plan.streaming_configs.values() - if step_axis_allows_config( - context.step_axis_filters, - step_index=plan.step_index, - config=config, - axis_id=context.axis_id, - ) - } - if streams_artifact - else {} - ), - ) - @abstractmethod def persistent_backend_kwargs(self, context: "ProcessingContext") -> BackendKwargs: """Return persistent materialization backends owned by this policy.""" @@ -549,15 +346,6 @@ def persistent_backend_kwargs(self, context: "ProcessingContext") -> BackendKwar return {} -@dataclass(frozen=True, slots=True) -class ArtifactAnalysisOutputDescriptor: - """Filename plus source identity for an artifact materialization.""" - - filename: str - source_identity: SourceImageIdentity | None - source_filename: str | None = None - - @dataclass(frozen=True, slots=True) class PlannedArtifactMaterializationPath: """Compile-time preview of paths one materialized artifact group may emit.""" @@ -576,30 +364,193 @@ class PlannedArtifactMaterializationPreview: runtime_metadata_can_refine_paths: bool +def actual_materialization_records( + *, + store: RuntimeValueStore, + plan: CompiledStepPlan, + output_plan: ArtifactOutputPlan, +) -> tuple[StoredRuntimeValue, ...]: + """Return actually produced memory records for one planned artifact output.""" + if not output_plan.group_keys: + raise RuntimeError( + f"Artifact output plan '{output_plan.name}' has no group keys." + ) + artifact_type = output_plan.artifact_type + + if output_plan.group_component is not None and tuple(output_plan.group_keys) == ( + None, + ): + dynamic_records = tuple( + record + for record in store.find( + name=output_plan.name, + artifact_type=output_plan.artifact_type, + axis_id=plan.axis_id, + ) + if record.key.scope.value_text is not None + and record.location.backend == Backend.MEMORY.value + and store.get(record.key).location == record.location + ) + if dynamic_records: + record_sort_items = [] + dynamic_group_keys = tuple( + dict.fromkeys( + str(record.key.scope.value_text) for record in dynamic_records + ) + ) + group_order = { + group_key: index + for index, group_key in enumerate(sorted(dynamic_group_keys)) + } + for group_key in dynamic_group_keys: + records_for_group = tuple( + record + for record in dynamic_records + if str(record.key.scope.value_text) == group_key + ) + for record in artifact_type.reduce_materialization_scopes( + records=records_for_group, + output_plan=output_plan, + group_key=group_key, + ): + record_sort_items.append((group_order[group_key], record)) + return artifact_type.reduce_materialization_records( + records=tuple( + record + for _, record in sorted( + record_sort_items, + key=lambda item: item[0], + ) + ), + output_plan=output_plan, + ) + + group_order = { + group_key: index for index, group_key in enumerate(output_plan.group_keys) + } + record_sort_items = [] + missing_group_keys = [] + for group_key in output_plan.group_keys: + records = tuple( + record + for record in store.find( + name=output_plan.name, + artifact_type=output_plan.artifact_type, + axis_id=plan.axis_id, + group_key=group_key, + match_group=True, + ) + if record.location.backend == Backend.MEMORY.value + and store.get(record.key).location == record.location + ) + if not records: + missing_group_keys.append(group_key) + continue + for record in artifact_type.reduce_materialization_scopes( + records=records, + output_plan=output_plan, + group_key=group_key, + ): + record_sort_items.append((group_order[group_key], record)) + + if missing_group_keys and not record_sort_items: + candidates = tuple( + store.find( + name=output_plan.name, + artifact_type=output_plan.artifact_type, + axis_id=plan.axis_id, + ) + ) + candidate_locations = tuple( + ( + candidate.key.scope.value_text, + candidate.location.backend, + candidate.location.path, + ) + for candidate in candidates + ) + identity_records = tuple( + candidate + for candidate in candidates + if candidate.key.scope.value_text is None + and candidate.location.backend == Backend.MEMORY.value + and store.get(candidate.key).location == candidate.location + ) + if identity_records: + return artifact_type.reduce_materialization_records( + records=identity_records, + output_plan=output_plan, + ) + raise RuntimeError( + f"Missing RuntimeValueStore record for planned artifact materialization " + f"'{output_plan.name}' ({output_plan.artifact_type.value}) on axis " + f"'{plan.axis_id}' groups {tuple(missing_group_keys)!r}. " + f"Candidate same-name records: " + f"{candidate_locations!r}." + ) + return artifact_type.reduce_materialization_records( + records=tuple( + record for _, record in sorted(record_sort_items, key=lambda item: item[0]) + ), + output_plan=output_plan, + ) + + @dataclass(frozen=True, slots=True) -class ArtifactRecordSourceDescriptor: - """Resolved source stem and stream identity for one artifact record.""" +class RuntimeArtifactMaterialization: + """One exact compiled artifact value and its generic materialization target.""" - filename: str + output_plan: ArtifactOutputPlan + spec: MaterializationSpec + record: StoredRuntimeValue + data: MaterializationValue + base_path: Path source_identity: SourceImageIdentity | None + filename_source_identity: SourceImageIdentity | None - @property - def filename_stem(self) -> str: - return Path(self.filename).stem - + def stream_source_metadata_items( + self, + fallback_source_identity: SourceImageIdentity | None, + ) -> StreamSourceComponentMetadataItems: + """Project this occurrence's sources at the streaming request boundary.""" + fallback_source_identity = ( + fallback_source_identity or self.payload_source_identity(self.data) + ) + emitted_identities = self.spec.emitted_source_identities(self.data) + if emitted_identities: + return StreamSourceComponentMetadataItems.from_source_identities( + emitted_identities, + fallback_source_identity=fallback_source_identity, + ) + return StreamSourceComponentMetadataItems.from_values( + ( + ( + fallback_source_identity.component_metadata + if fallback_source_identity is not None + else None + ), + ) + ) -class AnalysisOutputDescriptorAuthority: - """Own analysis artifact filenames and their source component metadata.""" + @staticmethod + def payload_source_identity( + data: MaterializationValue, + ) -> SourceImageIdentity | None: + metadata = image_payload_metadata(data) + source_identity = metadata.source_provenance.scalar_source_identity + if source_identity.addressable: + return source_identity + return None @classmethod - def aggregate_descriptor( + def _aggregate_identity( cls, output_key: str, plan: CompiledStepPlan, *, scope: RuntimeExecutionAxisScope | None = None, source_identity: SourceImageIdentity | None = None, - ) -> ArtifactAnalysisOutputDescriptor: + ) -> tuple[str, SourceImageIdentity | None, str | None]: """Return an artifact-owned filename without a representative plane.""" fixed_scope_qualifier = ( @@ -611,16 +562,15 @@ def aggregate_descriptor( if not component.is_multiprocessing_axis() ) ) - return ArtifactAnalysisOutputDescriptor( - filename=( - f"{plan.axis_id}{fixed_scope_qualifier}_{output_key}_step" - f"{plan.pipeline_position}.roi.zip" - ), - source_identity=source_identity, + return ( + f"{plan.axis_id}{fixed_scope_qualifier}_{output_key}_step" + f"{plan.pipeline_position}.roi.zip", + source_identity, + None, ) @classmethod - def build( + def _analysis_identity( cls, output_key: str, plan: CompiledStepPlan, @@ -630,7 +580,7 @@ def build( record: StoredRuntimeValue | None = None, materialization_spec: MaterializationSpec | None = None, output_plan: ArtifactOutputPlan | None = None, - ) -> ArtifactAnalysisOutputDescriptor: + ) -> tuple[str, SourceImageIdentity | None, str | None]: """Build analysis output identity from the artifact's source metadata.""" record_source = None if record is not None: @@ -654,14 +604,14 @@ def build( ) if source_identity is not None and not source_identity.addressable: source_identity = None - return cls.aggregate_descriptor( + return cls._aggregate_identity( output_key, plan, scope=record.key.scope, source_identity=source_identity, ) try: - record_source = cls.record_source_descriptor( + record_source = cls._record_source_identity( context, plan, record, @@ -675,19 +625,17 @@ def build( tuple(plan.variable_components or ()), ): raise - return cls.aggregate_descriptor( + return cls._aggregate_identity( output_key, plan, scope=record.key.scope, ) if record_source is not None: - return ArtifactAnalysisOutputDescriptor( - filename=( - f"{record_source.filename_stem}_{output_key}" - f"_step{plan.pipeline_position}.roi.zip" - ), - source_identity=record_source.source_identity, - source_filename=record_source.filename, + source_filename, source_identity = record_source + return ( + f"{Path(source_filename).stem}_{output_key}_step{plan.pipeline_position}.roi.zip", + source_identity, + source_filename, ) if record is not None: @@ -707,11 +655,12 @@ def build( dict_key is not None or cls.source_identity_for_path(context, artifact_path) is not None ): - return ArtifactAnalysisOutputDescriptor( - filename=f"{Path(artifact_path).stem}.roi.zip", - source_identity=source_identity, + return ( + f"{Path(artifact_path).stem}.roi.zip", + source_identity, + None, ) - return cls.aggregate_descriptor( + return cls._aggregate_identity( output_key, plan, scope=record.key.scope, @@ -723,16 +672,18 @@ def build( artifact_path, ) if source_identity is not None: - return ArtifactAnalysisOutputDescriptor( - filename=f"{Path(artifact_path).stem}.roi.zip", - source_identity=source_identity, + return ( + f"{Path(artifact_path).stem}.roi.zip", + source_identity, + None, ) if dict_key is not None and artifact_path is not None: - return ArtifactAnalysisOutputDescriptor( - filename=f"{Path(artifact_path).stem}.roi.zip", - source_identity=None, + return ( + f"{Path(artifact_path).stem}.roi.zip", + None, + None, ) - return cls.aggregate_descriptor( + return cls._aggregate_identity( output_key, plan, ) @@ -771,7 +722,7 @@ def record_metadata_with_runtime_scope( cls, record: StoredRuntimeValue, metadata: ImagePayloadMetadata, - parser_context: FunctionOutputParserContext, + parser: FilenameParser, ) -> ImagePayloadMetadata: """Admit scalar source coordinates before attaching execution identity.""" @@ -780,8 +731,8 @@ def record_metadata_with_runtime_scope( not provenance.source_image_provenance_planes.has_values and not metadata.persists_whole_image() ): - source_identity = provenance.scalar_source_identity.with_parsed_path_components( - parser_context.parser + source_identity = ( + provenance.scalar_source_identity.with_parsed_path_components(parser) ) if source_identity.component_metadata is not None: component_metadata = SourceMetadataFields.with_fields( @@ -790,7 +741,9 @@ def record_metadata_with_runtime_scope( components=( ( component, - SourceMetadataFields.canonical_component_value(component, value), + SourceMetadataFields.canonical_component_value( + component, value + ), ) for component, value in source_component_metadata_items( source_identity.component_metadata @@ -810,7 +763,7 @@ def record_metadata_with_runtime_scope( ) @classmethod - def record_source_descriptor( + def _record_source_identity( cls, context: "ProcessingContext", plan: CompiledStepPlan, @@ -818,7 +771,7 @@ def record_source_descriptor( materialization_spec: MaterializationSpec, *, output_plan: ArtifactOutputPlan | None = None, - ) -> ArtifactRecordSourceDescriptor | None: + ) -> tuple[str, SourceImageIdentity | None] | None: """Return source filename stem and identity for one artifact record.""" exact_fixed_scope = record.key.scope.has_fixed_components if not materialization_spec.uses_source_identity_filename(): @@ -833,11 +786,12 @@ def record_source_descriptor( != output_plan.source_context_source() ): metadata = output_plan.materialization_metadata(record) - parser_context = FunctionOutputParserContext.from_processing_context(context) + handler = context.microscope_handler + parser = handler.parser metadata = cls.record_metadata_with_runtime_scope( record, metadata, - parser_context, + parser, ) source_identity = metadata.source_provenance.scalar_source_identity if not source_identity.addressable: @@ -847,7 +801,7 @@ def record_source_descriptor( ) if use_filename_identity or exact_fixed_scope: identity = FunctionOutputIdentity.from_filename_metadata( - parser_context.parser, + parser, metadata, ) if identity is None: @@ -858,19 +812,18 @@ def record_source_descriptor( ) else: identity = FunctionOutputIdentity.from_metadata( - parser_context.parser, + parser, metadata, fallback_identity_path=record.location.path, variable_components=plan.variable_components, ) if identity is not None: identity = materialization_spec.filename_identity_for_output( - identity, output_plan, + identity, + output_plan, ) try: - filename = Path( - identity.filename(parser_context.parser) - ).name + filename = Path(identity.filename(parser)).name except IncompleteFunctionOutputFilenameIdentityError as exc: if cls.missing_component_is_aggregated( exc.component_name, @@ -890,35 +843,16 @@ def record_source_descriptor( ): raise else: - return ArtifactRecordSourceDescriptor( - filename=filename, - source_identity=source_identity, + return ( + filename, + source_identity, ) source_path = metadata.source_provenance.scalar_source_identity.path if source_path is None: return None - return ArtifactRecordSourceDescriptor( - filename=Path(source_path).name, - source_identity=source_identity, - ) - - @classmethod - def materialization_base_path( - cls, - *, - plan: CompiledStepPlan, - output_descriptor: ArtifactAnalysisOutputDescriptor, - output_plan: ArtifactOutputPlan, - ) -> Path: - """Return the declared base path for one materialized artifact record.""" - return output_plan.artifact_type.materialization_base_path( - descriptor_filename=output_descriptor.filename, - source_filename=output_descriptor.source_filename, - uses_source_identity_filename=( - output_plan.materialization_uses_source_identity_filename() - ), - analysis_output_dir=plan.artifact_analysis_output_dir, - image_output_dir=plan.artifact_images_dir, + return ( + Path(source_path).name, + source_identity, ) @staticmethod @@ -927,7 +861,8 @@ def source_identity_for_path( path: str | Path, ) -> SourceImageIdentity | None: """Return microscope source identity for a source path when available.""" - parser = FunctionOutputParserContext.from_processing_context(context).parser + handler = context.microscope_handler + parser = handler.parser parsed = parser.parse_filename(Path(path).name) if parsed is None: return None @@ -939,7 +874,9 @@ def source_identity_for_path( components=( ( component, - SourceMetadataFields.canonical_component_value(component, value), + SourceMetadataFields.canonical_component_value( + component, value + ), ) for component, value in source_component_metadata_items( component_metadata @@ -948,155 +885,6 @@ def source_identity_for_path( ) ) - -def actual_materialization_records( - *, - store: RuntimeValueStore, - plan: CompiledStepPlan, - output_plan: ArtifactOutputPlan, -) -> tuple[StoredRuntimeValue, ...]: - """Return actually produced memory records for one planned artifact output.""" - if not output_plan.group_keys: - raise RuntimeError( - f"Artifact output plan '{output_plan.name}' has no group keys." - ) - reducer = ArtifactMaterializationRecordReducer.for_artifact_type( - output_plan.artifact_type - ) - - if output_plan.group_component is not None and tuple(output_plan.group_keys) == ( - None, - ): - dynamic_records = tuple( - record - for record in store.find( - name=output_plan.name, - artifact_type=output_plan.artifact_type, - axis_id=plan.axis_id, - ) - if record.key.scope.value_text is not None - and record.location.backend == Backend.MEMORY.value - and store.get(record.key).location == record.location - ) - if dynamic_records: - record_sort_items = [] - dynamic_group_keys = tuple( - dict.fromkeys( - str(record.key.scope.value_text) for record in dynamic_records - ) - ) - group_order = { - group_key: index - for index, group_key in enumerate(sorted(dynamic_group_keys)) - } - for group_key in dynamic_group_keys: - records_for_group = tuple( - record - for record in dynamic_records - if str(record.key.scope.value_text) == group_key - ) - for record in reducer.records_for_exact_scopes( - records=records_for_group, - output_plan=output_plan, - axis_id=plan.axis_id, - group_key=group_key, - ): - record_sort_items.append((group_order[group_key], record)) - return reducer.records_for_output( - records=tuple( - record - for _, record in sorted( - record_sort_items, - key=lambda item: item[0], - ) - ), - output_plan=output_plan, - ) - - group_order = { - group_key: index for index, group_key in enumerate(output_plan.group_keys) - } - record_sort_items = [] - missing_group_keys = [] - for group_key in output_plan.group_keys: - records = tuple( - record - for record in store.find( - name=output_plan.name, - artifact_type=output_plan.artifact_type, - axis_id=plan.axis_id, - group_key=group_key, - match_group=True, - ) - if record.location.backend == Backend.MEMORY.value - and store.get(record.key).location == record.location - ) - if not records: - missing_group_keys.append(group_key) - continue - for record in reducer.records_for_exact_scopes( - records=records, - output_plan=output_plan, - axis_id=plan.axis_id, - group_key=group_key, - ): - record_sort_items.append((group_order[group_key], record)) - - if missing_group_keys and not record_sort_items: - candidates = tuple( - store.find( - name=output_plan.name, - artifact_type=output_plan.artifact_type, - axis_id=plan.axis_id, - ) - ) - candidate_locations = tuple( - ( - candidate.key.scope.value_text, - candidate.location.backend, - candidate.location.path, - ) - for candidate in candidates - ) - identity_records = tuple( - candidate - for candidate in candidates - if candidate.key.scope.value_text is None - and candidate.location.backend == Backend.MEMORY.value - and store.get(candidate.key).location == candidate.location - ) - if identity_records: - return reducer.records_for_output( - records=identity_records, - output_plan=output_plan, - ) - raise RuntimeError( - f"Missing RuntimeValueStore record for planned artifact materialization " - f"'{output_plan.name}' ({output_plan.artifact_type.value}) on axis " - f"'{plan.axis_id}' groups {tuple(missing_group_keys)!r}. " - f"Candidate same-name records: " - f"{candidate_locations!r}." - ) - return reducer.records_for_output( - records=tuple( - record for _, record in sorted(record_sort_items, key=lambda item: item[0]) - ), - output_plan=output_plan, - ) - - -@dataclass(frozen=True, slots=True) -class RuntimeArtifactMaterialization: - """One exact compiled artifact value and its generic materialization target.""" - - output_plan: ArtifactOutputPlan - spec: MaterializationSpec - record: StoredRuntimeValue - data: MaterializationValue - base_path: Path - source_identity: SourceImageIdentity | None - filename_source_identity: SourceImageIdentity | None - @classmethod def from_record( cls, @@ -1119,11 +907,9 @@ def from_record( output_plan.materialization_uses_source_identity_filename() and emits_projected_planes ): - source_identity = ( - ArtifactStreamSourceMetadataAuthority.payload_source_identity(data) - ) + source_identity = cls.payload_source_identity(data) try: - record_source = AnalysisOutputDescriptorAuthority.record_source_descriptor( + record_source = cls._record_source_identity( context, plan, record, @@ -1131,7 +917,7 @@ def from_record( output_plan=output_plan, ) except IncompleteFunctionOutputFilenameIdentityError as exc: - if not AnalysisOutputDescriptorAuthority.missing_component_is_aggregated( + if not cls.missing_component_is_aggregated( exc.component_name, record.key.scope, tuple(plan.variable_components or ()), @@ -1141,27 +927,27 @@ def from_record( # The writer names each occurrence from its complete plane identity. record_source = None filename_source_identity = ( - None if record_source is None - else AnalysisOutputDescriptorAuthority.source_identity_for_path( - context, record_source.filename, + None + if record_source is None + else RuntimeArtifactMaterialization.source_identity_for_path( + context, + record_source[0], ) ) - aggregate_descriptor = ( - AnalysisOutputDescriptorAuthority.aggregate_descriptor( - output_plan.name, - plan, - scope=record.key.scope, - source_identity=source_identity, - ) + aggregate_filename, _, _ = cls._aggregate_identity( + output_plan.name, + plan, + scope=record.key.scope, + source_identity=source_identity, ) base_path = output_plan.artifact_type.projected_materialization_base_path( artifact_name=output_plan.name, - aggregate_filename=aggregate_descriptor.filename, + aggregate_filename=aggregate_filename, analysis_output_dir=plan.artifact_analysis_output_dir, image_output_dir=plan.artifact_images_dir, ) else: - output_descriptor = AnalysisOutputDescriptorAuthority.build( + filename, source_identity, source_filename = cls._analysis_identity( output_plan.name, plan, context, @@ -1171,18 +957,19 @@ def from_record( materialization_spec=spec, output_plan=output_plan, ) - base_path = AnalysisOutputDescriptorAuthority.materialization_base_path( - plan=plan, - output_descriptor=output_descriptor, - output_plan=output_plan, + base_path = output_plan.artifact_type.materialization_base_path( + descriptor_filename=filename, + source_filename=source_filename, + uses_source_identity_filename=( + output_plan.materialization_uses_source_identity_filename() + ), + analysis_output_dir=plan.artifact_analysis_output_dir, + image_output_dir=plan.artifact_images_dir, ) - source_identity = output_descriptor.source_identity filename_source_identity = ( - output_descriptor.source_identity - if output_descriptor.source_filename is None - else AnalysisOutputDescriptorAuthority.source_identity_for_path( - context, output_descriptor.source_filename, - ) + source_identity + if source_filename is None + else cls.source_identity_for_path(context, source_filename) ) return cls( output_plan=output_plan, @@ -1217,7 +1004,9 @@ def outputs( ) def reused_observation( - self, plan: CompiledStepPlan, context: "ProcessingContext", + self, + plan: CompiledStepPlan, + context: "ProcessingContext", ) -> StepExecutionObservation: """Report historical debug destinations and read their retained CSV text.""" from openhcs.core.orchestrator.analysis_consolidation import ( @@ -1230,10 +1019,12 @@ def reused_observation( backend = target.require_persistent_backend() outputs = self.outputs(plan, context) locations = ( - {RuntimeArtifactAddress.from_record(self.record): tuple( - RuntimeArtifactLocation(path=output.path, backend=backend) - for output in outputs - )} + { + RuntimeArtifactAddress.from_record(self.record): tuple( + RuntimeArtifactLocation(path=output.path, backend=backend) + for output in outputs + ) + } if self.spec.participates_in_persistent_materialization() else {} ) @@ -1243,8 +1034,11 @@ def reused_observation( else () ) return StepExecutionObservation( - MappingProxyType(locations), paths, - RuntimeAnalysisConsolidationInputs.from_reused_outputs(context, plan, self, outputs), + MappingProxyType(locations), + paths, + RuntimeAnalysisConsolidationInputs.from_reused_outputs( + context, plan, self, outputs + ), ) def viewer_outputs( @@ -1253,17 +1047,22 @@ def viewer_outputs( context: "ProcessingContext", ) -> tuple[Output, ...]: """Return exact writer outputs accepted by this step's viewer backends.""" - backend_plan = StreamingOnlyArtifactMaterializationTargetPlan().backend_plan( - plan, - context, - self, + surfaces = ( + StreamingOnlyArtifactMaterializationTargetPlan().streaming_viewer_surfaces( + plan, + context, + self, + ) ) return tuple( output for output in self.outputs(plan, context) - if backend_plan.supports_stream_output( - context.filemanager, - output, + if any( + context.filemanager._get_backend(backend).accepts_payload( + output.content, + output.path, + ) + for backend in surfaces ) ) @@ -1315,10 +1114,8 @@ def runtime_artifact_materializations_from_records( axis_id=plan.axis_id, ) ) - reducer = ArtifactMaterializationRecordReducer.for_artifact_type( - output_plan.artifact_type - ) - for record in reducer.records_for_output( + artifact_type = output_plan.artifact_type + for record in artifact_type.reduce_materialization_records( records=output_records, output_plan=output_plan, ): @@ -1344,7 +1141,9 @@ def preview_reused_step_outputs( return StepExecutionObservation.empty() return StepExecutionObservation.combine( item.reused_observation(plan, context) - for item in runtime_artifact_materializations_from_records(plan, context, records) + for item in runtime_artifact_materializations_from_records( + plan, context, records + ) ) @@ -1392,7 +1191,7 @@ def _planned_materialization_path( output_plan: ArtifactOutputPlan, materialization_spec: MaterializationSpec, ) -> PlannedArtifactMaterializationPath: - descriptor = AnalysisOutputDescriptorAuthority.build( + filename, _, _ = RuntimeArtifactMaterialization._analysis_identity( output_key, plan, context, @@ -1400,7 +1199,7 @@ def _planned_materialization_path( artifact_path=output_plan.path, output_plan=output_plan, ) - base_path = str(plan.artifact_analysis_output_dir / descriptor.filename) + base_path = str(plan.artifact_analysis_output_dir / filename) shared_output_stem = materialization_spec.shared_output_stem(base_path) return PlannedArtifactMaterializationPath( group_key=output_plan.single_group_key, @@ -1416,7 +1215,9 @@ class MaterializedRuntimeArtifact(SavedMaterializationOutputs): materialization: RuntimeArtifactMaterialization def observation( - self, plan: CompiledStepPlan, context: "ProcessingContext", + self, + plan: CompiledStepPlan, + context: "ProcessingContext", ) -> StepExecutionObservation: target = plan.runtime_artifact_materialization if not target.has_persistent_target: @@ -1440,71 +1241,7 @@ def observation( ) return StepExecutionObservation( - MappingProxyType({address: locations}), paths, + MappingProxyType({address: locations}), + paths, RuntimeAnalysisConsolidationInputs.from_saved_outputs(context, plan, self), ) - - -def materialize_artifact_outputs( - filemanager: "FileManager", - plan: CompiledStepPlan, - target_plan: ArtifactMaterializationTargetPlan, - context: "ProcessingContext", -) -> tuple[MaterializedRuntimeArtifact, ...]: - """Save each exact artifact batch once and return its successful outputs.""" - saved_materializations = [] - images_dir = plan.artifact_images_dir - - for materialization in runtime_artifact_materializations(plan, context): - backend_plan = target_plan.backend_plan(plan, context, materialization) - record = materialization.record - data = materialization.data - filemanager.ensure_directory(Path(record.location.path).parent, record.location.backend) - stream_output_paths = materialization.spec.candidate_paths( - str(materialization.base_path) - ) - backends = backend_plan.backends_for( - materialization_spec=materialization.spec, - filemanager=filemanager, - stream_output_paths=stream_output_paths, - ) - if not backends: - continue - batch = prepare_materialization( - materialization.spec, - data, - str(materialization.base_path), - filemanager, - backends, - backend_plan.backend_kwargs( - materialization_spec=materialization.spec, - data=data, - fallback_source_identity=( - materialization.filename_source_identity - if materialization.spec.uses_filename_source_identity(data) - else materialization.source_identity - ), - producer_identity=( - plan.producer_identity_for_artifact(materialization.output_plan) - ), - context=context, - filemanager=filemanager, - images_dir=images_dir, - stream_output_paths=stream_output_paths, - ), - context=context, - artifact_source_identity=materialization.source_identity, - artifact_filename_identity=materialization.filename_source_identity, - variable_components=materialization.output_plan.variable_components, - pipeline_position=plan.pipeline_position, - output_plan=materialization.output_plan, - ) - saved_materializations.append( - MaterializedRuntimeArtifact( - outputs_by_backend=MappingProxyType( - dict(batch.save().outputs_by_backend) - ), - materialization=materialization, - ) - ) - return tuple(saved_materializations) diff --git a/openhcs/core/steps/function_execution.py b/openhcs/core/steps/function_execution.py index 17724ef765..efd2251dc8 100644 --- a/openhcs/core/steps/function_execution.py +++ b/openhcs/core/steps/function_execution.py @@ -6,7 +6,6 @@ import time import traceback from collections.abc import Callable, Mapping, Sequence -from dataclasses import dataclass from itertools import zip_longest from typing import TYPE_CHECKING @@ -76,23 +75,6 @@ ] -def record_function_step_runtime_profile( - plan: CompiledStepPlan, - label: str, - seconds: float, - *, - extra_fields: RuntimeProfileExtraFields = None, -) -> None: - """Record one runtime profile event for a function-step plan.""" - fields: dict[str, RuntimeProfileFieldValue] = { - "step": plan.step_index, - "step_name": plan.step_name, - } - if extra_fields is not None: - fields.update(extra_fields) - RuntimeProfileLogger.log(logger, label, seconds, **fields) - - def _single_execution_group_patterns( patterns: DiscoveredPatternCollection, ) -> Sequence[SourceCandidatePath]: @@ -439,8 +421,7 @@ def default_source_bound_anchor_patterns( before_count = sum(map(len, grouped_patterns.values())) after_count = sum(map(len, filtered.values())) if before_count != after_count: - record_function_step_runtime_profile( - self.plan, + self.record_runtime_profile( "step_filter_source_anchors", 0.0, extra_fields={ @@ -539,8 +520,7 @@ def apply( before_count = sum(map(len, grouped_patterns.values())) after_count = sum(map(len, filtered.values())) if before_count != after_count: - record_function_step_runtime_profile( - self.plan, + self.record_runtime_profile( label, 0.0, extra_fields={ @@ -553,9 +533,7 @@ def apply( def source_pattern_context(self) -> SourcePatternResolutionContext: """Return source-path context used to filter source-bound anchors.""" - projection = ( - self.context.runtime_source_workspace_projection_authority.projection_or_empty() - ) + projection = self.context.runtime_source_workspace_projection_authority.projection_or_empty() return self.context.runtime_source_binding_context_cache.source_pattern_context( parser=self.context.microscope_handler.parser, projection=self.context.runtime_source_workspace_projection_cache.filtered_by_axis( @@ -572,12 +550,13 @@ def record_runtime_profile( *, extra_fields: RuntimeProfileExtraFields = None, ) -> None: - record_function_step_runtime_profile( - self.plan, - label, - seconds, - extra_fields=extra_fields, - ) + fields: dict[str, RuntimeProfileFieldValue] = { + "step": self.plan.step_index, + "step_name": self.plan.step_name, + } + if extra_fields is not None: + fields.update(extra_fields) + RuntimeProfileLogger.log(logger, label, seconds, **fields) @classmethod def execute( @@ -625,7 +604,9 @@ def candidate_scopes( return RuntimeArtifactInput( edge_plan=edge, axis_scope=RuntimeExecutionAxisScope.from_raw( - plan.axis_id, component=None, value=None, + plan.axis_id, + component=None, + value=None, ), backend=Backend.MEMORY.value, source_binding_plan=plan.source_binding_plan, @@ -669,12 +650,16 @@ def candidate_scopes( selected_groups.append((component_key, group, edges)) requests = [] - for component_index, (component_key, group, edges) in enumerate(selected_groups): + for component_index, (component_key, group, edges) in enumerate( + selected_groups + ): cohorts = None for edge in edges: edge_cohorts = candidate_scopes( edge, - ComponentGroupScope.from_raw((component_key,), component=scope.component), + ComponentGroupScope.from_raw( + (component_key,), component=scope.component + ), ) if not edge_cohorts: raise ValueError( @@ -832,9 +817,7 @@ def _detect_patterns(self) -> dict[str, DiscoveredPatternCollection]: axis_filter = {f"{axis_name}_filter": [plan.axis_id]} source_files = step_output_manifest(self.context).producer_paths_for(plan) if source_files is None: - source_projection = ( - self.context.runtime_source_workspace_projection_authority.projection_if_available() - ) + source_projection = self.context.runtime_source_workspace_projection_authority.projection_if_available() if ( plan.main_input_dependency.kind is StepInputDependencyKind.PIPELINE_START diff --git a/openhcs/core/steps/function_output_identity.py b/openhcs/core/steps/function_output_identity.py index 98ef10c7d3..ba429c253f 100644 --- a/openhcs/core/steps/function_output_identity.py +++ b/openhcs/core/steps/function_output_identity.py @@ -5,7 +5,7 @@ from dataclasses import dataclass, field, replace from pathlib import Path import re -from typing import TYPE_CHECKING, ClassVar, Mapping, Sequence, TypeAlias +from typing import ClassVar, Mapping, Sequence, TypeAlias from openhcs.core.source_path_identity import source_path_identity from openhcs.constants.constants import AllComponents, VariableComponents @@ -30,9 +30,6 @@ from openhcs.core.source_projection import OpenHCSPlaneAddress from openhcs.microscopes.microscope_interfaces import FilenameParser -if TYPE_CHECKING: - from openhcs.core.context.processing_context import ProcessingContext - ParsedFilenameValue: TypeAlias = str | int | float | bool | None FunctionOutputComponentValue: TypeAlias = str | int FunctionOutputComponentValues: TypeAlias = Mapping[str, FunctionOutputComponentValue] @@ -122,6 +119,36 @@ class FunctionOutputIdentity: ) filename_qualifier: str | None = field(default=None, kw_only=True) + @staticmethod + def validate_output_paths( + output_paths: Sequence[str], + *, + input_paths: Sequence[str], + step_name: str, + pattern_repr: str, + identities: Sequence[FunctionOutputIdentity] = (), + ) -> None: + """Reject filename collisions before publishing a resolved output batch.""" + counts: dict[str, int] = {} + for path in output_paths: + counts[path] = counts.get(path, 0) + 1 + duplicates = tuple(path for path, count in counts.items() if count > 1) + if not duplicates: + return + details = tuple( + f"#{index}: input={input_paths[index] if index < len(input_paths) else None!r}, " + f"output={output_paths[index]!r}, " + f"identity={dict(identity.component_values)!r}, " + f"filename_identity={dict(identity.filename_values)!r}, " + f"source={identity.source!r}" + for index, identity in enumerate(identities) + ) + raise ValueError( + f"Step {step_name!r} produced duplicate output path(s) " + f"for pattern {pattern_repr}: {duplicates!r}. Input files: " + f"{tuple(input_paths)!r}. Output identity details: {details!r}." + ) + @property def filename_values(self) -> FunctionOutputComponentValues: """Storage coordinates, distinct from collapsed semantic components.""" @@ -165,14 +192,17 @@ def filename_component_metadata(self) -> SourceComponentMetadata: def with_filename_qualifier(self, qualifier: str) -> "FunctionOutputIdentity": """Return this identity qualified by a declared output surface name.""" return replace( - self, filename_qualifier=self._normalize_filename_qualifier(qualifier), + self, + filename_qualifier=self._normalize_filename_qualifier(qualifier), ) def without_filename_qualifier(self) -> "FunctionOutputIdentity": """Return this identity without its output-surface filename qualifier.""" return replace(self, filename_qualifier=None) - _unsafe_qualifier_pattern: ClassVar[re.Pattern[str]] = re.compile(r"[^A-Za-z0-9_.-]+") + _unsafe_qualifier_pattern: ClassVar[re.Pattern[str]] = re.compile( + r"[^A-Za-z0-9_.-]+" + ) @classmethod def _normalize_filename_qualifier(cls, value: str) -> str: @@ -185,7 +215,8 @@ def _normalize_filename_qualifier(cls, value: str) -> str: def path_for_request(self, request: FunctionOutputPathRequest) -> Path: """Construct this identity's path in the request's output directory.""" return Path(request.output_dir) / self.cached_filename( - request.parser, request.identity_cache, + request.parser, + request.identity_cache, ) @classmethod @@ -214,7 +245,9 @@ def filename(self, parser: FilenameParser) -> str: bound = parser.bind_component_values(component_values, extension=extension) filename = parser.construct_filename(bound) return self._qualified_filename( - filename, self.filename_qualifier, extension=bound.extension, + filename, + self.filename_qualifier, + extension=bound.extension, ) except MissingFilenameComponentError as exc: raise IncompleteFunctionOutputFilenameIdentityError( @@ -239,15 +272,22 @@ def _construction_error_message( @staticmethod def _qualified_filename( - filename: str, qualifier: str | None, *, extension: str, + filename: str, + qualifier: str | None, + *, + extension: str, ) -> str: if qualifier is None: return filename if not filename.endswith(extension): - raise ValueError("Constructed filename does not retain its declared extension.") + raise ValueError( + "Constructed filename does not retain its declared extension." + ) return f"{filename[:-len(extension)]}_{qualifier}{extension}" - def _filename_cache_key(self, parser: FilenameParser) -> FunctionOutputFilenameCacheKey: + def _filename_cache_key( + self, parser: FilenameParser + ) -> FunctionOutputFilenameCacheKey: return FunctionOutputFilenameCacheKey( parser_id=id(parser), component_values=tuple( @@ -305,7 +345,9 @@ def _extension_from_source( extension = cls._extension_from_metadata(metadata) if extension is not None: return extension - return cls._extension_from_path(path, parser=parser, identity_cache=identity_cache) + return cls._extension_from_path( + path, parser=parser, identity_cache=identity_cache + ) @staticmethod def _extension_from_raw(raw_extension: ParsedFilenameValue) -> str | None: @@ -324,7 +366,9 @@ def _component_values_from_source_metadata( if metadata is None: return {} return { - component.value: SourceMetadataFields.canonical_component_value(component, value) + component.value: SourceMetadataFields.canonical_component_value( + component, value + ) for component, value in source_component_metadata_items(metadata) } @@ -334,7 +378,9 @@ def component_values_from_parsed( parsed: FilenameParseResult, ) -> dict[str, FunctionOutputComponentValue]: return { - str(component.value): SourceMetadataFields.canonical_component_value(component, value) + str(component.value): SourceMetadataFields.canonical_component_value( + component, value + ) for component, value in parsed.declared_values() if value is not None } @@ -483,8 +529,10 @@ def _identity_from_metadata_uncached( identity = cls._identity_from_metadata( metadata.source_component_metadata, extension=cls._extension_from_source( - metadata.source_component_metadata, metadata.source_path, - parser=parser, identity_cache=identity_cache, + metadata.source_component_metadata, + metadata.source_path, + parser=parser, + identity_cache=identity_cache, ), source="payload component metadata", ) @@ -538,8 +586,10 @@ def _identity_from_metadata_uncached( identity = cls._identity_from_metadata( source_identity.component_metadata, extension=cls._extension_from_source( - source_identity.component_metadata, source_identity.path, - parser=parser, identity_cache=identity_cache, + source_identity.component_metadata, + source_identity.path, + parser=parser, + identity_cache=identity_cache, ), source="single represented payload source metadata", ) @@ -597,8 +647,10 @@ def from_filename_metadata( identity = cls._identity_from_metadata( metadata.source_component_metadata, extension=cls._extension_from_source( - metadata.source_component_metadata, metadata.source_path, - parser=parser, identity_cache=identity_cache, + metadata.source_component_metadata, + metadata.source_path, + parser=parser, + identity_cache=identity_cache, ), source="payload component metadata", ) @@ -720,9 +772,7 @@ def _parsed_path_identity( if parsed is None: return None return FunctionOutputIdentity( - component_values=cls.component_values_from_parsed( - parsed - ), + component_values=cls.component_values_from_parsed(parsed), extension=parsed.extension, source=source, ) @@ -797,8 +847,10 @@ def _source_stack_source_identity( identity = cls._identity_from_metadata( source_identity.component_metadata, extension=cls._extension_from_source( - source_identity.component_metadata, source_identity.path, - parser=parser, identity_cache=identity_cache, + source_identity.component_metadata, + source_identity.path, + parser=parser, + identity_cache=identity_cache, ), source=f"represented source identity {identity_index} metadata", ) @@ -1018,9 +1070,7 @@ def _identity_from_metadata( extension: str | None, source: str, ) -> FunctionOutputIdentity | None: - component_values = ( - cls._component_values_from_source_metadata(metadata) - ) + component_values = cls._component_values_from_source_metadata(metadata) if not component_values: return None return FunctionOutputIdentity( @@ -1028,30 +1078,3 @@ def _identity_from_metadata( extension=extension, source=source, ) - - -@dataclass(frozen=True, slots=True) -class FunctionOutputParserContext: - """Parser-facing microscope context for FunctionStep output finalization.""" - - parser: FilenameParser - microscope_type: str - - @classmethod - def from_processing_context( - cls, - context: "ProcessingContext", - ) -> "FunctionOutputParserContext": - handler = context.microscope_handler - return cls( - parser=handler.parser, - microscope_type=handler.microscope_type, - ) - - @property - def parser_name(self) -> str: - return self.parser.__class__.__name__ - - def parse_path_metadata(self, path: str | Path) -> SourceComponentMetadata | None: - parsed = self.parser.parse_filename(source_path_identity(str(path)).name) - return None if parsed is None else parsed.wire_mapping() diff --git a/openhcs/core/steps/function_output_manifest.py b/openhcs/core/steps/function_output_manifest.py index ba0e610998..139527fd39 100644 --- a/openhcs/core/steps/function_output_manifest.py +++ b/openhcs/core/steps/function_output_manifest.py @@ -422,7 +422,8 @@ def image_records_for( ) -> tuple[ProducedOutputSemantics, ...]: """Select image occurrences directly from this step's current producer cohort.""" return tuple( - record for record in self.produced_records_for(plan) + record + for record in self.produced_records_for(plan) if record.is_image_payload ) @@ -453,12 +454,15 @@ def producer_output_records_for_paths( return None if index is None else index.records_for_paths(paths) def producer_record_index_for( - self, plan: CompiledStepPlan, parser: FilenameParser, + self, + plan: CompiledStepPlan, + parser: FilenameParser, ) -> ProducedPathRecordIndex | None: """Admit one current producer cohort with its correlated address aliases.""" records = self._selected_unique_producer_records_for(plan, path_ordered=True) return ( - None if records is None + None + if records is None else ProducedPathRecordIndex.from_records(records, parser) ) @@ -510,7 +514,10 @@ def _unique_output_path_records( records_by_path: dict[str, ProducedOutputSemantics] = {} for record in records: existing = records_by_path.get(record.output_path) - if existing is not None and existing.main_flow_plane_axis is not record.main_flow_plane_axis: + if ( + existing is not None + and existing.main_flow_plane_axis is not record.main_flow_plane_axis + ): raise ValueError( "One produced output path cannot declare conflicting main-flow image axes: " f"{record.output_path!r}." @@ -654,11 +661,13 @@ def contains(self, path: str) -> bool: return next(self.matching_tokens(path), None) is not None def matching_records(self, path: str) -> tuple[ProducedOutputSemantics, ...]: - indices = sorted({ - index - for token in self.matching_tokens(path) - for index in self.record_indices_by_token[token] - }) + indices = sorted( + { + index + for token in self.matching_tokens(path) + for index in self.record_indices_by_token[token] + } + ) return tuple(self.records[index] for index in indices) def record_for_path(self, path: str) -> ProducedOutputSemantics: @@ -672,12 +681,14 @@ def record_for_path(self, path: str) -> ProducedOutputSemantics: return records[0] def records_for_paths( - self, paths: Sequence[str], + self, + paths: Sequence[str], ) -> tuple[ProducedOutputSemantics, ...]: return tuple(self.record_for_path(path) for path in paths) def validate_input_records( - self, records: Sequence[ProducedOutputSemantics], + self, + records: Sequence[ProducedOutputSemantics], ) -> None: """Validate address cardinality while retaining the already-selected cohort.""" for record in records: diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index 82eb17a7e6..06d236eaec 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -26,7 +26,6 @@ from openhcs.core.axis_filter import step_axis_allows_config from openhcs.core.compiled_step_plan import ( CompiledStepPlan, - RuntimeArtifactMaterializationPlan, ) from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.image_file_serialization import ( @@ -58,10 +57,8 @@ ) from openhcs.core.steps.abstract import StepExecutionObservation from openhcs.core.steps.function_artifact_materialization import ( + ArtifactMaterializationTargetPlan, MaterializedRuntimeArtifact, - PersistentArtifactMaterializationTargetPlan, - StreamingOnlyArtifactMaterializationTargetPlan, - materialize_artifact_outputs, ) from openhcs.core.steps.function_io import ( prepare_storage_image_payloads, @@ -70,7 +67,6 @@ ) from openhcs.core.steps.function_output_identity import ( FunctionOutputIdentity, - FunctionOutputParserContext, ) from openhcs.core.steps.function_output_manifest import ( ProducedOutputSemantics, @@ -117,10 +113,8 @@ def finalize_function_step_outputs( MemoryOutputWriter.write_if_needed(context, plan) MaterializedImageOutputWriter.write_if_needed(context, plan) StreamOutputsAuthority.stream_outputs(context, plan) - materializations = RuntimeArtifactMaterializationAuthority.materialize( - context, plan - ) - OpenHCSMetadataWriter.write( + materializations = ArtifactMaterializationTargetPlan.materialize(context, plan) + OpenHCSMetadataTarget.write_for_step( context, plan, artifact_materializations=materializations ) else: @@ -141,12 +135,12 @@ def finalize_function_step_outputs( ) materializations = _profile_finalization_phase( "finalize_runtime_artifacts", - lambda: RuntimeArtifactMaterializationAuthority.materialize(context, plan), + lambda: ArtifactMaterializationTargetPlan.materialize(context, plan), plan, ) _profile_finalization_phase( "finalize_openhcs_metadata", - lambda: OpenHCSMetadataWriter.write( + lambda: OpenHCSMetadataTarget.write_for_step( context, plan, artifact_materializations=materializations ), plan, @@ -198,11 +192,12 @@ def write_if_needed( Backend.MEMORY.value, ) output_paths = [ - record.path_under(plan.output_dir) - for record in produced_outputs + record.path_under(plan.output_dir) for record in produced_outputs ] - parser_context = FunctionOutputParserContext.from_processing_context(context) - row, col = parser_context.parser.extract_component_coordinates(plan.axis_id) + handler = context.microscope_handler + parser = handler.parser + microscope_type = handler.microscope_type + row, col = parser.extract_component_coordinates(plan.axis_id) context.filemanager.ensure_directory( plan.output_dir, plan.write_backend, @@ -227,8 +222,8 @@ def write_if_needed( ), row=row, col=col, - parser_name=parser_context.parser_name, - microscope_type=parser_context.microscope_type, + parser_name=parser.__class__.__name__, + microscope_type=microscope_type, **({"tiff_config": config} if config is not None else {}), ) @@ -258,10 +253,7 @@ def write_if_needed( return produced_outputs = step_output_manifest(context).image_records_for(plan) - memory_paths = [ - record.memory_path(plan) - for record in produced_outputs - ] + memory_paths = [record.memory_path(plan) for record in produced_outputs] if not produced_outputs: return memory_data = context.filemanager.load_batch( @@ -363,7 +355,10 @@ def from_projection( items: list[StreamOutputItem] = [] for payload, path, produced_output in zip( - payloads, paths, produced_outputs, strict=True, + payloads, + paths, + produced_outputs, + strict=True, ): projected_items = tuple( cls.project_item( @@ -419,7 +414,10 @@ def from_projection_groups( tuple[str, ...], list[tuple[StreamPayload, str, ProducedOutputSemantics]] ] = {} for payload, path, produced_output in zip( - payloads, paths, produced_outputs, strict=True, + payloads, + paths, + produced_outputs, + strict=True, ): projection = produced_output.producer_identity.route_parts() projections.setdefault(projection, []).append( @@ -545,10 +543,7 @@ def stream_outputs( ) continue produced_outputs = step_output_manifest(context).image_records_for(plan) - memory_paths = [ - record.memory_path(plan) - for record in produced_outputs - ] + memory_paths = [record.memory_path(plan) for record in produced_outputs] if not memory_paths: logger.info( "No produced image outputs to stream for step %s.", @@ -618,399 +613,386 @@ def stream_outputs( ) -class OpenHCSMetadataWriter: - """Publish the declared storage targets' durable source projections.""" +@dataclass(frozen=True) +class OpenHCSMetadataTarget(ABC, metaclass=AutoRegisterMeta): + """One compiled output location projected into OpenHCS metadata.""" - @dataclass(frozen=True) - class OutputTarget(ABC, metaclass=AutoRegisterMeta): - """One compiled output location projected into OpenHCS metadata.""" + __registry_family__ = RegistryFamily("declaration_key") + __key_extractor__ = staticmethod(extract_key_from_class_name) + declaration_key: ClassVar[str | None] = None + is_main: ClassVar[bool] = False - __registry_family__ = RegistryFamily("declaration_key") - __key_extractor__ = staticmethod(extract_key_from_class_name) - declaration_key: ClassVar[str | None] = None - is_main: ClassVar[bool] = False + output_dir: Path + backend: str + plate_root: str + sub_dir: str + results_dir: str | None + artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = field( + default=(), compare=False, hash=False, repr=False + ) - output_dir: Path - backend: str - plate_root: str - sub_dir: str - results_dir: str | None - artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = field( - default=(), compare=False, hash=False, repr=False + @classmethod + @abstractmethod + def from_plan(cls, plan: CompiledStepPlan) -> OpenHCSMetadataTarget | None: + """Resolve this declaration's independently compiled storage target.""" + + @classmethod + def for_plan(cls, plan: CompiledStepPlan) -> tuple[OpenHCSMetadataTarget, ...]: + """Derive targets from their declarations, without a consumer roster.""" + return tuple( + target + for declaration in cls.__registry__.values() + if (target := declaration.from_plan(plan)) is not None ) - @classmethod - @abstractmethod - def from_plan( - cls, plan: CompiledStepPlan - ) -> OpenHCSMetadataWriter.OutputTarget | None: - """Resolve this declaration's independently compiled storage target.""" - - @classmethod - def for_plan( - cls, plan: CompiledStepPlan - ) -> tuple[OpenHCSMetadataWriter.OutputTarget, ...]: - """Derive targets from their declarations, without a consumer roster.""" - return tuple( - target - for declaration in cls.__registry__.values() - if (target := declaration.from_plan(plan)) is not None - ) + @classmethod + def from_execution( + cls, context: ProcessingContext, plan: CompiledStepPlan + ) -> OpenHCSMetadataTarget | None: + """Resolve the target participating in this step's publication.""" + return cls.from_plan(plan) + + @classmethod + def for_execution( + cls, + context: ProcessingContext, + plan: CompiledStepPlan, + *, + artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = (), + ) -> tuple[OpenHCSMetadataTarget, ...]: + return tuple( + target + 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 + ).production_targets(context, plan) + ) - @classmethod - def from_execution( - cls, context: ProcessingContext, plan: CompiledStepPlan - ) -> OpenHCSMetadataWriter.OutputTarget | None: - """Resolve the target participating in this step's publication.""" - return cls.from_plan(plan) - - @classmethod - def for_execution( - cls, - context: ProcessingContext, - plan: CompiledStepPlan, - *, - artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = (), - ) -> tuple[OpenHCSMetadataWriter.OutputTarget, ...]: - return tuple( - target - 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 - ).production_targets(context, plan) + def production_targets( + self, + context: ProcessingContext, + plan: CompiledStepPlan, + ) -> tuple[OpenHCSMetadataTarget, ...]: + """Project this declaration's exact storage destinations for the step.""" + return (self,) + + def reconciliation_targets( + self, context: ProcessingContext + ) -> tuple[OpenHCSMetadataTarget, ...]: + """Resolve destinations after runtime values have been released.""" + return (self,) + + def produced_records( + self, context: ProcessingContext, plan: CompiledStepPlan + ) -> tuple[ProducedOutputSemantics, ...]: + """Targets without main-flow image storage have no produced records.""" + return () + + def runtime_artifact_projection_paths( + self, + context: ProcessingContext, + plan: CompiledStepPlan, + *, + produced_projections: Mapping[ + Path, tuple[ProducedOutputSemantics, SourceProjection] + ] = MappingProxyType({}), + ) -> tuple[tuple[SourceArtifactProjection, str], ...]: + """Publish artifacts persisted in this declared storage target.""" + materialization = plan.runtime_artifact_materialization + if materialization.persists_to_backend(self.backend): + return self.project_runtime_artifacts( + context, plan, produced_projections=produced_projections ) + return () - def production_targets( - self, - context: ProcessingContext, - plan: CompiledStepPlan, - ) -> tuple[OpenHCSMetadataWriter.OutputTarget, ...]: - """Project this declaration's exact storage destinations for the step.""" - return (self,) - - def reconciliation_targets( - self, context: ProcessingContext - ) -> tuple[OpenHCSMetadataWriter.OutputTarget, ...]: - """Resolve destinations after runtime values have been released.""" - return (self,) - - def produced_records( - self, context: ProcessingContext, plan: CompiledStepPlan - ) -> tuple[ProducedOutputSemantics, ...]: - """Targets without main-flow image storage have no produced records.""" - return () - - def runtime_artifact_projection_paths( - self, - context: ProcessingContext, - plan: CompiledStepPlan, - *, - produced_projections: Mapping[ - Path, tuple[ProducedOutputSemantics, SourceProjection] - ] = MappingProxyType({}), - ) -> tuple[tuple[SourceArtifactProjection, str], ...]: - """Publish artifacts persisted in this declared storage target.""" - materialization = plan.runtime_artifact_materialization - if materialization.persists_to_backend(self.backend): - return self.project_runtime_artifacts( - context, plan, produced_projections=produced_projections - ) - return () + def stored_output_paths(self, context: ProcessingContext) -> tuple[str, ...]: + """Return this declaration's outputs eligible for publication.""" + return tuple( + context.filemanager.list_image_files(self.output_dir, self.backend) + ) + + def contains_outputs(self, context: ProcessingContext) -> bool: + """Return whether this declared destination has publishable outputs.""" - def stored_output_paths(self, context: ProcessingContext) -> tuple[str, ...]: - """Return this declaration's outputs eligible for publication.""" - return tuple( - context.filemanager.list_image_files(self.output_dir, self.backend) + if context.filemanager is None: + raise ValueError("OpenHCS metadata requires a file manager.") + if not context.filemanager.is_dir(self.output_dir, self.backend): + return False + return bool(self.stored_output_paths(context)) + + def write( + self, + context: ProcessingContext, + *, + produced_plan: CompiledStepPlan | None = None, + ) -> None: + """Project the target's current storage state into plate metadata.""" + + if context.filemanager is None: + raise ValueError("OpenHCS metadata requires a file manager.") + if context.metadata_cache is None: + raise ValueError("Produced metadata requires declared component labels.") + projection_entries = self.produced_projection_entries(context, produced_plan) + handler = context.microscope_handler + parser = handler.parser + microscope_type = handler.microscope_type + saved_image_paths = tuple( + str(Path(path).relative_to(self.plate_root)) + for path in context.filemanager.list_image_files( + str(self.output_dir), self.backend ) + ) + AtomicMetadataWriter().publish_source_projection_metadata( + METADATA_CONFIG.metadata_path(self.plate_root), + self.sub_dir, + projection_entries, + serializer=SourceProjectionMetadataSerializer(parser), + saved_image_paths=saved_image_paths, + microscope_handler_name=microscope_type, + source_filename_parser_name=parser.__class__.__name__, + component_labels=context.metadata_cache, + backend=self.backend, + is_main=self.is_main, + results_dir=( + str(Path(self.results_dir).relative_to(self.plate_root)) + if self.results_dir is not None + else None + ), + ) - def contains_outputs(self, context: ProcessingContext) -> bool: - """Return whether this declared destination has publishable outputs.""" - - if context.filemanager is None: - raise ValueError("OpenHCS metadata requires a file manager.") - if not context.filemanager.is_dir(self.output_dir, self.backend): - return False - return bool(self.stored_output_paths(context)) - - def write( - self, - context: ProcessingContext, - *, - produced_plan: CompiledStepPlan | None = None, - ) -> None: - """Project the target's current storage state into plate metadata.""" - - if context.filemanager is None: - raise ValueError("OpenHCS metadata requires a file manager.") - if context.metadata_cache is None: - raise ValueError( - "Produced metadata requires declared component labels." - ) - projection_entries = self.produced_projection_entries( - context, produced_plan + def produced_projection_entries( + self, + context: ProcessingContext, + plan: CompiledStepPlan | None, + ) -> VirtualWorkspaceSourceProjectionEntries | None: + """Project the current saved plan while its typed memory outputs remain.""" + if plan is None: + return None # Plate reconciliation must not reload cleaned step memory. + if context.filemanager is None: + 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 + ).production_targets(context, plan): + raise ValueError("Produced metadata plan does not own this output target.") + records = self.produced_records(context, plan) + payloads = ( + context.filemanager.load_batch( + [record.memory_path(plan) for record in records], + Backend.MEMORY.value, ) - parser_context = FunctionOutputParserContext.from_processing_context( - context + if records + else () + ) + projection_paths = [] + produced_projections = {} + declared_addresses: set[OpenHCSPlaneAddress] = set() + for record, payload in zip(records, payloads, strict=True): + destination = record.path_under(self.output_dir) + virtual_path = str(Path(destination).relative_to(self.plate_root)) + metadata = self.persisted_image_metadata( + context, + destination=destination, + payload=payload, ) - saved_image_paths = tuple( - str(Path(path).relative_to(self.plate_root)) - for path in context.filemanager.list_image_files( - str(self.output_dir), self.backend - ) + source_metadata = record.source_metadata_for_projection( + metadata, destination ) - AtomicMetadataWriter().publish_source_projection_metadata( - METADATA_CONFIG.metadata_path(self.plate_root), - self.sub_dir, - projection_entries, - serializer=SourceProjectionMetadataSerializer(parser_context.parser), - saved_image_paths=saved_image_paths, - microscope_handler_name=parser_context.microscope_type, - source_filename_parser_name=parser_context.parser_name, - component_labels=context.metadata_cache, - backend=self.backend, - is_main=self.is_main, - results_dir=( - str(Path(self.results_dir).relative_to(self.plate_root)) - if self.results_dir is not None else None - ), + address = ( + None + if metadata.persists_whole_image() + else OpenHCSPlaneAddress.from_complete_source_metadata(source_metadata) ) - - def produced_projection_entries( - self, - context: ProcessingContext, - plan: CompiledStepPlan | None, - ) -> VirtualWorkspaceSourceProjectionEntries | None: - """Project the current saved plan while its typed memory outputs remain.""" - if plan is None: - return None # Plate reconciliation must not reload cleaned step memory. - if context.filemanager is None: - 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 - ).production_targets(context, plan): - raise ValueError( - "Produced metadata plan does not own this output target." + if address is None: + projection_paths.append( + ( + SourceArtifactProjection( + address=None, + ref=SourcePixelRef(self.backend, virtual_path), + source_alias=record.producer_identity.output_key, + artifact_kind=ImageArtifactType, + source_metadata=source_metadata, + image_metadata=metadata, + execution_scope=record.execution_scope(plan), + ), + virtual_path, + ) ) - records = self.produced_records(context, plan) - payloads = ( - context.filemanager.load_batch( - [ - record.memory_path(plan) - for record in records - ], - Backend.MEMORY.value, + produced_projections[Path(destination)] = ( + record, + projection_paths[-1][0], + ) + continue + if address not in declared_addresses: + declared_addresses.add(address) + projection_paths.append( + ( + SourcePlaneProjection( + address=address, + ref=SourcePixelRef(self.backend, virtual_path), + source_alias=record.output_context.persisted_source_alias, + source_metadata=source_metadata, + image_metadata=metadata, + ), + virtual_path, + ) ) - if records - else () + produced_projections[Path(destination)] = ( + record, + projection_paths[-1][0], + ) + continue + projection_paths.append( + ( + SourceArtifactProjection( + address=address, + ref=SourcePixelRef(self.backend, virtual_path), + source_alias=record.producer_identity.output_key, + artifact_kind=ImageArtifactType, + source_metadata=source_metadata, + image_metadata=metadata, + ), + virtual_path, + ) + ) + produced_projections[Path(destination)] = ( + record, + projection_paths[-1][0], ) - projection_paths = [] - produced_projections = {} - declared_addresses: set[OpenHCSPlaneAddress] = set() - for record, payload in zip(records, payloads, strict=True): - destination = record.path_under(self.output_dir) + projection_paths.extend( + self.runtime_artifact_projection_paths( + context, plan, produced_projections=produced_projections + ) + ) + if not projection_paths: + return None + return VirtualWorkspaceSourceProjectionEntries.from_projection_paths( + projection_paths + ) + + def project_runtime_artifacts( + self, + context: ProcessingContext, + plan: CompiledStepPlan, + *, + produced_projections: Mapping[ + Path, tuple[ProducedOutputSemantics, SourceProjection] + ] = MappingProxyType({}), + ) -> tuple[tuple[SourceArtifactProjection, str], ...]: + """Project persisted image artifacts into the target source authority.""" + + projection_paths = [] + for saved_artifact in self.artifact_materializations: + materialization = saved_artifact.materialization + for output in saved_artifact.outputs_for_backend(self.backend): + if not ImageFileFormat.is_image_path(output.path) or Path( + output.path + ).parent != Path(self.output_dir): + continue + if output.metadata is None: + raise ValueError( + f"Image artifact {output.path!r} has no typed image " + "metadata." + ) + destination = output.path virtual_path = str(Path(destination).relative_to(self.plate_root)) + payload = output.metadata.attach_to(output.content) metadata = self.persisted_image_metadata( context, destination=destination, payload=payload, ) - source_metadata = record.source_metadata_for_projection( - metadata, destination + address = SourceArtifactProjection.scalar_address_for_image_metadata( + metadata ) - address = ( - None if metadata.persists_whole_image() - else OpenHCSPlaneAddress.from_complete_source_metadata(source_metadata) + produced = produced_projections.get(Path(destination)) + if produced is not None: + record, projection = produced + if record.owns_persisted_artifact( + materialization.output_plan, destination, self.output_dir + ): + if ( + projection.address != address + or projection.image_metadata != metadata + or ( + address is None + and projection.execution_scope + != materialization.record.key.scope + ) + ): + raise ValueError( + "Conflicting metadata for persisted image " + f"occurrence {destination!r}." + ) + continue + source_metadata = metadata.source_component_metadata or {} + persisted_source_metadata = dict(source_metadata) + metadata.source_voxel_spacing.merge_into( + persisted_source_metadata, path=destination ) - if address is None: - projection_paths.append( - ( - SourceArtifactProjection( - address=None, - ref=SourcePixelRef(self.backend, virtual_path), - source_alias=record.producer_identity.output_key, - artifact_kind=ImageArtifactType, - source_metadata=source_metadata, - image_metadata=metadata, - execution_scope=record.execution_scope(plan), - ), - virtual_path, - ) - ) - produced_projections[Path(destination)] = ( - record, projection_paths[-1][0] - ) - continue - if address not in declared_addresses: - declared_addresses.add(address) - projection_paths.append( - ( - SourcePlaneProjection( - address=address, - ref=SourcePixelRef(self.backend, virtual_path), - source_alias=record.output_context.persisted_source_alias, - source_metadata=source_metadata, - image_metadata=metadata, - ), - virtual_path, - ) - ) - produced_projections[Path(destination)] = ( - record, projection_paths[-1][0] - ) - continue projection_paths.append( ( SourceArtifactProjection( address=address, ref=SourcePixelRef(self.backend, virtual_path), - source_alias=record.producer_identity.output_key, - artifact_kind=ImageArtifactType, - source_metadata=source_metadata, + source_alias=materialization.output_plan.name, + artifact_kind=materialization.output_plan.artifact_type, + source_metadata=persisted_source_metadata, image_metadata=metadata, + execution_scope=materialization.record.key.scope, ), virtual_path, ) ) - produced_projections[Path(destination)] = ( - record, projection_paths[-1][0] - ) - projection_paths.extend( - self.runtime_artifact_projection_paths( - context, plan, produced_projections=produced_projections - ) - ) - if not projection_paths: - return None - return VirtualWorkspaceSourceProjectionEntries.from_projection_paths( - projection_paths - ) + return tuple(projection_paths) - def project_runtime_artifacts( - self, - context: ProcessingContext, - plan: CompiledStepPlan, - *, - produced_projections: Mapping[ - Path, tuple[ProducedOutputSemantics, SourceProjection] - ] = MappingProxyType({}), - ) -> tuple[tuple[SourceArtifactProjection, str], ...]: - """Project persisted image artifacts into the target source authority.""" - - projection_paths = [] - for saved_artifact in self.artifact_materializations: - materialization = saved_artifact.materialization - for output in saved_artifact.outputs_for_backend(self.backend): - if not ImageFileFormat.is_image_path(output.path) or Path( - output.path - ).parent != Path(self.output_dir): - continue - if output.metadata is None: - raise ValueError( - f"Image artifact {output.path!r} has no typed image " - "metadata." - ) - destination = output.path - virtual_path = str(Path(destination).relative_to(self.plate_root)) - payload = output.metadata.attach_to(output.content) - metadata = self.persisted_image_metadata( - context, - destination=destination, - payload=payload, - ) - address = ( - SourceArtifactProjection.scalar_address_for_image_metadata( - metadata - ) - ) - produced = produced_projections.get(Path(destination)) - if produced is not None: - record, projection = produced - if record.owns_persisted_artifact( - materialization.output_plan, destination, self.output_dir - ): - if ( - projection.address != address - or projection.image_metadata != metadata - or ( - address is None - and projection.execution_scope - != materialization.record.key.scope - ) - ): - raise ValueError( - "Conflicting metadata for persisted image " - f"occurrence {destination!r}." - ) - continue - source_metadata = metadata.source_component_metadata or {} - persisted_source_metadata = dict(source_metadata) - metadata.source_voxel_spacing.merge_into( - persisted_source_metadata, path=destination - ) - projection_paths.append( - ( - SourceArtifactProjection( - address=address, - ref=SourcePixelRef(self.backend, virtual_path), - source_alias=materialization.output_plan.name, - artifact_kind=materialization.output_plan.artifact_type, - source_metadata=persisted_source_metadata, - image_metadata=metadata, - execution_scope=materialization.record.key.scope, - ), - virtual_path, - ) - ) - return tuple(projection_paths) - - def persisted_image_metadata( - self, - context: ProcessingContext, - *, - destination: str, - payload, - ) -> ImagePayloadMetadata: - """Describe one saved image through its backend or physical format.""" - - if context.filemanager is None: - raise ValueError("OpenHCS metadata requires a file manager.") - physical_path = context.filemanager.physical_source_path( - destination, - self.backend, - base_path=self.output_dir, + def persisted_image_metadata( + self, + context: ProcessingContext, + *, + destination: str, + payload, + ) -> ImagePayloadMetadata: + """Describe one saved image through its backend or physical format.""" + + if context.filemanager is None: + raise ValueError("OpenHCS metadata requires a file manager.") + physical_path = context.filemanager.physical_source_path( + destination, + self.backend, + base_path=self.output_dir, + ) + if physical_path is not None: + return ImageFileFormat.require_path(physical_path).persisted_metadata( + Path(physical_path), payload ) - if physical_path is not None: - return ImageFileFormat.require_path(physical_path).persisted_metadata( - Path(physical_path), payload - ) - native_dtype = context.filemanager.source_image_dtype( - destination, + native_dtype = context.filemanager.source_image_dtype( + destination, + self.backend, + base_path=self.output_dir, + ) + return ImageFileSourceMetadata( + source_dtype=native_dtype, + intensity_scale=image_intensity_scale_for_dtype(native_dtype), + ).project_image_metadata( + image_payload_metadata(payload), + values_preserved=context.filemanager.image_serialization_preserves_values( self.backend, - base_path=self.output_dir, - ) - return ImageFileSourceMetadata( - source_dtype=native_dtype, - intensity_scale=image_intensity_scale_for_dtype(native_dtype), - ).project_image_metadata( - image_payload_metadata(payload), - values_preserved=context.filemanager.image_serialization_preserves_values( - self.backend, - image_payload_data(payload).dtype, - native_dtype, - ), - ) + image_payload_data(payload).dtype, + native_dtype, + ), + ) @classmethod - def write( + def write_for_step( cls, context: ProcessingContext, plan: CompiledStepPlan, *, artifact_materializations: tuple[MaterializedRuntimeArtifact, ...] = (), ) -> None: - for target in cls.OutputTarget.for_execution( + for target in cls.for_execution( context, plan, artifact_materializations=artifact_materializations ): if not plan.create_openhcs_metadata: @@ -1032,14 +1014,12 @@ def finalize_completed_plate( ) -> None: """Write each populated metadata target after all axis outputs exist.""" - target_contexts: dict[OpenHCSMetadataWriter.OutputTarget, ProcessingContext] = ( - {} - ) + target_contexts: dict[OpenHCSMetadataTarget, ProcessingContext] = {} for context in compiled_contexts.values(): for plan in context.step_plans.values(): if not plan.create_openhcs_metadata: continue - for target in cls.OutputTarget.for_plan(plan): + for target in cls.for_plan(plan): target_contexts.setdefault(target, context) for owner, context in target_contexts.items(): @@ -1058,7 +1038,7 @@ def produced_records( class PrimaryImageMetadataTarget( - ProducedImageMetadataCapability, OpenHCSMetadataWriter.OutputTarget + ProducedImageMetadataCapability, OpenHCSMetadataTarget ): """The persistent main-flow image directory owns primary plate identity.""" @@ -1099,7 +1079,7 @@ def from_plan(cls, plan: CompiledStepPlan) -> PrimaryImageMetadataTarget | None: class MaterializedImageMetadataTarget( - ProducedImageMetadataCapability, OpenHCSMetadataWriter.OutputTarget + ProducedImageMetadataCapability, OpenHCSMetadataTarget ): """Explicit main-flow checkpoints retain their own compiled storage identity.""" @@ -1122,7 +1102,7 @@ def from_plan( ) -class RuntimeArtifactMetadataTarget(OpenHCSMetadataWriter.OutputTarget): +class RuntimeArtifactMetadataTarget(OpenHCSMetadataTarget): """Saved artifacts own result destinations independently of image storage.""" def stored_output_paths(self, context: ProcessingContext) -> tuple[str, ...]: @@ -1187,50 +1167,3 @@ def from_plan(cls, plan: CompiledStepPlan) -> RuntimeArtifactMetadataTarget | No sub_dir=str(output_dir.relative_to(plate_root)), results_dir=str(output_dir), ) - - -class RuntimeArtifactMaterializationAuthority: - """Materializes runtime artifacts for persistent output and streaming.""" - - @classmethod - def materialize( - cls, - context: ProcessingContext, - plan: CompiledStepPlan, - ) -> tuple[MaterializedRuntimeArtifact, ...]: - if not plan.artifact_outputs: - return () - materialization_plan = plan.runtime_artifact_materialization - has_persistent_target = materialization_plan.has_persistent_target - has_streaming_target = bool(plan.streaming_configs) - if not has_persistent_target and not has_streaming_target: - logger.info("Skipping runtime artifact materialization and streaming") - return () - - logger.info( - "Starting materialization for %s artifact outputs", - len(plan.artifact_outputs), - ) - materializations = materialize_artifact_outputs( - context.filemanager, - plan, - cls.target_plan(materialization_plan), - context, - ) - logger.info("Completed artifact materialization") - return materializations - - @staticmethod - def target_plan( - materialization_plan: RuntimeArtifactMaterializationPlan, - ) -> ( - PersistentArtifactMaterializationTargetPlan - | StreamingOnlyArtifactMaterializationTargetPlan - ): - if not materialization_plan.has_persistent_target: - logger.info("Skipping persistent runtime artifact materialization") - return StreamingOnlyArtifactMaterializationTargetPlan() - - return PersistentArtifactMaterializationTargetPlan( - materialization_plan.require_persistent_backend() - ) diff --git a/openhcs/core/steps/function_runtime.py b/openhcs/core/steps/function_runtime.py index 431626de24..d2eee630bb 100644 --- a/openhcs/core/steps/function_runtime.py +++ b/openhcs/core/steps/function_runtime.py @@ -11,7 +11,6 @@ from pathlib import Path from types import MappingProxyType from typing import ( - Generic, Mapping, Sequence, TypeVar, @@ -38,7 +37,6 @@ ) from openhcs.core.component_set import ComponentSet from openhcs.core.context.processing_context import ProcessingContext -from openhcs.core.runtime_profile import RuntimeProfileLogger from openhcs.core.debug import ( DebugCursor, DebugEvent, @@ -76,6 +74,7 @@ from openhcs.core.runtime_output_matching import ( split_runtime_output, ) +from openhcs.core.runtime_profile import RuntimeProfileLogger from openhcs.core.runtime_adapters import ( RuntimeAdapterRequest, ) @@ -94,7 +93,6 @@ VirtualWorkspacePathLookup, VirtualWorkspaceSourceProjection, VirtualWorkspaceSourceProjectionAuthority, - VirtualWorkspaceSourceProjectionCache, ) from openhcs.core.source_binding_selection import ( SourceBindingCandidateMatcher, @@ -227,97 +225,6 @@ def project_object_label_declared_source_identity( return source_payload -@dataclass(frozen=True) -class ComponentArtifactPlans(Generic[ArtifactInputPlanKeyT, ArtifactInputPlanT]): - """Artifact plans selected for one grouped component execution.""" - - inputs: ArtifactInputPlans[ArtifactInputPlanKeyT, ArtifactInputPlanT] - outputs: ArtifactOutputPlans - - @classmethod - def from_step_component( - cls, - plan: CompiledStepPlan, - component_key: str | None, - ) -> "ComponentArtifactPlans[ArtifactSpecRef, ArtifactInputPlan]": - ArtifactInputPlan.require_exact_map( - plan.artifact_inputs, - boundary="Component artifact input", - ) - return cls( - inputs=dict(plan.artifact_inputs), - outputs=cls._select_output_plans_for_component( - plan.artifact_outputs, - plan.execution_group_scope, - component_key, - ), - ) - - def select_for_invocation( - self: "ComponentArtifactPlans[ArtifactSpecRef, ArtifactInputPlan]", - invocation: CompiledFunctionInvocation, - *, - execution_scope: ComponentGroupScope, - component_key: str | None, - declared_source_bindings: CompiledSourceBindingPlan = CompiledSourceBindingPlan(), - active_source_bindings: CompiledSourceBindingPlan = CompiledSourceBindingPlan(), - ) -> "ComponentArtifactPlans[InvocationArtifactInputProjectionKey, InvocationArtifactInputEdgePlan] | None": - active_outputs = invocation.output_plans_for_component( - execution_scope, - component_key, - ) - if active_outputs is None: - return None - inputs = {} - for edge_key, edge in invocation.select_inputs( - self.inputs, active_output_plans=active_outputs, - ).items(): - if ( - edge.main_flow_projection is not None - and declared_source_bindings.declares_artifact_ref(edge.spec.ref()) - and not active_source_bindings.declares_artifact_ref(edge.spec.ref()) - ): - if not invocation.adapter_manages_artifact_inputs: - continue - if edge.storage_plan is not None: - raise ValueError( - f"Stored primary input {edge.spec.ref()!r} is not represented " - "by this main-flow payload; its producer cannot substitute " - "for the current payload epoch." - ) - edge = replace(edge, main_flow_projection=None) - inputs[edge_key] = edge - return ComponentArtifactPlans( - inputs=inputs, - outputs=invocation.select_outputs( - self.outputs, compiled_output_plans=active_outputs, - ), - ) - - @classmethod - def _select_output_plans_for_component( - cls, - plans: ArtifactOutputPlans, - execution_scope: ComponentGroupScope, - component_key: str | None, - ) -> ArtifactOutputPlans: - ArtifactOutputPlan.require_exact_map( - plans, - boundary="Component artifact output", - ) - return { - output_key: projected_plan - for output_key, output_plan in plans.items() - if ( - projected_plan := output_plan.for_execution_scope( - execution_scope, - component_key, - ) - ) - is not None - } - - @dataclass(frozen=True, slots=True, kw_only=True) class PatternGroupExecutionScope: """Shared pattern-group execution coordinates.""" @@ -425,6 +332,36 @@ def axis_scope(self) -> RuntimeExecutionAxisScope: fixed_component_values=self.fixed_component_values, ) + @staticmethod + def _select_output_plans_for_component( + plans: ArtifactOutputPlans, + execution_scope: ComponentGroupScope, + component_key: str | None, + ) -> ArtifactOutputPlans: + ArtifactOutputPlan.require_exact_map( + plans, + boundary="Component artifact output", + ) + return { + output_key: projected_plan + for output_key, output_plan in plans.items() + if ( + projected_plan := output_plan.for_execution_scope( + execution_scope, + component_key, + ) + ) + is not None + } + + def selected_artifact_output_plans(self) -> ArtifactOutputPlans: + """Project current compiled output declarations into this group scope.""" + return self._select_output_plans_for_component( + self.execution_plan.artifact_outputs, + self.execution_plan.execution_group_scope, + self.component_key, + ) + @dataclass(frozen=True, slots=True, kw_only=True) class PatternGroupExecutionRequest(PatternGroupExecutionScope): @@ -434,12 +371,6 @@ class PatternGroupExecutionRequest(PatternGroupExecutionScope): component_index: int component_count: int - def load_input_stack( - self, runtime: "PatternGroupRuntime", - ) -> tuple[list[str], RuntimeArrayData]: - """Admit the filename-selected source cohort.""" - return runtime._load_input_stack() - def loaded_plane_count( self, matching_files: Sequence[str], @@ -454,7 +385,8 @@ def loaded_plane_count( ) def loaded_fixed_component_values( - self, payload: RuntimeArrayData, + self, + payload: RuntimeArrayData, ) -> RuntimeFixedComponentValues: """Capture the source-selected cohort's common fixed coordinates.""" source_provenance = image_payload_metadata( @@ -464,9 +396,7 @@ def loaded_fixed_component_values( variable_components = ComponentSet.coerce( self.execution_plan.variable_components or () ) - execution_group_component = ( - self.execution_plan.execution_group_scope.component - ) + execution_group_component = self.execution_plan.execution_group_scope.component fixed_components = tuple( component for component in AllComponents @@ -482,7 +412,8 @@ def loaded_fixed_component_values( return source_provenance.require_common_component_values(fixed_components) def passthrough_producer_records( - self, matching_files: Sequence[str], + self, + matching_files: Sequence[str], ) -> tuple[ProducedOutputSemantics, ...] | None: """Resolve the physical source paths selected by this request.""" return step_output_manifest(self.context).producer_output_records_for_paths( @@ -491,1885 +422,1864 @@ def passthrough_producer_records( self.context.microscope_handler.parser, ) + @property + def pattern_repr(self) -> str: + return str(self.pattern_group_info)[:100] -@dataclass(frozen=True, slots=True, kw_only=True) -class ArtifactPatternGroupExecutionRequest(PatternGroupExecutionRequest): - """Admit exact canonical producer values into an independent cohort.""" - - def load_input_stack( - self, runtime: "PatternGroupRuntime", - ) -> tuple[list[str], RuntimeArrayData]: - edges = self.execution_plan.stored_primary_input_edges_for_group( - self.compiled_group, self.component_key, - ) - if not edges: - raise ValueError("Artifact cohort requires complete stored primary inputs.") - payloads = [] - matching_files = [] - for edge in edges: - artifact_input = RuntimeArtifactInput( - edge_plan=edge, - axis_scope=self.axis_scope, - backend=Backend.MEMORY.value, - source_binding_plan=self.source_binding_plan, - ) - records = artifact_input.records(self.context.runtime_value_store) - source_payload = edge.spec.artifact_type.source_image_payload_from_runtime_value( - artifact_input.composed_value(records), - ) - if source_payload is None: - raise ValueError( - f"Artifact cohort source {edge.spec.ref()!r} has no image context." - ) - payloads.append( - ImagePayloadStackComposition.copy_whole_image( - source_payload, - memory_type=self.execution_plan.input_memory_type, - device_id=self.execution_plan.device_id_for( - self.execution_plan.input_memory_type, - ), - ) - ) - matching_files.extend(record.location.path for record in records) - main_data_stack = ImagePayloadConsumption.NATURAL.compose_image_payload( - self.execution_plan.step_name, tuple(payloads), - ).payload - return matching_files, main_data_stack - - def loaded_plane_count( - self, matching_files: Sequence[str], payload: RuntimeArrayData, - ) -> int: - """Canonical payloads declare their runtime axis independently of paths.""" - count = RuntimeSliceProjection.slice_count_from_values((payload,)) - return 1 if count is None else count - - def loaded_fixed_component_values( - self, payload: RuntimeArrayData, - ) -> RuntimeFixedComponentValues: - """Retain exact producer coordinates admitted by typed discovery.""" - return self.fixed_component_values - - def passthrough_producer_records( - self, matching_files: Sequence[str], - ) -> tuple[ProducedOutputSemantics, ...]: - """Preserve input transport independently of artifact context admission.""" - records = step_output_manifest(self.context).producer_records_for( - self.execution_plan, - ) - if records is None: - raise ValueError("Artifact input passthrough requires producer lineage.") - return records - - -@dataclass(frozen=True, slots=True, kw_only=True) -class PatternGroupData(PatternGroupExecutionScope): - """Complete loaded cohort and its original execution coordinates.""" + def source_workspace_projection_authority( + self, + ) -> VirtualWorkspaceSourceProjectionAuthority: + return self.context.runtime_source_workspace_projection_authority - artifacts: ComponentArtifactPlans[ArtifactSpecRef, ArtifactInputPlan] - runtime_plane_index: int - runtime_plane_count: int - matching_files: list[str] - main_data_stack: RuntimeArrayData + @staticmethod + def _is_relative_to(path: Path, root: Path) -> bool: + try: + path.relative_to(root) + except ValueError: + return False + return True @classmethod - def from_loaded_group( - cls, - request: "PatternGroupExecutionRequest", - matching_files: list[str], - main_data_stack: RuntimeArrayData, - ) -> "PatternGroupData": - artifacts = ComponentArtifactPlans.from_step_component( - request.execution_plan, - request.component_key, - ) - logger.debug( - "Selected artifact outputs for component %s: %s", - request.component_key, - artifacts.outputs, - ) - return cls( - matching_files=matching_files, - main_data_stack=main_data_stack, - context=request.context, - execution_plan=request.execution_plan, - compiled_group=request.compiled_group, - artifacts=artifacts, - runtime_plane_index=request.component_index, - runtime_plane_count=request.loaded_plane_count( - matching_files, main_data_stack, - ), - component_value=request.component_value, - fixed_component_values=request.loaded_fixed_component_values(main_data_stack), - ) - - def require_invocations(self) -> None: - if self.compiled_group.invocations: - return - raise ValueError( - f"Compiled function group {self.compiled_group.group_key} has no invocations." - ) - - -@dataclass(frozen=True, slots=True) -class OutputPathBatchEntry: - """Resolved identity for one output path in a runtime save batch.""" - - index: int - input_path: str | None - output_path: str - identity: FunctionOutputIdentity + def _input_memory_path(cls, input_dir: Path, matched_path: str) -> str: + """Return the VFS memory path for one matched source path.""" + path = Path(matched_path) + if path.is_absolute() or cls._is_relative_to(path, input_dir): + return str(path) + return str(input_dir / path) - def diagnostic(self) -> str: - filename_components = ( - self.identity.filename_component_values - if self.identity.filename_component_values is not None - else self.identity.component_values - ) - return ( - f"#{self.index}: input={self.input_path!r}, output={self.output_path!r}, " - f"identity={dict(self.identity.component_values)!r}, " - f"filename_identity={dict(filename_components)!r}, " - f"source={self.identity.source!r}" - ) + @classmethod + def _input_relative_path(cls, input_dir: Path, matched_path: str) -> Path: + """Return matched path identity relative to the step input root.""" + path = Path(matched_path) + if cls._is_relative_to(path, input_dir): + return path.relative_to(input_dir) + if path.is_absolute(): + return Path(path.name) + return path + def run(self) -> None: + start_time = time.time() if logger.isEnabledFor(logging.DEBUG) else None + plan = self.execution_plan + logger.debug("Processing pattern %s for axis %s", self.pattern_repr, plan.axis_id) -@dataclass(frozen=True, slots=True) -class OutputPathBatchUniqueness: - """Validate that one runtime output batch has unique destination paths.""" - - output_paths: Sequence[str] - input_paths: Sequence[str] - step_name: str - pattern_repr: str - entries: Sequence[OutputPathBatchEntry] = () - - def validate(self) -> None: - counts: dict[str, int] = {} - for path in self.output_paths: - if path not in counts: - counts[path] = 1 - continue - counts[path] += 1 - duplicates = tuple(path for path, count in counts.items() if count > 1) - if not duplicates: + try: + load_started_at = time.perf_counter() + matching_files, main_data_stack = self.load_input_stack() + except NoStepOutputManifestMatch: + logger.debug( + "Skipping stale pattern group %s for step %s (%s); no files " + "belong to producer manifest.", + self.pattern_repr, + plan.step_index, + plan.step_name, + ) return - raise ValueError( - f"Step {self.step_name!r} produced duplicate output path(s) " - f"for pattern {self.pattern_repr}: {duplicates!r}. Input files: " - f"{tuple(self.input_paths)!r}. Output identity details: " - f"{tuple(entry.diagnostic() for entry in self.entries)!r}." - ) - - -def _save_artifact_value( - context: ProcessingContext, - output_plan: ArtifactOutputPlan, - value: RuntimePayload, - source_payload: RuntimePayload, - *, - execution_scope: RuntimeExecutionAxisScope, - group_key: str | None, - plane_projector: RuntimePlaneAxisProjector | None, - materialization_source_metadata: ImagePayloadMetadata | None = None, -) -> RuntimePayload: - """Validate and save one planned artifact value to the memory VFS.""" - resolved_output_plan = output_plan.for_invocation_group(group_key) - vfs_path = resolved_output_plan.path - runtime_value = RuntimeValue.normalize_output_from_projector( - resolved_output_plan, - value, - source_payload=source_payload, - plane_projector=plane_projector, - execution_scope=execution_scope, - materialization_source_metadata=materialization_source_metadata, - ) - - location = RuntimeArtifactLocation( - path=vfs_path, - backend=Backend.MEMORY.value, - ) - runtime_value_store = context.runtime_value_store - runtime_value_store.replace( - runtime_value, - path=location.path, - backend=location.backend, - ) - replace_runtime_artifact_payload( - context.filemanager, - runtime_value.data, - location, - ) - return runtime_value.data - - -@dataclass(frozen=True, slots=True) -class FunctionCoreExecutor: - """Execute one scoped callable invocation and route declared artifact I/O.""" + try: + RuntimeProfileLogger.log( + logger, + "pattern_load_stack", + time.perf_counter() - load_started_at, + step=plan.step_index, + step_name=plan.step_name, + pattern=self.pattern_repr, + ) + execute_started_at = time.perf_counter() + loaded = PatternGroupData.from_loaded_group( + self, + matching_files, + main_data_stack, + ) + processed_stack = loaded.execute_chain() + RuntimeProfileLogger.log( + logger, + "pattern_execute_chain", + time.perf_counter() - execute_started_at, + step=plan.step_index, + step_name=plan.step_name, + pattern=self.pattern_repr, + ) + if isinstance(processed_stack, NoMainFlowOutput): + self._record_main_flow_passthrough(loaded.matching_files) + RuntimeProfileLogger.log( + logger, + "pattern_no_main_flow_output", + 0.0, + step=plan.step_index, + step_name=plan.step_name, + pattern=self.pattern_repr, + ) + logger.debug( + "Pattern group %s for step %s recorded artifacts without " + "publishing main-flow output.", + self.pattern_repr, + plan.step_name, + ) + return + if not plan.requires_main_flow_checkpoint(self.context.step_plans): + return + output_records = self._save_outputs(processed_stack, loaded.matching_files) + output_paths = [record.output_path for record in output_records] + cleanup_started_at = time.perf_counter() + self._cleanup_collapsed_domains( + output_records, + loaded.matching_files, + output_paths, + ) + step_output_manifest(self.context).record_outputs( + plan, + output_records, + collapsed_input_domain=( + len(output_records) < len(loaded.matching_files) + ), + ) + RuntimeProfileLogger.log( + logger, + "pattern_cleanup", + time.perf_counter() - cleanup_started_at, + step=plan.step_index, + step_name=plan.step_name, + pattern=self.pattern_repr, + ) + if start_time is not None and logger.isEnabledFor(logging.DEBUG): + logger.debug( + "Finished pattern group %s in %.2fs.", + self.pattern_repr, + time.time() - start_time, + ) + except Exception as e: + logger.error( + "Error processing pattern group %s: %s", self.pattern_repr, e, + exc_info=True, + ) + raise ValueError( + f"Failed to process pattern group {self.pattern_repr}: {e}" + ) from e - group_data: PatternGroupData - invocation: CompiledFunctionInvocation - artifacts: ComponentArtifactPlans[ - InvocationArtifactInputProjectionKey, - InvocationArtifactInputEdgePlan, - ] - group_key: str | None - plane_projection: RuntimePlaneProjection - main_data_arg: RuntimeArrayData - source_memory_type: str + def _record_main_flow_passthrough(self, matching_files: Sequence[str]) -> None: + """Record existing main-flow anchors for artifact-only step outputs.""" + if not matching_files: + return + plan = self.execution_plan + if not plan.requires_main_flow_checkpoint(self.context.step_plans): + return + parser = self.context.microscope_handler.parser + manifest = step_output_manifest(self.context) + producer_records = self.passthrough_producer_records(matching_files) + if producer_records is None: + records = tuple( + ProducedOutputSemantics.from_existing_main_flow_path( + plan, + self._input_memory_path(plan.input_dir, matching_file), + parser, + ) + for matching_file in matching_files + ) + else: + records = tuple(record.passed_through(plan) for record in producer_records) + manifest.record_outputs(plan, records) - @property - def selected_artifact_input_edges( + def _producer_output_contexts( self, - ) -> tuple[InvocationArtifactInputEdgePlan, ...]: - """Return component-selected compiled occurrences in declaration order.""" - - return tuple(self.artifacts.inputs.values()) + matching_files: Sequence[str], + ) -> tuple[AlignedImageSliceContext, ...]: + """Resolve exact producer contexts for the loaded main-flow paths.""" - def runtime_adapter_request( - self, - source_payload: RuntimePayload, - ) -> RuntimeAdapterRequest: - return RuntimeAdapterRequest( - context=self.group_data.context, - callable_contract=self.invocation.contract, - artifact_inputs={ - edge.key: edge for edge in self.selected_artifact_input_edges - }, - artifact_outputs=self.artifacts.outputs, - group_key=self.group_key, - plane_projection=self.plane_projection, - source_payload=source_payload, - source_binding_plan=self.group_data.source_binding_plan, - axis_scope=self.group_data.axis_scope, - variable_components=tuple( - self.group_data.execution_plan.variable_components - ), - source_load_plan=self.group_data.execution_plan.source_load_plan, + return step_output_manifest(self.context).producer_output_contexts_for_paths( + self.execution_plan, + matching_files, + self.context.microscope_handler.parser, ) - @property - def function_name(self) -> str: - return self.invocation.contract.function_name - - def declared_source_payload( + def load_input_stack( self, - source_ref: ArtifactSpecRef, - primary_source_payload: RuntimePayload, - *, - loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], - ) -> RuntimePayload: - input_spec = self.invocation.contract.artifact_inputs.by_ref(source_ref) - if input_spec is None: - raise ValueError( - f"Invocation {self.invocation.key!r} does not declare source artifact " - f"{source_ref!r}." - ) - stored_payload = loaded_artifact_payloads.get(source_ref) - source_binding = ( - self.group_data.source_binding_plan.binding_for_artifact_ref(source_ref) + ) -> tuple[list[str], RuntimeArrayData]: + context = self.context + plan = self.execution_plan + request = self + if not context.microscope_handler: + raise RuntimeError("MicroscopeHandler not available in context.") + + output_manifest = step_output_manifest(context) + producer_index = output_manifest.producer_record_index_for( + plan, + context.microscope_handler.parser, ) - main_flow_edges = tuple( - edge - for edge in self.selected_artifact_input_edges - if edge.spec.ref() == source_ref and edge.main_flow_projection is not None + producer_records = ( + None + if producer_index is None + else producer_index.matching_records(str(request.pattern_group_info)) ) - uses_main_flow = bool( - stored_payload is None and source_binding is None and main_flow_edges + producer_matching_files = ( + () + if producer_records is None + else tuple(record.output_path for record in producer_records) ) - resolved_origins = sum( - ( - stored_payload is not None, - source_binding is not None, - uses_main_flow, - ) + matching_files = list(producer_matching_files) + source_projection = ( + self.source_workspace_projection_authority().projection_if_available() ) - if resolved_origins != 1: - raise ValueError( - f"Invocation {self.invocation.key!r} source artifact {source_ref!r} " - "must resolve to exactly one compiled producer, source binding, or " - f"main-flow input; resolved {resolved_origins}." - ) - if stored_payload is not None: - return stored_payload - if source_binding is not None: - return cast( - RuntimePayload, - self.runtime_adapter_request( - primary_source_payload - ).source_artifact_payload(source_ref), - ) - if len(main_flow_edges) != 1: - raise ValueError( - f"Invocation {self.invocation.key!r} source artifact {source_ref!r} " - "must resolve through exactly one selected main-flow input edge; " - f"resolved {len(main_flow_edges)}." + if not matching_files: + matching_files = context.microscope_handler.path_list_from_pattern( + str(plan.input_dir), + request.pattern_group_info, + context.filemanager, + plan.read_backend, + ( + [component.value for component in plan.variable_components] + if plan.variable_components + else None + ), + pattern_cache=context.runtime_pattern_discovery_cache, ) - main_flow_projection = main_flow_edges[0].main_flow_projection - if main_flow_projection is MainFlowInputProjection.COMPLETE_PAYLOAD: - return primary_source_payload - if main_flow_projection is not MainFlowInputProjection.DECLARED_SOURCE_IMAGE: + if producer_index is not None and not producer_matching_files: + selected_paths = [ + path for path in matching_files if producer_index.contains(path) + ] + if matching_files and not selected_paths: + raise NoStepOutputManifestMatch + matching_files = selected_paths + + if not matching_files: raise ValueError( - f"Invocation {self.invocation.key!r} source artifact {source_ref!r} " - "consumes main flow without a compiled projection." + f"No matching files found for pattern group {self.pattern_repr} " + f"in {plan.input_dir}. " + f"This indicates either: (1) no image files exist in the directory, " + f"(2) files don't match the pattern, or (3) pattern parsing failed. " + f"Check that input files exist and match the expected naming convention." ) - return project_declared_source_identity(primary_source_payload, source_ref) - def load_artifact_inputs( - self, - final_kwargs: dict[str, RuntimeCallableArgument], - source_payload: RuntimePayload, - ) -> dict[ArtifactSpecRef, RuntimePayload]: - if not self.should_load_artifact_inputs(): - return {} - logger.info( - "Artifact inputs for %s: %s", self.function_name, self.artifacts.inputs - ) - loaded_artifact_payloads: dict[ArtifactSpecRef, RuntimePayload] = {} - parameter_values: dict[str, list[RuntimeValue]] = {} - for input_plan in self.selected_artifact_input_edges: - parameter_name = input_plan.spec.parameter_name - if not input_plan.requires_callable_binding(): - continue - if parameter_name is None: - raise ValueError( - f"Compiled invocation {self.invocation.key!r} runtime-loaded input " - f"edge {input_plan.key!r} has no callable parameter." - ) - artifact_ref = input_plan.spec.ref() - projected_values = ( - self.load_artifact_input(input_plan.spec.name, input_plan) - if input_plan.uses_runtime_storage() - and input_plan.main_flow_projection is None - else ( - RuntimeValue.from_spec( - input_plan.spec, - input_plan.resolve_unstored_payload(self, source_payload), - execution_scope=self.group_data.axis_scope, - ), - ) - ) - loaded_value = RuntimeValue.compose(projected_values) - loaded_artifact_payloads[artifact_ref] = loaded_value - parameter_values.setdefault(parameter_name, []).extend(projected_values) - for parameter_name, projected_values in parameter_values.items(): - final_kwargs[parameter_name] = RuntimeValue.compose(tuple(projected_values)) - return loaded_artifact_payloads + matching_files = self._filter_matching_files_for_group(matching_files) - def should_load_artifact_inputs(self) -> bool: - return bool( - any( - edge.requires_callable_binding() - for edge in self.selected_artifact_input_edges + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "Pattern %s matched %d files: %s", + self.pattern_repr, + len(matching_files), + [Path(f).name for f in matching_files], ) - and not self.invocation.adapter_manages_artifact_inputs + + if not producer_matching_files: + matching_files.sort() + logger.debug( + f"Pattern {self.pattern_repr} sorted files: {[Path(f).name for f in matching_files]}" ) + matching_files = self._filter_matching_files_for_source_bindings(matching_files) - def load_artifact_input( - self, - arg_name: str, - edge_plan: InvocationArtifactInputEdgePlan, - ) -> tuple[RuntimeValue, ...]: - storage_plan = edge_plan.storage_plan - if storage_plan is None: - raise ValueError("Artifact input loading requires a storage-backed edge.") - logger.info( - "Loading artifact input '%s' from path '%s' (memory backend)", - arg_name, - storage_plan.path, + full_file_paths = [ + self._input_memory_path(plan.input_dir, file_path) + for file_path in matching_files + ] + workspace_path_lookups = tuple( + VirtualWorkspacePathLookup.from_paths( + virtual_path, + full_virtual_path, + ) + for virtual_path, full_virtual_path in zip( + matching_files, + full_file_paths, + strict=True, + ) ) - load_started_at = time.perf_counter() - try: - loaded_values = RuntimeArtifactInput( - edge_plan=edge_plan, - axis_scope=self.group_data.axis_scope, - backend=Backend.MEMORY.value, - source_binding_plan=self.group_data.source_binding_plan, - ).projected_values(self.group_data.context.runtime_value_store) - except Exception as exc: - logger.error( - "Failed to load artifact input '%s' from '%s': %s", - arg_name, - storage_plan.path, - exc, - exc_info=True, + workspace_source_lookups = ( + self._workspace_source_binding_lookups( + source_projection, + workspace_path_lookups, ) - raise + if source_projection is not None + else () + ) + if producer_index is not None: + if producer_matching_files: + producer_index.validate_input_records(producer_records) + else: + producer_records = producer_index.records_for_paths(matching_files) + ImagePayloadStackComposition.validate_main_flow_cohort(producer_records) + cached_stack = context.runtime_image_stack_cache.get( + tuple(full_file_paths), + memory_type=plan.input_memory_type, + ) RuntimeProfileLogger.log( logger, - "artifact_input_load", - time.perf_counter() - load_started_at, - function=self.function_name, - artifact=arg_name, - artifact_type=storage_plan.artifact_type.value, + "runtime_stack_cache_get", + 0.0, + step=plan.step_index, + step_name=plan.step_name, + hit=cached_stack is not None, + paths=len(full_file_paths), + memory_type=plan.input_memory_type, ) - return loaded_values + if cached_stack is None: + raw_slices = SourceFileUniverse( + tuple(full_file_paths), + ( + Backend.MEMORY + if plan.main_input_dependency.kind + is StepInputDependencyKind.STEP_OUTPUT + else Backend(plan.read_backend) + ), + ).load_images(context.filemanager, zarr_config=plan.zarr_config) + if source_projection is not None or not producer_matching_files: + raw_slices = self._apply_source_image_loading_semantics( + raw_slices, + workspace_path_lookups, + workspace_source_lookups, + source_projection, + ) - def debug_cursor(self) -> DebugCursor: - return DebugCursor.from_invocation( - step_index=self.group_data.execution_plan.step_index, - step_scope_id=self.group_data.execution_plan.step_scope_id, - invocation=self.invocation, - pattern_group_identity=str(self.group_data.runtime_plane_index), - ) + if not raw_slices: + raise ValueError( + f"No valid images loaded for pattern group {self.pattern_repr} " + f"in {plan.input_dir}. " + f"Found {len(matching_files)} matching files but failed to load any valid images. " + f"This indicates corrupted image files, unsupported formats, or I/O errors. " + f"Check file integrity and format compatibility." + ) - def debug_artifacts( + main_data_stack = ImagePayloadStackComposition.from_loaded_images( + raw_slices, + producer_records=producer_records, + execution_plan=plan, + source_projection=source_projection, + workspace_source_lookups=workspace_source_lookups, + ) + if not producer_records: + metadata = image_payload_metadata(main_data_stack) + domain = request.source_binding_plan.source_spatial_domain.admit_source_cohort( + metadata.source_spatial_domain, + depth=len(matching_files), + ) + main_data_stack = metadata.replace_fields( + source_spatial_domain=domain, + ).attach_to(main_data_stack) + else: + main_data_stack = cached_stack + + return matching_files, main_data_stack + + def _workspace_source_binding_lookups( self, - artifact_plans: ArtifactInputPlans | ArtifactOutputPlans, - artifact_values: Mapping[ArtifactSpecRef, object] | None = None, - ) -> DebugArtifactRefProjection: - return DebugArtifactRefProjection.from_artifact_plans( - artifact_plans=artifact_plans, - cursor=self.debug_cursor(), - artifact_values=artifact_values, + source_projection: VirtualWorkspaceSourceProjection, + lookups: Sequence[VirtualWorkspacePathLookup], + ) -> tuple[VirtualWorkspacePathLookup, ...]: + """Return workspace paths owned by this step's exact source bindings.""" + + bindings = self.source_binding_plan.binding_declarations + return tuple( + lookup + for lookup in lookups + for projection in (source_projection.source_projection_for(lookup),) + if projection is not None + and any(projection.matches_binding(binding) for binding in bindings) ) - def debug_event( + def _filter_matching_files_for_group( self, - event_type: DebugEventType, - *, - exception: Exception | None = None, - timing_seconds: float | None = None, - invocation_parameters: tuple[DebugInvocationParameter, ...] = (), - input_artifact_values: Mapping[ArtifactSpecRef, object] | None = None, - ) -> DebugEvent: - return DebugEvent.for_invocation( - event_type=event_type, - cursor=self.debug_cursor(), - step_name=self.group_data.execution_plan.step_name, - callable_name=self.invocation.key.function_name, - axis_id=self.group_data.execution_plan.axis_id, - input_artifacts=self.debug_artifacts( - { - edge.storage_plan.ref(): edge.storage_plan - for edge in self.artifacts.inputs.values() - if edge.storage_plan is not None - }, - input_artifact_values, - ), - output_artifacts=self.debug_artifacts(self.artifacts.outputs), - exception=exception, - timing_seconds=timing_seconds, - invocation_parameters=invocation_parameters, + matching_files: list[str], + ) -> list[str]: + """Constrain grouped executions to files from the current component.""" + if ( + self.execution_plan.main_input_dependency.kind + is StepInputDependencyKind.STEP_OUTPUT + or self.compiled_group.runtime_domain + is RuntimeInvocationDomain.ARTIFACT_MANAGED + ): + return matching_files + if self.main_flow_source_binding_plan.has_primary_content: + return matching_files + + group_component = self.execution_plan.execution_group_value + component_value = self.component_value + if group_component is None or component_value is None: + return matching_files + + parser = self.context.microscope_handler.parser + filtered = self.context.runtime_pattern_discovery_cache.files_for_component( + parser, + matching_files, + parser.component_for_name(group_component), + component_value, ) + if not filtered: + raise ValueError( + f"Pattern group {self.pattern_repr} for {group_component}=" + f"{component_value!r} matched files, but none carried the " + f"expected grouped component. Matched files: {matching_files}" + ) + return filtered - def execute( + def _filter_matching_files_for_source_bindings( self, - *, - debug_sink: DebugEventSink | None = None, - ) -> RuntimePayload | NoMainFlowOutput: - converted_data = self.invocation.convert_input( - image_payload_data(self.main_data_arg), - self.source_memory_type, - ) - source_payload = with_image_payload_data(self.main_data_arg, converted_data) - main_data_arg = self.invocation.main_flow_call_argument(source_payload) - final_kwargs = dict(self.invocation.runtime_kwargs) - loads_artifact_inputs = self.should_load_artifact_inputs() - loaded_artifact_payloads: dict[ArtifactSpecRef, RuntimePayload] = {} - if loads_artifact_inputs: - loaded_artifact_payloads = self.load_artifact_inputs( - final_kwargs, - source_payload, + matching_files: list[str], + ) -> list[str]: + """Constrain the loaded main stack to declared image source bindings.""" + + if ( + self.execution_plan.main_input_dependency.kind + is StepInputDependencyKind.STEP_OUTPUT + ): + return matching_files + + source_binding_plan = self.main_flow_source_binding_plan + if not source_binding_plan.has_primary_content: + return matching_files + bindings = tuple( + binding + for binding in source_binding_plan.bindings + if binding.projection_role is SourceProjectionRole.PRIMARY_PLANE + ) + if not bindings: + return matching_files + selector_bindings = SourceBindingCandidateMatcher.selector_bindings(bindings) + + source_context = self._source_binding_candidate_context() + if ( + not selector_bindings + and not source_context.source_projections_by_virtual_path + ): + return matching_files + compatible = list( + SourceBindingMatchedImageSet.from_plan( + bindings=bindings, + match_plan=source_binding_plan.match_plan, + source_context=source_context, + identity_policy=(self.context.source_image_set_identity_policy), + ).expand( + matching_files, + source_universe=self._source_binding_load_universe(), ) - self.bind_runtime_owned_parameters(final_kwargs) - self.bind_runtime_adapter(final_kwargs, source_payload) - raw_output = self.invoke( - main_data_arg, - final_kwargs, - loaded_artifact_payloads=loaded_artifact_payloads, - debug_sink=debug_sink, ) - return self.save_artifact_outputs( - raw_output, - source_payload, - loaded_artifact_payloads=loaded_artifact_payloads, + if compatible: + return compatible + + raise ValueError( + f"Source-bound step {self.execution_plan.step_name!r} resolved no files for " + f"image bindings {[binding.alias for binding in bindings]!r} in pattern " + f"{self.pattern_repr}. Matched files before source filtering: " + f"{matching_files!r}." ) - def execution_group_source_payload( - self, - source_payload: RuntimePayload, - ) -> RuntimePayload: - """Return source payload metadata carrying the current grouped identity.""" - component = self.group_data.execution_plan.execution_group_scope.component - if component is None or self.group_key is None: - return source_payload - metadata = image_payload_metadata(source_payload) - component_metadata = metadata.source_component_metadata or {} - component_metadata = with_source_component_metadata( - component_metadata, - component, - self.group_key, + def _source_binding_load_universe(self) -> tuple[str, ...]: + """Return loadable files available for source image-set expansion.""" + source_projection = ( + self.source_workspace_projection_authority().projection_if_available() ) - return metadata.with_source_component_metadata(component_metadata).attach_to( - source_payload + request = SourceUniverseRequest.from_context( + context=self.context, + plan=self.execution_plan, + matching_files=(), + source_projection=source_projection, ) + return request.runtime_universe_state().require_load_universe().files - def bind_runtime_owned_parameters( - self, - final_kwargs: dict[str, RuntimeCallableArgument], - ) -> None: - context_parameter_name = self.invocation.contract.runtime_context_parameter - if context_parameter_name is not None: - final_kwargs[context_parameter_name] = self.group_data.context - - def bind_runtime_adapter( - self, - final_kwargs: dict[str, RuntimeCallableArgument], - source_payload: RuntimePayload, - ) -> None: - runtime_adapter = self.invocation.contract.runtime_adapter - if runtime_adapter is None: - return - adapter_parameter = self.invocation.adapter_parameter_name - adapter_started_at = time.perf_counter() - final_kwargs[adapter_parameter] = runtime_adapter.factory( - self.runtime_adapter_request(source_payload) - ) - RuntimeProfileLogger.log( - logger, - "runtime_adapter_factory", - time.perf_counter() - adapter_started_at, - function=self.function_name, - adapter=adapter_parameter, + def _source_binding_candidate_context(self) -> SourcePatternResolutionContext: + projection = self.source_workspace_projection_authority().projection_or_empty() + return self.context.runtime_source_binding_context_cache.source_pattern_context( + parser=self.context.microscope_handler.parser, + projection=self.context.runtime_source_workspace_projection_cache.filtered_by_axis( + projection, + axis_id=self.execution_plan.axis_id, + ), + metadata_rules=self.source_binding_plan.metadata_rules, ) - def invoke( + def _apply_source_image_loading_semantics( self, - main_data_arg: RuntimeCallableArgument, - final_kwargs: dict[str, RuntimeCallableArgument], - *, - loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], - debug_sink: DebugEventSink | None, - ) -> RuntimeFunctionOutput: - logger.info("Executing function: %s", self.function_name) - func_callable = self.invocation.runtime_callable - contract = self.invocation.contract - primary_parameter = self.invocation.primary_input_parameter_name - plane_projector: RuntimePlaneAxisProjector = self.plane_projection - runtime_adapter = self.invocation.contract.runtime_adapter - if runtime_adapter is not None: - adapter_parameter = self.invocation.adapter_parameter_name - adapter_value = final_kwargs[adapter_parameter] - if isinstance(adapter_value, RuntimePlaneAxisProjector): - plane_projector = adapter_value - if debug_sink is not None: - if primary_parameter is None: - raise TypeError( - f"Callable {self.function_name!r} has no declared primary input " - "parameter for runtime invocation diagnostics." - ) - bound_parameters = dict(final_kwargs) - bound_parameters[primary_parameter] = main_data_arg - debug_sink.record( - self.debug_event( - DebugEventType.BEFORE_INVOCATION, - invocation_parameters=DebugInvocationParameter.from_kwargs( - bound_parameters, - plane_projector=plane_projector, - ), - input_artifact_values=loaded_artifact_payloads, + raw_slices: Sequence[RuntimeArrayData], + workspace_path_lookups: Sequence[VirtualWorkspacePathLookup], + workspace_source_lookups: Sequence[VirtualWorkspacePathLookup], + source_projection: VirtualWorkspaceSourceProjection | None, + ) -> list[RuntimeArrayData]: + if source_projection is not None: + source_lookups = frozenset(workspace_source_lookups) + return [ + ( + self._apply_workspace_source_binding_payload( + payload, + source_projection=source_projection, + lookup=lookup, + ) + if lookup in source_lookups + else self._apply_workspace_source_payload( + payload, + source_projection=source_projection, + lookup=lookup, + ) ) - ) - call_started_at = time.perf_counter() - try: - with self.invocation.execution_device_scope(): - raw_output = func_callable( - main_data_arg, - **final_kwargs, + for payload, lookup in zip( + raw_slices, + workspace_path_lookups, + strict=True, ) - except RuntimeSliceProjectionDeclarationError as exc: - bound_parameters = dict(final_kwargs) - if primary_parameter is not None: - bound_parameters[primary_parameter] = main_data_arg - cursor = self.debug_cursor() - invocation_parameters = DebugInvocationParameter.from_kwargs( - bound_parameters, - plane_projector=plane_projector, - ) - selected_plane = plane_projector.runtime_slice_plane_index() - selected_plane_status = ( - "preserved_stack" if selected_plane is None else str(selected_plane) + ] + + universe_state = SourceUniverseRequest.from_context( + context=self.context, + plan=self.execution_plan, + matching_files=tuple( + lookup.virtual_path for lookup in workspace_path_lookups + ), + source_projection=None, + ).runtime_universe_state() + cache = self.context.runtime_source_binding_context_cache + source_metadata = cache.normalized_source_metadata( + universe_state.source_metadata_by_path + ) + source_context = SourcePatternResolutionContext.from_sources( + parser=self.context.microscope_handler.parser, + source_paths_by_virtual_path=universe_state.step_input_source_paths, + source_metadata_by_path=source_metadata, + metadata_rules=self.source_binding_plan.metadata_rules, + ) + return [ + self._apply_source_binding_payload( + payload, + source_metadata=source_context.merged_metadata_for_paths( + ( + lookup.virtual_path, + lookup.full_virtual_path, + ) + ), + source_path=source_context.source_path_for(lookup.full_virtual_path), + read_backend=self.execution_plan.read_backend, ) - artifact_refs = ( - *(edge.spec.ref() for edge in self.selected_artifact_input_edges), - *self.artifacts.outputs, + for payload, lookup in zip( + raw_slices, + workspace_path_lookups, + strict=True, ) - raise type(exc)( - f"{exc} Invocation boundary: step_index={cursor.step_index}; " - f"step_name={self.group_data.execution_plan.step_name!r}; " - f"function_invocation_key={self.invocation.key!r}; " - f"module={contract.module_name!r}; " - f"callable={contract.function_name!r}; " - f"artifact_spec_refs={artifact_refs!r}; " - f"kwarg_names={tuple(sorted(final_kwargs))!r}; " - f"nominal_values={tuple((parameter.name, parameter.value_repr) for parameter in invocation_parameters)!r}; " - f"selected_runtime_plane={selected_plane_status}; " - "execution_axis_cardinality=" - f"{plane_projector.runtime_slice_axis_size()!r}; " - "image_payload_execution_mode=" - f"{contract.runtime_image_execution_mode}; " - f"processing_contract={contract.processing_contract}." - ) from exc - RuntimeProfileLogger.log( - logger, - "function_call", - time.perf_counter() - call_started_at, - function=self.function_name, - ) - return raw_output + ] - def save_artifact_outputs( + def _apply_workspace_source_payload( self, - raw_output: RuntimeFunctionOutput, - source_payload: RuntimePayload, + payload: RuntimeArrayData, *, - loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], - ) -> RuntimePayload | NoMainFlowOutput: - """Save declared outputs and qualify unsaved canonical returns afterward.""" - if self.invocation.adapter_records_artifact_outputs: - return self.save_module_recorded_output(raw_output) - output_plans = tuple(self.artifacts.outputs.values()) - declared_specs = self.invocation.contract.artifact_outputs - if not declared_specs: - if isinstance(raw_output, tuple): - raise TypeError( - "Tuple returns require declared special-output slots; multiple " - "main-flow images must be packed as AlignedImageStack." - ) - main_output = raw_output - else: - _returned_values, matched_outputs = ( - self.invocation.contract.resolve_returned_plan_values( - raw_output, - output_plans, - ) - ) - saved_values = { - output_plan.ref(): self.save_artifact_output( - output_plan.name, - output_plan, - output_value, - source_payload, - loaded_artifact_payloads=loaded_artifact_payloads, - ) - for output_plan, _output_spec, output_value in matched_outputs - } - canonical_refs = self.invocation.contract.canonical_return_output_refs - main_outputs = tuple( - (output_plan, output_spec, saved_values[output_plan.ref()]) - for output_plan, output_spec, _output_value in matched_outputs - if output_plan.ref() in canonical_refs - ) - if main_outputs: - # These values already own their declared source transformation. - # Reapplying the input context would restore consumed planes. - output_values = tuple( - output_value - for _output_plan, _output_spec, output_value in main_outputs - ) - if len(output_values) == 1: - return output_values[0] - return ImageOutputBundle( - output_values, - AlignedImageSliceContext.main_flow_for_output_plans( - tuple( - output_plan - for output_plan, _output_spec, _output_value in main_outputs - ) - ), - ) - main_output = split_runtime_output(raw_output)[0] - if isinstance(main_output, NoMainFlowOutput): - return main_output - output_source_payload = self.invocation.main_flow_output_source_payload( - self.execution_group_source_payload(source_payload) + source_projection: VirtualWorkspaceSourceProjection, + lookup: VirtualWorkspacePathLookup, + ) -> RuntimeArrayData: + """Attach workspace-owned source identity without requiring a binding.""" + + source_ref = source_projection.source_ref_for(lookup) + if source_ref is None: + return payload + source_context = ImagePayloadSourceMetadataContext( + SourceImageIdentity( + lookup.full_virtual_path, + source_projection.source_metadata_for(lookup), + ), + source_ref.backend, + self.context.filemanager, + source_ref.backend_address, ) - return ImageArtifactType.contextualize_output_from_projector( - output_source_payload, - main_output, - None, - self.plane_projection, + metadata = source_context.metadata(payload) + return source_projection.project_unbound_payload( + lookup, + metadata.payload_with( + image_payload_data(payload), + image_payload_mask(payload), + ), ) - def save_module_recorded_output( + def _apply_workspace_source_binding_payload( self, - raw_output: RuntimeFunctionOutput, - ) -> RuntimePayload | NoMainFlowOutput: - """Return the main-flow value from a module that records outputs internally.""" - if isinstance(raw_output, NoMainFlowOutput): - return raw_output - if isinstance(raw_output, tuple): - raise TypeError( - "Module artifact contracts with runtime adapters record declared " - "outputs internally; they must return one main-flow payload, not a " - "tuple of artifact values." - ) - return raw_output + payload: RuntimeArrayData, + *, + source_projection: VirtualWorkspaceSourceProjection, + lookup: VirtualWorkspacePathLookup, + ) -> RuntimeArrayData: + projection = source_projection.require_source_projection_for(lookup) + payload = source_projection.project_payload(lookup, payload) + return self._apply_source_binding_payload( + payload, + source_metadata=source_projection.source_metadata_for(lookup), + source_path=lookup.full_virtual_path, + source_address=projection.ref.backend_address, + read_backend=projection.ref.backend, + ) - def save_artifact_output( + def _apply_source_binding_payload( self, - output_key: str, - output_plan: ArtifactOutputPlan, - value: RuntimePayload, - source_payload: RuntimePayload, + payload: RuntimeArrayData, *, - loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], - ) -> RuntimePayload: - logger.info( - "Saving artifact output '%s' to VFS path '%s' (memory backend)", - output_key, - output_plan.path, - ) - save_started_at = time.perf_counter() - artifact_source_payload = self.artifact_output_source_payload( - output_plan, - source_payload, - loaded_artifact_payloads=loaded_artifact_payloads, - ) - output_source_payload = self.invocation.main_flow_output_source_payload( - self.execution_group_source_payload(artifact_source_payload) + source_metadata: Mapping[str, object] | None, + source_path: str, + source_address: str | None = None, + read_backend: str | None, + ) -> RuntimeArrayData: + source_context = ImagePayloadSourceMetadataContext( + SourceImageIdentity(source_path, source_metadata), + read_backend, + self.context.filemanager, + source_address, ) - materialization_source_metadata = None - materialization_source_ref = output_plan.materialization_source() - if ( - materialization_source_ref is not None - and materialization_source_ref != output_plan.source_context_source() - ): - materialization_source_payload = self.declared_source_payload( - materialization_source_ref, - source_payload, - loaded_artifact_payloads=loaded_artifact_payloads, + source_bindings = self.source_binding_plan + if not source_bindings.binding_declarations: + metadata = source_context.metadata(payload) + return metadata.payload_with( + image_payload_data(payload), + image_payload_mask(payload), ) - materialization_source_metadata = image_payload_metadata( - materialization_source_payload + alias = ( + None + if source_metadata is None + else source_metadata_value( + source_metadata, + SOURCE_BINDING_ALIAS_METADATA_FIELD, ) - saved_value = _save_artifact_value( - self.group_data.context, - output_plan, - value, - output_source_payload, - execution_scope=self.group_data.axis_scope, - group_key=self.group_key, - materialization_source_metadata=materialization_source_metadata, - plane_projector=self.plane_projection, - ) - RuntimeProfileLogger.log( - logger, - "artifact_output_save", - time.perf_counter() - save_started_at, - function=self.function_name, - artifact=output_key, - artifact_type=output_plan.artifact_type.value, ) - return saved_value + if alias is None: + raise ValueError( + f"Source-bound payload {source_path!r} has no declared source alias." + ) + binding = source_bindings.binding_for_alias(alias) + if binding is None: + raise ValueError( + f"Source-bound payload {source_path!r} declares unknown alias " + f"{alias!r}." + ) + return binding.apply_loaded_payload(payload, source_context) - def artifact_output_source_payload( + def _project_output_slices( self, - output_plan: ArtifactOutputPlan, - primary_source_payload: RuntimePayload, - *, - loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], - ) -> RuntimePayload: - source_ref = output_plan.source_context_source() - if source_ref is None: - return primary_source_payload - return self.declared_source_payload( - source_ref, - primary_source_payload, - loaded_artifact_payloads=loaded_artifact_payloads, + processed_stack: RuntimeArrayData, + matching_files: Sequence[str], + ) -> tuple[tuple[RuntimeArrayData, AlignedImageSliceContext | None], ...]: + """Project the original output through its nominal image topology.""" + if isinstance(processed_stack, ImagePayloadMetadataCarrier) and ( + processed_stack.metadata.plane_axis is None + or processed_stack.metadata.persists_whole_image() + ): + output_context = self._unwrapped_main_flow_output_context() + contexts = ( + (output_context,) + if output_context is not None + else ( + self._producer_output_contexts(matching_files) + if len(matching_files) == 1 + else () + ) + ) + context = ( + contexts[0] + if contexts + else AlignedImageSliceContext.anonymous_main_flow() + ) + return ((processed_stack, context),) + if isinstance(processed_stack, AlignedImageStack): + return tuple(processed_stack.projected_output_slices()) + output_context = self._unwrapped_main_flow_output_context() + output_projection = RuntimeSliceProjection.preserved_context_for_value( + processed_stack ) - - -class PatternGroupRuntime: - """Staged runtime for one pattern group.""" - - def __init__(self, request: PatternGroupExecutionRequest) -> None: - self.request = request - self.pattern_repr = str(request.pattern_group_info)[:100] - - def source_workspace_projection_cache( - self, - ) -> VirtualWorkspaceSourceProjectionCache: - """Return the per-context source-workspace projection cache.""" - return self.request.context.runtime_source_workspace_projection_cache - - def source_workspace_projection_authority( - self, - ) -> VirtualWorkspaceSourceProjectionAuthority: - return self.request.context.runtime_source_workspace_projection_authority - - @staticmethod - def _is_relative_to(path: Path, root: Path) -> bool: - try: - path.relative_to(root) - except ValueError: - return False - return True - - @classmethod - def _input_memory_path(cls, input_dir: Path, matched_path: str) -> str: - """Return the VFS memory path for one matched source path.""" - path = Path(matched_path) - if path.is_absolute() or cls._is_relative_to(path, input_dir): - return str(path) - return str(input_dir / path) - - @classmethod - def _input_relative_path(cls, input_dir: Path, matched_path: str) -> Path: - """Return matched path identity relative to the step input root.""" - path = Path(matched_path) - if cls._is_relative_to(path, input_dir): - return path.relative_to(input_dir) - if path.is_absolute(): - return Path(path.name) - return path - - def run(self) -> None: - start_time = time.time() if logger.isEnabledFor(logging.DEBUG) else None - plan = self.request.execution_plan - logger.debug("Processing pattern %s for axis %s", self.pattern_repr, plan.axis_id) - - try: - load_started_at = time.perf_counter() - matching_files, main_data_stack = ( - self.request.load_input_stack(self) - ) - except NoStepOutputManifestMatch: - logger.debug( - "Skipping stale pattern group %s for step %s (%s); no files " - "belong to producer manifest.", - self.pattern_repr, - plan.step_index, - plan.step_name, - ) - return - try: - RuntimeProfileLogger.log( - logger, - "pattern_load_stack", - time.perf_counter() - load_started_at, - step=plan.step_index, - step_name=plan.step_name, - pattern=self.pattern_repr, - ) - execute_started_at = time.perf_counter() - loaded = PatternGroupData.from_loaded_group( - self.request, matching_files, main_data_stack, + if output_projection is not None: + unstack_started_at = time.perf_counter() + output_slices = list( + RuntimeSliceProjection.value_for_slice( + processed_stack, + output_projection.selected_plane(slice_index), + ) + for slice_index in range(output_projection.axis_size) ) - processed_stack = self.execute_chain(loaded) RuntimeProfileLogger.log( logger, - "pattern_execute_chain", - time.perf_counter() - execute_started_at, - step=plan.step_index, - step_name=plan.step_name, - pattern=self.pattern_repr, + "pattern_source_unstack", + time.perf_counter() - unstack_started_at, + step=self.execution_plan.step_index, + step_name=self.execution_plan.step_name, + slices=len(output_slices), ) - if isinstance(processed_stack, NoMainFlowOutput): - self._record_main_flow_passthrough(loaded.matching_files) + output_payloads = output_slices + else: + processed_data = image_payload_data(processed_stack) + try: + unstack_started_at = time.perf_counter() + output_slices = list( + unstack_runtime_slices( + processed_data, + self.execution_plan.output_memory_type, + self.execution_plan.device_id_for( + self.execution_plan.output_memory_type + ), + expected_count=len(matching_files), + ) + ) RuntimeProfileLogger.log( logger, - "pattern_no_main_flow_output", - 0.0, - step=plan.step_index, - step_name=plan.step_name, - pattern=self.pattern_repr, - ) - logger.debug( - "Pattern group %s for step %s recorded artifacts without " - "publishing main-flow output.", - self.pattern_repr, - plan.step_name, + "pattern_source_unstack", + time.perf_counter() - unstack_started_at, + step=self.execution_plan.step_index, + step_name=self.execution_plan.step_name, + slices=len(output_slices), ) - return - if not plan.requires_main_flow_checkpoint(self.request.context.step_plans): - return - output_records = self._save_outputs(processed_stack, loaded.matching_files) - output_paths = [record.output_path for record in output_records] - cleanup_started_at = time.perf_counter() - self._cleanup_collapsed_domains( - output_records, - loaded.matching_files, - output_paths, - ) - step_output_manifest(self.request.context).record_outputs( - plan, - output_records, - collapsed_input_domain=(len(output_records) < len(loaded.matching_files)), + except ValueError as exc: + output_shape = np.shape(processed_data) + output_ndim = np.ndim(processed_data) + logger.error("Function output is not an OpenHCS image stack.") + logger.error("Output type: %s", type(processed_stack)) + logger.error("Output shape: %s", output_shape) + logger.error("Output ndim: %s", output_ndim) + raise ValueError( + "Main processing must result in an image stack shaped " + f"(N, H, W) or (N, H, W, C), got " + f"{output_shape}" + ) from exc + + context_started_at = time.perf_counter() + output_payloads = unstack_image_payload_context( + processed_stack, + output_slices, + default_plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, ) RuntimeProfileLogger.log( logger, - "pattern_cleanup", - time.perf_counter() - cleanup_started_at, - step=plan.step_index, - step_name=plan.step_name, - pattern=self.pattern_repr, - ) - if start_time is not None and logger.isEnabledFor(logging.DEBUG): - logger.debug( - "Finished pattern group %s in %.2fs.", - self.pattern_repr, - time.time() - start_time, - ) - except Exception as e: - logger.error( - "Error processing pattern group %s: %s", self.pattern_repr, e, - exc_info=True, + "pattern_payload_context_unstack", + time.perf_counter() - context_started_at, + step=self.execution_plan.step_index, + step_name=self.execution_plan.step_name, + slices=len(output_payloads), ) - raise ValueError( - f"Failed to process pattern group {self.pattern_repr}: {e}" - ) from e - - def _record_main_flow_passthrough(self, matching_files: Sequence[str]) -> None: - """Record existing main-flow anchors for artifact-only step outputs.""" - if not matching_files: - return - plan = self.request.execution_plan - if not plan.requires_main_flow_checkpoint(self.request.context.step_plans): - return - parser = self.request.context.microscope_handler.parser - manifest = step_output_manifest(self.request.context) - producer_records = self.request.passthrough_producer_records(matching_files) - if producer_records is None: - records = tuple( - ProducedOutputSemantics.from_existing_main_flow_path( - plan, - self._input_memory_path(plan.input_dir, matching_file), - parser, - ) - for matching_file in matching_files + slice_contexts = ( + (output_context,) * len(output_payloads) + if output_context is not None + else () + ) + if not slice_contexts and len(output_payloads) == len(matching_files): + slice_contexts = self._producer_output_contexts(matching_files) + if not slice_contexts: + slice_contexts = tuple( + AlignedImageSliceContext.anonymous_main_flow() + for _payload in output_payloads ) - else: - records = tuple(record.passed_through(plan) for record in producer_records) - manifest.record_outputs(plan, records) + return tuple(zip(output_payloads, slice_contexts, strict=True)) - def _producer_output_contexts( + def _unwrapped_main_flow_output_context( self, - matching_files: Sequence[str], - ) -> tuple[AlignedImageSliceContext, ...]: - """Resolve exact producer contexts for the loaded main-flow paths.""" - - return step_output_manifest( - self.request.context - ).producer_output_contexts_for_paths( - self.request.execution_plan, - matching_files, - self.request.context.microscope_handler.parser, + ) -> AlignedImageSliceContext | None: + ArtifactInputPlan.require_exact_map( + self.execution_plan.artifact_inputs, + boundary="Component artifact input", + ) + return self.compiled_group.unwrapped_main_flow_output_context( + self.selected_artifact_output_plans() ) - def _load_input_stack( + def _save_outputs( self, - ) -> tuple[list[str], RuntimeArrayData]: - context = self.request.context - plan = self.request.execution_plan - request = self.request - if not context.microscope_handler: - raise RuntimeError("MicroscopeHandler not available in context.") - - output_manifest = step_output_manifest(context) - producer_index = output_manifest.producer_record_index_for( - plan, context.microscope_handler.parser, - ) - producer_records = ( - None if producer_index is None - else producer_index.matching_records(str(request.pattern_group_info)) - ) - producer_matching_files = ( - () if producer_records is None - else tuple(record.output_path for record in producer_records) - ) - matching_files = list(producer_matching_files) - source_projection = ( - self.source_workspace_projection_authority().projection_if_available() - ) - if not matching_files: - matching_files = context.microscope_handler.path_list_from_pattern( - str(plan.input_dir), - request.pattern_group_info, - context.filemanager, - plan.read_backend, - ( - [component.value for component in plan.variable_components] - if plan.variable_components - else None - ), - pattern_cache=context.runtime_pattern_discovery_cache, + processed_stack: RuntimeArrayData, + matching_files: list[str], + ) -> list[ProducedOutputSemantics]: + context = self.context + unstack_started_at = time.perf_counter() + projected_outputs = self._project_output_slices(processed_stack, matching_files) + plan = self.execution_plan + explicit_output_surfaces = isinstance(processed_stack, AlignedImageStack) + if explicit_output_surfaces: + stack_payload = processed_stack.copy_projected_output_stack( + projected_outputs, + memory_type=plan.output_memory_type, + device_id=plan.device_id_for(plan.output_memory_type), ) - if producer_index is not None and not producer_matching_files: - selected_paths = [ - path for path in matching_files if producer_index.contains(path) - ] - if matching_files and not selected_paths: - raise NoStepOutputManifestMatch - matching_files = selected_paths - - if not matching_files: - raise ValueError( - f"No matching files found for pattern group {self.pattern_repr} " - f"in {plan.input_dir}. " - f"This indicates either: (1) no image files exist in the directory, " - f"(2) files don't match the pattern, or (3) pattern parsing failed. " - f"Check that input files exist and match the expected naming convention." + elif isinstance(processed_stack, ImagePayloadMetadataCarrier) and ( + processed_stack.metadata.plane_axis is None + or processed_stack.metadata.persists_whole_image() + ): + stack_payload = ImagePayloadStackComposition.copy_whole_image( + processed_stack, + memory_type=plan.output_memory_type, + device_id=plan.device_id_for(plan.output_memory_type), ) - - matching_files = self._filter_matching_files_for_group(matching_files) - - if logger.isEnabledFor(logging.DEBUG): - logger.debug( - "Pattern %s matched %d files: %s", - self.pattern_repr, - len(matching_files), - [Path(f).name for f in matching_files], + else: + stack_payload = processed_stack + RuntimeProfileLogger.log( + logger, + "pattern_validate_unstack", + time.perf_counter() - unstack_started_at, + step=plan.step_index, + step_name=plan.step_name, + pattern=self.pattern_repr, + ) + output_contexts = tuple( + ( + context + if context is not None + else AlignedImageSliceContext.anonymous_main_flow() ) - - if not producer_matching_files: - matching_files.sort() - if logger.isEnabledFor(logging.DEBUG): + for _payload, context in projected_outputs + ) + save_started_at = time.perf_counter() + + def plane_axis_for_output( + context: AlignedImageSliceContext, + ) -> RuntimePlaneAxis | None: + if isinstance(processed_stack, AlignedImageStack): + return processed_stack.plane_axis_for_output_context(context) + if isinstance(processed_stack, ImagePayloadMetadataCarrier): + return image_payload_metadata(processed_stack).plane_axis + return RuntimePlaneAxis.RUNTIME_SLICE + + output_slices = tuple(payload for payload, _context in projected_outputs) + num_outputs = len(output_slices) + num_inputs = len(matching_files) + + if num_outputs < num_inputs: logger.debug( - "Pattern %s sorted files: %s", - self.pattern_repr, - [Path(f).name for f in matching_files], + "Function returned %d images from %d inputs - likely " + "flattening operation", + num_outputs, + num_inputs, + ) + elif num_outputs > num_inputs: + logger.debug( + "Function returned %s output slices from %s positional input " + "files; extra slices must carry payload component identity.", + num_outputs, + num_inputs, ) - matching_files = self._filter_matching_files_for_source_bindings(matching_files) - full_file_paths = [ - self._input_memory_path(plan.input_dir, file_path) - for file_path in matching_files - ] - workspace_path_lookups = tuple( - VirtualWorkspacePathLookup.from_paths( - virtual_path, - full_virtual_path, + output_payloads = [] + output_payload_metadata = [] + output_paths_batch = [] + output_records = [] + + overwritten_output_paths: list[str] = [] + output_directory_exists = context.filemanager.exists( + str(self.execution_plan.output_dir), + Backend.MEMORY.value, + ) + for i, img_slice in enumerate(output_slices): + input_filename = None + if i < len(matching_files): + input_filename = matching_files[i] + output_path_request = FunctionOutputPathRequest( + parser=context.microscope_handler.parser, + output_dir=self.execution_plan.output_dir, + output_payload=img_slice, + input_path=input_filename, + variable_components=self.execution_plan.variable_components, + input_aligned_output=num_outputs == num_inputs, + identity_cache=context.runtime_function_output_identity_cache, ) - for virtual_path, full_virtual_path in zip( - matching_files, - full_file_paths, - strict=True, + try: + output_identity = FunctionOutputIdentity.from_request( + output_path_request + ) + except ValueError as exc: + if input_filename is None: + raise ValueError( + f"Function returned {num_outputs} output slices but only " + f"{num_inputs} input files were available, and output slice " + f"{i} does not carry payload component identity." + ) from exc + raise + output_context = output_contexts[i] + # Only explicit aligned output surfaces own filename qualifiers. + # An unwrapped canonical artifact still owns its typed source + # context, while its ordinary main-flow checkpoint keeps the + # source filename independently of named artifact materialization. + if explicit_output_surfaces and not output_context.is_anonymous_main_flow: + output_identity = output_identity.with_filename_qualifier( + output_context.output_key + ) + output_path = output_identity.path_for_request(output_path_request) + output_path_text = str(output_path) + img_slice = output_context.contextualize_image_payload(img_slice) + output_metadata = image_payload_metadata(img_slice) + output_component_metadata = output_identity.component_metadata( + output_metadata.source_component_metadata, + ) + if output_metadata.source_component_metadata != output_component_metadata: + output_metadata = output_metadata.with_source_component_metadata( + output_component_metadata + ) + img_slice = output_metadata.attach_to(img_slice) + output_record = ProducedOutputSemantics.from_output( + self.execution_plan, + output_path_text, + output_identity, + output_context=output_context, + image_metadata=output_metadata, + main_flow_plane_axis=plane_axis_for_output(output_context), ) + + if output_directory_exists and context.filemanager.exists( + output_path_text, + Backend.MEMORY.value, + ): + overwritten_output_paths.append(output_path_text) + + output_payloads.append(img_slice) + output_payload_metadata.append(output_metadata) + output_paths_batch.append(output_path_text) + output_records.append(output_record) + + FunctionOutputIdentity.validate_output_paths( + output_paths_batch, + input_paths=matching_files, + step_name=self.execution_plan.step_name, + pattern_repr=self.pattern_repr, + identities=output_records, ) - workspace_source_lookups = ( - self._workspace_source_binding_lookups( - source_projection, - workspace_path_lookups, + + if overwritten_output_paths: + for output_path_text in overwritten_output_paths: + context.filemanager.delete(output_path_text, Backend.MEMORY.value) + context.runtime_image_stack_cache.discard_paths( + tuple(overwritten_output_paths) ) - if source_projection is not None - else () + + context.filemanager.ensure_directory( + str(self.execution_plan.output_dir), + Backend.MEMORY.value, ) - if producer_index is not None: - if producer_matching_files: - producer_index.validate_input_records(producer_records) - else: - producer_records = producer_index.records_for_paths(matching_files) - ImagePayloadStackComposition.validate_main_flow_cohort(producer_records) - cached_stack = context.runtime_image_stack_cache.get( - tuple(full_file_paths), - memory_type=plan.input_memory_type, + context.filemanager.save_batch( + output_payloads, + output_paths_batch, + Backend.MEMORY.value, ) + if stack_payload is not None: + stack_payload = ImagePayloadStackComposition.with_saved_output_context( + stack_payload, + output_payloads, + output_payload_metadata, + single_output_plane_axis=( + plane_axis_for_output(output_contexts[0]) + if len(output_payloads) == 1 + else None + ), + ) + context.runtime_image_stack_cache.store( + tuple(output_paths_batch), + memory_type=self.execution_plan.output_memory_type, + stack=stack_payload, + ) + RuntimeProfileLogger.log( + logger, + "runtime_stack_cache_store", + 0.0, + step=self.execution_plan.step_index, + step_name=self.execution_plan.step_name, + paths=len(output_paths_batch), + memory_type=self.execution_plan.output_memory_type, + ) RuntimeProfileLogger.log( logger, - "runtime_stack_cache_get", - 0.0, + "pattern_save_outputs", + time.perf_counter() - save_started_at, step=plan.step_index, step_name=plan.step_name, - hit=cached_stack is not None, - paths=len(full_file_paths), - memory_type=plan.input_memory_type, + pattern=self.pattern_repr, ) - if cached_stack is None: - raw_slices = SourceFileUniverse( - tuple(full_file_paths), - Backend.MEMORY - if plan.main_input_dependency.kind is StepInputDependencyKind.STEP_OUTPUT - else Backend(plan.read_backend), - ).load_images(context.filemanager, zarr_config=plan.zarr_config) - if source_projection is not None or not producer_matching_files: - raw_slices = self._apply_source_image_loading_semantics( - raw_slices, - workspace_path_lookups, - workspace_source_lookups, - source_projection, - ) + return output_records - if not raw_slices: - raise ValueError( - f"No valid images loaded for pattern group {self.pattern_repr} " - f"in {plan.input_dir}. " - f"Found {len(matching_files)} matching files but failed to load any valid images. " - f"This indicates corrupted image files, unsupported formats, or I/O errors. " - f"Check file integrity and format compatibility." - ) + def _cleanup_collapsed_domains( + self, + output_records: Sequence[ProducedOutputSemantics], + matching_files: list[str], + output_paths: Sequence[str], + ) -> None: + context = self.context + num_outputs = len(output_records) + num_inputs = len(matching_files) - main_data_stack = ImagePayloadStackComposition.from_loaded_images( - raw_slices, - producer_records=producer_records, - execution_plan=plan, - source_projection=source_projection, - workspace_source_lookups=workspace_source_lookups, + if num_outputs >= num_inputs: + return + + if self.execution_plan.input_dir == self.execution_plan.output_dir: + return + + retained_paths = {Path(path).as_posix() for path in output_paths} + retained_paths.update( + Path(record.output_path).as_posix() + for record in step_output_manifest(context).produced_records_for( + self.execution_plan ) - if not producer_records: - metadata = image_payload_metadata(main_data_stack) - domain = request.source_binding_plan.source_spatial_domain.admit_source_cohort( - metadata.source_spatial_domain, - depth=len(matching_files), + ) + for j in range(num_outputs, num_inputs): + unused_filename = matching_files[j] + unused_relative_path = self._input_relative_path( + self.execution_plan.input_dir, + unused_filename, + ) + unused_path = self.execution_plan.output_dir / unused_relative_path + if unused_path.as_posix() in retained_paths: + continue + if context.filemanager.exists( + str(unused_path), + Backend.MEMORY.value, + ): + context.runtime_image_stack_cache.discard_paths((str(unused_path),)) + context.filemanager.delete( + str(unused_path), + Backend.MEMORY.value, + ) + logger.debug( + "Deleted unused collapsed-domain file after reduced " + "output cardinality: %s", + unused_path, ) - main_data_stack = metadata.replace_fields( - source_spatial_domain=domain, - ).attach_to(main_data_stack) - else: - main_data_stack = cached_stack - return matching_files, main_data_stack - def _workspace_source_binding_lookups( +@dataclass(frozen=True, slots=True, kw_only=True) +class ArtifactPatternGroupExecutionRequest(PatternGroupExecutionRequest): + """Admit exact canonical producer values into an independent cohort.""" + + def load_input_stack( self, - source_projection: VirtualWorkspaceSourceProjection, - lookups: Sequence[VirtualWorkspacePathLookup], - ) -> tuple[VirtualWorkspacePathLookup, ...]: - """Return workspace paths owned by this step's exact source bindings.""" - - bindings = self.request.source_binding_plan.binding_declarations - return tuple( - lookup - for lookup in lookups - for projection in (source_projection.source_projection_for(lookup),) - if projection is not None - and any(projection.matches_binding(binding) for binding in bindings) + ) -> tuple[list[str], RuntimeArrayData]: + edges = self.execution_plan.stored_primary_input_edges_for_group( + self.compiled_group, + self.component_key, ) + if not edges: + raise ValueError("Artifact cohort requires complete stored primary inputs.") + payloads = [] + matching_files = [] + for edge in edges: + artifact_input = RuntimeArtifactInput( + edge_plan=edge, + axis_scope=self.axis_scope, + backend=Backend.MEMORY.value, + source_binding_plan=self.source_binding_plan, + ) + records = artifact_input.records(self.context.runtime_value_store) + source_payload = ( + edge.spec.artifact_type.source_image_payload_from_runtime_value( + artifact_input.composed_value(records), + ) + ) + if source_payload is None: + raise ValueError( + f"Artifact cohort source {edge.spec.ref()!r} has no image context." + ) + payloads.append( + ImagePayloadStackComposition.copy_whole_image( + source_payload, + memory_type=self.execution_plan.input_memory_type, + device_id=self.execution_plan.device_id_for( + self.execution_plan.input_memory_type, + ), + ) + ) + matching_files.extend(record.location.path for record in records) + main_data_stack = ImagePayloadConsumption.NATURAL.compose_image_payload( + self.execution_plan.step_name, + tuple(payloads), + ).payload + return matching_files, main_data_stack - def _filter_matching_files_for_group( + def loaded_plane_count( self, - matching_files: list[str], - ) -> list[str]: - """Constrain grouped executions to files from the current component.""" - if ( - self.request.execution_plan.main_input_dependency.kind - is StepInputDependencyKind.STEP_OUTPUT - or self.request.compiled_group.runtime_domain - is RuntimeInvocationDomain.ARTIFACT_MANAGED - ): - return matching_files - if self.request.main_flow_source_binding_plan.has_primary_content: - return matching_files + matching_files: Sequence[str], + payload: RuntimeArrayData, + ) -> int: + """Canonical payloads declare their runtime axis independently of paths.""" + count = RuntimeSliceProjection.slice_count_from_values((payload,)) + return 1 if count is None else count - group_component = self.request.execution_plan.execution_group_value - component_value = self.request.component_value - if group_component is None or component_value is None: - return matching_files + def loaded_fixed_component_values( + self, + payload: RuntimeArrayData, + ) -> RuntimeFixedComponentValues: + """Retain exact producer coordinates admitted by typed discovery.""" + return self.fixed_component_values - parser = self.request.context.microscope_handler.parser - filtered = self.request.context.runtime_pattern_discovery_cache.files_for_component( - parser, - matching_files, - parser.component_for_name(group_component), - component_value, + def passthrough_producer_records( + self, + matching_files: Sequence[str], + ) -> tuple[ProducedOutputSemantics, ...]: + """Preserve input transport independently of artifact context admission.""" + records = step_output_manifest(self.context).producer_records_for( + self.execution_plan, ) - if not filtered: - raise ValueError( - f"Pattern group {self.pattern_repr} for {group_component}=" - f"{component_value!r} matched files, but none carried the " - f"expected grouped component. Matched files: {matching_files}" - ) - return filtered + if records is None: + raise ValueError("Artifact input passthrough requires producer lineage.") + return records - def _filter_matching_files_for_source_bindings( - self, - matching_files: list[str], - ) -> list[str]: - """Constrain the loaded main stack to declared image source bindings.""" - if ( - self.request.execution_plan.main_input_dependency.kind - is StepInputDependencyKind.STEP_OUTPUT - ): - return matching_files +@dataclass(frozen=True, slots=True, kw_only=True) +class PatternGroupData(PatternGroupExecutionScope): + """Complete loaded cohort and its original execution coordinates.""" - source_binding_plan = self.request.main_flow_source_binding_plan - if not source_binding_plan.has_primary_content: - return matching_files - bindings = tuple( - binding - for binding in source_binding_plan.bindings - if binding.projection_role is SourceProjectionRole.PRIMARY_PLANE - ) - if not bindings: - return matching_files - selector_bindings = SourceBindingCandidateMatcher.selector_bindings(bindings) + artifact_inputs: Mapping[ArtifactSpecRef, ArtifactInputPlan] + artifact_outputs: ArtifactOutputPlans + runtime_plane_index: int + runtime_plane_count: int + matching_files: list[str] + main_data_stack: RuntimeArrayData - source_context = self._source_binding_candidate_context() - if ( - not selector_bindings - and not source_context.source_projections_by_virtual_path - ): - return matching_files - compatible = list( - SourceBindingMatchedImageSet.from_plan( - bindings=bindings, - match_plan=source_binding_plan.match_plan, - source_context=source_context, - identity_policy=(self.request.context.source_image_set_identity_policy), - ).expand( + @classmethod + def from_loaded_group( + cls, + request: "PatternGroupExecutionRequest", + matching_files: list[str], + main_data_stack: RuntimeArrayData, + ) -> "PatternGroupData": + ArtifactInputPlan.require_exact_map( + request.execution_plan.artifact_inputs, + boundary="Component artifact input", + ) + artifact_inputs = dict(request.execution_plan.artifact_inputs) + artifact_outputs = request.selected_artifact_output_plans() + logger.debug( + "Selected artifact outputs for component %s: %s", + request.component_key, + artifact_outputs, + ) + return cls( + matching_files=matching_files, + main_data_stack=main_data_stack, + context=request.context, + execution_plan=request.execution_plan, + compiled_group=request.compiled_group, + artifact_inputs=artifact_inputs, + artifact_outputs=artifact_outputs, + runtime_plane_index=request.component_index, + runtime_plane_count=request.loaded_plane_count( matching_files, - source_universe=self._source_binding_load_universe(), - ) + main_data_stack, + ), + component_value=request.component_value, + fixed_component_values=request.loaded_fixed_component_values( + main_data_stack + ), ) - if compatible: - return compatible + def require_invocations(self) -> None: + if self.compiled_group.invocations: + return raise ValueError( - f"Source-bound step {self.request.execution_plan.step_name!r} resolved no files for " - f"image bindings {[binding.alias for binding in bindings]!r} in pattern " - f"{self.pattern_repr}. Matched files before source filtering: " - f"{matching_files!r}." - ) - - def _source_binding_load_universe(self) -> tuple[str, ...]: - """Return loadable files available for source image-set expansion.""" - source_projection = ( - self.source_workspace_projection_authority().projection_if_available() - ) - request = SourceUniverseRequest.from_context( - context=self.request.context, - plan=self.request.execution_plan, - matching_files=(), - source_projection=source_projection, + f"Compiled function group {self.compiled_group.group_key} has no invocations." ) - return request.runtime_universe_state().require_load_universe().files - def _source_binding_candidate_context(self) -> SourcePatternResolutionContext: - projection = self.source_workspace_projection_authority().projection_or_empty() - return self.request.context.runtime_source_binding_context_cache.source_pattern_context( - parser=self.request.context.microscope_handler.parser, - projection=self.source_workspace_projection_cache().filtered_by_axis( - projection, - axis_id=self.request.execution_plan.axis_id, - ), - metadata_rules=self.request.source_binding_plan.metadata_rules, - ) + def execute_chain(self) -> RuntimeArrayData | NoMainFlowOutput: + self.require_invocations() + current_stack: RuntimeArrayData | NoMainFlowOutput = self.main_data_stack + current_memory_type = self.execution_plan.input_memory_type + debug_sink = debug_event_sink_from_context(self.context) + declared_source_bindings = self.execution_plan.source_binding_plan + for invocation in self.compiled_group.invocations: + executor = FunctionCoreExecutor.from_group_invocation( + self, + invocation, + main_data_arg=current_stack, + source_memory_type=current_memory_type, + declared_source_bindings=declared_source_bindings, + ) + if executor is None: + continue + captures_debug = debug_sink.captures_invocation_events() + if captures_debug and debug_sink.should_skip_invocation( + executor.debug_cursor() + ): + continue - def _apply_source_image_loading_semantics( - self, - raw_slices: Sequence[RuntimeArrayData], - workspace_path_lookups: Sequence[VirtualWorkspacePathLookup], - workspace_source_lookups: Sequence[VirtualWorkspacePathLookup], - source_projection: VirtualWorkspaceSourceProjection | None, - ) -> list[RuntimeArrayData]: - if source_projection is not None: - source_lookups = frozenset(workspace_source_lookups) - return [ - ( - self._apply_workspace_source_binding_payload( - payload, - source_projection=source_projection, - lookup=lookup, - ) - if lookup in source_lookups - else self._apply_workspace_source_payload( - payload, - source_projection=source_projection, - lookup=lookup, - ) + invocation_started_at = time.perf_counter() + try: + current_stack = executor.execute( + debug_sink=debug_sink if captures_debug else None, ) - for payload, lookup in zip( - raw_slices, - workspace_path_lookups, - strict=True, + except Exception as exc: + if captures_debug: + debug_sink.record( + executor.debug_event( + DebugEventType.EXCEPTION, + exception=exc, + ) + ) + raise + invocation_seconds = time.perf_counter() - invocation_started_at + if captures_debug: + after_event = executor.debug_event( + DebugEventType.AFTER_INVOCATION, + timing_seconds=invocation_seconds, ) - ] + debug_sink.record(after_event) + if debug_sink.should_stop_after_invocation(after_event): + break + RuntimeProfileLogger.log( + logger, + "invocation_total", + invocation_seconds, + function=invocation.key.function_name, + group=invocation.key.group_key, + position=invocation.key.position, + ) + if isinstance(current_stack, NoMainFlowOutput): + return current_stack + current_memory_type = executor.invocation.contract.output_memory_type + if self.compiled_group.preserves_input_main_flow() and all( + invocation.contract.artifact_output_policy.records_outputs + for invocation in self.compiled_group.invocations + ): + return NoMainFlowOutput() + return current_stack - universe_state = SourceUniverseRequest.from_context( - context=self.request.context, - plan=self.request.execution_plan, - matching_files=tuple( - lookup.virtual_path for lookup in workspace_path_lookups - ), - source_projection=None, - ).runtime_universe_state() - cache = self.request.context.runtime_source_binding_context_cache - source_metadata = cache.normalized_source_metadata( - universe_state.source_metadata_by_path + +def _save_artifact_value( + context: ProcessingContext, + output_plan: ArtifactOutputPlan, + value: RuntimePayload, + source_payload: RuntimePayload, + *, + execution_scope: RuntimeExecutionAxisScope, + group_key: str | None, + plane_projector: RuntimePlaneAxisProjector | None, + materialization_source_metadata: ImagePayloadMetadata | None = None, +) -> RuntimePayload: + """Validate and save one planned artifact value to the memory VFS.""" + resolved_output_plan = output_plan.for_invocation_group(group_key) + vfs_path = resolved_output_plan.path + runtime_value = RuntimeValue.normalize_output_from_projector( + resolved_output_plan, + value, + source_payload=source_payload, + plane_projector=plane_projector, + execution_scope=execution_scope, + materialization_source_metadata=materialization_source_metadata, + ) + + location = RuntimeArtifactLocation( + path=vfs_path, + backend=Backend.MEMORY.value, + ) + runtime_value_store = context.runtime_value_store + runtime_value_store.replace( + runtime_value, + path=location.path, + backend=location.backend, + ) + replace_runtime_artifact_payload( + context.filemanager, + runtime_value.data, + location, + ) + return runtime_value.data + + + + + + +@dataclass(frozen=True, slots=True) +class FunctionCoreExecutor: + """Execute one scoped callable invocation and route declared artifact I/O.""" + + group_data: PatternGroupData + invocation: CompiledFunctionInvocation + artifact_inputs: Mapping[ + InvocationArtifactInputProjectionKey, InvocationArtifactInputEdgePlan + ] + artifact_outputs: ArtifactOutputPlans + group_key: str | None + plane_projection: RuntimePlaneProjection + main_data_arg: RuntimeArrayData + source_memory_type: str + + @classmethod + def from_group_invocation( + cls, + group_data: PatternGroupData, + invocation: CompiledFunctionInvocation, + *, + main_data_arg: RuntimeArrayData, + source_memory_type: str, + declared_source_bindings: CompiledSourceBindingPlan, + ) -> "FunctionCoreExecutor | None": + """Admit the selected compiled edges and outputs for this live invocation.""" + group_key = invocation.key.runtime_group_key(group_data.component_value) + active_source_bindings = group_data.active_main_flow_source_binding_plan( + main_data_arg ) - source_context = SourcePatternResolutionContext.from_sources( - parser=self.request.context.microscope_handler.parser, - source_paths_by_virtual_path=universe_state.step_input_source_paths, - source_metadata_by_path=source_metadata, - metadata_rules=self.request.source_binding_plan.metadata_rules, + active_outputs = invocation.output_plans_for_component( + group_data.execution_plan.execution_group_scope, + group_data.component_key, ) - return [ - self._apply_source_binding_payload( - payload, - source_metadata=source_context.merged_metadata_for_paths( - ( - lookup.virtual_path, - lookup.full_virtual_path, + if active_outputs is None: + return None + inputs = {} + for edge_key, edge in invocation.select_inputs( + group_data.artifact_inputs, + active_output_plans=active_outputs, + ).items(): + if ( + edge.main_flow_projection is not None + and declared_source_bindings.declares_artifact_ref(edge.spec.ref()) + and not active_source_bindings.declares_artifact_ref(edge.spec.ref()) + ): + if not invocation.adapter_manages_artifact_inputs: + continue + if edge.storage_plan is not None: + raise ValueError( + f"Stored primary input {edge.spec.ref()!r} is not represented " + "by this main-flow payload; its producer cannot substitute " + "for the current payload epoch." ) - ), - source_path=source_context.source_path_for(lookup.full_virtual_path), - read_backend=self.request.execution_plan.read_backend, - ) - for payload, lookup in zip( - raw_slices, - workspace_path_lookups, - strict=True, - ) - ] - - def _apply_workspace_source_payload( - self, - payload: RuntimeArrayData, - *, - source_projection: VirtualWorkspaceSourceProjection, - lookup: VirtualWorkspacePathLookup, - ) -> RuntimeArrayData: - """Attach workspace-owned source identity without requiring a binding.""" - - source_ref = source_projection.source_ref_for(lookup) - if source_ref is None: - return payload - source_context = ImagePayloadSourceMetadataContext( - SourceImageIdentity( - lookup.full_virtual_path, - source_projection.source_metadata_for(lookup), + edge = replace(edge, main_flow_projection=None) + inputs[edge_key] = edge + return cls( + group_data=group_data, + invocation=invocation, + artifact_inputs=inputs, + artifact_outputs=invocation.select_outputs( + group_data.artifact_outputs, + compiled_output_plans=active_outputs, ), - source_ref.backend, - self.request.context.filemanager, - source_ref.backend_address, - ) - metadata = source_context.metadata(payload) - return source_projection.project_unbound_payload( - lookup, - metadata.payload_with( - image_payload_data(payload), - image_payload_mask(payload), + group_key=group_key, + plane_projection=RuntimePlaneProjection.stack( + group_data.runtime_plane_count ), + main_data_arg=main_data_arg, + source_memory_type=source_memory_type, ) - def _apply_workspace_source_binding_payload( + def runtime_adapter_request( self, - payload: RuntimeArrayData, - *, - source_projection: VirtualWorkspaceSourceProjection, - lookup: VirtualWorkspacePathLookup, - ) -> RuntimeArrayData: - projection = source_projection.require_source_projection_for(lookup) - payload = source_projection.project_payload(lookup, payload) - return self._apply_source_binding_payload( - payload, - source_metadata=source_projection.source_metadata_for(lookup), - source_path=lookup.full_virtual_path, - source_address=projection.ref.backend_address, - read_backend=projection.ref.backend, + source_payload: RuntimePayload, + ) -> RuntimeAdapterRequest: + return RuntimeAdapterRequest( + context=self.group_data.context, + callable_contract=self.invocation.contract, + artifact_inputs=self.artifact_inputs, + artifact_outputs=self.artifact_outputs, + group_key=self.group_key, + plane_projection=self.plane_projection, + source_payload=source_payload, + source_binding_plan=self.group_data.source_binding_plan, + axis_scope=self.group_data.axis_scope, + variable_components=tuple( + self.group_data.execution_plan.variable_components + ), + source_load_plan=self.group_data.execution_plan.source_load_plan, ) - def _apply_source_binding_payload( + def declared_source_payload( self, - payload: RuntimeArrayData, + source_ref: ArtifactSpecRef, + primary_source_payload: RuntimePayload, *, - source_metadata: Mapping[str, object] | None, - source_path: str, - source_address: str | None = None, - read_backend: str | None, - ) -> RuntimeArrayData: - source_context = ImagePayloadSourceMetadataContext( - SourceImageIdentity(source_path, source_metadata), - read_backend, - self.request.context.filemanager, - source_address, - ) - source_bindings = self.request.source_binding_plan - if not source_bindings.binding_declarations: - metadata = source_context.metadata(payload) - return metadata.payload_with( - image_payload_data(payload), - image_payload_mask(payload), - ) - alias = ( - None - if source_metadata is None - else source_metadata_value( - source_metadata, - SOURCE_BINDING_ALIAS_METADATA_FIELD, + loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], + ) -> RuntimePayload: + input_spec = self.invocation.contract.artifact_inputs.by_ref(source_ref) + if input_spec is None: + raise ValueError( + f"Invocation {self.invocation.key!r} does not declare source artifact " + f"{source_ref!r}." ) + stored_payload = loaded_artifact_payloads.get(source_ref) + source_binding = self.group_data.source_binding_plan.binding_for_artifact_ref( + source_ref ) - if alias is None: - raise ValueError( - f"Source-bound payload {source_path!r} has no declared source alias." + main_flow_edges = tuple( + edge + for edge in self.artifact_inputs.values() + if edge.spec.ref() == source_ref and edge.main_flow_projection is not None + ) + uses_main_flow = bool( + stored_payload is None and source_binding is None and main_flow_edges + ) + resolved_origins = sum( + ( + stored_payload is not None, + source_binding is not None, + uses_main_flow, ) - binding = source_bindings.binding_for_alias(alias) - if binding is None: + ) + if resolved_origins != 1: raise ValueError( - f"Source-bound payload {source_path!r} declares unknown alias " - f"{alias!r}." + f"Invocation {self.invocation.key!r} source artifact {source_ref!r} " + "must resolve to exactly one compiled producer, source binding, or " + f"main-flow input; resolved {resolved_origins}." ) - return binding.apply_loaded_payload(payload, source_context) - - @staticmethod - def execute_chain( - group_data: PatternGroupData - ) -> RuntimeArrayData | NoMainFlowOutput: - group_data.require_invocations() - current_stack: RuntimeArrayData | NoMainFlowOutput = group_data.main_data_stack - current_memory_type = group_data.execution_plan.input_memory_type - debug_sink = debug_event_sink_from_context(group_data.context) - declared_source_bindings = group_data.execution_plan.source_binding_plan - for invocation in group_data.compiled_group.invocations: - group_key = invocation.key.runtime_group_key(group_data.component_value) - artifacts = group_data.artifacts.select_for_invocation( - invocation, - execution_scope=group_data.execution_plan.execution_group_scope, - component_key=group_data.component_key, - declared_source_bindings=declared_source_bindings, - active_source_bindings=group_data.active_main_flow_source_binding_plan( - current_stack - ), + if stored_payload is not None: + return stored_payload + if source_binding is not None: + return cast( + RuntimePayload, + self.runtime_adapter_request( + primary_source_payload + ).source_artifact_payload(source_ref), ) - if artifacts is None: - continue - executor = FunctionCoreExecutor( - main_data_arg=current_stack, - source_memory_type=current_memory_type, - group_data=group_data, - invocation=invocation, - artifacts=artifacts, - group_key=group_key, - plane_projection=RuntimePlaneProjection.stack( - group_data.runtime_plane_count - ), + if len(main_flow_edges) != 1: + raise ValueError( + f"Invocation {self.invocation.key!r} source artifact {source_ref!r} " + "must resolve through exactly one selected main-flow input edge; " + f"resolved {len(main_flow_edges)}." ) - captures_debug = debug_sink.captures_invocation_events() - if captures_debug and debug_sink.should_skip_invocation( - executor.debug_cursor() - ): - continue - - invocation_started_at = time.perf_counter() - try: - current_stack = executor.execute( - debug_sink=debug_sink if captures_debug else None, - ) - except Exception as exc: - if captures_debug: - debug_sink.record( - executor.debug_event( - DebugEventType.EXCEPTION, - exception=exc, - ) - ) - raise - invocation_seconds = time.perf_counter() - invocation_started_at - if captures_debug: - after_event = executor.debug_event( - DebugEventType.AFTER_INVOCATION, - timing_seconds=invocation_seconds, - ) - debug_sink.record(after_event) - if debug_sink.should_stop_after_invocation(after_event): - break - RuntimeProfileLogger.log( - logger, - "invocation_total", - invocation_seconds, - function=invocation.key.function_name, - group=invocation.key.group_key, - position=invocation.key.position, + main_flow_projection = main_flow_edges[0].main_flow_projection + if main_flow_projection is MainFlowInputProjection.COMPLETE_PAYLOAD: + return primary_source_payload + if main_flow_projection is not MainFlowInputProjection.DECLARED_SOURCE_IMAGE: + raise ValueError( + f"Invocation {self.invocation.key!r} source artifact {source_ref!r} " + "consumes main flow without a compiled projection." ) - if isinstance(current_stack, NoMainFlowOutput): - return current_stack - current_memory_type = executor.invocation.contract.output_memory_type - if group_data.compiled_group.preserves_input_main_flow() and all( - invocation.contract.artifact_output_policy.records_outputs - for invocation in group_data.compiled_group.invocations - ): - return NoMainFlowOutput() - return current_stack + return project_declared_source_identity(primary_source_payload, source_ref) - def _project_output_slices( + def load_artifact_inputs( self, - processed_stack: RuntimeArrayData, - matching_files: Sequence[str], - ) -> tuple[tuple[RuntimeArrayData, AlignedImageSliceContext | None], ...]: - """Project the original output through its nominal image topology.""" - if isinstance(processed_stack, ImagePayloadMetadataCarrier) and ( - processed_stack.metadata.plane_axis is None - or processed_stack.metadata.persists_whole_image() - ): - output_context = self._unwrapped_main_flow_output_context() - contexts = ( - (output_context,) - if output_context is not None + final_kwargs: dict[str, RuntimeCallableArgument], + source_payload: RuntimePayload, + ) -> dict[ArtifactSpecRef, RuntimePayload]: + if not self.should_load_artifact_inputs(): + return {} + logger.info( + f"Artifact inputs for {self.invocation.contract.function_name}: {self.artifact_inputs}" + ) + loaded_artifact_payloads: dict[ArtifactSpecRef, RuntimePayload] = {} + parameter_values: dict[str, list[RuntimeValue]] = {} + for input_plan in self.artifact_inputs.values(): + parameter_name = input_plan.spec.parameter_name + if not input_plan.requires_callable_binding(): + continue + if parameter_name is None: + raise ValueError( + f"Compiled invocation {self.invocation.key!r} runtime-loaded input " + f"edge {input_plan.key!r} has no callable parameter." + ) + artifact_ref = input_plan.spec.ref() + projected_values = ( + self.load_artifact_input(input_plan.spec.name, input_plan) + if input_plan.uses_runtime_storage() + and input_plan.main_flow_projection is None else ( - self._producer_output_contexts(matching_files) - if len(matching_files) == 1 - else () + RuntimeValue.from_spec( + input_plan.spec, + input_plan.resolve_unstored_payload(self, source_payload), + execution_scope=self.group_data.axis_scope, + ), ) ) - context = ( - contexts[0] if contexts - else AlignedImageSliceContext.anonymous_main_flow() + loaded_value = RuntimeValue.compose(projected_values) + loaded_artifact_payloads[artifact_ref] = loaded_value + parameter_values.setdefault(parameter_name, []).extend(projected_values) + for parameter_name, projected_values in parameter_values.items(): + final_kwargs[parameter_name] = RuntimeValue.compose(tuple(projected_values)) + return loaded_artifact_payloads + + def should_load_artifact_inputs(self) -> bool: + return bool( + any( + edge.requires_callable_binding() + for edge in self.artifact_inputs.values() ) - return ((processed_stack, context),) - if isinstance(processed_stack, AlignedImageStack): - return tuple(processed_stack.projected_output_slices()) - output_context = self._unwrapped_main_flow_output_context() - output_projection = RuntimeSliceProjection.preserved_context_for_value( - processed_stack + and not self.invocation.adapter_manages_artifact_inputs ) - if output_projection is not None: - unstack_started_at = time.perf_counter() - output_slices = list( - RuntimeSliceProjection.value_for_slice( - processed_stack, - output_projection.selected_plane(slice_index), - ) - for slice_index in range(output_projection.axis_size) - ) - RuntimeProfileLogger.log( - logger, - "pattern_source_unstack", - time.perf_counter() - unstack_started_at, - step=self.request.execution_plan.step_index, - step_name=self.request.execution_plan.step_name, - slices=len(output_slices), - ) - output_payloads = output_slices - else: - processed_data = image_payload_data(processed_stack) - try: - unstack_started_at = time.perf_counter() - output_slices = list( - unstack_runtime_slices( - processed_data, - self.request.execution_plan.output_memory_type, - self.request.execution_plan.device_id_for( - self.request.execution_plan.output_memory_type - ), - expected_count=len(matching_files), - ) - ) - RuntimeProfileLogger.log( - logger, - "pattern_source_unstack", - time.perf_counter() - unstack_started_at, - step=self.request.execution_plan.step_index, - step_name=self.request.execution_plan.step_name, - slices=len(output_slices), - ) - except ValueError as exc: - output_shape = np.shape(processed_data) - output_ndim = np.ndim(processed_data) - logger.error("Function output is not an OpenHCS image stack.") - logger.error("Output type: %s", type(processed_stack)) - logger.error("Output shape: %s", output_shape) - logger.error("Output ndim: %s", output_ndim) - raise ValueError( - "Main processing must result in an image stack shaped " - f"(N, H, W) or (N, H, W, C), got " - f"{output_shape}" - ) from exc - context_started_at = time.perf_counter() - output_payloads = unstack_image_payload_context( - processed_stack, - output_slices, - default_plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, - ) - RuntimeProfileLogger.log( - logger, - "pattern_payload_context_unstack", - time.perf_counter() - context_started_at, - step=self.request.execution_plan.step_index, - step_name=self.request.execution_plan.step_name, - slices=len(output_payloads), + def load_artifact_input( + self, + arg_name: str, + edge_plan: InvocationArtifactInputEdgePlan, + ) -> tuple[RuntimeValue, ...]: + storage_plan = edge_plan.storage_plan + if storage_plan is None: + raise ValueError("Artifact input loading requires a storage-backed edge.") + logger.info( + "Loading artifact input '%s' from path '%s' (memory backend)", + arg_name, + storage_plan.path, + ) + load_started_at = time.perf_counter() + try: + loaded_values = RuntimeArtifactInput( + edge_plan=edge_plan, + axis_scope=self.group_data.axis_scope, + backend=Backend.MEMORY.value, + source_binding_plan=self.group_data.source_binding_plan, + ).projected_values(self.group_data.context.runtime_value_store) + except Exception as exc: + logger.error( + "Failed to load artifact input '%s' from '%s': %s", + arg_name, + storage_plan.path, + exc, + exc_info=True, ) - slice_contexts = ( - (output_context,) * len(output_payloads) - if output_context is not None - else () + raise + RuntimeProfileLogger.log( + logger, + "artifact_input_load", + time.perf_counter() - load_started_at, + function=self.invocation.contract.function_name, + artifact=arg_name, + artifact_type=storage_plan.artifact_type.value, + ) + return loaded_values + + def debug_cursor(self) -> DebugCursor: + return DebugCursor.from_invocation( + step_index=self.group_data.execution_plan.step_index, + step_scope_id=self.group_data.execution_plan.step_scope_id, + invocation=self.invocation, + pattern_group_identity=str(self.group_data.runtime_plane_index), + ) + + def debug_artifacts( + self, + artifact_plans: ArtifactInputPlans | ArtifactOutputPlans, + artifact_values: Mapping[ArtifactSpecRef, object] | None = None, + ) -> DebugArtifactRefProjection: + return DebugArtifactRefProjection.from_artifact_plans( + artifact_plans=artifact_plans, + cursor=self.debug_cursor(), + artifact_values=artifact_values, + ) + + def debug_event( + self, + event_type: DebugEventType, + *, + exception: Exception | None = None, + timing_seconds: float | None = None, + invocation_parameters: tuple[DebugInvocationParameter, ...] = (), + input_artifact_values: Mapping[ArtifactSpecRef, object] | None = None, + ) -> DebugEvent: + return DebugEvent.for_invocation( + event_type=event_type, + cursor=self.debug_cursor(), + step_name=self.group_data.execution_plan.step_name, + callable_name=self.invocation.key.function_name, + axis_id=self.group_data.execution_plan.axis_id, + input_artifacts=self.debug_artifacts( + { + edge.storage_plan.ref(): edge.storage_plan + for edge in self.artifact_inputs.values() + if edge.storage_plan is not None + }, + input_artifact_values, + ), + output_artifacts=self.debug_artifacts(self.artifact_outputs), + exception=exception, + timing_seconds=timing_seconds, + invocation_parameters=invocation_parameters, ) - if not slice_contexts and len(output_payloads) == len(matching_files): - slice_contexts = self._producer_output_contexts(matching_files) - if not slice_contexts: - slice_contexts = tuple( - AlignedImageSliceContext.anonymous_main_flow() - for _payload in output_payloads - ) - return tuple(zip(output_payloads, slice_contexts, strict=True)) - def _unwrapped_main_flow_output_context( + def execute( self, - ) -> AlignedImageSliceContext | None: - return self.request.compiled_group.unwrapped_main_flow_output_context( - ComponentArtifactPlans.from_step_component( - self.request.execution_plan, - self.request.component_key, - ).outputs + *, + debug_sink: DebugEventSink | None = None, + ) -> RuntimePayload | NoMainFlowOutput: + converted_data = self.invocation.convert_input( + image_payload_data(self.main_data_arg), + self.source_memory_type, + ) + source_payload = with_image_payload_data(self.main_data_arg, converted_data) + main_data_arg = self.invocation.main_flow_call_argument(source_payload) + final_kwargs = dict(self.invocation.runtime_kwargs) + loads_artifact_inputs = self.should_load_artifact_inputs() + loaded_artifact_payloads: dict[ArtifactSpecRef, RuntimePayload] = {} + if loads_artifact_inputs: + loaded_artifact_payloads = self.load_artifact_inputs( + final_kwargs, + source_payload, + ) + self.bind_runtime_owned_parameters(final_kwargs) + self.bind_runtime_adapter(final_kwargs, source_payload) + raw_output = self.invoke( + main_data_arg, + final_kwargs, + loaded_artifact_payloads=loaded_artifact_payloads, + debug_sink=debug_sink, + ) + return self.save_artifact_outputs( + raw_output, + source_payload, + loaded_artifact_payloads=loaded_artifact_payloads, ) - def _save_outputs( + def execution_group_source_payload( self, - processed_stack: RuntimeArrayData, - matching_files: list[str], - ) -> list[ProducedOutputSemantics]: - context = self.request.context - unstack_started_at = time.perf_counter() - projected_outputs = self._project_output_slices(processed_stack, matching_files) - plan = self.request.execution_plan - explicit_output_surfaces = isinstance(processed_stack, AlignedImageStack) - if explicit_output_surfaces: - stack_payload = processed_stack.copy_projected_output_stack( - projected_outputs, - memory_type=plan.output_memory_type, - device_id=plan.device_id_for(plan.output_memory_type), - ) - elif isinstance(processed_stack, ImagePayloadMetadataCarrier) and ( - processed_stack.metadata.plane_axis is None - or processed_stack.metadata.persists_whole_image() - ): - stack_payload = ImagePayloadStackComposition.copy_whole_image( - processed_stack, - memory_type=plan.output_memory_type, - device_id=plan.device_id_for(plan.output_memory_type), - ) - else: - stack_payload = processed_stack - RuntimeProfileLogger.log( - logger, - "pattern_validate_unstack", - time.perf_counter() - unstack_started_at, - step=plan.step_index, - step_name=plan.step_name, - pattern=self.pattern_repr, + source_payload: RuntimePayload, + ) -> RuntimePayload: + """Return source payload metadata carrying the current grouped identity.""" + component = self.group_data.execution_plan.execution_group_scope.component + if component is None or self.group_key is None: + return source_payload + metadata = image_payload_metadata(source_payload) + component_metadata = metadata.source_component_metadata or {} + component_metadata = with_source_component_metadata( + component_metadata, + component, + self.group_key, ) - output_contexts = tuple( - context if context is not None else AlignedImageSliceContext.anonymous_main_flow() - for _payload, context in projected_outputs + return metadata.with_source_component_metadata(component_metadata).attach_to( + source_payload ) - save_started_at = time.perf_counter() - def plane_axis_for_output( - context: AlignedImageSliceContext, - ) -> RuntimePlaneAxis | None: - if isinstance(processed_stack, AlignedImageStack): - return processed_stack.plane_axis_for_output_context(context) - if isinstance(processed_stack, ImagePayloadMetadataCarrier): - return image_payload_metadata(processed_stack).plane_axis - return RuntimePlaneAxis.RUNTIME_SLICE + def bind_runtime_owned_parameters( + self, + final_kwargs: dict[str, RuntimeCallableArgument], + ) -> None: + context_parameter_name = self.invocation.contract.runtime_context_parameter + if context_parameter_name is not None: + final_kwargs[context_parameter_name] = self.group_data.context - output_slices = tuple(payload for payload, _context in projected_outputs) - num_outputs = len(output_slices) - num_inputs = len(matching_files) + def bind_runtime_adapter( + self, + final_kwargs: dict[str, RuntimeCallableArgument], + source_payload: RuntimePayload, + ) -> None: + runtime_adapter = self.invocation.contract.runtime_adapter + if runtime_adapter is None: + return + adapter_parameter = self.invocation.adapter_parameter_name + adapter_started_at = time.perf_counter() + final_kwargs[adapter_parameter] = runtime_adapter.factory( + self.runtime_adapter_request(source_payload) + ) + RuntimeProfileLogger.log( + logger, + "runtime_adapter_factory", + time.perf_counter() - adapter_started_at, + function=self.invocation.contract.function_name, + adapter=adapter_parameter, + ) - if num_outputs < num_inputs: - logger.debug( - "Function returned %d images from %d inputs - likely " - "flattening operation", - num_outputs, - num_inputs, + def invoke( + self, + main_data_arg: RuntimeCallableArgument, + final_kwargs: dict[str, RuntimeCallableArgument], + *, + loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], + debug_sink: DebugEventSink | None, + ) -> RuntimeFunctionOutput: + logger.info("Executing function: %s", self.invocation.contract.function_name) + func_callable = self.invocation.runtime_callable + contract = self.invocation.contract + primary_parameter = self.invocation.primary_input_parameter_name + plane_projector: RuntimePlaneAxisProjector = self.plane_projection + runtime_adapter = self.invocation.contract.runtime_adapter + if runtime_adapter is not None: + adapter_parameter = self.invocation.adapter_parameter_name + adapter_value = final_kwargs[adapter_parameter] + if isinstance(adapter_value, RuntimePlaneAxisProjector): + plane_projector = adapter_value + if debug_sink is not None: + if primary_parameter is None: + raise TypeError( + f"Callable {self.invocation.contract.function_name!r} has no declared primary input " + "parameter for runtime invocation diagnostics." + ) + bound_parameters = dict(final_kwargs) + bound_parameters[primary_parameter] = main_data_arg + debug_sink.record( + self.debug_event( + DebugEventType.BEFORE_INVOCATION, + invocation_parameters=DebugInvocationParameter.from_kwargs( + bound_parameters, + plane_projector=plane_projector, + ), + input_artifact_values=loaded_artifact_payloads, + ) ) - elif num_outputs > num_inputs: - logger.debug( - "Function returned %s output slices from %s positional input " - "files; extra slices must carry payload component identity.", - num_outputs, - num_inputs, + call_started_at = time.perf_counter() + try: + with self.invocation.execution_device_scope(): + raw_output = func_callable( + main_data_arg, + **final_kwargs, + ) + except RuntimeSliceProjectionDeclarationError as exc: + bound_parameters = dict(final_kwargs) + if primary_parameter is not None: + bound_parameters[primary_parameter] = main_data_arg + cursor = self.debug_cursor() + invocation_parameters = DebugInvocationParameter.from_kwargs( + bound_parameters, + plane_projector=plane_projector, ) - - output_payloads = [] - output_payload_metadata = [] - output_paths_batch = [] - output_path_entries = [] - output_records = [] - - overwritten_output_paths: list[str] = [] - output_directory_exists = context.filemanager.exists( - str(self.request.execution_plan.output_dir), - Backend.MEMORY.value, - ) - for i, img_slice in enumerate(output_slices): - input_filename = None - if i < len(matching_files): - input_filename = matching_files[i] - output_path_request = FunctionOutputPathRequest( - parser=context.microscope_handler.parser, - output_dir=self.request.execution_plan.output_dir, - output_payload=img_slice, - input_path=input_filename, - variable_components=self.request.execution_plan.variable_components, - input_aligned_output=num_outputs == num_inputs, - identity_cache=context.runtime_function_output_identity_cache, + selected_plane = plane_projector.runtime_slice_plane_index() + selected_plane_status = ( + "preserved_stack" if selected_plane is None else str(selected_plane) ) - try: - output_identity = FunctionOutputIdentity.from_request( - output_path_request - ) - except ValueError as exc: - if input_filename is None: - raise ValueError( - f"Function returned {num_outputs} output slices but only " - f"{num_inputs} input files were available, and output slice " - f"{i} does not carry payload component identity." - ) from exc - raise - output_context = output_contexts[i] - # Only explicit aligned output surfaces own filename qualifiers. - # An unwrapped canonical artifact still owns its typed source - # context, while its ordinary main-flow checkpoint keeps the - # source filename independently of named artifact materialization. - if ( - explicit_output_surfaces - and not output_context.is_anonymous_main_flow - ): - output_identity = output_identity.with_filename_qualifier( - output_context.output_key + artifact_refs = ( + *(edge.spec.ref() for edge in tuple(self.artifact_inputs.values())), + *self.artifact_outputs, + ) + raise type(exc)( + f"{exc} Invocation boundary: step_index={cursor.step_index}; " + f"step_name={self.group_data.execution_plan.step_name!r}; " + f"function_invocation_key={self.invocation.key!r}; " + f"module={contract.module_name!r}; " + f"callable={contract.function_name!r}; " + f"artifact_spec_refs={artifact_refs!r}; " + f"kwarg_names={tuple(sorted(final_kwargs))!r}; " + f"nominal_values={tuple((parameter.name, parameter.value_repr) for parameter in invocation_parameters)!r}; " + f"selected_runtime_plane={selected_plane_status}; " + "execution_axis_cardinality=" + f"{plane_projector.runtime_slice_axis_size()!r}; " + "image_payload_execution_mode=" + f"{contract.runtime_image_execution_mode}; " + f"processing_contract={contract.processing_contract}." + ) from exc + RuntimeProfileLogger.log( + logger, + "function_call", + time.perf_counter() - call_started_at, + function=self.invocation.contract.function_name, + ) + return raw_output + + def save_artifact_outputs( + self, + raw_output: RuntimeFunctionOutput, + source_payload: RuntimePayload, + *, + loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], + ) -> RuntimePayload | NoMainFlowOutput: + """Save declared outputs and qualify unsaved canonical returns afterward.""" + if self.invocation.adapter_records_artifact_outputs: + return self.save_module_recorded_output(raw_output) + output_plans = tuple(self.artifact_outputs.values()) + declared_specs = self.invocation.contract.artifact_outputs + if not declared_specs: + if isinstance(raw_output, tuple): + raise TypeError( + "Tuple returns require declared special-output slots; multiple " + "main-flow images must be packed as AlignedImageStack." ) - output_path = output_identity.path_for_request(output_path_request) - output_path_text = str(output_path) - output_path_entries.append( - OutputPathBatchEntry( - index=i, - input_path=input_filename, - output_path=output_path_text, - identity=output_identity, + main_output = raw_output + else: + _returned_values, matched_outputs = ( + self.invocation.contract.resolve_returned_plan_values( + raw_output, + output_plans, ) ) - img_slice = output_context.contextualize_image_payload(img_slice) - output_metadata = image_payload_metadata(img_slice) - output_component_metadata = output_identity.component_metadata( - output_metadata.source_component_metadata, - ) - if output_metadata.source_component_metadata != output_component_metadata: - output_metadata = output_metadata.with_source_component_metadata( - output_component_metadata + saved_values = { + output_plan.ref(): self.save_artifact_output( + output_plan.name, + output_plan, + output_value, + source_payload, + loaded_artifact_payloads=loaded_artifact_payloads, ) - img_slice = output_metadata.attach_to(img_slice) - output_record = ProducedOutputSemantics.from_output( - self.request.execution_plan, - output_path_text, - output_identity, - output_context=output_context, - image_metadata=output_metadata, - main_flow_plane_axis=plane_axis_for_output(output_context), + for output_plan, _output_spec, output_value in matched_outputs + } + canonical_refs = self.invocation.contract.canonical_return_output_refs + main_outputs = tuple( + (output_plan, output_spec, saved_values[output_plan.ref()]) + for output_plan, output_spec, _output_value in matched_outputs + if output_plan.ref() in canonical_refs ) + if main_outputs: + # These values already own their declared source transformation. + # Reapplying the input context would restore consumed planes. + output_values = tuple( + output_value + for _output_plan, _output_spec, output_value in main_outputs + ) + if len(output_values) == 1: + return output_values[0] + return ImageOutputBundle( + output_values, + AlignedImageSliceContext.main_flow_for_output_plans( + tuple( + output_plan + for output_plan, _output_spec, _output_value in main_outputs + ) + ), + ) + main_output = split_runtime_output(raw_output)[0] + if isinstance(main_output, NoMainFlowOutput): + return main_output + output_source_payload = self.invocation.main_flow_output_source_payload( + self.execution_group_source_payload(source_payload) + ) + return ImageArtifactType.contextualize_output_from_projector( + output_source_payload, + main_output, + None, + self.plane_projection, + ) - if output_directory_exists and context.filemanager.exists( - output_path_text, - Backend.MEMORY.value, - ): - overwritten_output_paths.append(output_path_text) - - output_payloads.append(img_slice) - output_payload_metadata.append(output_metadata) - output_paths_batch.append(output_path_text) - output_records.append(output_record) - - OutputPathBatchUniqueness( - output_paths=output_paths_batch, - input_paths=matching_files, - step_name=self.request.execution_plan.step_name, - pattern_repr=self.pattern_repr, - entries=output_path_entries, - ).validate() - - if overwritten_output_paths: - for output_path_text in overwritten_output_paths: - context.filemanager.delete(output_path_text, Backend.MEMORY.value) - context.runtime_image_stack_cache.discard_paths( - tuple(overwritten_output_paths) + def save_module_recorded_output( + self, + raw_output: RuntimeFunctionOutput, + ) -> RuntimePayload | NoMainFlowOutput: + """Return the main-flow value from a module that records outputs internally.""" + if isinstance(raw_output, NoMainFlowOutput): + return raw_output + if isinstance(raw_output, tuple): + raise TypeError( + "Module artifact contracts with runtime adapters record declared " + "outputs internally; they must return one main-flow payload, not a " + "tuple of artifact values." ) + return raw_output - context.filemanager.ensure_directory( - str(self.request.execution_plan.output_dir), - Backend.MEMORY.value, + def save_artifact_output( + self, + output_key: str, + output_plan: ArtifactOutputPlan, + value: RuntimePayload, + source_payload: RuntimePayload, + *, + loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], + ) -> RuntimePayload: + logger.info( + "Saving artifact output '%s' to VFS path '%s' (memory backend)", + output_key, + output_plan.path, ) - context.filemanager.save_batch( - output_payloads, - output_paths_batch, - Backend.MEMORY.value, + save_started_at = time.perf_counter() + artifact_source_payload = self.artifact_output_source_payload( + output_plan, + source_payload, + loaded_artifact_payloads=loaded_artifact_payloads, ) - if stack_payload is not None: - stack_payload = ImagePayloadStackComposition.with_saved_output_context( - stack_payload, - output_payloads, - output_payload_metadata, - single_output_plane_axis=( - plane_axis_for_output(output_contexts[0]) - if len(output_payloads) == 1 else None - ), - ) - context.runtime_image_stack_cache.store( - tuple(output_paths_batch), - memory_type=self.request.execution_plan.output_memory_type, - stack=stack_payload, + output_source_payload = self.invocation.main_flow_output_source_payload( + self.execution_group_source_payload(artifact_source_payload) + ) + materialization_source_metadata = None + materialization_source_ref = output_plan.materialization_source() + if ( + materialization_source_ref is not None + and materialization_source_ref != output_plan.source_context_source() + ): + materialization_source_payload = self.declared_source_payload( + materialization_source_ref, + source_payload, + loaded_artifact_payloads=loaded_artifact_payloads, ) - RuntimeProfileLogger.log( - logger, - "runtime_stack_cache_store", - 0.0, - step=self.request.execution_plan.step_index, - step_name=self.request.execution_plan.step_name, - paths=len(output_paths_batch), - memory_type=self.request.execution_plan.output_memory_type, + materialization_source_metadata = image_payload_metadata( + materialization_source_payload ) + saved_value = _save_artifact_value( + self.group_data.context, + output_plan, + value, + output_source_payload, + execution_scope=self.group_data.axis_scope, + group_key=self.group_key, + materialization_source_metadata=materialization_source_metadata, + plane_projector=self.plane_projection, + ) RuntimeProfileLogger.log( logger, - "pattern_save_outputs", + "artifact_output_save", time.perf_counter() - save_started_at, - step=plan.step_index, - step_name=plan.step_name, - pattern=self.pattern_repr, + function=self.invocation.contract.function_name, + artifact=output_key, + artifact_type=output_plan.artifact_type.value, ) - return output_records + return saved_value - def _cleanup_collapsed_domains( + def artifact_output_source_payload( self, - output_records: Sequence[ProducedOutputSemantics], - matching_files: list[str], - output_paths: Sequence[str], - ) -> None: - context = self.request.context - num_outputs = len(output_records) - num_inputs = len(matching_files) - - if num_outputs >= num_inputs: - return - - if ( - self.request.execution_plan.input_dir - == self.request.execution_plan.output_dir - ): - return - - retained_paths = {Path(path).as_posix() for path in output_paths} - retained_paths.update( - Path(record.output_path).as_posix() - for record in step_output_manifest(context).produced_records_for( - self.request.execution_plan - ) + output_plan: ArtifactOutputPlan, + primary_source_payload: RuntimePayload, + *, + loaded_artifact_payloads: Mapping[ArtifactSpecRef, RuntimePayload], + ) -> RuntimePayload: + source_ref = output_plan.source_context_source() + if source_ref is None: + return primary_source_payload + return self.declared_source_payload( + source_ref, + primary_source_payload, + loaded_artifact_payloads=loaded_artifact_payloads, ) - for j in range(num_outputs, num_inputs): - unused_filename = matching_files[j] - unused_relative_path = self._input_relative_path( - self.request.execution_plan.input_dir, - unused_filename, - ) - unused_path = self.request.execution_plan.output_dir / unused_relative_path - if unused_path.as_posix() in retained_paths: - continue - if context.filemanager.exists( - str(unused_path), - Backend.MEMORY.value, - ): - context.runtime_image_stack_cache.discard_paths((str(unused_path),)) - context.filemanager.delete( - str(unused_path), - Backend.MEMORY.value, - ) - logger.debug( - "Deleted unused collapsed-domain file after reduced " - "output cardinality: %s", - unused_path, - ) def _process_single_pattern_group(request: PatternGroupExecutionRequest) -> None: """Process one image pattern group through its assigned callable pattern.""" - PatternGroupRuntime(request).run() + request.run() diff --git a/openhcs/interop/cellprofiler/runtime/output_recording.py b/openhcs/interop/cellprofiler/runtime/output_recording.py index ee1f5f89a6..1247a519f9 100644 --- a/openhcs/interop/cellprofiler/runtime/output_recording.py +++ b/openhcs/interop/cellprofiler/runtime/output_recording.py @@ -439,20 +439,31 @@ def record(self, request: CellProfilerOutputRecordRequest) -> None: f"CellProfiler object-label output {request.spec.name!r} must be " "an ObjectLabelValue." ) - value = request.output_value.with_source_image_context( - source_context.source_payload - ) - if source_context.parent_image_payload is not None: - value = value.with_parent_image_context(source_context.parent_image_payload) - request.adapter.add_objects( + construct_started_at = time.perf_counter() + labels = request.output_value + object_labels = ObjectLabelSet.from_payload( request.spec.name, - value, - source_image_name=request.source.source_image_name, - source_image_names=( - request.source.source_aliases - or source_context.source_metadata.source_image_names - ), + labels, + source_image_name=request.source.source_image_name + or labels.source_image_name, + dimensions=labels.dimensions, source_image_payload=source_context.source_payload, + parent_image_payload=source_context.parent_image_payload, + source_image_names=request.source.source_aliases, + ) + if source_context.source_payload is not None: + object_labels.validate_source_alignment(request.spec.name) + CellProfilerRuntimeProfileLogger.object_label_artifact( + "recorder_construct_object_labels", + time.perf_counter() - construct_started_at, + artifact_name=request.spec.name, + payload_type=type(labels).__name__, + labels=object_labels, + ) + request.adapter._record_native_value( + request.spec.name, + ObjectLabelsArtifactType, + object_labels, ) diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index cc114b48d4..991dfd9a0f 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -136,7 +136,7 @@ def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_bi StepSourceBindingsConfig, ) from openhcs.core.source_image_provenance import SourceImageProvenance - from openhcs.core.steps.function_outputs import OpenHCSMetadataWriter + from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget from openhcs.core.steps.function_step import FunctionStep from openhcs.core.virtual_workspace_metadata import ( FIELDS, @@ -364,7 +364,7 @@ def step(func, name, kwargs): primary_plan = context.step_plans[0] assert primary_plan.write_backend == "memory" assert primary_plan.materialized_output is None - OpenHCSMetadataWriter.finalize_completed_plate(bundle.runtime_contexts) + OpenHCSMetadataTarget.finalize_completed_plate(bundle.runtime_contexts) metadata_path = METADATA_CONFIG.metadata_path(primary_plan.output_plate_root) metadata_document = json.loads(metadata_path.read_text()) persisted_source_provenance = SourceImageProvenance.from_mapping( diff --git a/tests/unit/test_aggregate_layer_materialization_515.py b/tests/unit/test_aggregate_layer_materialization_515.py index f287820902..76ae717972 100644 --- a/tests/unit/test_aggregate_layer_materialization_515.py +++ b/tests/unit/test_aggregate_layer_materialization_515.py @@ -39,7 +39,6 @@ ) from openhcs.core.steps.function_artifact_materialization import ( PersistentArtifactMaterializationTargetPlan, - materialize_artifact_outputs, ) from polystore.napari_stream import NapariStreamingBackend from polystore.base import ensure_storage_registry, storage_registry @@ -147,9 +146,7 @@ def save_batch(contents, paths, backend, **kwargs): streaming_configs={"napari_stream": ComponentDisplayConfig(component, mode)}, variable_components=(VariableComponents(component.value),), ), analysis_results_dir=str(tmp_path / "analysis"), output_dir=tmp_path / "images") - materialize_artifact_outputs( - filemanager, plan, PersistentArtifactMaterializationTargetPlan("disk"), context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, plan, context) assert len(disk_outputs) == 1 import tifffile diff --git a/tests/unit/test_aligned_output_projection.py b/tests/unit/test_aligned_output_projection.py index 54f7462a09..27539b6d45 100644 --- a/tests/unit/test_aligned_output_projection.py +++ b/tests/unit/test_aligned_output_projection.py @@ -4,6 +4,9 @@ import pytest from openhcs.core import aligned_image_payload +from openhcs.core.compiled_step_plan import CompiledStepPlan +from openhcs.core.context.processing_context import ProcessingContext +from openhcs.core.function_patterns import compile_function_pattern from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, AlignedImageStack, @@ -17,7 +20,7 @@ image_payload_metadata, ) from openhcs.core.runtime_plane_projection import RuntimePlaneAxis -from openhcs.core.steps.function_runtime import PatternGroupRuntime +from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest def test_runtime_projects_mixed_output_planes_once_with_their_contexts(monkeypatch): @@ -42,15 +45,15 @@ def counted(payload): return original(payload) monkeypatch.setattr(aligned_image_payload, "payload_slices_for_alignment", counted) - runtime = PatternGroupRuntime( - SimpleNamespace( - pattern_group_info="generic-output-projection", - execution_plan=SimpleNamespace( - output_memory_type=MemoryType.NUMPY, - device_id_for=lambda _memory_type: None, + runtime = PatternGroupExecutionRequest(pattern_group_info="generic-output-projection", + execution_plan=CompiledStepPlan( + step_index=0, step_name="output-projection", step_type="FunctionStep", + axis_id="A01", output_memory_type=MemoryType.NUMPY, ), - ) - ) + context=ProcessingContext(axis_id="A01"), + compiled_group=compile_function_pattern(lambda image: image, {}, {}).default_group, + component_index=0, + component_count=1) result = runtime._project_output_slices(bundle, []) assert len(calls) == 2 diff --git a/tests/unit/test_artifact_publication_journey.py b/tests/unit/test_artifact_publication_journey.py index c89ca1cd1d..99268e1100 100644 --- a/tests/unit/test_artifact_publication_journey.py +++ b/tests/unit/test_artifact_publication_journey.py @@ -44,7 +44,7 @@ SourceProjectionSet, ) from openhcs.core.steps.function_step import FunctionStep -from openhcs.core.steps.function_outputs import OpenHCSMetadataWriter +from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.processing.backends.cellprofiler.object_images import ( ImageMode, @@ -163,7 +163,7 @@ def test_converted_checkpoint_has_typed_address_on_final_reconciliation(tmp_path for context in bundle.runtime_contexts.values(): for index, step in enumerate(steps): step.process(context, index) - OpenHCSMetadataWriter.finalize_completed_plate(bundle.runtime_contexts) + OpenHCSMetadataTarget.finalize_completed_plate(bundle.runtime_contexts) saved = tmp_path / "source_out" / "converted" files = tuple(saved.glob("*.tif")) assert len(files) == 1 diff --git a/tests/unit/test_automatic_image_role_materialization_435.py b/tests/unit/test_automatic_image_role_materialization_435.py index 8e501c928e..6611949f58 100644 --- a/tests/unit/test_automatic_image_role_materialization_435.py +++ b/tests/unit/test_automatic_image_role_materialization_435.py @@ -26,8 +26,9 @@ from openhcs.core.steps.function_output_identity import ( FunctionOutputIdentity, ) +from openhcs.core.steps.function_artifact_materialization import ArtifactMaterializationTargetPlan from openhcs.core.steps.function_outputs import ( - PrimaryImageMetadataTarget, RuntimeArtifactMaterializationAuthority, + PrimaryImageMetadataTarget, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser @@ -111,7 +112,7 @@ def test_automatic_two_role_images_publish_their_actual_saved_occurrences(tmp_pa image_metadata=payload.metadata, identity=identity, ) expected[output.name].append((destination, payload.data)) - saved = RuntimeArtifactMaterializationAuthority.materialize(context, plan) + saved = ArtifactMaterializationTargetPlan.materialize(context, plan) target = replace(PrimaryImageMetadataTarget.from_plan(plan), artifact_materializations=saved) # The original implementation raises its real duplicate projection guard # here: both automatic materializations used the same unqualified path. @@ -289,9 +290,9 @@ def test_distinct_aliases_that_normalize_to_one_filename_still_conflict(tmp_path assert paths[0] == paths[1] # Existing main-flow destination authority rejects this declared naming # collision instead of choosing a new suffix or inventing a channel. - from openhcs.core.steps.function_runtime import OutputPathBatchUniqueness + from openhcs.core.steps.function_output_identity import FunctionOutputIdentity with pytest.raises(ValueError, match="duplicate"): - OutputPathBatchUniqueness(output_paths=paths, input_paths=[], step_name=plan.step_name, pattern_repr="declared roles").validate() + FunctionOutputIdentity.validate_output_paths(paths, input_paths=[], step_name=plan.step_name, pattern_repr="declared roles") def test_batch_binds_actual_purpose_once_without_rewriting_plan_or_source(monkeypatch, tmp_path): diff --git a/tests/unit/test_cellprofiler_module_execution.py b/tests/unit/test_cellprofiler_module_execution.py index a122081550..80ee14593c 100644 --- a/tests/unit/test_cellprofiler_module_execution.py +++ b/tests/unit/test_cellprofiler_module_execution.py @@ -179,8 +179,11 @@ ) from openhcs.core.source_metadata import SourceVoxelSpacing from openhcs.core.source_spatial_domain import SourceSpatialDomain +from openhcs.core.context.processing_context import ProcessingContext +from openhcs.core.function_patterns import compile_function_pattern +from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.core.steps.function_runtime import ( - PatternGroupRuntime, + PatternGroupExecutionRequest, ) from openhcs.core.steps.stream_component_semantics import ( StreamImagePayloadMetadataProjector, @@ -2924,7 +2927,8 @@ def get_objects(name, *, current_image=None): assert name == "Nuclei" return object_payload - def add_objects(name, labels, **kwargs): + def record_native_value(name, kind, labels, **kwargs): + assert kind is ObjectLabelsArtifactType recorded["name"] = name recorded["labels"] = labels recorded["kwargs"] = kwargs @@ -2958,7 +2962,7 @@ def add_objects(name, labels, **kwargs): ), ) runtime.get_objects = get_objects - runtime.add_objects = add_objects + runtime._record_native_value = record_native_value output = _output_from_input("ResizedNuclei", "Nuclei") request = _cellprofiler_output_record_request( @@ -3020,13 +3024,14 @@ def test_contextual_object_label_recorder_fills_missing_parent_spacing_from_decl ) recorded: dict[str, object] = {} - def add_objects(name, labels, **kwargs): + def record_native_value(name, kind, labels, **kwargs): + assert kind is ObjectLabelsArtifactType recorded["name"] = name recorded["labels"] = labels recorded["kwargs"] = kwargs runtime = _FakeCellProfilerRuntime({"Memb": image_payload}) - runtime.add_objects = add_objects + runtime._record_native_value = record_native_value output = _output_from_input( "Cells", @@ -4261,14 +4266,16 @@ def add_measurements( ) -> None: self.measurements.append(table) - def add_objects( + def _record_native_value( self, name: str, - labels: object, + expected_kind: ArtifactType, + native_value: object, **kwargs: object, - ) -> object: - self.objects.append((name, labels, kwargs)) - return super().add_objects(name, labels, **kwargs) + ) -> StoredRuntimeValue: + if expected_kind is ObjectLabelsArtifactType: + self.objects.append((name, native_value, kwargs)) + return super()._record_native_value(name, expected_kind, native_value, **kwargs) def _seed_runtime_object( self, @@ -9538,18 +9545,21 @@ def test_image_output_context_preserves_aligned_image_stack_payload(): def _pattern_group_runtime_for_output_memory( output_memory_type: str, -) -> PatternGroupRuntime: - runtime = object.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( +) -> PatternGroupExecutionRequest: + context = ProcessingContext(axis_id="A01") + context.microscope_handler = SimpleNamespace(parser=SourceSchemaFilenameParser()) + return PatternGroupExecutionRequest( + context=context, + compiled_group=compile_function_pattern(lambda image: image, {}, {}).default_group, + pattern_group_info="", component_index=0, component_count=1, execution_plan=CompiledStepPlan( step_index=0, step_name="pattern output", step_type="FunctionStep", axis_id="A01", output_memory_type=output_memory_type, - ) + ), ) - return runtime def test_pattern_group_runtime_unstacks_aligned_image_stack_output(): @@ -11922,7 +11932,7 @@ def test_object_label_output_recorder_uses_output_label_domain() -> None: ) _name, recorded_payload, _kwargs = runtime.objects[0] - assert isinstance(recorded_payload, ObjectLabelPayload) + assert isinstance(recorded_payload, ObjectLabelSet) assert recorded_payload.domain.declared_object_count is None assert recorded_payload.domain.declared_object_ids == tuple(range(1, 5)) np.testing.assert_array_equal(recorded_payload.labels, output_labels) diff --git a/tests/unit/test_collapsed_persisted_occurrence_435.py b/tests/unit/test_collapsed_persisted_occurrence_435.py index 11a52555cf..1c570dbff1 100644 --- a/tests/unit/test_collapsed_persisted_occurrence_435.py +++ b/tests/unit/test_collapsed_persisted_occurrence_435.py @@ -37,9 +37,9 @@ ) from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection from openhcs.core.steps.function_output_identity import FunctionOutputIdentity +from openhcs.core.steps.function_artifact_materialization import ArtifactMaterializationTargetPlan from openhcs.core.steps.function_outputs import ( PrimaryImageMetadataTarget, - RuntimeArtifactMaterializationAuthority, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.processing.materialization import ( @@ -133,11 +133,6 @@ def _actual_saved_occurrence(tmp_path, scenario): artifact_payload = metadata.with_source_component_metadata( {**semantic_components, "site": "2"}, ).payload_with(pixels) - context.runtime_value_store.record( - RuntimeValue.normalize(output_plan, artifact_payload, axis_id="A01"), - path=output_plan.path, - backend=Backend.MEMORY.value, - ) destination = plan.output_dir / filename filemanager.ensure_directory(plan.output_dir, Backend.MEMORY.value) filemanager.ensure_directory(plan.output_dir, Backend.DISK.value) @@ -160,6 +155,16 @@ def _actual_saved_occurrence(tmp_path, scenario): ), ) target = PrimaryImageMetadataTarget.from_plan(plan) + (record,) = target.produced_records(context, plan) + context.runtime_value_store.record( + RuntimeValue.normalize_for_execution_scope( + output_plan, + artifact_payload, + execution_scope=record.execution_scope(plan), + ), + path=output_plan.path, + backend=Backend.MEMORY.value, + ) # This is the existing accepted main-flow publication, before a mirror is added. original = target.produced_projection_entries(context, plan) original = SourceProjectionMetadataSerializer.projection_fields( @@ -168,9 +173,11 @@ def _actual_saved_occurrence(tmp_path, scenario): assert len(original["source_projection"]) == 1 if scenario == "collapsed_site": row = original["source_projection"][0] - assert row["address"]["site"] == "1" + assert row["address"] is None + (record,) = target.produced_records(context, plan) + assert record.filename_address.as_component_metadata()["site"] == "1" assert "site" not in row["source_metadata"] - saved = RuntimeArtifactMaterializationAuthority.materialize(context, plan) + saved = ArtifactMaterializationTargetPlan.materialize(context, plan) assert len(saved) == 1 (output,) = saved[0].outputs_for_backend(Backend.DISK.value) assert output.path == str(destination) @@ -305,7 +312,9 @@ def test_collapsed_same_path_mirror_retains_filename_and_semantic_views(tmp_path structured.projection_paths ) (row,) = structured["source_projection"] - assert row["address"]["site"] == "1" + assert row["address"] is None + (record,) = target.produced_records(context, plan) + assert record.filename_address.as_component_metadata()["site"] == "1" assert row["source_alias"] == "Mosaic" assert "site" not in row["source_metadata"] metadata = ImagePayloadMetadata.from_mapping( @@ -321,7 +330,7 @@ def test_collapsed_same_path_mirror_retains_filename_and_semantic_views(tmp_path tmp_path, document ) projection = reopened.source_projections_by_virtual_path[row["virtual_path"]] - assert projection.address.as_component_metadata()["site"] == "1" + assert projection.address is None assert "site" not in projection.image_metadata.source_component_metadata assert ( len(projection.image_metadata.source_provenance.represented_source_identities) diff --git a/tests/unit/test_debug_runtime.py b/tests/unit/test_debug_runtime.py index 3274195fb1..dc79b7acc6 100644 --- a/tests/unit/test_debug_runtime.py +++ b/tests/unit/test_debug_runtime.py @@ -133,9 +133,7 @@ ) from openhcs.core.source_load_plan import SourceLoadPlan from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, PatternGroupData, - PatternGroupRuntime, ) from openhcs.core.runtime_stores import RuntimeValueStore from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract @@ -342,7 +340,9 @@ def execute_function_chain( resolved_artifact_inputs = {} if artifact_inputs is None else artifact_inputs resolved_artifact_outputs = {} if artifact_outputs is None else artifact_outputs runtime_scope = PatternGroupData( - matching_files=[f"input-{index}.tif" for index in range(runtime_plane_count)], + matching_files=[ + f"input-{index}.tif" for index in range(runtime_plane_count) + ], main_data_stack=initial_data_stack, context=context, execution_plan=cls.execution_plan( @@ -353,14 +353,12 @@ def execute_function_chain( group_key=cls.GROUP_KEY, invocations=invocations, ), - artifacts=ComponentArtifactPlans( - inputs=resolved_artifact_inputs, - outputs=resolved_artifact_outputs, - ), + artifact_inputs=resolved_artifact_inputs, + artifact_outputs=resolved_artifact_outputs, runtime_plane_index=runtime_plane_index, runtime_plane_count=runtime_plane_count, ) - return PatternGroupRuntime.execute_chain(runtime_scope) + return runtime_scope.execute_chain() @classmethod def cursor(cls) -> DebugCursor: diff --git a/tests/unit/test_derived_role_publication_435.py b/tests/unit/test_derived_role_publication_435.py index 8b5e35763f..98592c2da4 100644 --- a/tests/unit/test_derived_role_publication_435.py +++ b/tests/unit/test_derived_role_publication_435.py @@ -33,8 +33,9 @@ ) from openhcs.core.source_projection import SourceProjectionMetadataSerializer from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection +from openhcs.core.steps.function_artifact_materialization import ArtifactMaterializationTargetPlan from openhcs.core.steps.function_outputs import ( - PrimaryImageMetadataTarget, RuntimeArtifactMaterializationAuthority, + PrimaryImageMetadataTarget, ) from openhcs.core.steps.function_output_identity import FunctionOutputIdentity @@ -262,7 +263,7 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a ), identity=output_identity, ) - saved = RuntimeArtifactMaterializationAuthority.materialize(context, plan) + saved = ArtifactMaterializationTargetPlan.materialize(context, plan) assert len(saved) == len(roles) target = replace(PrimaryImageMetadataTarget.from_plan(plan), artifact_materializations=saved) records = target.produced_records(context, plan) diff --git a/tests/unit/test_framework_execution_scope.py b/tests/unit/test_framework_execution_scope.py index 228c15965c..c6018d8bc9 100644 --- a/tests/unit/test_framework_execution_scope.py +++ b/tests/unit/test_framework_execution_scope.py @@ -8,7 +8,6 @@ from openhcs.core.function_patterns import compile_function_pattern from openhcs.core.runtime_plane_projection import RuntimePlaneProjection from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, FunctionCoreExecutor, ) @@ -43,7 +42,8 @@ def memory_device_scope(memory_type, device_id): executor = FunctionCoreExecutor( group_data=SimpleNamespace(), invocation=invocation, - artifacts=ComponentArtifactPlans(inputs={}, outputs={}), + artifact_inputs={}, + artifact_outputs={}, group_key=None, plane_projection=RuntimePlaneProjection.stack(), main_data_arg=np.zeros((1, 2, 2)), diff --git a/tests/unit/test_function_artifact_materialization.py b/tests/unit/test_function_artifact_materialization.py index 269ec4d8e9..8965817ed3 100644 --- a/tests/unit/test_function_artifact_materialization.py +++ b/tests/unit/test_function_artifact_materialization.py @@ -118,11 +118,9 @@ from openhcs.core.source_spatial_domain import SourceSpatialDomain from openhcs.core.steps.abstract import StepExecutionObservation from openhcs.core.steps.function_artifact_materialization import ( - ArtifactMaterializationBackendPlan, PersistentArtifactMaterializationTargetPlan, StreamingOnlyArtifactMaterializationTargetPlan, actual_materialization_records, - materialize_artifact_outputs, preview_reused_step_outputs, RuntimeArtifactMaterialization, planned_materialization_preview, @@ -517,29 +515,51 @@ def test_named_artifact_streaming_respects_compiled_streaming_filter(): ) target = StreamingOnlyArtifactMaterializationTargetPlan() - excluded = target.backend_plan(plan, context, materialization) + excluded = target.streaming_viewer_surfaces(plan, context, materialization) - assert excluded.streaming_viewer_surfaces == {} + assert excluded == {} context.axis_id = "B03" - included = target.backend_plan(plan, context, materialization) + included = target.streaming_viewer_surfaces(plan, context, materialization) - assert tuple(included.streaming_viewer_surfaces) == ("napari_stream",) + assert tuple(included) == ("napari_stream",) def test_viewer_output_expectation_omits_empty_stream_payload() -> None: filemanager = FileManager({"napari_stream": NapariStreamingBackend()}) context = _context(filemanager) - viewer_surface = streaming_config_stub().streaming_viewer_surface(context) - backend_plan = ArtifactMaterializationBackendPlan( - persistent_backend_kwargs={}, - streaming_viewer_surfaces={"napari_stream": viewer_surface}, + output_plan = ArtifactOutputPlan( + name="Nuclei", + path="/memory/Nuclei.pkl", + artifact_type=ObjectLabelsArtifactType, + materialization=roi_zip(), ) - - assert not backend_plan.supports_stream_output( - filemanager, - Output(path="/analysis/A01_neurites.graph.roi.zip", content=[]), + record = context.runtime_value_store.record( + RuntimeValue.normalize( + output_plan, + ObjectLabelPayload( + variant_data=ObjectLabelVariantData( + labels=np.zeros((8, 8), dtype=np.int32) + ), + domain=ObjectLabelDomain(declared_object_count=0), + ), + axis_id="A01", + ), + path=output_plan.path, + backend="memory", ) + plan = _plan( + output_plan, streaming_configs={"napari_stream": streaming_config_stub()} + ) + materialization = RuntimeArtifactMaterialization.from_record( + output_plan=output_plan, + record=record, + plan=plan, + context=context, + ) + + assert materialization.outputs(plan, context) + assert materialization.viewer_outputs(plan, context) == () def test_planned_materialization_preview_uses_declared_candidate_paths(): @@ -802,12 +822,7 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert materialized == [ ({"x": "from-runtime"}, "/analysis/A01_positions_step7.roi.zip") @@ -852,18 +867,13 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan( output_plan, variable_components=( VariableComponents.Z_INDEX, VariableComponents.CHANNEL, ), - ), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + ), context) assert len(materialized) == 1 data, path = materialized[0] @@ -955,12 +965,7 @@ def fake_materialize(spec, data, path, manager, *_args, **kwargs): == expected_paths ) - materialize_artifact_outputs( - filemanager, - plan, - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, plan, context) assert output_paths == [str(path) for path in expected_paths] @@ -976,12 +981,7 @@ def test_materialize_artifact_outputs_requires_runtime_store_record(): context = _context(filemanager) with pytest.raises(RuntimeError, match="Missing RuntimeValueStore record"): - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) def test_materialize_artifact_outputs_does_not_require_vfs_payload_for_store_record( @@ -1010,12 +1010,7 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert materialized == [({"x": 1}, "/analysis/A01_positions_step7.roi.zip")] @@ -1065,12 +1060,7 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert [(data.row_mappings(), path) for data, path in materialized] == [ (({"object_id": 1, "area": 42},), "/analysis/measurements_1.roi.zip") @@ -1119,12 +1109,7 @@ def fake_materialize(spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) spec, data, path = materialized[0] assert isinstance(spec.outputs[0], CsvOptions) @@ -1719,10 +1704,7 @@ def record_for_site(site: str) -> None: current_execution_records = context.runtime_value_store.observed_values_after( current_execution_cursor ) - saved = materialize_artifact_outputs( - context.filemanager, plan, - PersistentArtifactMaterializationTargetPlan("disk"), context, - ) + saved = PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(context.filemanager, plan, context) selected_saved = tuple( artifact for artifact in saved if artifact.materialization.record.key == current_execution_records[0].key @@ -1855,10 +1837,7 @@ def test_consolidation_preserves_export_bundle_and_text_tables(options, payload) persistent_backend="disk", ) context.step_plans = {plan.step_index: plan} - saved = materialize_artifact_outputs( - context.filemanager, plan, - PersistentArtifactMaterializationTargetPlan("disk"), context, - ) + saved = PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(context.filemanager, plan, context) consolidation = StepExecutionObservation.combine( artifact.observation(plan, context) for artifact in saved ).analysis_inputs @@ -1921,10 +1900,7 @@ def test_completed_observation_projects_tables_before_worker_payload_release( ), path=table_plan.path, backend="memory", ) - saved = materialize_artifact_outputs( - context.filemanager, table_step, - PersistentArtifactMaterializationTargetPlan("disk"), context, - ) + saved = PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(context.filemanager, table_step, context) monkeypatch.setattr( RuntimeArtifactMaterialization, "outputs", lambda *_args, **_kwargs: pytest.fail("Saved tables must not render again"), @@ -2028,12 +2004,7 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert materialized == [ ( @@ -2331,14 +2302,9 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config_stub()} - ), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + ), context) spec, data, path, backends, backend_kwargs = materialized[0] assert isinstance(spec.outputs[0], CsvOptions) @@ -2397,12 +2363,7 @@ def fake_materialize(spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert len(materialized) == 1 spec, data, path = materialized[0] @@ -2677,12 +2638,7 @@ def fake_materialize(spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert [path for _spec, _data, path in materialized] == [ "/analysis/A01_s001_w5_z001_t001_measurements_step7.roi.zip", @@ -2741,12 +2697,7 @@ def fake_materialize(spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan, group_by_value="channel"), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan, group_by_value="channel"), context) assert [path for _spec, _data, path in materialized] == [ "/analysis/A01_w2_measurements_step7.roi.zip", @@ -2807,14 +2758,9 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config_stub()} - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/A01_s001_w2_z001_t001_Nuclei_step7.roi.zip" @@ -2879,12 +2825,7 @@ def fake_materialize( streaming_config = streaming_config_stub() - materialize_artifact_outputs( - filemanager, - _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/A01_Nuclei_step7.roi.zip" @@ -3027,12 +2968,7 @@ def fake_materialize(spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) spec, data, _path = materialized[0] assert isinstance(spec.outputs[0], JsonOptions) @@ -3061,12 +2997,7 @@ def fake_materialize(*args, **kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert materialized == [] @@ -3122,12 +3053,7 @@ def test_tile_positions_runtime_materializes_native_json_without_changing_payloa analysis_results_dir=str(tmp_path / "results"), ) - materialize_artifact_outputs( - filemanager, - plan, - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, plan, context) (retained,) = tuple((tmp_path / "results").rglob("*.json")) assert json.loads(retained.read_text()) == [list(pair) for pair in positions] @@ -3159,12 +3085,7 @@ def fake_materialize(*args, **kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) assert materialized == [] @@ -3200,12 +3121,7 @@ def fake_materialize(spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan), context) spec, data, path = materialized[0] assert isinstance(spec.outputs[0], ROIOptions) @@ -3257,12 +3173,7 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), context) spec, data, path, backends, backend_kwargs = materialized[0] assert isinstance(spec.outputs[0], ROIOptions) @@ -3346,16 +3257,11 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config_stub()}, compiled_function_pattern=_main_flow_output_compiled_pattern(output_plan), - ), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + ), context) assert len(materialized) == 1 backends, backend_kwargs = materialized[0] @@ -3411,15 +3317,10 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/A01_s002_w3_z001_t001_labels_step7.roi.zip" @@ -3469,8 +3370,12 @@ def test_materialize_artifact_outputs_streams_payload_component_metadata( ) filemanager = FileManagerStub() context = _context(filemanager) + context.axis_id = "01" + context.execution_runtime = SimpleNamespace(execution_axis_values=("01",)) + plan = _plan(output_plan, streaming_configs={"napari_stream": streaming_config}) + plan.axis_id = "01" context.runtime_value_store.record( - RuntimeValue.normalize(output_plan, labels, axis_id="A01"), + RuntimeValue.normalize(output_plan, labels, axis_id="01"), path=output_plan.path, backend="memory", ) @@ -3493,12 +3398,7 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, plan, context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/01_POS002_D_Nuclei_step7.roi.zip" @@ -3555,16 +3455,11 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan( output_plan, group_by_value="timepoint", variable_components=(VariableComponents.TIMEPOINT,), - ), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + ), context) assert materialized == [ ( @@ -3626,12 +3521,7 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan(output_plan, streaming_configs={"napari_stream": streaming_config}), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/A01_s002_w3_z001_t001_Nuclei_step7.roi.zip" @@ -3727,16 +3617,11 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, variable_components=(VariableComponents.Z_INDEX,), - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/A01_Nuclei_step7.roi.zip" @@ -3796,16 +3681,11 @@ def test_materialize_artifact_outputs_streams_singleton_roi_plane_from_output_pl backend="memory", ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config_stub()}, variable_components=(VariableComponents.Z_INDEX,), - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) roi_saves = [item for item in filemanager.saved if item[1].endswith(".roi.zip")] assert len(roi_saves) == 1 @@ -3899,16 +3779,11 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, variable_components=(VariableComponents.CHANNEL,), - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/analysis/A01_segmentation_masks_step7.roi.zip" @@ -4002,16 +3877,11 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, variable_components=(VariableComponents.CHANNEL,), - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/images/A01_s001_w3_z001_t001.TIF" @@ -4088,12 +3958,7 @@ def fake_materialize(_spec, _data, path, *_args, **_kwargs): fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan(output_plan, variable_components=(VariableComponents.CHANNEL,)), - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan, variable_components=(VariableComponents.CHANNEL,)), context) assert materialized == ["/images/A01_s001_w1_z001_t001.TIF"] @@ -4320,16 +4185,11 @@ def fake_materialize( fake_materialize, ) - materialize_artifact_outputs( - filemanager, - _plan( + StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, variable_components=(VariableComponents.SITE,), - ), - StreamingOnlyArtifactMaterializationTargetPlan(), - context, - ) + ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] assert path == "/images/A01_s001_w2_z001_t001.TIF" diff --git a/tests/unit/test_function_artifact_materialization_io_hotpath.py b/tests/unit/test_function_artifact_materialization_io_hotpath.py index b6627f4cfa..4ca638da96 100644 --- a/tests/unit/test_function_artifact_materialization_io_hotpath.py +++ b/tests/unit/test_function_artifact_materialization_io_hotpath.py @@ -3,6 +3,7 @@ from __future__ import annotations import inspect +from pathlib import Path import numpy as np import pytest @@ -11,9 +12,13 @@ from polystore.streaming.identity import StreamProducerIdentity from openhcs.core.steps.function_artifact_materialization import ( - ArtifactMaterializationBackendPlan, - ArtifactStreamSourceMetadataAuthority, + ArtifactMaterializationTargetPlan, + PersistentArtifactMaterializationTargetPlan, + RuntimeArtifactMaterialization, ) +from openhcs.core.artifacts import ArtifactOutputPlan, ImageArtifactType +from openhcs.core.runtime_artifact_values import RuntimeValue +from openhcs.core.runtime_stores import RuntimeValueStore from openhcs.processing.materialization.core import ( MaterializationSpec, Output, @@ -81,26 +86,42 @@ def test_persistent_only_backend_kwargs_skip_stream_payload_projection( payload: np.ndarray, streaming_viewer_surfaces: dict[str, object], ) -> None: - def unexpected_stream_metadata(**_kwargs: object) -> None: + def unexpected_stream_metadata(*_args: object, **_kwargs: object) -> None: raise AssertionError( "persistent-only materialization projected stream metadata" ) monkeypatch.setattr( - ArtifactStreamSourceMetadataAuthority, - "metadata_items", + RuntimeArtifactMaterialization, + "stream_source_metadata_items", unexpected_stream_metadata, ) - backend_plan = ArtifactMaterializationBackendPlan( - persistent_backend_kwargs={"disk": RawBackendKwargs()}, - streaming_viewer_surfaces=streaming_viewer_surfaces, + spec = MaterializationSpec(ImageFileOptions(filename_suffix=".tif")) + output_plan = ArtifactOutputPlan( + name="SavedImage", + path="/memory/SavedImage.pkl", + artifact_type=ImageArtifactType, + materialization=spec, ) - - kwargs = backend_plan.backend_kwargs( - materialization_spec=MaterializationSpec( - ImageFileOptions(filename_suffix=".tif") - ), + record = RuntimeValueStore().record( + RuntimeValue.normalize(output_plan, payload, axis_id="A01"), + path=output_plan.path, + backend="memory", + ) + materialization = RuntimeArtifactMaterialization( + output_plan=output_plan, + spec=spec, + record=record, data=payload, + base_path=Path("/images/SavedImage.tif"), + source_identity=None, + filename_source_identity=None, + ) + target = PersistentArtifactMaterializationTargetPlan("disk") + kwargs = target.backend_kwargs( + materialization=materialization, + persistent_backend_kwargs={"disk": RawBackendKwargs()}, + streaming_viewer_surfaces=streaming_viewer_surfaces, fallback_source_identity=None, producer_identity=StreamProducerIdentity( origin="pipeline", @@ -122,6 +143,6 @@ def test_backend_kwargs_no_longer_accepts_eager_stream_metadata() -> None: assert ( "source_metadata_items" not in inspect.signature( - ArtifactMaterializationBackendPlan.backend_kwargs + ArtifactMaterializationTargetPlan.backend_kwargs ).parameters ) diff --git a/tests/unit/test_function_artifact_outputs.py b/tests/unit/test_function_artifact_outputs.py index c00a5891c8..ba2ecf1574 100644 --- a/tests/unit/test_function_artifact_outputs.py +++ b/tests/unit/test_function_artifact_outputs.py @@ -1,3 +1,4 @@ +from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest from collections.abc import Callable, Mapping from dataclasses import dataclass, replace from types import SimpleNamespace @@ -75,10 +76,9 @@ from openhcs.core.runtime_tabular_values import FieldSpec from openhcs.core.progress.live_measurements import LiveMeasurementProgressPayload from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, + PatternGroupExecutionScope, FunctionCoreExecutor, PatternGroupData, - PatternGroupRuntime, ) from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, @@ -244,7 +244,9 @@ def _execute_function_core(request: CoreExecutionRequest): None if request.execution_group_scope.is_ungrouped else request.group_key ) runtime_scope = PatternGroupData( - matching_files=[f"input-{index}.tif" for index in range(request.runtime_plane_count)], + matching_files=[ + f"input-{index}.tif" for index in range(request.runtime_plane_count) + ], main_data_stack=request.main_data_arg, context=request.context, execution_plan=execution_plan, @@ -253,28 +255,21 @@ def _execute_function_core(request: CoreExecutionRequest): invocations=(invocation,), ), component_value=component_value, - artifacts=ComponentArtifactPlans.from_step_component( - execution_plan, + artifact_inputs=dict(execution_plan.artifact_inputs), + artifact_outputs=PatternGroupExecutionScope._select_output_plans_for_component( + execution_plan.artifact_outputs, + execution_plan.execution_group_scope, component_value, ), runtime_plane_index=0, runtime_plane_count=request.runtime_plane_count, ) - group_key = invocation.key.runtime_group_key(runtime_scope.component_value) - return FunctionCoreExecutor( + return FunctionCoreExecutor.from_group_invocation( + runtime_scope, + invocation, main_data_arg=request.main_data_arg, source_memory_type=MEMORY_TYPE_NUMPY, - group_data=runtime_scope, - invocation=invocation, - artifacts=runtime_scope.artifacts.select_for_invocation( - invocation, - execution_scope=runtime_scope.execution_plan.execution_group_scope, - component_key=runtime_scope.component_key, - ), - group_key=group_key, - plane_projection=RuntimePlaneProjection.stack( - runtime_scope.runtime_plane_count - ), + declared_source_bindings=runtime_scope.execution_plan.source_binding_plan, ).execute() @@ -1755,8 +1750,7 @@ def rgb_output(image): {plan.ref(): plan for plan in (output_plan,)}, ).iter_invocations() ) - runtime = object.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( compiled_group=CompiledFunctionGroup( group_key="default", invocations=(invocation,), @@ -1773,10 +1767,16 @@ def rgb_output(image): output_plan.ref(): output_plan, }, ), - component_key=None, + component_value=None, + context=SimpleNamespace(), + pattern_group_info="fixture", + component_index=0, + component_count=1, ) - output = runtime._project_output_slices(scalar_output, ["source-1.tif", "source-2.tif"]) + output = runtime._project_output_slices( + scalar_output, ["source-1.tif", "source-2.tif"] + ) assert tuple(payload for payload, _context in output) == (scalar_output,) assert tuple(context for _payload, context in output) == ( AlignedImageSliceContext.main_flow( @@ -1785,8 +1785,11 @@ def rgb_output(image): ), ) from openhcs.core.aligned_image_payload import ImagePayloadStackComposition + stack_payload = ImagePayloadStackComposition.copy_whole_image( - scalar_output, memory_type=MEMORY_TYPE_NUMPY, device_id=None, + scalar_output, + memory_type=MEMORY_TYPE_NUMPY, + device_id=None, ) assert image_payload_data(stack_payload).shape == (2, 3, 3) stack_metadata = image_payload_metadata(stack_payload) @@ -1799,8 +1802,7 @@ def test_pattern_group_runtime_uses_declared_output_slice_cardinality(): plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, ).payload_with(np.ones((1, 4, 5), dtype=np.float32), None) - runtime = object.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( compiled_group=compile_function_pattern(passthrough, {}, {}).default_group, execution_plan=CompiledStepPlan( step_index=0, @@ -1812,13 +1814,22 @@ def test_pattern_group_runtime_uses_declared_output_slice_cardinality(): execution_group_scope=ComponentGroupScope.ungrouped(), artifact_outputs={}, ), - component_key=None, + component_value=None, + context=SimpleNamespace(), + pattern_group_info="fixture", + component_index=0, + component_count=1, ) - output = runtime._project_output_slices(declared_output, ["source-1.tif", "source-2.tif"]) + output = runtime._project_output_slices( + declared_output, ["source-1.tif", "source-2.tif"] + ) assert len(output) == 1 assert image_payload_data(output[0][0]).shape == (4, 5) - assert image_payload_metadata(declared_output).plane_axis is RuntimePlaneAxis.RUNTIME_SLICE + assert ( + image_payload_metadata(declared_output).plane_axis + is RuntimePlaneAxis.RUNTIME_SLICE + ) def test_pattern_group_runtime_projects_nominal_object_label_stack(): @@ -1839,8 +1850,7 @@ def test_pattern_group_runtime_projects_nominal_object_label_stack(): ), ) - runtime = object.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( compiled_group=compile_function_pattern(passthrough, {}, {}).default_group, execution_plan=CompiledStepPlan( step_index=0, @@ -1852,7 +1862,11 @@ def test_pattern_group_runtime_projects_nominal_object_label_stack(): execution_group_scope=ComponentGroupScope.ungrouped(), artifact_outputs={}, ), - component_key=None, + component_value=None, + context=SimpleNamespace(), + pattern_group_info="fixture", + component_index=0, + component_count=1, ) projected = runtime._project_output_slices(declared_output, ["source-anchor.tif"]) @@ -2914,7 +2928,6 @@ def declared_source_origin(image, *, image_to_save=None): spec=spec, storage_plan=None, projection=None, - main_flow_projection=main_flow_projection, ) invocation = invocation.with_artifact_input_edges((edge,)) @@ -2933,7 +2946,8 @@ def declared_source_origin(image, *, image_to_save=None): ), ), invocation=invocation, - artifacts=ComponentArtifactPlans(inputs={edge.key: edge}, outputs={}), + artifact_inputs={edge.key: edge}, + artifact_outputs={}, group_key=None, plane_projection=RuntimePlaneProjection.stack(), main_data_arg=object(), @@ -3109,14 +3123,20 @@ def test_declared_source_payload_prefers_exact_loaded_ref_over_main_flow() -> No def test_missing_source_origin_is_not_satisfied_by_an_authored_kwarg(): - spec = ArtifactSpec.input("MissingImage", ImageArtifactType, parameter_name="image_to_save") + spec = ArtifactSpec.input( + "MissingImage", ImageArtifactType, parameter_name="image_to_save" + ) executor = _declared_source_executor(spec) (original_edge,) = executor.invocation.artifact_input_edges - edge = replace(original_edge, main_flow_projection=None) + edge = replace(original_edge, main_flow_projection=None) primary = ImagePayloadMetadata().payload_with(np.zeros((1, 2, 3), dtype=np.uint16)) invocation = replace(executor.invocation, kwargs=(("image_to_save", primary),)) - executor = replace(executor, invocation=invocation, - artifacts=ComponentArtifactPlans(inputs={edge.key: edge}, outputs={})) + executor = replace( + executor, + invocation=invocation, + artifact_inputs={edge.key: edge}, + artifact_outputs={}, + ) with pytest.raises(ValueError, match="must resolve to exactly one .* resolved 0"): executor.load_artifact_inputs(invocation.kwargs_dict, primary) diff --git a/tests/unit/test_function_core_executor_ownership.py b/tests/unit/test_function_core_executor_ownership.py index f53a51991c..96e20bf892 100644 --- a/tests/unit/test_function_core_executor_ownership.py +++ b/tests/unit/test_function_core_executor_ownership.py @@ -8,7 +8,11 @@ import numpy as np import pytest -from openhcs.core.artifacts import ArtifactSpec, ArtifactSpecCollection, MetadataArtifactType +from openhcs.core.artifacts import ( + ArtifactSpec, + ArtifactSpecCollection, + MetadataArtifactType, +) from openhcs.core.compiled_step_plan import CompiledStepPlan from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.function_patterns import ( @@ -21,12 +25,10 @@ from openhcs.core.runtime_plane_projection import RuntimePlaneProjection from openhcs.core.source_bindings import CompiledSourceBindingPlan from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, FunctionCoreExecutor, PatternGroupData, ) - _FIRST = ArtifactSpec.input("First", MetadataArtifactType, parameter_name="first") _SECOND = ArtifactSpec.input("Second", MetadataArtifactType, parameter_name="second") @@ -39,11 +41,15 @@ def _consume_metadata(image, *, first, second): def _executor(): first = {"value": 1} second = {"value": 2} - pattern = compile_function_pattern((_consume_metadata, {"first": first, "second": second}), {}, {}) + pattern = compile_function_pattern( + (_consume_metadata, {"first": first, "second": second}), {}, {} + ) invocation = next(pattern.iter_invocations()) edges = tuple( InvocationArtifactInputEdgePlan.from_source_declarations( - key=InvocationArtifactInputProjectionKey(invocation_key=invocation.key, input_index=index), + key=InvocationArtifactInputProjectionKey( + invocation_key=invocation.key, input_index=index + ), spec=spec, main_flow_artifacts=ArtifactSpecCollection(()), invocation_sources=ArtifactSpecCollection(()), @@ -63,7 +69,7 @@ def _executor(): execution_group_scope=ComponentGroupScope.ungrouped(), source_binding_plan=CompiledSourceBindingPlan.empty(), ) - artifacts = ComponentArtifactPlans(inputs={edge.key: edge for edge in edges}, outputs={}) + artifacts = ({edge.key: edge for edge in edges}, {}) initial_image = np.arange(6, dtype=np.float32).reshape(1, 2, 3) scope = PatternGroupData( matching_files=["input.tif"], @@ -71,26 +77,44 @@ def _executor(): context=SimpleNamespace(axis_id="A01"), execution_plan=plan, compiled_group=replace(pattern.default_group, invocations=(invocation,)), - artifacts=ComponentArtifactPlans(inputs={}, outputs={}), + artifact_inputs={}, + artifact_outputs={}, runtime_plane_index=0, runtime_plane_count=1, ) return FunctionCoreExecutor( - scope, invocation, artifacts, None, RuntimePlaneProjection.stack(), - initial_image, "numpy", + scope, + invocation, + *artifacts, + None, + RuntimePlaneProjection.stack(), + initial_image, + "numpy", ) def test_executor_retains_positional_layout_with_loaded_group_owner_and_frozen_slots(): expected = ( - "group_data", "invocation", "artifacts", "group_key", "plane_projection", - "main_data_arg", "source_memory_type", + "group_data", + "invocation", + "artifact_inputs", + "artifact_outputs", + "group_key", + "plane_projection", + "main_data_arg", + "source_memory_type", ) declaration = fields(FunctionCoreExecutor) assert tuple(field.name for field in declaration) == expected assert tuple(inspect.signature(FunctionCoreExecutor).parameters) == expected - assert all(field.init and field.compare and field.repr and not field.kw_only for field in declaration) - assert all(field.default is MISSING and field.default_factory is MISSING for field in declaration) + assert all( + field.init and field.compare and field.repr and not field.kw_only + for field in declaration + ) + assert all( + field.default is MISSING and field.default_factory is MISSING + for field in declaration + ) executor = _executor() assert not hasattr(executor, "__dict__") with pytest.raises(FrozenInstanceError): @@ -98,7 +122,8 @@ def test_executor_retains_positional_layout_with_loaded_group_owner_and_frozen_s replaced = replace(executor, group_key="changed") assert replaced.group_key == "changed" assert replaced.group_data is executor.group_data - assert replaced.artifacts is executor.artifacts + assert replaced.artifact_inputs is executor.artifact_inputs + assert replaced.artifact_outputs is executor.artifact_outputs def test_executor_pickle_retains_real_scope_edges_and_ordered_field_state(): @@ -110,8 +135,14 @@ def test_executor_pickle_retains_real_scope_edges_and_ordered_field_state(): restored = pickle.loads(pickle.dumps(executor)) assert type(restored) is FunctionCoreExecutor assert restored.group_data.execution_plan.step_scope_id == "metadata-binding" - assert tuple(edge.spec.ref() for edge in restored.selected_artifact_input_edges) == (_FIRST.ref(), _SECOND.ref()) - assert all(isinstance(edge, CompiledMetadataArtifactInputEdgePlan) for edge in restored.selected_artifact_input_edges) + assert tuple(edge.spec.ref() for edge in restored.artifact_inputs.values()) == ( + _FIRST.ref(), + _SECOND.ref(), + ) + assert all( + isinstance(edge, CompiledMetadataArtifactInputEdgePlan) + for edge in restored.artifact_inputs.values() + ) assert restored.invocation.kwargs_dict == executor.invocation.kwargs_dict np.testing.assert_array_equal(restored.main_data_arg, executor.main_data_arg) assert not hasattr(restored, "__dict__") @@ -149,4 +180,6 @@ def test_missing_metadata_argument_error_stays_on_selected_edge_before_later_bin def test_missing_storage_error_remains_owned_by_executor(): executor = _executor() with pytest.raises(ValueError, match="storage-backed edge"): - executor.load_artifact_input("first", executor.selected_artifact_input_edges[0]) + executor.load_artifact_input( + "first", next(iter(executor.artifact_inputs.values())) + ) diff --git a/tests/unit/test_function_outputs.py b/tests/unit/test_function_outputs.py index 51d220763f..c0e21e09c2 100644 --- a/tests/unit/test_function_outputs.py +++ b/tests/unit/test_function_outputs.py @@ -71,11 +71,11 @@ MaterializedRuntimeArtifact, RuntimeArtifactMaterialization, ) +from openhcs.core.steps.function_artifact_materialization import ArtifactMaterializationTargetPlan from openhcs.core.steps.function_outputs import ( MaterializedImageOutputWriter, MemoryOutputWriter, - OpenHCSMetadataWriter, - RuntimeArtifactMaterializationAuthority, + OpenHCSMetadataTarget, MaterializedImageMetadataTarget, RuntimeArtifactMetadataTarget, StreamOutputsAuthority, @@ -135,11 +135,11 @@ def test_function_step_metadata_follows_runtime_artifact_persistence( (MaterializedImageOutputWriter, "write_if_needed", "materialized"), (StreamOutputsAuthority, "stream_outputs", "stream"), ( - RuntimeArtifactMaterializationAuthority, + ArtifactMaterializationTargetPlan, "materialize", "runtime_artifacts", ), - (OpenHCSMetadataWriter, "write", "metadata"), + (OpenHCSMetadataTarget, "write_for_step", "metadata"), ): monkeypatch.setattr( authority, @@ -475,7 +475,7 @@ def test_memory_output_writer_materializes_preserved_source_at_current_destinati np.testing.assert_array_equal( filemanager.load(str(source_path), Backend.MEMORY.value), memory_pixels ) - (target,) = OpenHCSMetadataWriter.OutputTarget.for_execution(context, plan) + (target,) = OpenHCSMetadataTarget.for_execution(context, plan) assert target.produced_projection_entries(context, plan) is not None @@ -1436,11 +1436,11 @@ def test_image_persistence_skips_object_label_main_flow_payloads(): def test_metadata_target_family_discovers_new_declaration_without_consumer_edits( tmp_path, ): - registry = OpenHCSMetadataWriter.OutputTarget.__registry__ + registry = OpenHCSMetadataTarget.__registry__ original_keys = set(registry) try: - class SupplementalImageMetadataTarget(OpenHCSMetadataWriter.OutputTarget): + class SupplementalImageMetadataTarget(OpenHCSMetadataTarget): @classmethod def from_plan(cls, plan): return cls( @@ -1454,9 +1454,9 @@ def from_plan(cls, plan): plan = function_step_plan("memory-only") plan.write_backend = Backend.MEMORY.value context = context_stub(FileManagerStub({})) - (target,) = OpenHCSMetadataWriter.OutputTarget.for_plan(plan) + (target,) = OpenHCSMetadataTarget.for_plan(plan) assert type(target) is SupplementalImageMetadataTarget - assert OpenHCSMetadataWriter.OutputTarget.for_execution(context, plan) == ( + assert OpenHCSMetadataTarget.for_execution(context, plan) == ( target, ) assert target.produced_projection_entries(context, plan) is None @@ -1482,7 +1482,7 @@ def test_metadata_writer_skips_owner_without_image_outputs(): ), ) - OpenHCSMetadataWriter.write(context, plan) + OpenHCSMetadataTarget.write_for_step(context, plan) def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifact( @@ -1526,7 +1526,7 @@ def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifac plan.create_openhcs_metadata = True record_output_path(context, plan, output_path) - OpenHCSMetadataWriter.write(context, plan) + OpenHCSMetadataTarget.write_for_step(context, plan) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -1619,8 +1619,8 @@ def test_produced_projection_metadata_persists_typed_collapsed_semantics( str(path), Backend.MEMORY.value, ) - OpenHCSMetadataWriter.write(context, plan) - OpenHCSMetadataWriter.finalize_completed_plate({"A01": context}) + OpenHCSMetadataTarget.write_for_step(context, plan) + OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -1982,7 +1982,7 @@ def test_produced_projection_derives_artifact_alias_for_same_address_outputs( ), ) - OpenHCSMetadataWriter.write(context, plan) + OpenHCSMetadataTarget.write_for_step(context, plan) subdirectory = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") @@ -2090,12 +2090,12 @@ def reject_generated_path_parse(_filename): raise AssertionError("Publication must consume the typed produced address.") monkeypatch.setattr(parser, "parse_filename", reject_generated_path_parse) - OpenHCSMetadataWriter.write(context, plan) + OpenHCSMetadataTarget.write_for_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: filemanager.delete(record.output_path, Backend.MEMORY.value) - OpenHCSMetadataWriter.finalize_completed_plate({well: context}) + OpenHCSMetadataTarget.finalize_completed_plate({well: context}) subdirectory = json.loads((plate_root / "openhcs_metadata.json").read_text())[ FIELDS.SUBDIRECTORIES ]["images"] @@ -2116,14 +2116,14 @@ def reject_generated_path_parse(_filename): unregistered = output_dir / "unowned_s001_w1_z001_t001.tif" tifffile.imwrite(unregistered, pixels) with pytest.raises(MetadataWriteError, match="lack typed produced addresses"): - OpenHCSMetadataWriter.finalize_completed_plate({well: context}) + OpenHCSMetadataTarget.finalize_completed_plate({well: context}) assert metadata_path.read_bytes() == previous_metadata unregistered.unlink() # This fixture owns the synthetic file. if len(paths) > 1: removed = paths[0] (plate_root / removed).unlink() - OpenHCSMetadataWriter.finalize_completed_plate({well: context}) + OpenHCSMetadataTarget.finalize_completed_plate({well: context}) reconciled = json.loads(metadata_path.read_text())[FIELDS.SUBDIRECTORIES][ "images" ] @@ -2212,7 +2212,7 @@ 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)) - OpenHCSMetadataWriter.write(owner_context, owner_plan) + OpenHCSMetadataTarget.write_for_step(owner_context, owner_plan) initial_metadata = json.loads( (plate_root / "openhcs_metadata.json").read_text(encoding="utf-8") )["subdirectories"]["images"] @@ -2231,9 +2231,9 @@ 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)) - OpenHCSMetadataWriter.write(follower_context, follower_plan) + OpenHCSMetadataTarget.write_for_step(follower_context, follower_plan) - OpenHCSMetadataWriter.finalize_completed_plate( + OpenHCSMetadataTarget.finalize_completed_plate( {"A01": owner_context, "B03": follower_context} ) @@ -2261,7 +2261,7 @@ def test_completed_plate_metadata_skips_unmaterialized_output_target(tmp_path): plan.create_openhcs_metadata = True context.step_plans = {plan.step_index: plan} - OpenHCSMetadataWriter.finalize_completed_plate({"A01": context}) + OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) assert not (plate_root / "openhcs_metadata.json").exists() @@ -2346,7 +2346,7 @@ def test_runtime_image_metadata_target_requires_persisted_images(tmp_path, conte materialization=materialization, ), ) - selected = OpenHCSMetadataWriter.OutputTarget.for_execution( + selected = OpenHCSMetadataTarget.for_execution( context, plan, artifact_materializations=saved_artifacts ) if contents == "images": @@ -2354,7 +2354,7 @@ def test_runtime_image_metadata_target_requires_persisted_images(tmp_path, conte else: assert selected == () plan.create_openhcs_metadata = True - OpenHCSMetadataWriter.write(context, plan) + OpenHCSMetadataTarget.write_for_step(context, plan) assert not (tmp_path / "openhcs_metadata.json").exists() assert directory.exists() == (contents != "absent") @@ -2420,19 +2420,19 @@ def test_declared_image_destinations_publish_and_reconcile_after_value_cleanup( path=output_plan.path, backend=Backend.MEMORY.value, ) - materializations = RuntimeArtifactMaterializationAuthority.materialize( + materializations = ArtifactMaterializationTargetPlan.materialize( context, plan ) - OpenHCSMetadataWriter.write( + OpenHCSMetadataTarget.write_for_step( context, plan, artifact_materializations=materializations ) context.runtime_value_store.clear() if stray_image: tifffile.imwrite(tmp_path / "images/review/unowned.tif", pixels) with pytest.raises(MetadataWriteError, match="lack typed produced addresses"): - OpenHCSMetadataWriter.finalize_completed_plate({"A01": context}) + OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) return - OpenHCSMetadataWriter.finalize_completed_plate({"A01": context}) + OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) subdirectories = json.loads((tmp_path / "openhcs_metadata.json").read_text())[ FIELDS.SUBDIRECTORIES ] @@ -2517,7 +2517,7 @@ def test_actual_array_exports_only_publish_declared_raster_inventory( backend=Backend.MEMORY.value, ) - materializations = RuntimeArtifactMaterializationAuthority.materialize( + materializations = ArtifactMaterializationTargetPlan.materialize( context, plan ) saved_outputs = tuple( @@ -2543,11 +2543,11 @@ def test_actual_array_exports_only_publish_declared_raster_inventory( ) assert {Path(location.path) for location in observed_locations} == expected_paths - OpenHCSMetadataWriter.write( + OpenHCSMetadataTarget.write_for_step( context, plan, artifact_materializations=materializations ) context.runtime_value_store.clear() - OpenHCSMetadataWriter.finalize_completed_plate({"A01": context}) + OpenHCSMetadataTarget.finalize_completed_plate({"A01": context}) metadata_path = tmp_path / "openhcs_metadata.json" subdirectories = json.loads(metadata_path.read_text())[FIELDS.SUBDIRECTORIES] assert set(subdirectories) == {"images/exports"} @@ -2774,7 +2774,7 @@ def test_whole_volume_checkpoint_publication_retains_exact_producer_scope( ) MemoryOutputWriter.write_if_needed(context, plan) np.testing.assert_array_equal(tifffile.imread(path), pixels) - (target,) = OpenHCSMetadataWriter.OutputTarget.for_execution(context, plan) + (target,) = OpenHCSMetadataTarget.for_execution(context, plan) materializations = () if with_artifact: plan.streaming_configs = {} @@ -2811,7 +2811,7 @@ def test_whole_volume_checkpoint_publication_retains_exact_producer_scope( path=output_plan.path, backend=Backend.MEMORY.value, ) - materializations = RuntimeArtifactMaterializationAuthority.materialize( + materializations = ArtifactMaterializationTargetPlan.materialize( context, plan ) assert { diff --git a/tests/unit/test_function_patterns.py b/tests/unit/test_function_patterns.py index 35c3c5a481..47e05492bf 100644 --- a/tests/unit/test_function_patterns.py +++ b/tests/unit/test_function_patterns.py @@ -56,7 +56,6 @@ from openhcs.core.runtime_adapters import runtime_adapter from openhcs.core.runtime_object_labels import ObjectLabelValue from openhcs.core.runtime_relationships import ObjectRelationshipDeclaration -from openhcs.core.steps.function_runtime import ComponentArtifactPlans from openhcs.processing.materialization import csv_only @@ -779,23 +778,23 @@ def measure_channels(image, *, runtime): ) for edge in invocation.artifact_input_edges )) - artifacts = ComponentArtifactPlans( - inputs=storage_plans, outputs={plan.ref(): plan for plan in green_outputs}, + selected_inputs = stored_invocation.select_inputs( + storage_plans, active_output_plans=green_outputs, ) - selected = artifacts.select_for_invocation( - stored_invocation, execution_scope=execution_scope, component_key="2", + selected_outputs = stored_invocation.select_outputs( + {plan.ref(): plan for plan in green_outputs}, + compiled_output_plans=green_outputs, ) - assert selected is not None - assert tuple(key.input_index for key in selected.inputs) == (1,) - assert tuple(selected.outputs.values()) == green_outputs + assert tuple(key.input_index for key in selected_inputs) == (1,) + assert tuple(selected_outputs.values()) == green_outputs assert stored_invocation.artifact_output_plans == (output_plan,) # Sparse admission still validates the complete compiled producer owner at # this epoch, including a producer whose output lineage is inactive here. storage_plans.pop(blue.ref()) with pytest.raises(ValueError, match="input plan.*unavailable"): - artifacts.select_for_invocation( - stored_invocation, execution_scope=execution_scope, component_key="2", + stored_invocation.select_inputs( + storage_plans, active_output_plans=green_outputs, ) @@ -1096,13 +1095,8 @@ def consume_mixed_inputs(image, *, runtime): second_spec, ) with pytest.raises(ValueError, match="input plan.*unavailable"): - ComponentArtifactPlans( - inputs={first_plan.ref(): first_plan}, - outputs={}, - ).select_for_invocation( - invocation, - execution_scope=ComponentGroupScope.ungrouped(), - component_key=None, + invocation.select_inputs( + {first_plan.ref(): first_plan}, ) @@ -1213,16 +1207,9 @@ def consume_cross_channel(image, *, runtime): ), ) ) - scoped_artifacts = ComponentArtifactPlans( - inputs={current_channel_plan.ref(): current_channel_plan.for_group("1")}, - outputs={}, - ) - with pytest.raises(ValueError, match="input plan.*unavailable"): - scoped_artifacts.select_for_invocation( - invocation, - execution_scope=ComponentGroupScope.ungrouped(), - component_key=None, + invocation.select_inputs( + {current_channel_plan.ref(): current_channel_plan.for_group("1")}, ) diff --git a/tests/unit/test_function_runtime_source_projection.py b/tests/unit/test_function_runtime_source_projection.py index b82a18cef3..ca060904c6 100644 --- a/tests/unit/test_function_runtime_source_projection.py +++ b/tests/unit/test_function_runtime_source_projection.py @@ -1,3 +1,9 @@ +from openhcs.core.steps.function_runtime import ( + PatternGroupExecutionRequest, + PatternGroupExecutionScope, + PatternGroupData, + FunctionCoreExecutor, +) from collections.abc import Callable from dataclasses import replace from pathlib import Path @@ -505,7 +511,7 @@ def test_workspace_source_loading_preserves_declared_tiff_intensity_scale( ) -> None: import tifffile - from openhcs.core.steps.function_runtime import PatternGroupRuntime + from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest source_path = tmp_path / "source.tif" source_pixels = np.array([[0, 4095]], dtype=np.uint16) @@ -545,10 +551,21 @@ def resolve_address(backend_address, backend, *, base_path): physical_source_path = resolve_address - runtime = PatternGroupRuntime.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( - source_binding_plan=source_binding_plan, + runtime = PatternGroupExecutionRequest( context=SimpleNamespace(filemanager=SourceFileManager()), + execution_plan=CompiledStepPlan( + step_index=0, + step_name="source fixture", + step_type="FunctionStep", + axis_id="A01", + source_binding_plan=source_binding_plan, + ), + compiled_group=compile_function_pattern( + lambda image: image, {}, {} + ).default_group, + pattern_group_info="fixture", + component_index=0, + component_count=1, ) payload = runtime._apply_workspace_source_binding_payload( @@ -575,8 +592,10 @@ def test_physical_source_loading_preserves_tiff_calibration_and_live_buffers( from openhcs.constants.constants import Backend from openhcs.core.runtime_image_values import image_payload_mask - from openhcs.core.runtime_source_binding_cache import RuntimeSourceBindingContextCache - from openhcs.core.steps.function_runtime import PatternGroupRuntime + from openhcs.core.runtime_source_binding_cache import ( + RuntimeSourceBindingContextCache, + ) + from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest from openhcs.microscopes.source_schema import SourceSchemaFilenameParser source_path = tmp_path / "A01_s002_w1_z003_t004.tif" @@ -587,30 +606,48 @@ def test_physical_source_loading_preserves_tiff_calibration_and_live_buffers( filemanager = FileManager(dict(storage_registry)) bindings = CompiledSourceBindingPlan.empty() plan = CompiledStepPlan( - step_index=0, step_name="Physical source", step_type="FunctionStep", - axis_id="A01", input_dir=tmp_path, output_dir=tmp_path / "outputs", - output_plate_root=tmp_path / "outputs", sub_dir="images", - read_backend=Backend.DISK.value, write_backend=Backend.MEMORY.value, - pipeline_position=0, variable_components=(), source_binding_plan=bindings, + step_index=0, + step_name="Physical source", + step_type="FunctionStep", + axis_id="A01", + input_dir=tmp_path, + output_dir=tmp_path / "outputs", + output_plate_root=tmp_path / "outputs", + sub_dir="images", + read_backend=Backend.DISK.value, + write_backend=Backend.MEMORY.value, + pipeline_position=0, + variable_components=(), + source_binding_plan=bindings, compiled_function_pattern=compile_function_pattern(lambda image: image, {}, {}), ) context = SimpleNamespace( - input_dir=tmp_path, filemanager=filemanager, + input_dir=tmp_path, + filemanager=filemanager, microscope_handler=SimpleNamespace( parser=SourceSchemaFilenameParser(), get_primary_backend=lambda *_args: Backend.DISK.value, ), runtime_source_binding_context_cache=RuntimeSourceBindingContextCache(), ) - runtime = PatternGroupRuntime.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( - context=context, execution_plan=plan, source_binding_plan=bindings, + runtime = PatternGroupExecutionRequest( + context=context, + execution_plan=replace(plan, source_binding_plan=bindings), + compiled_group=compile_function_pattern( + lambda image: image, {}, {} + ).default_group, + pattern_group_info="fixture", + component_index=0, + component_count=1, ) payload = ImagePayloadMetadata().payload_with(pixels, mask) lookup = VirtualWorkspacePathLookup.from_paths(source_path.name, str(source_path)) (loaded,) = runtime._apply_source_image_loading_semantics( - (payload,), (lookup,), (), None, + (payload,), + (lookup,), + (), + None, ) metadata = image_payload_metadata(loaded) @@ -1540,17 +1577,22 @@ def producer_output_contexts_for_paths(self, *_args): "step_output_manifest", lambda _context: MissingProducerManifest(), ) - runtime = function_runtime.PatternGroupRuntime( - SimpleNamespace( - context=SimpleNamespace( - microscope_handler=SimpleNamespace(parser=SourceSchemaFilenameParser()) - ), - execution_plan=SimpleNamespace(), - compiled_group=SimpleNamespace( - runtime_domain=RuntimeInvocationDomain.ARTIFACT_MANAGED, - ), - pattern_group_info="A01_s001_w2_z001_t001.tif", - ) + runtime = PatternGroupExecutionRequest( + context=SimpleNamespace( + microscope_handler=SimpleNamespace(parser=SourceSchemaFilenameParser()) + ), + execution_plan=CompiledStepPlan( + step_index=0, + step_name="source fixture", + step_type="FunctionStep", + axis_id="A01", + ), + compiled_group=SimpleNamespace( + runtime_domain=RuntimeInvocationDomain.ARTIFACT_MANAGED, + ), + pattern_group_info="A01_s001_w2_z001_t001.tif", + component_index=0, + component_count=1, ) with pytest.raises(NoStepOutputManifestMatch): @@ -2059,8 +2101,8 @@ def test_first_step_prepares_raw_source_anchors_under_semantic_binding_groups( from openhcs.core.progress import set_progress_queue from openhcs.core.source_bindings import LazyStepSourceBindingsConfig from openhcs.core.steps.function_runtime import ( + PatternGroupExecutionScope, PatternGroupExecutionRequest, - PatternGroupRuntime, ) from openhcs.core.steps.function_step import FunctionStep @@ -2138,7 +2180,7 @@ def test_first_step_prepares_raw_source_anchors_under_semantic_binding_groups( component_index=0, component_count=2, ) - loaded = PatternGroupRuntime(request)._load_input_stack() + loaded = request.load_input_stack() assert loaded[0] == ["A01_s001_w1_z001_t001.tif"] assert context.filemanager.exists( @@ -2293,7 +2335,6 @@ def test_grouped_runtime_adapter_receives_component_selected_source_bindings() - ) from openhcs.core.source_load_plan import SourceLoadPlan from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, PatternGroupData, FunctionCoreExecutor, ) @@ -2333,7 +2374,8 @@ def test_grouped_runtime_adapter_receives_component_selected_source_bindings() - execution_plan=execution_plan, compiled_group=compiled_pattern.default_group, component_value="1", - artifacts=ComponentArtifactPlans(inputs={}, outputs={}), + artifact_inputs={}, + artifact_outputs={}, runtime_plane_index=0, runtime_plane_count=2, ) @@ -2341,9 +2383,12 @@ def test_grouped_runtime_adapter_receives_component_selected_source_bindings() - executor = FunctionCoreExecutor( group_data=scope, invocation=compiled_pattern.default_group.invocations[0], - artifacts=ComponentArtifactPlans(inputs={}, outputs={}), - group_key="1", plane_projection=RuntimePlaneProjection.stack(), - main_data_arg=scope.main_data_stack, source_memory_type="numpy", + artifact_inputs={}, + artifact_outputs={}, + group_key="1", + plane_projection=RuntimePlaneProjection.stack(), + main_data_arg=scope.main_data_stack, + source_memory_type="numpy", ) request = executor.runtime_adapter_request(scope.main_data_stack) @@ -2370,7 +2415,6 @@ def test_runtime_invocation_uses_only_active_source_bound_main_flow_edges( from openhcs.core.source_load_plan import SourceLoadPlan from openhcs.core.steps import function_runtime from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, PatternGroupData, ) @@ -2458,16 +2502,20 @@ def consume_channel_source(image): execution_plan=execution_plan, compiled_group=compiled_group, component_value="1", - artifacts=ComponentArtifactPlans.from_step_component(execution_plan, "1"), + artifact_inputs=dict(execution_plan.artifact_inputs), + artifact_outputs=PatternGroupExecutionScope._select_output_plans_for_component( + execution_plan.artifact_outputs, execution_plan.execution_group_scope, "1" + ), runtime_plane_index=0, runtime_plane_count=1, ) captured_executor_kwargs = [] core_executor_type = function_runtime.FunctionCoreExecutor - class CapturingExecutor: + class CapturingExecutor(FunctionCoreExecutor): def __init__(self, **kwargs): captured_executor_kwargs.append(kwargs) + super().__init__(**kwargs) def execute(self, *, debug_sink=None): return NoMainFlowOutput() @@ -2483,18 +2531,20 @@ def execute(self, *, debug_sink=None): source_image_names=("OrigStain1",), ).payload_with(np.zeros((1, 3, 4), dtype=np.uint16)) scope = replace(scope, main_data_stack=active_payload) - result = function_runtime.PatternGroupRuntime.execute_chain(scope) + result = scope.execute_chain() assert isinstance(result, NoMainFlowOutput) assert tuple( edge.spec.name for edge in captured_executor_kwargs[0]["invocation"].artifact_input_edges ) == ("OrigStain1", "OrigStain2") - selected_artifacts = captured_executor_kwargs[0]["artifacts"] - assert tuple(edge.spec.name for edge in selected_artifacts.inputs.values()) == ( - "OrigStain1", + assert tuple( + edge.spec.name + for edge in captured_executor_kwargs[0]["artifact_inputs"].values() + ) == ("OrigStain1",) + assert tuple(captured_executor_kwargs[0]["artifact_outputs"]) == ( + output_specs[0].ref(), ) - assert tuple(selected_artifacts.outputs) == (output_specs[0].ref(),) request = core_executor_type(**captured_executor_kwargs[0]).runtime_adapter_request( np.zeros((1, 3, 4), dtype=np.uint16) @@ -2508,10 +2558,18 @@ def execute(self, *, debug_sink=None): def test_source_roster_selection_cannot_replace_missing_stored_primary_epoch() -> None: from openhcs.core.artifacts import ArtifactInputProjectionPlan - from openhcs.core.steps.function_runtime import ComponentArtifactPlans + from openhcs.core.steps.function_runtime import ( + PatternGroupExecutionScope, + FunctionCoreExecutor, + PatternGroupData, + ) - bindings = CompiledSourceBindingPlan(bindings=(NamedSourceBinding(alias="Original"),)) - (source_spec,) = tuple(binding.input_spec() for binding in bindings.binding_declarations) + bindings = CompiledSourceBindingPlan( + bindings=(NamedSourceBinding(alias="Original"),) + ) + (source_spec,) = tuple( + binding.input_spec() for binding in bindings.binding_declarations + ) @runtime_adapter("runtime", lambda _request: object(), manages_artifact_inputs=True) @artifact_inputs(source_spec) @@ -2519,27 +2577,60 @@ def consume_original(image, *, runtime): return image storage = ArtifactInputPlan( - name=source_spec.name, artifact_type=source_spec.artifact_type, - path="/memory/Original.pkl", source_step_id=0, - ) - invocation = compile_function_pattern(consume_original, {storage.ref(): storage}, {}).default_group.invocations[0] + name=source_spec.name, + artifact_type=source_spec.artifact_type, + path="/memory/Original.pkl", + source_step_id=0, + ) + invocation = compile_function_pattern( + consume_original, {storage.ref(): storage}, {} + ).default_group.invocations[0] (key,) = InvocationArtifactInputProjectionKey.for_input_count(invocation.key, 1) - invocation = invocation.with_artifact_input_edges(( - InvocationArtifactInputEdgePlan( - key=key, spec=source_spec, storage_plan=storage, - projection=ArtifactInputProjectionPlan( - invocation_scope=ComponentGroupScope.ungrouped(), - producer_selection_scope=storage.producer_group_scope(), + invocation = invocation.with_artifact_input_edges( + ( + InvocationArtifactInputEdgePlan( + key=key, + spec=source_spec, + storage_plan=storage, + projection=ArtifactInputProjectionPlan( + invocation_scope=ComponentGroupScope.ungrouped(), + producer_selection_scope=storage.producer_group_scope(), + ), + main_flow_projection=MainFlowInputProjection.COMPLETE_PAYLOAD, ), - main_flow_projection=MainFlowInputProjection.COMPLETE_PAYLOAD, - ), - )) - plans = ComponentArtifactPlans(inputs={storage.ref(): storage}, outputs={}) - with pytest.raises(ValueError, match="producer cannot substitute.*current payload epoch"): - plans.select_for_invocation( - invocation, execution_scope=ComponentGroupScope.ungrouped(), component_key=None, - declared_source_bindings=bindings, - active_source_bindings=CompiledSourceBindingPlan.empty(), + ) + ) + payload = ImagePayloadMetadata(source_image_names=("Other",)).payload_with( + np.zeros((1, 2, 3)) + ) + loaded = PatternGroupData( + context=SimpleNamespace(), + execution_plan=CompiledStepPlan( + step_index=0, + step_name="Stored", + step_type="FunctionStep", + axis_id="A01", + source_binding_plan=bindings, + ), + compiled_group=compile_function_pattern( + consume_original, {storage.ref(): storage}, {} + ).default_group, + artifact_inputs={storage.ref(): storage}, + artifact_outputs={}, + runtime_plane_index=0, + runtime_plane_count=1, + matching_files=["source.tif"], + main_data_stack=payload, + ) + with pytest.raises( + ValueError, match="producer cannot substitute.*current payload epoch" + ): + FunctionCoreExecutor.from_group_invocation( + loaded, + invocation, + main_data_arg=payload, + source_memory_type="numpy", + declared_source_bindings=loaded.execution_plan.source_binding_plan, ) @@ -2550,7 +2641,6 @@ def test_runtime_chain_skips_adapter_invocation_without_component_outputs( from openhcs.core.source_load_plan import SourceLoadPlan from openhcs.core.steps import function_runtime from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, PatternGroupData, ) @@ -2636,15 +2726,18 @@ def record_second_labels(image, *, runtime): execution_plan=execution_plan, compiled_group=compiled_group, component_value="1", - artifacts=ComponentArtifactPlans.from_step_component(execution_plan, "1"), + artifact_inputs=dict(execution_plan.artifact_inputs), + artifact_outputs=PatternGroupExecutionScope._select_output_plans_for_component( + execution_plan.artifact_outputs, execution_plan.execution_group_scope, "1" + ), runtime_plane_index=0, runtime_plane_count=1, ) executed = [] - class CapturingExecutor: + class CapturingExecutor(FunctionCoreExecutor): def __init__(self, **kwargs): - self.invocation = kwargs["invocation"] + super().__init__(**kwargs) def execute(self, *, debug_sink=None): del debug_sink @@ -2661,7 +2754,7 @@ def memory_types(self): lambda context: SimpleNamespace(captures_invocation_events=lambda: False), ) - function_runtime.PatternGroupRuntime.execute_chain(scope) + scope.execute_chain() assert executed == ["record_first_labels"] @@ -3263,7 +3356,6 @@ def test_runtime_plane_count_comes_from_loaded_slices_not_dispatch_groups() -> N def test_grouped_main_flow_context_uses_component_selected_output_plan() -> None: from openhcs.core.steps.function_runtime import ( PatternGroupExecutionRequest, - PatternGroupRuntime, ) corrected_stain_1_spec = ArtifactSpec.output( @@ -3311,16 +3403,14 @@ def correct_illumination(image): {}, {plan.ref(): plan for plan in (corrected_stain_1, corrected_stain_2)}, ).default_group - runtime = PatternGroupRuntime( - PatternGroupExecutionRequest( - context=SimpleNamespace(), - execution_plan=plan, - compiled_group=compiled_group, - component_value="1", - pattern_group_info="A01_s{iii}_w1_z001_t001.tif", - component_index=0, - component_count=2, - ) + runtime = PatternGroupExecutionRequest( + context=SimpleNamespace(), + execution_plan=plan, + compiled_group=compiled_group, + component_value="1", + pattern_group_info="A01_s{iii}_w1_z001_t001.tif", + component_index=0, + component_count=2, ) context = runtime._unwrapped_main_flow_output_context() @@ -3333,7 +3423,6 @@ def correct_illumination(image): def test_adapter_recorded_outputs_use_compiled_canonical_context() -> None: from openhcs.core.steps.function_runtime import ( PatternGroupExecutionRequest, - PatternGroupRuntime, ) outline_spec = ArtifactSpec.output("outline", ImageArtifactType) @@ -3363,21 +3452,19 @@ def record_mixed_outputs(image, *, runtime): {}, output_plans, ).default_group - runtime = PatternGroupRuntime( - PatternGroupExecutionRequest( - context=SimpleNamespace(), - execution_plan=SimpleNamespace( - artifact_inputs={}, - artifact_outputs=output_plans, - execution_group_scope=ComponentGroupScope.ungrouped(), - source_binding_plan=CompiledSourceBindingPlan.empty(), - ), - compiled_group=compiled_group, - component_value="default", - pattern_group_info="A01_s001_w1_z001_t001.tif", - component_index=0, - component_count=1, - ) + runtime = PatternGroupExecutionRequest( + context=SimpleNamespace(), + execution_plan=SimpleNamespace( + artifact_inputs={}, + artifact_outputs=output_plans, + execution_group_scope=ComponentGroupScope.ungrouped(), + source_binding_plan=CompiledSourceBindingPlan.empty(), + ), + compiled_group=compiled_group, + component_value="default", + pattern_group_info="A01_s001_w1_z001_t001.tif", + component_index=0, + component_count=1, ) context = runtime._unwrapped_main_flow_output_context() @@ -3388,7 +3475,11 @@ def record_mixed_outputs(image, *, runtime): def test_component_output_selection_keeps_distinct_axes_with_equal_keys() -> None: - from openhcs.core.steps.function_runtime import ComponentArtifactPlans + from openhcs.core.steps.function_runtime import ( + PatternGroupExecutionScope, + FunctionCoreExecutor, + PatternGroupData, + ) channel_1 = ArtifactOutputPlan( name="Stain1", @@ -3412,15 +3503,21 @@ def test_component_output_selection_keeps_distinct_axes_with_equal_keys() -> Non execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), ) - selected = ComponentArtifactPlans.from_step_component(plan, "1") + selected = PatternGroupExecutionScope._select_output_plans_for_component( + plan.artifact_outputs, plan.execution_group_scope, "1" + ) - assert tuple(selected.outputs) == (channel_1.ref(), channel_2.ref()) - assert selected.outputs[channel_1.ref()].path == "/memory/Stain1_1.pkl" - assert selected.outputs[channel_2.ref()].path == "/memory/Stain2_2.pkl" + assert tuple(selected) == (channel_1.ref(), channel_2.ref()) + assert selected[channel_1.ref()].path == "/memory/Stain1_1.pkl" + assert selected[channel_2.ref()].path == "/memory/Stain2_2.pkl" def test_component_artifact_plans_reject_malformed_exact_plan_maps() -> None: - from openhcs.core.steps.function_runtime import ComponentArtifactPlans + from openhcs.core.steps.function_runtime import ( + PatternGroupExecutionScope, + FunctionCoreExecutor, + PatternGroupData, + ) input_plan = ArtifactInputPlan( name="InputImage", @@ -3482,7 +3579,17 @@ def test_component_artifact_plans_reject_malformed_exact_plan_maps() -> None: execution_group_scope=ComponentGroupScope.ungrouped(), ) with pytest.raises(error_type, match=message): - ComponentArtifactPlans.from_step_component(step_plan, None) + request = PatternGroupExecutionRequest( + context=SimpleNamespace(), + execution_plan=step_plan, + compiled_group=compile_function_pattern( + lambda image: image, {}, {} + ).default_group, + pattern_group_info="fixture", + component_index=0, + component_count=1, + ) + PatternGroupData.from_loaded_group(request, [], np.zeros((1, 2, 3))) def test_grouped_runtime_scope_preserves_empty_source_binding_plan() -> None: @@ -3544,29 +3651,25 @@ def test_grouped_runtime_source_expansion_uses_scoped_bindings( {}, {}, ) - runtime = function_runtime.PatternGroupRuntime( - function_runtime.PatternGroupExecutionRequest( - context=SimpleNamespace( - source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.SITE,)) - ) - ), - execution_plan=SimpleNamespace( - axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic( - AllComponents.CHANNEL - ), - main_input_dependency=StepInputDependency.pipeline_start(), - source_binding_plan=source_binding_plan, - compiled_function_pattern=compiled_pattern, - variable_component_values=(VariableComponents.SITE.value,), - ), - compiled_group=compiled_pattern.require_group("1"), - component_value="1", - pattern_group_info="A01_s{iii}_w1_z001_t001.png", - component_index=0, - component_count=2, - ) + runtime = function_runtime.PatternGroupExecutionRequest( + context=SimpleNamespace( + source_image_set_identity_policy=SourceImageSetIdentityPolicy( + frozenset((AllComponents.SITE,)) + ) + ), + execution_plan=SimpleNamespace( + axis_id="A01", + execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + main_input_dependency=StepInputDependency.pipeline_start(), + source_binding_plan=source_binding_plan, + compiled_function_pattern=compiled_pattern, + variable_component_values=(VariableComponents.SITE.value,), + ), + compiled_group=compiled_pattern.require_group("1"), + component_value="1", + pattern_group_info="A01_s{iii}_w1_z001_t001.png", + component_index=0, + component_count=2, ) captured_aliases: tuple[str, ...] = () @@ -3586,14 +3689,14 @@ def matched_image_set_from_plan(*, bindings, **_kwargs): matched_image_set_from_plan, ) monkeypatch.setattr( - runtime, + type(runtime), "_source_binding_candidate_context", - lambda: SimpleNamespace(), + lambda _request, *args, **kwargs: (lambda: SimpleNamespace())(*args, **kwargs), ) monkeypatch.setattr( - runtime, + type(runtime), "_source_binding_load_universe", - lambda: (), + lambda _request, *args, **kwargs: (lambda: ())(*args, **kwargs), ) matching_files = ["/input/A01_s001_N_R.png"] @@ -3651,28 +3754,34 @@ def test_alias_only_workspace_filter_excludes_unselected_source_and_orders_stack NamedSourceBinding(alias="Hoechst"), ) ) - runtime = function_runtime.PatternGroupRuntime.__new__( - function_runtime.PatternGroupRuntime - ) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( context=SimpleNamespace( source_image_set_identity_policy=SourceImageSetIdentityPolicy() ), - execution_plan=SimpleNamespace( - main_input_dependency=StepInputDependency.pipeline_start(), + execution_plan=CompiledStepPlan( + step_index=0, step_name="MetaXpress", + step_type="FunctionStep", + axis_id="A01", + main_input_dependency=StepInputDependency.pipeline_start(), + source_binding_plan=selected_plan, ), - main_flow_source_binding_plan=selected_plan, + compiled_group=compile_function_pattern( + lambda image: image, {}, {} + ).default_group, + pattern_group_info="fixture", + component_index=0, + component_count=1, ) monkeypatch.setattr( - runtime, + type(runtime), "_source_binding_candidate_context", - lambda: source_context, + lambda _request, *args, **kwargs: (lambda: source_context)(*args, **kwargs), ) monkeypatch.setattr( - runtime, + type(runtime), "_source_binding_load_universe", - lambda: virtual_paths, + lambda _request, *args, **kwargs: (lambda: virtual_paths)(*args, **kwargs), ) assert runtime._filter_matching_files_for_source_bindings(list(virtual_paths)) == [ @@ -3730,14 +3839,23 @@ def resolve_address(backend_address, backend, *, base_path): physical_source_path = resolve_address - runtime = function_runtime.PatternGroupRuntime.__new__( - function_runtime.PatternGroupRuntime - ) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( context=SimpleNamespace(filemanager=SourceFileManager()), - source_binding_plan=CompiledSourceBindingPlan( - bindings=(NamedSourceBinding(alias="FilenamePrefix"),), + execution_plan=CompiledStepPlan( + step_index=0, + step_name="source fixture", + step_type="FunctionStep", + axis_id="A01", + source_binding_plan=CompiledSourceBindingPlan( + bindings=(NamedSourceBinding(alias="FilenamePrefix"),), + ), ), + compiled_group=compile_function_pattern( + lambda image: image, {}, {} + ).default_group, + pattern_group_info="fixture", + component_index=0, + component_count=1, ) payload = ImagePayloadMetadata(source_path=full_virtual_path).payload_with( np.zeros((4, 5), dtype=np.uint16), @@ -3772,7 +3890,7 @@ def resolve_address(backend_address, backend, *, base_path): def test_step_output_load_filter_skips_source_binding_filter() -> None: - from openhcs.core.steps.function_runtime import PatternGroupRuntime + from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest plan = SimpleNamespace( main_input_dependency=StepInputDependency.step_output( @@ -3783,8 +3901,16 @@ def test_step_output_load_filter_skips_source_binding_filter() -> None: bindings=(NamedSourceBinding(alias="OrigDNA"),) ), ) - runtime = PatternGroupRuntime.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace(execution_plan=plan) + runtime = PatternGroupExecutionRequest( + execution_plan=plan, + context=SimpleNamespace(), + compiled_group=compile_function_pattern( + lambda image: image, {}, {} + ).default_group, + pattern_group_info="fixture", + component_index=0, + component_count=1, + ) matching_files = ["/tmp/outputs/A14_s001_w3_z001_t001.tif"] assert ( @@ -3796,7 +3922,6 @@ def test_step_output_load_filter_skips_source_binding_filter() -> None: def test_empty_source_binding_plan_does_not_filter_runtime_inputs() -> None: from openhcs.core.steps.function_runtime import ( PatternGroupExecutionRequest, - PatternGroupRuntime, ) compiled_pattern = compile_function_pattern(lambda image: image, {}, {}) @@ -3806,8 +3931,7 @@ def test_empty_source_binding_plan_does_not_filter_runtime_inputs() -> None: main_input_dependency=StepInputDependency.pipeline_start(), source_binding_plan=CompiledSourceBindingPlan.empty(), ) - runtime = PatternGroupRuntime.__new__(PatternGroupRuntime) - runtime.request = PatternGroupExecutionRequest( + runtime = PatternGroupExecutionRequest( context=SimpleNamespace(), execution_plan=plan, compiled_group=compiled_pattern.default_group, @@ -3926,7 +4050,7 @@ def resolve_address(backend_address, backend, *, base_path): lambda _context: StepOutputManifestStore(), ) monkeypatch.setattr( - function_runtime.PatternGroupRuntime, + function_runtime.PatternGroupExecutionRequest, "source_workspace_projection_authority", lambda _self: SimpleNamespace( projection_if_available=lambda: projection, @@ -3961,23 +4085,21 @@ def resolve_address(backend_address, backend, *, base_path): ), source_image_set_identity_policy=SourceImageSetIdentityPolicy(), ) - runtime = function_runtime.PatternGroupRuntime( - function_runtime.PatternGroupExecutionRequest( - context=context, - execution_plan=plan, - compiled_group=compiled_pattern.default_group, - pattern_group_info="A01_s001_w{iii}_z001_t001.tif", - component_index=0, - component_count=1, - ) + runtime = function_runtime.PatternGroupExecutionRequest( + context=context, + execution_plan=plan, + compiled_group=compiled_pattern.default_group, + pattern_group_info="A01_s001_w{iii}_z001_t001.tif", + component_index=0, + component_count=1, ) monkeypatch.setattr( - runtime, + type(runtime), "_source_binding_load_universe", - lambda: virtual_paths, + lambda _request, *args, **kwargs: (lambda: virtual_paths)(*args, **kwargs), ) - loaded = runtime._load_input_stack() + loaded = runtime.load_input_stack() data = image_payload_data(loaded[1]) metadata = image_payload_metadata(loaded[1]) @@ -4032,19 +4154,19 @@ def load_batch(self, paths, backend): lambda _context: producer_manifest, ) monkeypatch.setattr( - function_runtime.PatternGroupRuntime, + function_runtime.PatternGroupExecutionRequest, "source_workspace_projection_authority", lambda _self: SimpleNamespace( projection_if_available=lambda: VirtualWorkspaceSourceProjection.empty() ), ) monkeypatch.setattr( - function_runtime.PatternGroupRuntime, + function_runtime.PatternGroupExecutionRequest, "_filter_matching_files_for_group", lambda _self, paths: paths, ) monkeypatch.setattr( - function_runtime.PatternGroupRuntime, + function_runtime.PatternGroupExecutionRequest, "_filter_matching_files_for_source_bindings", lambda _self, paths: paths, ) @@ -4058,46 +4180,59 @@ def load_batch(self, paths, backend): variable_components=(VariableComponents.Z_INDEX,), compiled_function_pattern=compile_function_pattern(lambda image: image, {}, {}), main_input_dependency=StepInputDependency.step_output( - source_step_index=0, source_step_scope_id="producer", + source_step_index=0, + source_step_scope_id="producer", ), ) producer = CompiledStepPlan( - step_index=0, step_name="producer", step_type="FunctionStep", - step_scope_id="producer", axis_id="A01", output_dir=tmp_path, + step_index=0, + step_name="producer", + step_type="FunctionStep", + step_scope_id="producer", + axis_id="A01", + output_dir=tmp_path, ) producer_manifest = StepOutputManifestStore() producer_manifest.begin_step(producer) - producer_manifest.record_outputs(producer, ( - ProducedOutputSemantics.from_output( - producer, output_path, - FunctionOutputIdentity( - component_values={"well": "A01", "site": "1", "channel": "2", "z_index": "1", "timepoint": "1"}, - extension=".tif", source="test", - ), - ).with_filename_qualifier("RescaledDNA"), - )) + producer_manifest.record_outputs( + producer, + ( + ProducedOutputSemantics.from_output( + producer, + output_path, + FunctionOutputIdentity( + component_values={ + "well": "A01", + "site": "1", + "channel": "2", + "z_index": "1", + "timepoint": "1", + }, + extension=".tif", + source="test", + ), + ).with_filename_qualifier("RescaledDNA"), + ), + ) context = SimpleNamespace( microscope_handler=SimpleNamespace(parser=SourceSchemaFilenameParser()), filemanager=MemoryFileManager(), runtime_image_stack_cache=RuntimeImageStackCache(), ) - runtime = function_runtime.PatternGroupRuntime( - SimpleNamespace( - context=context, - execution_plan=plan, - source_binding_plan=CompiledSourceBindingPlan.empty(), - compiled_group=SimpleNamespace( - runtime_domain=RuntimeInvocationDomain.SOURCE_ANCHORED, - ), - pattern_group_info="A01_s001_w2_z{iii}_t001.tif", - ) + runtime = PatternGroupExecutionRequest( + context=context, + execution_plan=replace( + plan, source_binding_plan=CompiledSourceBindingPlan.empty() + ), + compiled_group=plan.compiled_function_pattern.default_group, + pattern_group_info="A01_s001_w2_z{iii}_t001.tif", + component_index=0, + component_count=1, ) - loaded = runtime._load_input_stack() + loaded = runtime.load_input_stack() - provenance_planes = image_payload_metadata( - loaded[1] - ).source_image_provenance_planes + provenance_planes = image_payload_metadata(loaded[1]).source_image_provenance_planes assert provenance_planes.count == 2 assert provenance_planes.contributor_count == 0 plane_metadata = provenance_planes.component_metadata @@ -4107,18 +4242,24 @@ def load_batch(self, paths, backend): def test_artifact_managed_group_uses_compiler_group_without_filtering_anchor_files() -> ( None ): - from openhcs.core.steps.function_runtime import PatternGroupRuntime + from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest - runtime = PatternGroupRuntime.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( compiled_group=SimpleNamespace( runtime_domain=RuntimeInvocationDomain.ARTIFACT_MANAGED, ), - execution_plan=SimpleNamespace( - execution_group_value="channel", + execution_plan=CompiledStepPlan( + step_index=0, + step_name="source fixture", + step_type="FunctionStep", + axis_id="A01", main_input_dependency=StepInputDependency.pipeline_start(), ), component_value="1", + context=SimpleNamespace(), + pattern_group_info="fixture", + component_index=0, + component_count=1, ) matching_files = ["/tmp/outputs/A01_s001_w2_z001_t001.tif"] @@ -4126,21 +4267,27 @@ def test_artifact_managed_group_uses_compiler_group_without_filtering_anchor_fil def test_step_output_group_does_not_reinterpret_producer_path_component() -> None: - from openhcs.core.steps.function_runtime import PatternGroupRuntime + from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest - runtime = PatternGroupRuntime.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( compiled_group=SimpleNamespace( runtime_domain=RuntimeInvocationDomain.SOURCE_ANCHORED, ), - execution_plan=SimpleNamespace( - execution_group_value="channel", + execution_plan=CompiledStepPlan( + step_index=0, + step_name="source fixture", + step_type="FunctionStep", + axis_id="A01", main_input_dependency=StepInputDependency.step_output( source_step_index=4, source_step_scope_id="object_to_image", ), ), component_value="0", + context=SimpleNamespace(), + pattern_group_info="fixture", + component_index=0, + component_count=1, ) matching_files = ["/tmp/outputs/A01_s001_w2_z001_t001.tif"] @@ -5343,7 +5490,7 @@ def test_save_outputs_positional_lowering_preserves_explicit_payload_identity( tmp_path: Path, named_topology: str, ) -> None: - from openhcs.core.steps.function_runtime import PatternGroupRuntime + from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest from openhcs.core.runtime_stack_cache import RuntimeImageStackCache from openhcs.core.compiled_step_plan import CompiledStepPlan from openhcs.core.component_group_scope import ComponentGroupScope @@ -5383,33 +5530,33 @@ def save_batch( output_plans[output_plan.ref()] = output_plan func = artifact_outputs(spec)(func) filemanager = OutputFileManager() - runtime = PatternGroupRuntime( - SimpleNamespace( - context=SimpleNamespace( - filemanager=filemanager, - microscope_handler=SimpleNamespace( - parser=SourceSchemaFilenameParser(), - ), - runtime_function_output_identity_cache=FunctionOutputIdentityCache(), - runtime_image_stack_cache=RuntimeImageStackCache(), - ), - compiled_group=compile_function_pattern(func, {}, output_plans).default_group, - component_key=None, - execution_plan=CompiledStepPlan( - step_index=0, - step_type="FunctionStep", - axis_id="A01", - output_dir=tmp_path, - output_memory_type="numpy", - variable_components=(VariableComponents.SITE,), - step_name="ExplicitIdentity", - pipeline_position=0, - step_scope_id="explicit-identity", - execution_group_scope=ComponentGroupScope.ungrouped(), - artifact_outputs=output_plans, + runtime = PatternGroupExecutionRequest( + context=SimpleNamespace( + filemanager=filemanager, + microscope_handler=SimpleNamespace( + parser=SourceSchemaFilenameParser(), ), - pattern_group_info="A01_s{iii}_w1_z001_t001.tif", - ) + runtime_function_output_identity_cache=FunctionOutputIdentityCache(), + runtime_image_stack_cache=RuntimeImageStackCache(), + ), + compiled_group=compile_function_pattern(func, {}, output_plans).default_group, + execution_plan=CompiledStepPlan( + step_index=0, + step_type="FunctionStep", + axis_id="A01", + output_dir=tmp_path, + output_memory_type="numpy", + variable_components=(VariableComponents.SITE,), + step_name="ExplicitIdentity", + pipeline_position=0, + step_scope_id="explicit-identity", + execution_group_scope=ComponentGroupScope.ungrouped(), + artifact_outputs=output_plans, + ), + pattern_group_info="A01_s{iii}_w1_z001_t001.tif", + component_value=None, + component_index=0, + component_count=1, ) payload = ImagePayloadMetadata( source_path="/source/A01_s001_w1_z001_t001.tif", @@ -5423,11 +5570,13 @@ def save_batch( ).payload_with(np.zeros((4, 5), dtype=np.float32), None) named_context = AlignedImageSliceContext.main_flow( - "Corrected", artifact_kind=ImageArtifactType.value, + "Corrected", + artifact_kind=ImageArtifactType.value, ) output = ( AlignedImageStack((payload,), (named_context,)) - if named_topology == "explicit" else payload + if named_topology == "explicit" + else payload ) records = runtime._save_outputs( output, @@ -5447,10 +5596,12 @@ def save_batch( assert records[0].component_values["site"] == 1 if named_topology != "anonymous": assert records[0].output_context == named_context - assert image_payload_metadata(filemanager.saved_payloads[0]).source_image_names == ( - "Corrected", - ) - assert image_payload_data(filemanager.saved_payloads[0]) is image_payload_data(payload) + assert image_payload_metadata( + filemanager.saved_payloads[0] + ).source_image_names == ("Corrected",) + assert image_payload_data(filemanager.saved_payloads[0]) is image_payload_data( + payload + ) @pytest.fixture @@ -5644,7 +5795,6 @@ def test_producer_admission_rederives_live_storage_aliases_each_epoch( new_alias = record.without_filename_qualifier().filename(parser) with pytest.raises(NoStepOutputManifestMatch): store.filter_to_producer_paths(consumer, (old_alias,), parser) - assert old_index.matching_records(new_alias) == () current_index = store.producer_record_index_for(consumer, parser) assert current_index.matching_records(new_alias) == (record,) @@ -5657,31 +5807,54 @@ def test_producer_loader_validates_ambiguity_before_cache( from openhcs.core.steps import function_runtime producer = CompiledStepPlan( - step_index=0, step_name="producer", step_type="FunctionStep", - step_scope_id="producer", axis_id="A01", output_dir=Path("/memory"), + step_index=0, + step_name="producer", + step_type="FunctionStep", + step_scope_id="producer", + axis_id="A01", + output_dir=Path("/memory"), ) plan = CompiledStepPlan( - step_index=1, step_name="consumer", step_type="FunctionStep", - axis_id="A01", input_dir=Path("/memory"), input_memory_type="numpy", + step_index=1, + step_name="consumer", + step_type="FunctionStep", + axis_id="A01", + input_dir=Path("/memory"), + input_memory_type="numpy", compiled_function_pattern=compile_function_pattern(lambda image: image, {}, {}), main_input_dependency=StepInputDependency.step_output( - source_step_index=0, source_step_scope_id="producer", + source_step_index=0, + source_step_scope_id="producer", ), ) manifest = StepOutputManifestStore() manifest.begin_step(producer) - manifest.record_outputs(producer, ( - ProducedOutputSemantics.from_existing_main_flow_path( - producer, "A01_s001_w1_z001_t001.tif", SourceSchemaFilenameParser(), - ), - ProducedOutputSemantics.from_output( - producer, "/memory/other/A01_s001_w1_z001_t001.tif", - FunctionOutputIdentity( - component_values={"well": "A01", "site": 2, "channel": 1, "z_index": 1, "timepoint": 1}, - extension=".tif", source="test", + manifest.record_outputs( + producer, + ( + ProducedOutputSemantics.from_existing_main_flow_path( + producer, + "A01_s001_w1_z001_t001.tif", + SourceSchemaFilenameParser(), + ), + ProducedOutputSemantics.from_output( + producer, + "/memory/other/A01_s001_w1_z001_t001.tif", + FunctionOutputIdentity( + component_values={ + "well": "A01", + "site": 2, + "channel": 1, + "z_index": 1, + "timepoint": 1, + }, + extension=".tif", + source="test", + ), ), ), - )) + ) + class RejectImageCache: def get(self, *_args, **_kwargs): pytest.fail("Ambiguous producer admission must precede cached pixels") @@ -5690,20 +5863,29 @@ def get(self, *_args, **_kwargs): microscope_handler=SimpleNamespace(parser=SourceSchemaFilenameParser()), runtime_image_stack_cache=RejectImageCache(), ) - runtime = function_runtime.PatternGroupRuntime( - function_runtime.PatternGroupExecutionRequest( - context=context, execution_plan=plan, - compiled_group=plan.compiled_function_pattern.default_group, - pattern_group_info="A01_s001_w1_z001_t001.tif", component_index=0, component_count=1, - ) + runtime = function_runtime.PatternGroupExecutionRequest( + context=context, + execution_plan=plan, + compiled_group=plan.compiled_function_pattern.default_group, + pattern_group_info="A01_s001_w1_z001_t001.tif", + component_index=0, + component_count=1, + ) + monkeypatch.setattr( + function_runtime, "step_output_manifest", lambda _context: manifest + ) + monkeypatch.setattr( + type(runtime), + "source_workspace_projection_authority", + lambda _request, *args, **kwargs: ( + lambda: SimpleNamespace( + projection_if_available=lambda: None, + ) + )(*args, **kwargs), ) - monkeypatch.setattr(function_runtime, "step_output_manifest", lambda _context: manifest) - monkeypatch.setattr(runtime, "source_workspace_projection_authority", lambda: SimpleNamespace( - projection_if_available=lambda: None, - )) with pytest.raises(NoStepOutputManifestMatch, match="found 2"): - runtime._load_input_stack() + runtime.load_input_stack() def test_whole_volume_checkpoint_load_preserves_depth_and_independent_buffers(): diff --git a/tests/unit/test_function_step_execution_plan.py b/tests/unit/test_function_step_execution_plan.py index 2e5a5604f1..7388732411 100644 --- a/tests/unit/test_function_step_execution_plan.py +++ b/tests/unit/test_function_step_execution_plan.py @@ -40,9 +40,9 @@ StepInputDependencyKind, ) from openhcs.core.steps.function_artifact_materialization import ( - AnalysisOutputDescriptorAuthority, + RuntimeArtifactMaterialization, ) -from openhcs.core.steps.function_runtime import ComponentArtifactPlans +from openhcs.core.steps.function_runtime import PatternGroupExecutionScope def noop(image): @@ -392,11 +392,11 @@ def test_build_analysis_filename_falls_back_to_axis_and_pipeline_position_withou plan = context.step_plans[2].require_function_execution_ready() assert ( - AnalysisOutputDescriptorAuthority.build( + RuntimeArtifactMaterialization._analysis_identity( "measurements", plan, context=context, - ).filename + )[0] == "A01_measurements_step7.roi.zip" ) @@ -416,7 +416,7 @@ def test_component_artifact_plan_selection_merges_global_and_group_outputs(): paths_by_group={"A01": "/tmp/measurements/A01"}, ) - selected = ComponentArtifactPlans._select_output_plans_for_component( + selected = PatternGroupExecutionScope._select_output_plans_for_component( { global_output.ref(): global_output, grouped_output.ref(): grouped_output, @@ -441,7 +441,7 @@ def test_component_artifact_plan_selection_omits_unscoped_outputs_for_missing_gr paths_by_group={"3": "/tmp/objects_w3"}, ) - selected = ComponentArtifactPlans._select_output_plans_for_component( + selected = PatternGroupExecutionScope._select_output_plans_for_component( {output.ref(): output}, ComponentGroupScope(("1", "3"), component=AllComponents.CHANNEL), "1", @@ -464,7 +464,7 @@ def test_default_invocation_keeps_compiled_grouped_output_plan(): }, ) - selected = ComponentArtifactPlans._select_output_plans_for_component( + selected = PatternGroupExecutionScope._select_output_plans_for_component( {grouped_output.ref(): grouped_output}, ComponentGroupScope.ungrouped(), None, @@ -518,19 +518,17 @@ def test_invocation_output_selection_omits_inactive_component_outputs(): invocation, channel_one, _channel_two = _cross_channel_output_invocation() channel_one = channel_one.for_group("1") - selected = ComponentArtifactPlans( - inputs={}, - outputs={channel_one.ref(): channel_one}, - ).select_for_invocation( - invocation, - execution_scope=ComponentGroupScope.from_raw( - ("1", "2"), - component=AllComponents.CHANNEL, + selected_outputs = invocation.select_outputs( + {channel_one.ref(): channel_one}, + compiled_output_plans=invocation.output_plans_for_component( + ComponentGroupScope.from_raw( + ("1", "2"), component=AllComponents.CHANNEL, + ), + "1", ), - component_key="1", ) - assert selected.outputs == {channel_one.ref(): channel_one} + assert selected_outputs == {channel_one.ref(): channel_one} def test_compiler_handoff_preserves_exact_same_name_output_types(): @@ -708,54 +706,52 @@ def publish_derived_channels(image, *, illumination_function=None, runtime): ) active_output = output_plans[channel_one_output.ref()].for_group("1") - selected = ComponentArtifactPlans( - inputs=input_plans, - outputs={active_output.ref(): active_output}, - ).select_for_invocation( - invocation, - execution_scope=execution_scope, - component_key="1", + selected_inputs = invocation.select_inputs( + input_plans, + active_output_plans=invocation.output_plans_for_component(execution_scope, "1"), + ) + selected_outputs = invocation.select_outputs( + {active_output.ref(): active_output}, + compiled_output_plans=invocation.output_plans_for_component(execution_scope, "1"), ) - assert tuple(edge.spec for edge in selected.inputs.values()) == ( + assert tuple(edge.spec for edge in selected_inputs.values()) == ( channel_one_input, channel_one_illumination, shared_object_input, ) - assert selected.outputs == {active_output.ref(): active_output} + assert selected_outputs == {active_output.ref(): active_output} second_active_output = output_plans[channel_two_output.ref()].for_group("2") - second_selected = ComponentArtifactPlans( - inputs=input_plans, - outputs={second_active_output.ref(): second_active_output}, - ).select_for_invocation( - invocation, - execution_scope=execution_scope, - component_key="2", + second_selected_inputs = invocation.select_inputs( + input_plans, + active_output_plans=invocation.output_plans_for_component(execution_scope, "2"), + ) + second_selected_outputs = invocation.select_outputs( + {second_active_output.ref(): second_active_output}, + compiled_output_plans=invocation.output_plans_for_component(execution_scope, "2"), ) - assert tuple(edge.spec for edge in second_selected.inputs.values()) == ( + assert tuple(edge.spec for edge in second_selected_inputs.values()) == ( channel_two_input, channel_two_illumination, shared_object_input, ) - assert second_selected.outputs == {second_active_output.ref(): second_active_output} + assert second_selected_outputs == {second_active_output.ref(): second_active_output} def test_invocation_output_selection_rejects_missing_active_component_output(): invocation, _channel_one, _channel_two = _cross_channel_output_invocation() with pytest.raises(ValueError, match="channel_one.*unavailable"): - ComponentArtifactPlans( - inputs={}, - outputs={}, - ).select_for_invocation( - invocation, - execution_scope=ComponentGroupScope.from_raw( - ("1", "2"), - component=AllComponents.CHANNEL, + invocation.select_outputs( + {}, + compiled_output_plans=invocation.output_plans_for_component( + ComponentGroupScope.from_raw( + ("1", "2"), component=AllComponents.CHANNEL, + ), + "1", ), - component_key="1", ) @@ -771,16 +767,14 @@ def test_invocation_output_selection_rejects_active_projection_drift(): ) with pytest.raises(ValueError, match="runtime projection.*compiled owner"): - ComponentArtifactPlans( - inputs={}, - outputs={drifted_channel_one.ref(): drifted_channel_one}, - ).select_for_invocation( - invocation, - execution_scope=ComponentGroupScope.from_raw( - ("1", "2"), - component=AllComponents.CHANNEL, + invocation.select_outputs( + {drifted_channel_one.ref(): drifted_channel_one}, + compiled_output_plans=invocation.output_plans_for_component( + ComponentGroupScope.from_raw( + ("1", "2"), component=AllComponents.CHANNEL, + ), + "1", ), - component_key="1", ) @@ -833,13 +827,9 @@ def apply_illumination(image, *, runtime): ) invocation = invocation.with_artifact_input_edges((edge,)) - selected = ComponentArtifactPlans( - inputs={first_input.ref(): first_input}, - outputs={}, - ).select_for_invocation( - invocation, - execution_scope=scope, - component_key="1", + selected_inputs = invocation.select_inputs( + {first_input.ref(): first_input}, + active_output_plans=invocation.output_plans_for_component(scope, "1"), ) - assert selected.inputs == {edge.key: edge} + assert selected_inputs == {edge.key: edge} diff --git a/tests/unit/test_loaded_pattern_group_ownership.py b/tests/unit/test_loaded_pattern_group_ownership.py index 42ac20e205..d550097d6a 100644 --- a/tests/unit/test_loaded_pattern_group_ownership.py +++ b/tests/unit/test_loaded_pattern_group_ownership.py @@ -9,22 +9,24 @@ import pytest from openhcs.constants.constants import AllComponents, VariableComponents -from openhcs.core.runtime_profile import RuntimeProfileLogger from openhcs.core.compiled_step_plan import CompiledStepPlan from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.function_patterns import compile_function_pattern -from openhcs.core.runtime_image_values import ImagePayloadMetadata, image_payload_data, image_payload_metadata +from openhcs.core.runtime_image_values import ( + ImagePayloadMetadata, + image_payload_data, + image_payload_metadata, +) from openhcs.core.source_bindings import CompiledSourceBindingPlan from openhcs.core.source_image_provenance import SourceImageProvenancePlanes +from openhcs.core.runtime_profile import RuntimeProfileLogger from openhcs.core.steps import function_runtime from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, FunctionCoreExecutor, PatternGroupData, PatternGroupExecutionRequest, PatternGroupExecutionScope, - PatternGroupRuntime, ) from openhcs.core.steps.function_output_manifest import NoStepOutputManifestMatch @@ -36,17 +38,26 @@ def _identity(image): def _fixture(): pattern = compile_function_pattern(_identity, {}, {}) plan = CompiledStepPlan( - step_index=0, step_type="FunctionStep", step_name="Loaded", axis_id="A01", - step_scope_id="loaded-cohort", input_memory_type="numpy", output_memory_type="numpy", + step_index=0, + step_type="FunctionStep", + step_name="Loaded", + axis_id="A01", + step_scope_id="loaded-cohort", + input_memory_type="numpy", + output_memory_type="numpy", execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), variable_components=(VariableComponents.SITE,), source_binding_plan=CompiledSourceBindingPlan.empty(), ) context = ProcessingContext(axis_id="A01") request = PatternGroupExecutionRequest( - context=context, execution_plan=plan, compiled_group=pattern.default_group, - component_value="1", pattern_group_info="A01_s{iii}_w1_z003_t002.tif", - component_index=7, component_count=99, + context=context, + execution_plan=plan, + compiled_group=pattern.default_group, + component_value="1", + pattern_group_info="A01_s{iii}_w1_z003_t002.tif", + component_index=7, + component_count=99, fixed_component_values=((AllComponents.Z_INDEX, "dispatch-value"),), ) paths = ["A01_s001_w1_z003_t002.tif", "A01_s002_w1_z003_t002.tif"] @@ -54,7 +65,13 @@ def _fixture(): source_image_provenance_planes=SourceImageProvenancePlanes.from_components( paths=tuple(paths), component_metadata=tuple( - {"well": "A01", "site": str(site), "channel": "1", "z_index": "3", "timepoint": "2"} + { + "well": "A01", + "site": str(site), + "channel": "1", + "z_index": "3", + "timepoint": "2", + } for site in (1, 2) ), ), @@ -66,9 +83,17 @@ def test_complete_loaded_owner_has_one_frozen_ten_field_contract_and_pickle(): request, paths, payload = _fixture() loaded = PatternGroupData.from_loaded_group(request, paths, payload) expected = ( - "context", "execution_plan", "compiled_group", "component_value", "fixed_component_values", - "artifacts", "runtime_plane_index", "runtime_plane_count", - "matching_files", "main_data_stack", + "context", + "execution_plan", + "compiled_group", + "component_value", + "fixed_component_values", + "artifact_inputs", + "artifact_outputs", + "runtime_plane_index", + "runtime_plane_count", + "matching_files", + "main_data_stack", ) assert PatternGroupData.__bases__ == (PatternGroupExecutionScope,) assert tuple(item.name for item in fields(loaded)) == expected @@ -85,7 +110,9 @@ def test_complete_loaded_owner_has_one_frozen_ten_field_contract_and_pickle(): replaced = replace(loaded, component_value="2") assert replaced.main_data_stack is payload assert replaced.matching_files is paths - from openhcs.core.orchestrator.execution_result import RuntimeExecutionTransportSerialization + from openhcs.core.orchestrator.execution_result import ( + RuntimeExecutionTransportSerialization, + ) RuntimeExecutionTransportSerialization.register() restored = pickle.loads(pickle.dumps(loaded)) @@ -94,33 +121,48 @@ def test_complete_loaded_owner_has_one_frozen_ten_field_contract_and_pickle(): assert restored.runtime_plane_count == 2 assert restored.execution_plan.step_scope_id == "loaded-cohort" assert restored.fixed_component_values == loaded.fixed_component_values - np.testing.assert_array_equal(image_payload_data(restored.main_data_stack), image_payload_data(payload)) + np.testing.assert_array_equal( + image_payload_data(restored.main_data_stack), image_payload_data(payload) + ) def test_initial_coordinates_stay_captured_while_plan_selectors_follow_mutation(): request, paths, payload = _fixture() loaded = PatternGroupData.from_loaded_group(request, paths, payload) assert loaded.runtime_plane_count == 2 - assert loaded.fixed_component_values == ((AllComponents.Z_INDEX, "3"), (AllComponents.TIMEPOINT, "2")) + assert loaded.fixed_component_values == ( + (AllComponents.Z_INDEX, "3"), + (AllComponents.TIMEPOINT, "2"), + ) paths.append("later-mutation.tif") image_payload_data(payload)[:] = -1 assert loaded.runtime_plane_count == 2 assert len(loaded.matching_files) == 3 request.execution_plan.axis_id = "B02" - request.execution_plan.execution_group_scope = ComponentGroupScope.dynamic(AllComponents.SITE) + request.execution_plan.execution_group_scope = ComponentGroupScope.dynamic( + AllComponents.SITE + ) assert loaded.axis_scope.axis_id == "B02" assert loaded.axis_component == "site" - assert loaded.fixed_component_values == ((AllComponents.Z_INDEX, "3"), (AllComponents.TIMEPOINT, "2")) + assert loaded.fixed_component_values == ( + (AllComponents.Z_INDEX, "3"), + (AllComponents.TIMEPOINT, "2"), + ) def test_chain_shares_cohort_but_advances_only_current_image_and_memory(monkeypatch): request, paths, payload = _fixture() invocation = request.compiled_group.invocations[0] - invocation = replace(invocation, contract=replace( - invocation.contract, metadata=replace( - invocation.contract.metadata, output_memory_type="next-memory", + invocation = replace( + invocation, + contract=replace( + invocation.contract, + metadata=replace( + invocation.contract.metadata, + output_memory_type="next-memory", + ), ), - )) + ) group = replace(request.compiled_group, invocations=(invocation, invocation)) request = replace(request, compiled_group=group) loaded = PatternGroupData.from_loaded_group(request, paths, payload) @@ -130,7 +172,9 @@ def test_chain_shares_cohort_but_advances_only_current_image_and_memory(monkeypa def execute(executor, *, debug_sink=None): assert debug_sink is None - seen.append((executor.group_data, executor.main_data_arg, executor.source_memory_type)) + seen.append( + (executor.group_data, executor.main_data_arg, executor.source_memory_type) + ) if len(seen) == 1: paths.append("during-call.tif") image_payload_data(payload)[:] = -3 @@ -138,23 +182,42 @@ def execute(executor, *, debug_sink=None): return second_output monkeypatch.setattr(FunctionCoreExecutor, "execute", execute) - monkeypatch.setattr(function_runtime, "debug_event_sink_from_context", lambda _context: SimpleNamespace(captures_invocation_events=lambda: False)) - assert PatternGroupRuntime.execute_chain(loaded) is second_output + monkeypatch.setattr( + function_runtime, + "debug_event_sink_from_context", + lambda _context: SimpleNamespace(captures_invocation_events=lambda: False), + ) + assert loaded.execute_chain() is second_output assert seen[0][0] is loaded and seen[1][0] is loaded assert seen[0][1] is payload and seen[1][1] is first_output assert seen[0][2] == "numpy" and seen[1][2] == "next-memory" assert loaded.main_data_stack is payload assert loaded.runtime_plane_count == 2 - assert loaded.fixed_component_values == ((AllComponents.Z_INDEX, "3"), (AllComponents.TIMEPOINT, "2")) + assert loaded.fixed_component_values == ( + (AllComponents.Z_INDEX, "3"), + (AllComponents.TIMEPOINT, "2"), + ) -def test_scope_admission_follows_load_profile_inside_execution_error_boundary(monkeypatch): +def test_scope_admission_follows_load_profile_inside_execution_error_boundary( + monkeypatch, +): request, paths, payload = _fixture() - runtime = PatternGroupRuntime(request) + runtime = request events = [] failure = RuntimeError("cohort admission failed") - monkeypatch.setattr(runtime, "_load_input_stack", lambda: (events.append("load") or (paths, payload))) - monkeypatch.setattr(RuntimeProfileLogger, "log", lambda _logger, label, *_args, **_kwargs: events.append(label)) + monkeypatch.setattr( + type(runtime), + "load_input_stack", + lambda _request, *args, **kwargs: ( + lambda: (events.append("load") or (paths, payload)) + )(*args, **kwargs), + ) + monkeypatch.setattr( + RuntimeProfileLogger, + "log", + lambda _logger, label, *_args, **_kwargs: events.append(label), + ) def fail_capture(cls, observed_request, observed_paths, observed_payload): assert observed_request is request @@ -163,25 +226,41 @@ def fail_capture(cls, observed_request, observed_paths, observed_payload): events.append("capture") raise failure - monkeypatch.setattr(PatternGroupData, "from_loaded_group", classmethod(fail_capture)) + monkeypatch.setattr( + PatternGroupData, "from_loaded_group", classmethod(fail_capture) + ) with pytest.raises(ValueError, match="Failed to process pattern group") as exc: runtime.run() assert exc.value.__cause__ is failure assert events == ["load", "pattern_load_stack", "capture"] -@pytest.mark.parametrize("failure", [RuntimeError("load failed"), NoStepOutputManifestMatch("stale")]) -def test_load_errors_and_stale_skip_precede_capture_and_execution_wrapping(monkeypatch, failure): +@pytest.mark.parametrize( + "failure", [RuntimeError("load failed"), NoStepOutputManifestMatch("stale")] +) +def test_load_errors_and_stale_skip_precede_capture_and_execution_wrapping( + monkeypatch, failure +): request, _paths, _payload = _fixture() - runtime = PatternGroupRuntime(request) + runtime = request events = [] def failed_load(): events.append("load") raise failure - monkeypatch.setattr(runtime, "_load_input_stack", failed_load) - monkeypatch.setattr(RuntimeProfileLogger, "log", lambda *_args, **_kwargs: pytest.fail("failed load must not reach profile/capture")) + monkeypatch.setattr( + type(runtime), + "load_input_stack", + lambda _request, *args, **kwargs: (failed_load)(*args, **kwargs), + ) + monkeypatch.setattr( + RuntimeProfileLogger, + "log", + lambda *_args, **_kwargs: pytest.fail( + "failed load must not reach profile/capture" + ), + ) if isinstance(failure, NoStepOutputManifestMatch): assert runtime.run() is None else: @@ -193,11 +272,21 @@ def failed_load(): def test_empty_chain_is_rejected_after_full_capture_and_load_profile(monkeypatch): request, paths, payload = _fixture() - request = replace(request, compiled_group=replace(request.compiled_group, invocations=())) - runtime = PatternGroupRuntime(request) + request = replace( + request, compiled_group=replace(request.compiled_group, invocations=()) + ) + runtime = request labels = [] - monkeypatch.setattr(runtime, "_load_input_stack", lambda: (paths, payload)) - monkeypatch.setattr(RuntimeProfileLogger, "log", lambda _logger, label, *_args, **_kwargs: labels.append(label)) + monkeypatch.setattr( + type(runtime), + "load_input_stack", + lambda _request, *args, **kwargs: (lambda: (paths, payload))(*args, **kwargs), + ) + monkeypatch.setattr( + RuntimeProfileLogger, + "log", + lambda _logger, label, *_args, **_kwargs: labels.append(label), + ) with pytest.raises(ValueError, match="has no invocations") as exc: runtime.run() assert isinstance(exc.value.__cause__, ValueError) @@ -210,8 +299,14 @@ def test_adapter_request_projects_live_fields_and_preserves_current_payload_epoc current = np.ones((2, 3, 4), dtype=np.float32) invocation = loaded.compiled_group.invocations[0] executor = FunctionCoreExecutor( - loaded, invocation, ComponentArtifactPlans(inputs={}, outputs={}), "1", - function_runtime.RuntimePlaneProjection.stack(2), current, "numpy", + loaded, + invocation, + {}, + {}, + "1", + function_runtime.RuntimePlaneProjection.stack(2), + current, + "numpy", ) adapter = executor.runtime_adapter_request(current) assert adapter.context is loaded.context @@ -234,8 +329,14 @@ def test_adapter_tuple_admission_precedes_output_map_validation(): loaded = PatternGroupData.from_loaded_group(request, paths, initial) invocation = loaded.compiled_group.invocations[0] executor = FunctionCoreExecutor( - loaded, invocation, ComponentArtifactPlans(inputs={}, outputs={"invalid": object()}), "1", - function_runtime.RuntimePlaneProjection.stack(2), initial, "numpy", + loaded, + invocation, + {}, + {"invalid": object()}, + "1", + function_runtime.RuntimePlaneProjection.stack(2), + initial, + "numpy", ) request.execution_plan.variable_components = None with pytest.raises(TypeError, match="NoneType.*not iterable"): @@ -248,7 +349,13 @@ def test_adapter_tuple_admission_precedes_output_map_validation(): def test_component_artifact_admission_precedes_source_provenance_capture(monkeypatch): request, paths, initial = _fixture() request.execution_plan.artifact_inputs = {"invalid": object()} - monkeypatch.setattr(function_runtime, "image_payload_metadata", lambda _payload: pytest.fail("source projection must follow artifact-plan admission")) + monkeypatch.setattr( + function_runtime, + "image_payload_metadata", + lambda _payload: pytest.fail( + "source projection must follow artifact-plan admission" + ), + ) with pytest.raises(TypeError, match="Component artifact input"): PatternGroupData.from_loaded_group(request, paths, initial) @@ -256,11 +363,19 @@ def test_component_artifact_admission_precedes_source_provenance_capture(monkeyp def _stored_primary_fixture(*, preserves_main_flow=False): from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( - ArtifactInputPlan, ArtifactOutputPlan, ArtifactSpec, - ArtifactSpecCollection, GroupLineageSourceRelation, ImageArtifactType, SpecialArtifactType, + ArtifactInputPlan, + ArtifactOutputPlan, + ArtifactSpec, + ArtifactSpecCollection, + GroupLineageSourceRelation, + ImageArtifactType, + SpecialArtifactType, ) from openhcs.core.component_set import ComponentSet - from openhcs.core.pipeline.function_contracts import artifact_inputs, artifact_outputs + from openhcs.core.pipeline.function_contracts import ( + artifact_inputs, + artifact_outputs, + ) from openhcs.core.pipeline.path_planner import PathPlanner, PathPlannerArtifactStage from openhcs.core.runtime_adapters import runtime_adapter from openhcs.core.runtime_artifact_values import RuntimeValue @@ -270,7 +385,8 @@ def _stored_primary_fixture(*, preserves_main_flow=False): request, _, payload = _fixture() source = ArtifactSpec.input("Canonical", ImageArtifactType) output = ArtifactSpec.output( - "Processed", SpecialArtifactType if preserves_main_flow else ImageArtifactType, + "Processed", + SpecialArtifactType if preserves_main_flow else ImageArtifactType, relations=(GroupLineageSourceRelation(source=source.ref()),), ) @@ -281,15 +397,21 @@ def consume(image, *, runtime): return image output_plan = ArtifactOutputPlan( - name=output.name, path="/memory/processed", artifact_type=output.artifact_type, + name=output.name, + path="/memory/processed", + artifact_type=output.artifact_type, relations=output.relations, ) input_plan = ArtifactInputPlan( - name=source.name, path="/memory/canonical", artifact_type=ImageArtifactType, + name=source.name, + path="/memory/canonical", + artifact_type=ImageArtifactType, source_step_id=0, ) pattern = compile_function_pattern(consume, {}, {output_plan.ref(): output_plan}) - pattern = PathPlannerArtifactStage(PathPlanner.__new__(PathPlanner)).compile_invocation_input_edges( + pattern = PathPlannerArtifactStage( + PathPlanner.__new__(PathPlanner) + ).compile_invocation_input_edges( pattern, artifact_inputs={input_plan.ref(): input_plan}, relation_source_scopes={}, @@ -303,49 +425,89 @@ def consume(image, *, runtime): request.execution_plan.artifact_outputs = {output_plan.ref(): output_plan} request.execution_plan.compiled_function_pattern = pattern request = function_runtime.ArtifactPatternGroupExecutionRequest( - context=request.context, execution_plan=request.execution_plan, - compiled_group=pattern.default_group, pattern_group_info=input_plan.path, - component_index=7, component_count=99, - fixed_component_values=((AllComponents.Z_INDEX, "3"), (AllComponents.TIMEPOINT, "2")), - ) - payload = image_payload_metadata(payload).replace_fields( - plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, - ).payload_with(image_payload_data(payload), np.ones((2, 3, 4), dtype=bool)) + context=request.context, + execution_plan=request.execution_plan, + compiled_group=pattern.default_group, + pattern_group_info=input_plan.path, + component_index=7, + component_count=99, + fixed_component_values=( + (AllComponents.Z_INDEX, "3"), + (AllComponents.TIMEPOINT, "2"), + ), + ) + payload = ( + image_payload_metadata(payload) + .replace_fields( + plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, + ) + .payload_with(image_payload_data(payload), np.ones((2, 3, 4), dtype=bool)) + ) value = RuntimeValue.from_spec( - source, payload, - execution_scope=RuntimeExecutionAxisScope.from_raw("A01", component=None, value=None, fixed_component_values=request.fixed_component_values), + source, + payload, + execution_scope=RuntimeExecutionAxisScope.from_raw( + "A01", + component=None, + value=None, + fixed_component_values=request.fixed_component_values, + ), ) request.context.runtime_value_store.replace( - value, path=input_plan.path, backend=Backend.MEMORY.value, + value, + path=input_plan.path, + backend=Backend.MEMORY.value, ) return request, value -def test_stored_primary_admission_owns_independent_buffer_and_live_primary_binding(monkeypatch): +def test_stored_primary_admission_owns_independent_buffer_and_live_primary_binding( + monkeypatch, +): from openhcs.constants.constants import Backend from openhcs.core.runtime_image_values import image_payload_mask - from openhcs.interop.cellprofiler.runtime.artifact_binding import RuntimeInputBindingRequest - from tests.unit.cellprofiler_runtime_test_support import cellprofiler_runtime_adapter_for_test + from openhcs.interop.cellprofiler.runtime.artifact_binding import ( + RuntimeInputBindingRequest, + ) + from tests.unit.cellprofiler_runtime_test_support import ( + cellprofiler_runtime_adapter_for_test, + ) request, canonical = _stored_primary_fixture() - runtime = PatternGroupRuntime(request) + runtime = request monkeypatch.setattr( - runtime, "source_workspace_projection_authority", - lambda: SimpleNamespace(projection_if_available=lambda: None), + type(runtime), + "source_workspace_projection_authority", + lambda _request, *args, **kwargs: ( + lambda: SimpleNamespace(projection_if_available=lambda: None) + )(*args, **kwargs), ) - paths, admitted = request.load_input_stack(runtime) + paths, admitted = request.load_input_stack() assert paths == ["/memory/canonical"] - assert not np.shares_memory(image_payload_data(admitted), image_payload_data(canonical.data)) - assert not np.shares_memory(image_payload_mask(admitted), image_payload_mask(canonical.data)) + assert not np.shares_memory( + image_payload_data(admitted), image_payload_data(canonical.data) + ) + assert not np.shares_memory( + image_payload_mask(admitted), image_payload_mask(canonical.data) + ) loaded = PatternGroupData.from_loaded_group(request, paths, admitted) assert loaded.runtime_plane_count == 2 assert loaded.runtime_plane_index == 7 - assert loaded.fixed_component_values == ((AllComponents.Z_INDEX, "3"), (AllComponents.TIMEPOINT, "2")) - replacement = replace(canonical, data=image_payload_metadata(canonical.data).payload_with( - np.full((2, 3, 4), 31, dtype=np.float32), np.zeros((2, 3, 4), dtype=bool), - )) + assert loaded.fixed_component_values == ( + (AllComponents.Z_INDEX, "3"), + (AllComponents.TIMEPOINT, "2"), + ) + replacement = replace( + canonical, + data=image_payload_metadata(canonical.data).payload_with( + np.full((2, 3, 4), 31, dtype=np.float32), + np.zeros((2, 3, 4), dtype=bool), + ), + ) request.context.runtime_value_store.replace( - replacement, path=paths[0], backend=Backend.MEMORY.value, + replacement, + path=paths[0], + backend=Backend.MEMORY.value, ) image_payload_data(admitted)[:] = 17 image_payload_mask(admitted)[:] = False @@ -354,15 +516,20 @@ def test_stored_primary_admission_owns_independent_buffer_and_live_primary_bindi adapter = cellprofiler_runtime_adapter_for_test( runtime_value_store=request.context.runtime_value_store, callable_contract=invocation.contract, - artifact_inputs={edge.key: edge}, axis_scope=request.axis_scope, + artifact_inputs={edge.key: edge}, + axis_scope=request.axis_scope, ) - bound = RuntimeInputBindingRequest(adapter=adapter, kwargs={}, current_image=admitted).artifact_value(edge) + bound = RuntimeInputBindingRequest( + adapter=adapter, kwargs={}, current_image=admitted + ).artifact_value(edge) assert bound is admitted np.testing.assert_array_equal(image_payload_data(bound), 17) np.testing.assert_array_equal(image_payload_data(replacement.data), 31) - _, next_admitted = request.load_input_stack(runtime) + _, next_admitted = request.load_input_stack() np.testing.assert_array_equal(image_payload_data(next_admitted), 31) - assert not np.shares_memory(image_payload_data(next_admitted), image_payload_data(replacement.data)) + assert not np.shares_memory( + image_payload_data(next_admitted), image_payload_data(replacement.data) + ) assert loaded.runtime_plane_count == 2 @@ -371,16 +538,31 @@ def test_checkpoint_demand_follows_preserved_input_to_native_reader(): from openhcs.core.step_dependencies import StepInputDependency request, _ = _stored_primary_fixture() - source = replace(request.execution_plan, step_index=0, step_scope_id="source", write_backend=Backend.MEMORY.value) + source = replace( + request.execution_plan, + step_index=0, + step_scope_id="source", + write_backend=Backend.MEMORY.value, + ) preserving_request, _ = _stored_primary_fixture(preserves_main_flow=True) preserving_pattern = preserving_request.execution_plan.compiled_function_pattern preserving = replace( - source, step_index=1, step_scope_id="preserving", compiled_function_pattern=preserving_pattern, - main_input_dependency=StepInputDependency.step_output(source_step_index=0, source_step_scope_id="source"), + source, + step_index=1, + step_scope_id="preserving", + compiled_function_pattern=preserving_pattern, + main_input_dependency=StepInputDependency.step_output( + source_step_index=0, source_step_scope_id="source" + ), ) native = replace( - source, step_index=2, step_scope_id="native", compiled_function_pattern=compile_function_pattern(_identity, {}, {}), - main_input_dependency=StepInputDependency.step_output(source_step_index=1, source_step_scope_id="preserving"), + source, + step_index=2, + step_scope_id="native", + compiled_function_pattern=compile_function_pattern(_identity, {}, {}), + main_input_dependency=StepInputDependency.step_output( + source_step_index=1, source_step_scope_id="preserving" + ), ) plans = {0: source, 1: preserving, 2: native} assert source.requires_main_flow_checkpoint(plans) @@ -397,16 +579,28 @@ def test_checkpoint_demand_preserves_dependent_group_admission(pattern_kind): from openhcs.core.step_dependencies import StepInputDependency request, _ = _stored_primary_fixture() - source = replace(request.execution_plan, step_index=0, step_scope_id="source", write_backend=Backend.MEMORY.value) + source = replace( + request.execution_plan, + step_index=0, + step_scope_id="source", + write_backend=Backend.MEMORY.value, + ) consumer = replace( - source, step_index=1, step_scope_id="consumer", + source, + step_index=1, + step_scope_id="consumer", compiled_function_pattern=( - None if pattern_kind == "unknown" else replace( - source.compiled_function_pattern, groups=(), + None + if pattern_kind == "unknown" + else replace( + source.compiled_function_pattern, + groups=(), is_grouped=pattern_kind == "missing", ) ), - main_input_dependency=StepInputDependency.step_output(source_step_index=0, source_step_scope_id="source"), + main_input_dependency=StepInputDependency.step_output( + source_step_index=0, source_step_scope_id="source" + ), ) plans = {0: source, 1: consumer} if pattern_kind == "malformed": @@ -414,7 +608,9 @@ def test_checkpoint_demand_preserves_dependent_group_admission(pattern_kind): source.requires_main_flow_checkpoint(plans) else: assert source.requires_main_flow_checkpoint(plans) - consumer.main_input_dependency = StepInputDependency.step_output(source_step_index=99, source_step_scope_id="absent") + consumer.main_input_dependency = StepInputDependency.step_output( + source_step_index=99, source_step_scope_id="absent" + ) assert not source.requires_main_flow_checkpoint(plans) assert source.requires_main_flow_checkpoint({}) assert source.requires_main_flow_checkpoint({1: consumer}) @@ -425,16 +621,28 @@ def test_checkpoint_demand_propagates_only_through_preserved_outputs(): from openhcs.core.step_dependencies import StepInputDependency request, _ = _stored_primary_fixture() - source = replace(request.execution_plan, step_index=0, step_scope_id="source", write_backend=Backend.MEMORY.value) + source = replace( + request.execution_plan, + step_index=0, + step_scope_id="source", + write_backend=Backend.MEMORY.value, + ) consumer = replace( - source, step_index=1, step_scope_id="consumer", visualize=True, - main_input_dependency=StepInputDependency.step_output(source_step_index=0, source_step_scope_id="source"), + source, + step_index=1, + step_scope_id="consumer", + visualize=True, + main_input_dependency=StepInputDependency.step_output( + source_step_index=0, source_step_scope_id="source" + ), ) plans = {0: source, 1: consumer} assert consumer.requires_main_flow_checkpoint(plans) assert not source.requires_main_flow_checkpoint(plans) preserving, _ = _stored_primary_fixture(preserves_main_flow=True) - consumer.compiled_function_pattern = preserving.execution_plan.compiled_function_pattern + consumer.compiled_function_pattern = ( + preserving.execution_plan.compiled_function_pattern + ) assert source.requires_main_flow_checkpoint(plans) @@ -444,12 +652,21 @@ def test_checkpoint_demand_terminates_on_preserving_cycles_and_self_producers(): request, _ = _stored_primary_fixture(preserves_main_flow=True) first = replace( - request.execution_plan, step_index=1, step_scope_id="first", write_backend=Backend.MEMORY.value, - main_input_dependency=StepInputDependency.step_output(source_step_index=2, source_step_scope_id="second"), + request.execution_plan, + step_index=1, + step_scope_id="first", + write_backend=Backend.MEMORY.value, + main_input_dependency=StepInputDependency.step_output( + source_step_index=2, source_step_scope_id="second" + ), ) second = replace( - first, step_index=2, step_scope_id="second", - main_input_dependency=StepInputDependency.step_output(source_step_index=1, source_step_scope_id="first"), + first, + step_index=2, + step_scope_id="second", + main_input_dependency=StepInputDependency.step_output( + source_step_index=1, source_step_scope_id="first" + ), ) plans = {1: first, 2: second} assert not first.requires_main_flow_checkpoint(plans) @@ -457,11 +674,17 @@ def test_checkpoint_demand_terminates_on_preserving_cycles_and_self_producers(): second.streaming_configs = {"viewer": object()} assert first.requires_main_flow_checkpoint(plans) assert second.requires_main_flow_checkpoint(plans) - first.main_input_dependency = StepInputDependency.step_output(source_step_index=1, source_step_scope_id="first") + first.main_input_dependency = StepInputDependency.step_output( + source_step_index=1, source_step_scope_id="first" + ) assert not first.requires_main_flow_checkpoint({1: first}) self_producer = replace( - first, step_index=0, step_scope_id="self", - main_input_dependency=StepInputDependency.step_output(source_step_index=0, source_step_scope_id="self"), + first, + step_index=0, + step_scope_id="self", + main_input_dependency=StepInputDependency.step_output( + source_step_index=0, source_step_scope_id="self" + ), ) assert self_producer.requires_main_flow_checkpoint({0: self_producer}) @@ -474,12 +697,23 @@ def test_artifact_loaded_coordinates_keep_producer_authority_over_original_sourc (AllComponents.TIMEPOINT, "2"), ) request = replace(request, fixed_component_values=exact_coordinates) - assert image_payload_metadata(canonical.data).source_provenance.with_common_scalar_identity_from_planes().source_component_metadata["channel"] == "1" + assert ( + image_payload_metadata(canonical.data) + .source_provenance.with_common_scalar_identity_from_planes() + .source_component_metadata["channel"] + == "1" + ) loaded = PatternGroupData.from_loaded_group( - request, ["/memory/canonical"], canonical.data, + request, + ["/memory/canonical"], + canonical.data, ) assert loaded.fixed_component_values == exact_coordinates - canonical.data.metadata.source_provenance = canonical.data.metadata.source_provenance.with_source_component_metadata({"channel": "9"}) + canonical.data.metadata.source_provenance = ( + canonical.data.metadata.source_provenance.with_source_component_metadata( + {"channel": "9"} + ) + ) assert loaded.fixed_component_values == exact_coordinates @@ -487,22 +721,30 @@ def test_conversion_and_sequential_filter_use_the_same_transport_admission(): from pathlib import Path from openhcs.constants.constants import Backend, SequentialComponents from openhcs.core.compiled_step_plan import ( - InputConversionPlan, SequentialRuntimeFilter, SequentialRuntimeFilterPlan, + InputConversionPlan, + SequentialRuntimeFilter, + SequentialRuntimeFilterPlan, ) request, _ = _stored_primary_fixture() plan = request.execution_plan assert plan.stored_primary_input_edges_for_group(request.compiled_group, None) plan.input_conversion = InputConversionPlan( - output_dir=Path("/memory/input"), backend=Backend.MEMORY.value, - uses_virtual_workspace=True, original_subdir="images", + output_dir=Path("/memory/input"), + backend=Backend.MEMORY.value, + uses_virtual_workspace=True, + original_subdir="images", + ) + assert ( + plan.stored_primary_input_edges_for_group(request.compiled_group, None) is None ) - assert plan.stored_primary_input_edges_for_group(request.compiled_group, None) is None plan.input_conversion = None plan.sequential_filter_plan = SequentialRuntimeFilterPlan( filters=(SequentialRuntimeFilter(SequentialComponents.TIMEPOINT, "2"),), ) - assert plan.stored_primary_input_edges_for_group(request.compiled_group, None) is None + assert ( + plan.stored_primary_input_edges_for_group(request.compiled_group, None) is None + ) def test_same_step_primary_producer_is_not_queried_before_its_callable_runs(): @@ -511,11 +753,16 @@ def test_same_step_primary_producer_is_not_queried_before_its_callable_runs(): assert plan.stored_primary_input_edges_for_group(request.compiled_group, None) invocation = request.compiled_group.invocations[0] edge = invocation.artifact_input_edges[0] - later_edge = replace(edge, storage_plan=replace( - edge.storage_plan, source_step_id=plan.step_index, - source_step_scope_id=plan.step_scope_id, - )) - group = replace(request.compiled_group, invocations=( - invocation.with_artifact_input_edges((later_edge,)), - )) + later_edge = replace( + edge, + storage_plan=replace( + edge.storage_plan, + source_step_id=plan.step_index, + source_step_scope_id=plan.step_scope_id, + ), + ) + group = replace( + request.compiled_group, + invocations=(invocation.with_artifact_input_edges((later_edge,)),), + ) assert plan.stored_primary_input_edges_for_group(group, None) is None diff --git a/tests/unit/test_named_checkpoint_publication.py b/tests/unit/test_named_checkpoint_publication.py index 29d84378e2..8251ebbfb9 100644 --- a/tests/unit/test_named_checkpoint_publication.py +++ b/tests/unit/test_named_checkpoint_publication.py @@ -31,7 +31,7 @@ from openhcs.core.source_metadata import SourceVoxelSpacing from openhcs.core.source_projection import OpenHCSPlaneAddress, SourceArtifactProjection from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection -from openhcs.core.steps.function_outputs import OpenHCSMetadataWriter +from openhcs.core.steps.function_outputs import OpenHCSMetadataTarget from openhcs.core.steps.function_step import FunctionStep from openhcs.core.virtual_workspace_metadata import MetadataWriteError from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract @@ -95,7 +95,7 @@ def test_named_and_ordinary_checkpoint_inventory_owns_every_address(tmp_path, ma bundle = orchestrator.compile_pipelines([step]) for context in bundle.runtime_contexts.values(): step.process(context, 0) - OpenHCSMetadataWriter.finalize_completed_plate(bundle.runtime_contexts) + OpenHCSMetadataTarget.finalize_completed_plate(bundle.runtime_contexts) root = tmp_path / "source_out" metadata = json.loads((root / "openhcs_metadata.json").read_text()) reopened = VirtualWorkspaceSourceProjection.from_openhcs_metadata(root, metadata) @@ -147,4 +147,4 @@ def test_named_and_ordinary_checkpoint_inventory_owns_every_address(tmp_path, ma # error. This is not a missing-address permissive fallback. tifffile.imwrite(root / "checkpoints" / "unaddressed.tif", np.zeros((8, 8), dtype=np.uint16)) with pytest.raises(MetadataWriteError, match="Saved images lack typed produced addresses.*unaddressed"): - OpenHCSMetadataWriter.finalize_completed_plate(bundle.runtime_contexts) + OpenHCSMetadataTarget.finalize_completed_plate(bundle.runtime_contexts) diff --git a/tests/unit/test_opaque_main_flow_image_domain.py b/tests/unit/test_opaque_main_flow_image_domain.py index 7f02a14a48..6133360be1 100644 --- a/tests/unit/test_opaque_main_flow_image_domain.py +++ b/tests/unit/test_opaque_main_flow_image_domain.py @@ -19,7 +19,7 @@ from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.runtime_slice_projection import RuntimeSliceProjection from openhcs.core.source_spatial_domain import SourceSpatialDomain -from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest, PatternGroupRuntime +from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest from openhcs.core.aligned_image_payload import AlignedImageStack, ImageOutputBundle, AlignedImageSliceContext, ImagePayloadStackComposition from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.steps.function_output_manifest import step_output_manifest, StepOutputManifestStore @@ -35,8 +35,9 @@ def _identity(image): def _runtime(): pattern = compile_function_pattern(_identity, {}, {}) - runtime = object.__new__(PatternGroupRuntime) - runtime.request = SimpleNamespace( + runtime = PatternGroupExecutionRequest( + context=ProcessingContext(axis_id="A01"), + pattern_group_info="", component_index=0, component_count=1, compiled_group=pattern.default_group, execution_plan=CompiledStepPlan( step_index=0, @@ -50,7 +51,7 @@ def _runtime(): artifact_outputs={}, execution_group_scope=ComponentGroupScope.ungrouped(), ), - component_key=None, + component_value=None, ) return runtime @@ -132,8 +133,8 @@ def test_nominal_alignment_owner_preserves_single_output_topology(named, axis): @pytest.mark.parametrize("count", [1, 3]) def test_raw_array_fallback_keeps_explicit_runtime_unstack_contract(count): runtime = _runtime() - runtime.request.context = ProcessingContext(axis_id="A01") - runtime.request.context.microscope_handler = SimpleNamespace(parser=SourceSchemaFilenameParser()) + runtime = replace(runtime, context=ProcessingContext(axis_id="A01")) + runtime.context.microscope_handler = SimpleNamespace(parser=SourceSchemaFilenameParser()) pixels = np.arange(count * 4 * 5, dtype=np.float32).reshape(count, 4, 5) projected = runtime._project_output_slices(pixels, [f"source-{i}.tif" for i in range(count)]) payloads = tuple(payload for payload, _context in projected) @@ -190,13 +191,13 @@ def test_save_and_next_load_preserve_domain_and_independent_cache(tmp_path, monk mask = None producer = _runtime() pattern = compile_function_pattern(_identity, {}, {}) - plan = replace(producer.request.execution_plan, output_dir=tmp_path, step_scope_id="whole-producer", compiled_function_pattern=pattern) - producer.request.execution_plan = plan + plan = replace(producer.execution_plan, output_dir=tmp_path, step_scope_id="whole-producer", compiled_function_pattern=pattern) + producer = replace(producer, execution_plan=plan) files = _MemoryFiles() context = ProcessingContext(axis_id="A01", filemanager=files) context.microscope_handler = SimpleNamespace(parser=SourceSchemaFilenameParser()) - producer.request.context = context - producer.pattern_repr = "whole" + producer = replace(producer, context=context) + producer = replace(producer, pattern_group_info="whole") output = ( ImageOutputBundle((payload,), (AlignedImageSliceContext.main_flow("WholeImage"),)) if axis is not None or raw_named else payload @@ -213,13 +214,13 @@ def test_save_and_next_load_preserve_domain_and_independent_cache(tmp_path, monk plan, step_index=1, step_scope_id="whole-consumer", input_dir=tmp_path, main_input_dependency=StepInputDependency.step_output(source_step_index=0, source_step_scope_id=plan.step_scope_id), ) - consumer = PatternGroupRuntime(PatternGroupExecutionRequest( + consumer = PatternGroupExecutionRequest( context=context, execution_plan=consumer_plan, compiled_group=pattern.default_group, component_index=0, component_count=1, pattern_group_info="A01_s001_w1_z{iii}_t001.tif", - )) - monkeypatch.setattr(consumer, "source_workspace_projection_authority", lambda: SimpleNamespace(projection_if_available=lambda: None)) - loaded = consumer._load_input_stack()[1] + ) + monkeypatch.setattr(PatternGroupExecutionRequest, "source_workspace_projection_authority", lambda self: SimpleNamespace(projection_if_available=lambda: None)) + loaded = consumer.load_input_stack()[1] assert image_payload_data(loaded).shape == pixels.shape assert image_payload_metadata(loaded).plane_axis is axis np.testing.assert_array_equal(image_payload_data(loaded), pixels) @@ -257,7 +258,7 @@ def test_mixed_named_outputs_retain_each_original_axis_before_projection(runtime def test_passed_through_record_preserves_collapsed_and_filename_coordinates(tmp_path): from openhcs.core.steps.function_output_manifest import ProducedOutputSemantics from openhcs.core.steps.function_output_identity import FunctionOutputIdentity - plan = replace(_runtime().request.execution_plan, output_dir=tmp_path) + plan = replace(_runtime().execution_plan, output_dir=tmp_path) record = ProducedOutputSemantics.from_output( plan, tmp_path / "A01_s001_w1_z001_t001.tif", FunctionOutputIdentity(component_values={"well": "A01"}, filename_component_values={"well": "A01", "z_index": 1}, extension=".tif", source="test"), @@ -272,7 +273,7 @@ def test_passed_through_record_preserves_collapsed_and_filename_coordinates(tmp_ def test_duplicate_physical_path_rejects_contradictory_whole_axis(tmp_path): from openhcs.core.steps.function_output_manifest import ProducedOutputSemantics from openhcs.core.steps.function_output_identity import FunctionOutputIdentity - plan = replace(_runtime().request.execution_plan, output_dir=tmp_path) + plan = replace(_runtime().execution_plan, output_dir=tmp_path) opaque = ProducedOutputSemantics.from_output( plan, tmp_path / "A01_s001_w1_z001_t001.tif", FunctionOutputIdentity(component_values={"well": "A01"}, extension=".tif", source="test"), @@ -294,7 +295,7 @@ def test_record_axis_survives_replace_and_pickle(tmp_path): import pickle from openhcs.core.steps.function_output_manifest import ProducedOutputSemantics from openhcs.core.steps.function_output_identity import FunctionOutputIdentity - plan = replace(_runtime().request.execution_plan, output_dir=tmp_path) + plan = replace(_runtime().execution_plan, output_dir=tmp_path) for axis in (None, RuntimePlaneAxis.RUNTIME_SLICE, RuntimePlaneAxis.SOURCE_BINDING): record = ProducedOutputSemantics.from_output( plan, tmp_path / "A01_s001_w1_z001_t001.tif", @@ -342,13 +343,13 @@ def test_saved_mixed_named_cohort_rejects_joint_load_and_preserves_selected_doma opaque = scalar_metadata.payload_with(opaque_pixels) producer = _runtime() pattern = compile_function_pattern(_identity, {}, {}) - plan = replace(producer.request.execution_plan, output_dir=tmp_path, step_scope_id="mixed-producer", compiled_function_pattern=pattern) - producer.request.execution_plan = plan + plan = replace(producer.execution_plan, output_dir=tmp_path, step_scope_id="mixed-producer", compiled_function_pattern=pattern) + producer = replace(producer, execution_plan=plan) files = _MemoryFiles() context = ProcessingContext(axis_id="A01", filemanager=files) context.microscope_handler = SimpleNamespace(parser=SourceSchemaFilenameParser()) - producer.request.context = context - producer.pattern_repr = "mixed" + producer = replace(producer, context=context) + producer = replace(producer, pattern_group_info="mixed") # A prior homogeneous producer caches the same physical paths. Mixed replacement # must invalidate that cache rather than leave a false joint runtime domain. @@ -367,17 +368,21 @@ def consumer_for(compiled): consumer_plan = replace(plan, step_index=1, step_scope_id="mixed-consumer", input_dir=tmp_path, compiled_function_pattern=compiled, main_input_dependency=StepInputDependency.step_output(source_step_index=0, source_step_scope_id=plan.step_scope_id)) - consumer = PatternGroupRuntime(SimpleNamespace(context=context, execution_plan=consumer_plan, - compiled_group=compiled.default_group, source_binding_plan=CompiledSourceBindingPlan.empty(), - component_key=None, pattern_group_info="A01_s001_w1_z{iii}_t001.tif")) - monkeypatch.setattr(consumer, "source_workspace_projection_authority", lambda: SimpleNamespace(projection_if_available=lambda: None)) + consumer = PatternGroupExecutionRequest(context=context, + execution_plan=consumer_plan, + compiled_group=compiled.default_group, + component_value=None, + pattern_group_info="A01_s001_w1_z{iii}_t001.tif", + component_index=0, + component_count=1) + monkeypatch.setattr(PatternGroupExecutionRequest, "source_workspace_projection_authority", lambda self: SimpleNamespace(projection_if_available=lambda: None)) return consumer with pytest.raises(ValueError, match="different declared image axes"): - consumer_for(pattern)._load_input_stack() + consumer_for(pattern).load_input_stack() for name, expected, axis in (("Planes", image_payload_data(planes), RuntimePlaneAxis.RUNTIME_SLICE), ("Volume", opaque_pixels, None)): selected = consumer_for(_selected_pattern(name)) - actual = selected._load_input_stack()[1] + actual = selected.load_input_stack()[1] np.testing.assert_array_equal(image_payload_data(actual), expected) assert image_payload_metadata(actual).plane_axis is axis if not cache_hit: @@ -385,7 +390,7 @@ def consumer_for(compiled): else: selected_path = next(r.output_path for r in records if r.producer_identity.output_key == name) context.runtime_image_stack_cache.store((selected_path,), memory_type=MEMORY_TYPE_NUMPY, stack=actual) - repeated = selected._load_input_stack()[1] + repeated = selected.load_input_stack()[1] np.testing.assert_array_equal(image_payload_data(repeated), expected) assert image_payload_metadata(repeated).plane_axis is axis @@ -419,7 +424,7 @@ def test_opaque_named_bundle_uses_existing_same_slice_mask_composition(): def test_input_bundle_composition_retains_lazy_plan_device_resolution(tmp_path, monkeypatch): from openhcs.core.steps.function_output_manifest import ProducedOutputSemantics from openhcs.core.steps.function_output_identity import FunctionOutputIdentity - plan = replace(_runtime().request.execution_plan, output_dir=tmp_path) + plan = replace(_runtime().execution_plan, output_dir=tmp_path) records = tuple(ProducedOutputSemantics.from_output( plan, tmp_path / f"A01_s001_w1_z001_t001_{name}.tif", FunctionOutputIdentity(component_values={"well": "A01"}, extension=".tif", source="test"), diff --git a/tests/unit/test_orchestrator_lane_planning.py b/tests/unit/test_orchestrator_lane_planning.py index dc05afe6fe..85fc4a8cd9 100644 --- a/tests/unit/test_orchestrator_lane_planning.py +++ b/tests/unit/test_orchestrator_lane_planning.py @@ -1133,7 +1133,7 @@ def test_compiled_execution_returns_settled_nonpersistent_viewer_state_before_cl ): events = [] monkeypatch.setattr( - compiled_plate_execution_module.OpenHCSMetadataWriter, + compiled_plate_execution_module.OpenHCSMetadataTarget, "finalize_completed_plate", lambda _contexts: events.append("metadata"), ) diff --git a/tests/unit/test_output_publication_ownership.py b/tests/unit/test_output_publication_ownership.py index a8984c7f24..e2bcac6c7f 100644 --- a/tests/unit/test_output_publication_ownership.py +++ b/tests/unit/test_output_publication_ownership.py @@ -20,7 +20,7 @@ from openhcs.core.function_patterns import compile_function_pattern from openhcs.core.runtime_image_values import ImagePayloadMetadata, image_payload_data from openhcs.core.steps.function_output_manifest import step_output_manifest -from openhcs.core.steps.function_runtime import PatternGroupRuntime +from openhcs.core.steps.function_runtime import PatternGroupExecutionRequest from openhcs.microscopes.source_schema import SourceSchemaFilenameParser @@ -49,13 +49,13 @@ def _runtime(tmp_path): artifact_outputs={}, execution_group_scope=ComponentGroupScope.ungrouped(), ) - runtime = PatternGroupRuntime(SimpleNamespace( - context=context, - execution_plan=plan, - compiled_group=compile_function_pattern(_identity, {}, {}).default_group, - component_key=None, - pattern_group_info="A01_s001_w1_z001_t001.tif", - )) + runtime = PatternGroupExecutionRequest(context=context, + execution_plan=plan, + compiled_group=compile_function_pattern(_identity, {}, {}).default_group, + component_value=None, + pattern_group_info="A01_s001_w1_z001_t001.tif", + component_index=0, + component_count=1) payload = ImagePayloadMetadata( source_path=SOURCE, source_component_metadata={ @@ -67,7 +67,7 @@ def _runtime(tmp_path): def test_buffer_preparation_failure_precedes_any_vfs_publication(tmp_path, monkeypatch): runtime, payload = _runtime(tmp_path) - files = runtime.request.context.filemanager + files = runtime.context.filemanager events = [] def fail_copy(*args, **kwargs): @@ -82,12 +82,12 @@ def unexpected_exists(*args, **kwargs): with pytest.raises(ValueError, match="buffer allocation failed"): runtime._save_outputs(payload, [SOURCE]) assert events == ["copy"] - assert runtime.request.context.runtime_image_stack_cache.stacks == {} + assert runtime.context.runtime_image_stack_cache.stacks == {} def test_saved_metadata_failure_keeps_actual_commit_but_no_cache_or_manifest(tmp_path, monkeypatch): runtime, payload = _runtime(tmp_path) - files = runtime.request.context.filemanager + files = runtime.context.filemanager path = str(tmp_path / "A01_s001_w1_z001_t001.tif") def fail_attachment(*args, **kwargs): @@ -99,13 +99,13 @@ def fail_attachment(*args, **kwargs): with pytest.raises(ValueError, match="saved context failed"): runtime._save_outputs(payload, [SOURCE]) assert np.shares_memory(image_payload_data(files.load(path, "memory")), payload.data) - assert runtime.request.context.runtime_image_stack_cache.stacks == {} - assert step_output_manifest(runtime.request.context).produced_records_for(runtime.request.execution_plan) == () + assert runtime.context.runtime_image_stack_cache.stacks == {} + assert step_output_manifest(runtime.context).produced_records_for(runtime.execution_plan) == () def test_duplicate_output_paths_leave_existing_memory_value_and_cache_intact(tmp_path): runtime, payload = _runtime(tmp_path) - context = runtime.request.context + context = runtime.context path = str(tmp_path / "A01_s001_w1_z001_t001.tif") previous = np.full((4, 5), 9, dtype=np.float32) context.filemanager.ensure_directory(str(tmp_path), "memory") @@ -120,7 +120,7 @@ def test_duplicate_output_paths_leave_existing_memory_value_and_cache_intact(tmp def test_original_named_owner_is_consulted_at_saved_metadata_epoch(tmp_path): runtime, payload = _runtime(tmp_path) - files = runtime.request.context.filemanager + files = runtime.context.filemanager path = str(tmp_path / "A01_s001_w1_z001_t001_Named.tif") calls = [] @@ -136,7 +136,7 @@ def plane_axis_for_output_context(self, context): runtime._save_outputs(output, [SOURCE]) assert calls == [False, True] np.testing.assert_array_equal(image_payload_data(files.load(path, "memory")), payload.data) - assert runtime.request.context.runtime_image_stack_cache.stacks == {} + assert runtime.context.runtime_image_stack_cache.stacks == {} def test_anonymous_context_is_shared_by_record_and_post_save_axis_hooks(tmp_path): diff --git a/tests/unit/test_path_planner_materialization.py b/tests/unit/test_path_planner_materialization.py index 8eafe005d9..b90b9cc35c 100644 --- a/tests/unit/test_path_planner_materialization.py +++ b/tests/unit/test_path_planner_materialization.py @@ -33,7 +33,10 @@ ) from openhcs.core.callable_contract import CallableContract, FunctionStepExecutionScope from openhcs.core.component_set import ComponentSet -from openhcs.core.component_group_scope import ComponentGroupScope, RuntimeExecutionAxisScope +from openhcs.core.component_group_scope import ( + ComponentGroupScope, + RuntimeExecutionAxisScope, +) from openhcs.constants.constants import MEMORY_TYPE_NUMPY from openhcs.core.memory import numpy from openhcs.core.runtime_image_values import ImagePayloadMetadata, image_payload_data @@ -109,7 +112,7 @@ from openhcs.core.steps.abstract import AbstractStep from openhcs.core.steps.function_step import FunctionStep from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, + PatternGroupExecutionScope, FunctionCoreExecutor, PatternGroupData, ) @@ -140,9 +143,12 @@ def _execute_compiled_metadata_pattern(compiled, input_plans=None, stored_output for producer, value in stored_outputs: context.runtime_value_store.record( RuntimeValue.from_output_plan( - producer, value, execution_scope=RuntimeExecutionAxisScope(axis_id="A01") + producer, + value, + execution_scope=RuntimeExecutionAxisScope(axis_id="A01"), ), - path=producer.path, backend="memory", + path=producer.path, + backend="memory", ) scope = PatternGroupData( matching_files=["input.tif"], @@ -151,22 +157,21 @@ def _execute_compiled_metadata_pattern(compiled, input_plans=None, stored_output execution_plan=plan, compiled_group=compiled.default_group, component_value=None, - artifacts=ComponentArtifactPlans.from_step_component(plan, None), + artifact_inputs=dict(plan.artifact_inputs), + artifact_outputs=PatternGroupExecutionScope._select_output_plans_for_component( + plan.artifact_outputs, plan.execution_group_scope, None + ), runtime_plane_index=0, runtime_plane_count=1, ) (invocation,) = compiled.default_group.invocations source = np.arange(6, dtype=np.uint16).reshape(1, 2, 3) - result = FunctionCoreExecutor( + result = FunctionCoreExecutor.from_group_invocation( + scope, + invocation, main_data_arg=ImagePayloadMetadata().payload_with(source), source_memory_type=MEMORY_TYPE_NUMPY, - group_data=scope, - invocation=invocation, - artifacts=scope.artifacts.select_for_invocation( - invocation, execution_scope=plan.execution_group_scope, component_key=None - ), - group_key=None, - plane_projection=RuntimePlaneProjection.stack(), + declared_source_bindings=scope.execution_plan.source_binding_plan, ).execute() np.testing.assert_array_equal(image_payload_data(result), source) return result @@ -5423,31 +5428,22 @@ def apply_second(image): execution_group_scope=execution_scope, compiled_function_pattern=compiled, ) - component_plans = ComponentArtifactPlans.from_step_component(execution_plan, "1") invocations = tuple(compiled.iter_invocations()) - first_plans = component_plans.select_for_invocation( - invocations[0], - execution_scope=execution_scope, - component_key="1", - ) - second_plans = component_plans.select_for_invocation( - invocations[1], - execution_scope=execution_scope, - component_key="1", - ) + first_plans = invocations[0].select_inputs(storage) + second_plans = invocations[1].select_inputs(storage) assert tuple( edge.storage_plan.name - for edge in first_plans.inputs.values() + for edge in first_plans.values() if edge.storage_plan is not None ) == (first.name,) assert tuple( edge.storage_plan.name - for edge in second_plans.inputs.values() + for edge in second_plans.values() if edge.storage_plan is not None ) == (second.name,) - first_edge = next(iter(first_plans.inputs.values())) - second_edge = next(iter(second_plans.inputs.values())) + first_edge = next(iter(first_plans.values())) + second_edge = next(iter(second_plans.values())) assert first_edge.projection is not None assert second_edge.projection is not None assert first_edge.projection.invocation_scope == ( diff --git a/tests/unit/test_persisted_roi_only_publication.py b/tests/unit/test_persisted_roi_only_publication.py index 4ec049524a..caf1b6c937 100644 --- a/tests/unit/test_persisted_roi_only_publication.py +++ b/tests/unit/test_persisted_roi_only_publication.py @@ -31,7 +31,7 @@ RuntimeArtifactMaterialization, ) from openhcs.core.steps.function_outputs import ( - OpenHCSMetadataWriter, + OpenHCSMetadataTarget, ProducedImageMetadataCapability, RuntimeArtifactMetadataTarget, ) @@ -197,13 +197,13 @@ def test_saved_roi_only_batch_publishes_and_reconciles_without_rendering( publication_context, plate, destination, monkeypatch ) plan = plan_for(plate) - targets = OpenHCSMetadataWriter.OutputTarget.for_execution( + targets = OpenHCSMetadataTarget.for_execution( publication_context, plan, artifact_materializations=(outcome,), ) assert tuple(target.output_dir for target in targets) == (plate / destination,) - OpenHCSMetadataWriter.write( + OpenHCSMetadataTarget.write_for_step( publication_context, plan, artifact_materializations=(outcome,) ) assert result_paths(plate, publication_context) == (output.path,) @@ -219,7 +219,7 @@ def test_saved_roi_only_batch_publishes_and_reconciles_without_rendering( for target in owner.reconciliation_targets(publication_context) ) assert plate / destination in reconciled - OpenHCSMetadataWriter.finalize_completed_plate({"A01": publication_context}) + OpenHCSMetadataTarget.finalize_completed_plate({"A01": publication_context}) assert result_paths(plate, publication_context) == (output.path,) @@ -333,7 +333,7 @@ def test_new_result_declaration_composes_cooperative_hooks_without_consumer_edit outcome, output = save_archive_outcome( publication_context, plate, destination, monkeypatch ) - registry = OpenHCSMetadataWriter.OutputTarget.__registry__ + registry = OpenHCSMetadataTarget.__registry__ original_declarations = dict(registry) try: @@ -358,7 +358,7 @@ def from_plan(cls, plan): plan_for(plate), runtime_artifact_materialization=RuntimeArtifactMaterializationPlan(), ) - (target,) = OpenHCSMetadataWriter.OutputTarget.for_execution( + (target,) = OpenHCSMetadataTarget.for_execution( publication_context, plan, artifact_materializations=(outcome,), @@ -383,7 +383,7 @@ def test_files_without_successful_batch_outcomes_do_not_create_step_targets( directory.mkdir(parents=True) (directory / "not_a_saved_outcome.roi.zip").write_bytes(b"synthetic admission only") assert ( - OpenHCSMetadataWriter.OutputTarget.for_execution( + OpenHCSMetadataTarget.for_execution( publication_context, plan_for(plate), artifact_materializations=(), diff --git a/tests/unit/test_runtime_context_declaration.py b/tests/unit/test_runtime_context_declaration.py index 2ac6962887..0803058fd8 100644 --- a/tests/unit/test_runtime_context_declaration.py +++ b/tests/unit/test_runtime_context_declaration.py @@ -24,7 +24,6 @@ from openhcs.core.runtime_image_values import ImagePayloadMetadata from openhcs.core.runtime_plane_projection import RuntimePlaneProjection from openhcs.core.steps.function_runtime import ( - ComponentArtifactPlans, FunctionCoreExecutor, PatternGroupData, ) @@ -121,13 +120,16 @@ def process(image, *, context=None): @pytest.mark.parametrize( ("func", "parameter"), - [(_inferred_context, "context"), (_without_context, None), - (_named_context, "execution_context")], + [ + (_inferred_context, "context"), + (_without_context, None), + (_named_context, "execution_context"), + ], ) def test_runtime_binding_consumes_captured_selection(func, parameter): pattern = compile_function_pattern(func, {}, {}) context = ProcessingContext(axis_id="A01") - artifacts = ComponentArtifactPlans(inputs={}, outputs={}) + artifacts = ({}, {}) scope = PatternGroupData( matching_files=["input.tif"], main_data_stack=np.zeros((1, 3, 4), dtype=np.uint16), @@ -136,14 +138,16 @@ def test_runtime_binding_consumes_captured_selection(func, parameter): step_index=0, step_name="Context", step_type="FunctionStep", axis_id="A01" ), compiled_group=pattern.default_group, - artifacts=artifacts, + artifact_inputs=artifacts[0], + artifact_outputs=artifacts[1], runtime_plane_index=0, runtime_plane_count=1, ) executor = FunctionCoreExecutor( group_data=scope, invocation=next(pattern.iter_invocations()), - artifacts=artifacts, + artifact_inputs=artifacts[0], + artifact_outputs=artifacts[1], group_key=None, plane_projection=RuntimePlaneProjection(), main_data_arg=np.zeros((2, 3)), diff --git a/tests/unit/test_selected_plane_stream_materialization.py b/tests/unit/test_selected_plane_stream_materialization.py index 77afa3fe8e..e65fa6d838 100644 --- a/tests/unit/test_selected_plane_stream_materialization.py +++ b/tests/unit/test_selected_plane_stream_materialization.py @@ -44,7 +44,6 @@ from openhcs.core.steps.function_artifact_materialization import ( PersistentArtifactMaterializationTargetPlan, - materialize_artifact_outputs, runtime_artifact_materializations, ) from openhcs.processing.backends.analysis.neurite_outgrowth import ( @@ -336,12 +335,7 @@ def capture_stream(data_list, paths, backend, **kwargs): monkeypatch.setattr(filemanager, "save_batch", capture_stream) try: - materialize_artifact_outputs( - filemanager, - plan, - PersistentArtifactMaterializationTargetPlan("disk"), - context, - ) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, plan, context) materializations = runtime_artifact_materializations(plan, context) assert {item.output_plan.name for item in materializations} == set( specs.names()