From 4a01f486970afa81a5fe193e993e675727ef2189 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:01:15 +0000 Subject: [PATCH 01/27] Point benchmark imports at the modules that declare them Module moves left benchmark/ importing names from their old homes: measurement markers and the row-identity contract now live in measurement_declarations; ComponentGroupScope, AliasProperty and PartitionFilterProcessor moved out of axis_declarations/pipeline_config. The smoke job's test_agent_observation_export_zmq died importing benchmark.adapters.cellprofiler on this chain. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- benchmark/adapters/cellprofiler.py | 2 +- benchmark/annotated_validation.py | 4 +++- benchmark/equivalence/exported_relationships.py | 4 +++- benchmark/equivalence/measurement_requirements.py | 8 +++++--- benchmark/equivalence/measurement_rows.py | 8 +++++--- benchmark/equivalence/object_label_measurements.py | 4 +++- benchmark/equivalence/outputs.py | 4 +++- benchmark/equivalence/row_identity.py | 2 +- benchmark/equivalence/runtime.py | 14 +++++++++----- benchmark/equivalence/table_snapshots.py | 4 +++- benchmark/metrics/memory.py | 2 +- 11 files changed, 37 insertions(+), 19 deletions(-) diff --git a/benchmark/adapters/cellprofiler.py b/benchmark/adapters/cellprofiler.py index 6dba052c4..0141209de 100644 --- a/benchmark/adapters/cellprofiler.py +++ b/benchmark/adapters/cellprofiler.py @@ -48,7 +48,7 @@ materialize_source_binding_workspace, ) from openhcs.core.source.source_bindings import ImportedMetadataTable -from openhcs.core.config.pipeline_config.partition_filter import PartitionFilterProcessor +from openhcs.core.config.partition_filter import PartitionFilterProcessor from benchmark.equivalence.runtime import RuntimeOutputSnapshot from openhcs.interop.cellprofiler.parser import CPPipeParser from openhcs.interop.cellprofiler.pipeline_import import ( diff --git a/benchmark/annotated_validation.py b/benchmark/annotated_validation.py index 2ea70e160..440f0bcf4 100644 --- a/benchmark/annotated_validation.py +++ b/benchmark/annotated_validation.py @@ -21,7 +21,9 @@ from collections.abc import Iterator from metaclass_registry import AutoRegisterMeta from python_introspect import to_jsonable -from openhcs.core.measurements.runtime_measurements import MeasurementRowAxisField +from openhcs.core.measurements.runtime_measurements import ( + MeasurementRowAxisField, +) from openhcs.processing.backends.cellprofiler.intensity_family.intensity import ( MeasureObjectIntensityModule, ) diff --git a/benchmark/equivalence/exported_relationships.py b/benchmark/equivalence/exported_relationships.py index 528a0c48f..90879c00c 100644 --- a/benchmark/equivalence/exported_relationships.py +++ b/benchmark/equivalence/exported_relationships.py @@ -58,7 +58,9 @@ RelationshipAggregateFeatureContext, RelationshipAggregateFeatureSemantics, ) -from openhcs.core.measurements.runtime_measurements import RuntimeScopedMeasurementTable +from openhcs.core.measurements.runtime_measurements import ( + RuntimeScopedMeasurementTable, +) from openhcs.core.measurements.measurement_row_materialization import ( columnar_row_values, iter_measurement_rows, diff --git a/benchmark/equivalence/measurement_requirements.py b/benchmark/equivalence/measurement_requirements.py index e47132b63..7c46ecacb 100644 --- a/benchmark/equivalence/measurement_requirements.py +++ b/benchmark/equivalence/measurement_requirements.py @@ -17,13 +17,15 @@ object_measurement_feature_matches_marker, ) from openhcs.core.equivalence.policy import RuntimeEquivalencePolicy -from openhcs.core.measurements.runtime_measurements import ( +from openhcs.core.measurements.measurement_declarations import ( MeasurementScope, - MeasurementStatistic, - ObjectCoreMeasurementFeature, ObjectIdentifierFeatureMarker, ObjectLocationFeatureMarker, ) +from openhcs.core.measurements.runtime_measurements import ( + MeasurementStatistic, + ObjectCoreMeasurementFeature, +) @dataclass(frozen=True, slots=True) diff --git a/benchmark/equivalence/measurement_rows.py b/benchmark/equivalence/measurement_rows.py index fb1daf7dc..779e550cc 100644 --- a/benchmark/equivalence/measurement_rows.py +++ b/benchmark/equivalence/measurement_rows.py @@ -57,13 +57,15 @@ MeasurementRowSourceImageName, measurement_row_has_long_form_measurement_fields, ) +from openhcs.core.measurements.measurement_declarations import ( + MeasuredObjectAnchorFeatureMarker, + RuntimeMeasurementRowIdentityContract, +) from openhcs.core.measurements.runtime_measurements import ( - MeasurementRowValueField, MeasurementRowAxisField, + MeasurementRowValueField, MeasurementScope, - MeasuredObjectAnchorFeatureMarker, RuntimeMeasurementFeatureOwner, - RuntimeMeasurementRowIdentityContract, ) from openhcs.core.payload.runtime_tabular_values import ( MeasurementObjectRowIdentity, diff --git a/benchmark/equivalence/object_label_measurements.py b/benchmark/equivalence/object_label_measurements.py index 424812b4f..6a2ed0642 100644 --- a/benchmark/equivalence/object_label_measurements.py +++ b/benchmark/equivalence/object_label_measurements.py @@ -58,10 +58,12 @@ RuntimeObjectMeasurementRowIdentity, ) from openhcs.core.payload.runtime_identifier import normalize_runtime_identifier -from openhcs.core.measurements.runtime_measurements import ( +from openhcs.core.measurements.measurement_declarations import ( ObjectCountFeatureMarker, ObjectIdentifierFeatureMarker, ObjectLocationFeatureMarker, +) +from openhcs.core.measurements.runtime_measurements import ( RuntimeMeasurementFeatureSemanticMarker, ) from openhcs.core.artifact_store.runtime_stores import StoredRuntimeValue diff --git a/benchmark/equivalence/outputs.py b/benchmark/equivalence/outputs.py index 36462046a..d40645e53 100644 --- a/benchmark/equivalence/outputs.py +++ b/benchmark/equivalence/outputs.py @@ -1,7 +1,9 @@ """Runtime output snapshot construction for equivalence checks.""" from __future__ import annotations -from openhcs.core.measurements.runtime_measurements import MeasurementRowAxisField +from openhcs.core.measurements.runtime_measurements import ( + MeasurementRowAxisField, +) from abc import ABC, abstractmethod from dataclasses import dataclass, replace diff --git a/benchmark/equivalence/row_identity.py b/benchmark/equivalence/row_identity.py index a49b53a25..6900a528f 100644 --- a/benchmark/equivalence/row_identity.py +++ b/benchmark/equivalence/row_identity.py @@ -8,7 +8,7 @@ from dataclasses import dataclass -from openhcs.core.axes.axis_declarations.component_group_scope import ComponentGroupScope +from openhcs.core.axes.component_group_scope import ComponentGroupScope from openhcs.core.equivalence.cells import ( RuntimeCellSignature, RuntimeMeasurementCellSignatureProjection, diff --git a/benchmark/equivalence/runtime.py b/benchmark/equivalence/runtime.py index 98b08141b..58bb0114c 100644 --- a/benchmark/equivalence/runtime.py +++ b/benchmark/equivalence/runtime.py @@ -45,7 +45,7 @@ MeasurementBearingArtifactType, RelationshipsArtifactType, ) -from openhcs.core.axes.axis_declarations.component_group_scope import ComponentGroupScope +from openhcs.core.axes.component_group_scope import ComponentGroupScope from openhcs.core.measurements.measurement_row_materialization import ( iter_measurement_rows, measurement_row_source_image_name, @@ -54,13 +54,15 @@ RuntimeArtifactExecutionObservation, ) from openhcs.core.source.source_matching import SourceImageSetIdentityPolicy +from openhcs.core.measurements.measurement_declarations import ( + ObjectGroupInvariantFeatureMarker, + ObjectIdentifierFeatureMarker, + ObjectLocationFeatureMarker, +) from openhcs.core.measurements.runtime_measurements import ( MeasurementScope, MeasurementStatistic, ObjectCoreMeasurementFeature, - ObjectGroupInvariantFeatureMarker, - ObjectIdentifierFeatureMarker, - ObjectLocationFeatureMarker, ) from openhcs.core.payload.runtime_tabular_values import measurement_row_mapping from openhcs.core.artifact_store.runtime_stores import StoredRuntimeValue @@ -152,7 +154,9 @@ from openhcs.core.equivalence.relationships import ( RelationshipAggregateFeatureSemantics, ) -from openhcs.core.measurements.runtime_measurements import RuntimeScopedMeasurementTable +from openhcs.core.measurements.runtime_measurements import ( + RuntimeScopedMeasurementTable, +) from benchmark.equivalence.exported_relationships import ( RelationshipMeasurementSemantics, ) diff --git a/benchmark/equivalence/table_snapshots.py b/benchmark/equivalence/table_snapshots.py index 072ad1900..6bddaa7d7 100644 --- a/benchmark/equivalence/table_snapshots.py +++ b/benchmark/equivalence/table_snapshots.py @@ -24,13 +24,15 @@ MEASUREMENT_SPARSE_CELL, MeasurementSparseColumnarRows, ) +from openhcs.core.measurements.measurement_declarations import ( + RuntimeMeasurementRowIdentityContract, +) from openhcs.core.measurements.runtime_measurements import ( MeasurementRowAxisField, MeasurementScalarLiteral, MeasurementScope, MeasurementSubject, MeasurementTable, - RuntimeMeasurementRowIdentityContract, ) from openhcs.core.payload.runtime_tabular_values import ( FieldSpec, diff --git a/benchmark/metrics/memory.py b/benchmark/metrics/memory.py index 5e12b9845..87e4e6f79 100644 --- a/benchmark/metrics/memory.py +++ b/benchmark/metrics/memory.py @@ -12,7 +12,7 @@ import time from typing import ClassVar -from openhcs.core.axes.axis_declarations.alias_property import AliasProperty +from openhcs.core.axes.alias_property import AliasProperty import psutil from zmqruntime.messages import ProcessIdentity From 5be330da9bb33c0d95c03db3f723ad8ee8466eb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:08:21 +0000 Subject: [PATCH 02/27] Restore AbstractStep's Lazy config defaults; import them 7a012ae4a called the eight Lazy* step configs phantom and replaced their defaults with None. They are real: pipeline_config generates them at runtime, so grep finds no class line. The None default for source_bindings then failed AbstractStep's own isinstance check, so every FunctionStep built without explicit bindings raised TypeError. That broke all 7 smoke tests. The original NameError came from the missing import, not from missing classes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/steps/abstract.py | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/openhcs/core/steps/abstract.py b/openhcs/core/steps/abstract.py index 541d4cea5..c7b0407e5 100644 --- a/openhcs/core/steps/abstract.py +++ b/openhcs/core/steps/abstract.py @@ -19,8 +19,17 @@ from objectstate import get_base_type_for_lazy, semantic_values_equal -# Import LazyStepMaterializationConfig for type hints -from openhcs.core.config.pipeline_config import StepSourceBindingsConfig +from openhcs.core.config.pipeline_config import ( + LazyDtypeConfig, + LazyFijiStreamingConfig, + LazyNapariStreamingConfig, + LazyProcessingConfig, + LazyStepMaterializationConfig, + LazyStepPartitionFilterConfig, + LazyStepSourceBindingsConfig, + LazyStreamingDefaults, + StepSourceBindingsConfig, +) # def get_step_id(step: 'AbstractStep') -> str: @@ -151,14 +160,14 @@ def __init__( description: str = None, enabled: bool = True, debug_pause: bool = False, - dtype_config: object = None, - processing_config: object = None, - source_bindings: object = None, - step_partition_filter_config: object = None, - step_materialization_config: object = None, - streaming_defaults: object = None, - napari_streaming_config: object = None, - fiji_streaming_config: object = None, + dtype_config: LazyDtypeConfig = LazyDtypeConfig(), + processing_config: LazyProcessingConfig = LazyProcessingConfig(), + source_bindings: LazyStepSourceBindingsConfig = LazyStepSourceBindingsConfig(), + step_partition_filter_config: LazyStepPartitionFilterConfig = LazyStepPartitionFilterConfig(), + step_materialization_config: LazyStepMaterializationConfig = LazyStepMaterializationConfig(), + streaming_defaults: LazyStreamingDefaults = LazyStreamingDefaults(), + napari_streaming_config: LazyNapariStreamingConfig = LazyNapariStreamingConfig(), + fiji_streaming_config: LazyFijiStreamingConfig = LazyFijiStreamingConfig(), ) -> None: """ Initialize a step. These attributes are primarily used during the From b31e5515a00d48befeb06f3850b37d361d87cf27 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:14:10 +0000 Subject: [PATCH 03/27] Freeze the cell-count field base; call operations directly bc15c96ba pulled CellCountMeasurementFields out as a plain @dataclass shared by mutable CellCountResult and frozen CellCountMeasurementRow. Python rejects a frozen dataclass inheriting a non-frozen one, so cell_counting_cpu failed to import and took function registry preparation down with it, which is why every set_dataset_pipeline in smoke was rejected. Nothing assigns to these fields after construction, so the base and CellCountResult are now frozen too. 29c3d7a34 deleted the Session.invoke forwarder; the benchmark session runner still called it. It now calls operation.invoke(session, request). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- benchmark/session_measured_run.py | 4 ++-- openhcs/processing/backends/analysis/cell_counting_common.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/benchmark/session_measured_run.py b/benchmark/session_measured_run.py index fd44e217d..78612c99a 100644 --- a/benchmark/session_measured_run.py +++ b/benchmark/session_measured_run.py @@ -117,7 +117,7 @@ def stop(self) -> DatasetRowState: for force in (False, True): if not self.session.execution_state.busy: break - self.session.invoke(StopExecution, StopExecutionRequest(force=force)) + StopExecution.invoke(self.session, StopExecutionRequest(force=force)) deadline = time.monotonic() + STOP_GRACE_SECONDS while self.session.execution_state.busy and time.monotonic() < deadline: self.session.events_after( @@ -149,7 +149,7 @@ def _scope_id(self) -> str: def _require(self, operation, request) -> SessionOperationResult: self._sequence = self.session.event_log.last_sequence - result = self.session.invoke(operation, request) + result = operation.invoke(self.session, request) if not result.accepted: raise RuntimeError( f"{operation.operation_id} was rejected: " diff --git a/openhcs/processing/backends/analysis/cell_counting_common.py b/openhcs/processing/backends/analysis/cell_counting_common.py index 07b7604a6..95eae9b4b 100644 --- a/openhcs/processing/backends/analysis/cell_counting_common.py +++ b/openhcs/processing/backends/analysis/cell_counting_common.py @@ -113,7 +113,7 @@ class ThresholdMethod(Enum): MANUAL = "manual" -@dataclass +@dataclass(frozen=True) class CellCountMeasurementFields: """Shared measurement fields for cell counting results and serializable rows.""" @@ -127,7 +127,7 @@ class CellCountMeasurementFields: parameters_used: dict[str, Any] -@dataclass +@dataclass(frozen=True) class CellCountResult(CellCountMeasurementFields): """Results for single-channel cell counting.""" From ad22f413a53f3c76fda80a0d9216ac26b9f2fe56 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:27:28 +0000 Subject: [PATCH 04/27] Re-slot the concrete ImagePayload members; drop Session.view caller e009fc263 removed slots=True from 91 dataclasses on the claim that slots calls get_type_hints() and raises NameError on forward refs. dataclass(slots=True) does not call get_type_hints(). What slots did do was make the field `data` a slot descriptor that overrides the inherited abstract `data` property. Without it the annotation alone leaves the abstract property in place, so PlainImagePayload, ImageMetadataPayload and MaskedImagePayload became abstract. Every ImagePayload.of() raised, and function-registry preparation failed with it. A scan of all 91 finds exactly these three; they get slots=True back and import cleanly. 29c3d7a34 also deleted the Session.view forwarder; the benchmark runner now calls DatasetListView.state_of(session). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- benchmark/session_measured_run.py | 2 +- openhcs/core/payload/runtime_image_values.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/benchmark/session_measured_run.py b/benchmark/session_measured_run.py index 78612c99a..93e74a015 100644 --- a/benchmark/session_measured_run.py +++ b/benchmark/session_measured_run.py @@ -129,7 +129,7 @@ def stop(self) -> DatasetRowState: def row(self) -> DatasetRowState: (row,) = ( row - for row in self.session.view(DatasetListView).rows + for row in DatasetListView.state_of(self.session).rows if row.scope_id == self._scope_id ) return row diff --git a/openhcs/core/payload/runtime_image_values.py b/openhcs/core/payload/runtime_image_values.py index ada3bda27..730adb298 100644 --- a/openhcs/core/payload/runtime_image_values.py +++ b/openhcs/core/payload/runtime_image_values.py @@ -1975,7 +1975,7 @@ def as_runtime_value(value: Any) -> RuntimeSliceProjectableValue: return UnownedRuntimeValue(value) -@dataclass(frozen=True) +@dataclass(frozen=True, slots=True) class PlainImagePayload(DataBackedRuntimeArrayPayload, ImagePayload): """Pixels that carry no metadata and no mask.""" @@ -2024,7 +2024,7 @@ def aligned_value(self, resolver: Any) -> Any: return self -@dataclass(frozen=True) +@dataclass(frozen=True, slots=True) class ImageMetadataPayload(DataBackedRuntimeArrayPayload, ImagePayload): """Image data plus metadata, without requiring a validity mask.""" @@ -2059,7 +2059,7 @@ def with_data( ) -@dataclass(frozen=True) +@dataclass(frozen=True, slots=True) class MaskedImagePayload(DataBackedRuntimeArrayPayload, ImagePayload): """Image data plus an authoritative per-pixel validity mask.""" From 4f96a691fa4e218b91b4bee778bba86106e87984 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:31:07 +0000 Subject: [PATCH 05/27] Port the CellProfiler nuclei pipelines to MaterializationSpec 47fcfbfd3 deleted core.materialization.presets and materialize_segmentation_masks; these three pipelines (and the BBBC021/022 nuclei pipelines that import them) failed at import. Their CSV output is now MaterializationSpec(CsvOptions(fields=...)); analysis_type went with the old preset API. The mask output is MaterializationSpec(ROIOptions()), which is cell_counting_cpu's own segmentation_masks spec. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- benchmark/pipelines/cellprofiler_nuclei.py | 13 +++++-------- benchmark/pipelines/cellprofiler_nuclei_cupy.py | 13 +++++-------- benchmark/pipelines/cellprofiler_nuclei_gpu.py | 13 +++++-------- 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/benchmark/pipelines/cellprofiler_nuclei.py b/benchmark/pipelines/cellprofiler_nuclei.py index 5a4b233cc..dd22c0319 100644 --- a/benchmark/pipelines/cellprofiler_nuclei.py +++ b/benchmark/pipelines/cellprofiler_nuclei.py @@ -26,10 +26,8 @@ from openhcs.core.memory.decorators import numpy as numpy_func from openhcs.core.pipeline.function_contracts import artifact_outputs -from openhcs.core.materialization.presets import csv_materializer -from openhcs.processing.backends.analysis.cell_counting_cpu import ( - materialize_segmentation_masks, -) +from openhcs.core.materialization.core import MaterializationSpec +from openhcs.core.materialization.options import CsvOptions, ROIOptions @dataclass @@ -90,7 +88,7 @@ def declump_shape(binary: np.ndarray, min_distance: int = 7) -> np.ndarray: @artifact_outputs( ( "nuclei_measurements", - csv_materializer( + MaterializationSpec(CsvOptions( fields=[ "slice_index", "nuclei_count", @@ -98,10 +96,9 @@ def declump_shape(binary: np.ndarray, min_distance: int = 7) -> np.ndarray: "mean_area", "mean_intensity", ], - analysis_type="nuclei_counts", - ), + )), ), - ("segmentation_masks", materialize_segmentation_masks), + ("segmentation_masks", MaterializationSpec(ROIOptions())), ) def identify_primary_objects( image: np.ndarray, diff --git a/benchmark/pipelines/cellprofiler_nuclei_cupy.py b/benchmark/pipelines/cellprofiler_nuclei_cupy.py index 9736dc6c9..548d0c4ea 100644 --- a/benchmark/pipelines/cellprofiler_nuclei_cupy.py +++ b/benchmark/pipelines/cellprofiler_nuclei_cupy.py @@ -22,10 +22,8 @@ from openhcs.core.memory.decorators import cupy as cupy_func from openhcs.core.pipeline.function_contracts import artifact_outputs - from openhcs.core.materialization.presets import csv_materializer - from openhcs.processing.backends.analysis.cell_counting_cpu import ( - materialize_segmentation_masks, - ) + from openhcs.core.materialization.core import MaterializationSpec + from openhcs.core.materialization.options import CsvOptions, ROIOptions @dataclass class NucleiMeasurement: @@ -41,7 +39,7 @@ class NucleiMeasurement: @artifact_outputs( ( "nuclei_measurements", - csv_materializer( + MaterializationSpec(CsvOptions( fields=[ "slice_index", "nuclei_count", @@ -49,10 +47,9 @@ class NucleiMeasurement: "mean_area", "mean_intensity", ], - analysis_type="nuclei_counts", - ), + )), ), - ("segmentation_masks", materialize_segmentation_masks), + ("segmentation_masks", MaterializationSpec(ROIOptions())), ) def identify_primary_objects_cupy( image: np.ndarray, diff --git a/benchmark/pipelines/cellprofiler_nuclei_gpu.py b/benchmark/pipelines/cellprofiler_nuclei_gpu.py index 0252aa268..e933729bf 100644 --- a/benchmark/pipelines/cellprofiler_nuclei_gpu.py +++ b/benchmark/pipelines/cellprofiler_nuclei_gpu.py @@ -18,10 +18,8 @@ from openhcs.core.memory.decorators import pyclesperanto as pyclesperanto_func from openhcs.core.pipeline.function_contracts import artifact_outputs -from openhcs.core.materialization.presets import csv_materializer -from openhcs.processing.backends.analysis.cell_counting_cpu import ( - materialize_segmentation_masks, -) +from openhcs.core.materialization.core import MaterializationSpec +from openhcs.core.materialization.options import CsvOptions, ROIOptions @dataclass @@ -39,7 +37,7 @@ class NucleiMeasurement: @artifact_outputs( ( "nuclei_measurements", - csv_materializer( + MaterializationSpec(CsvOptions( fields=[ "slice_index", "nuclei_count", @@ -47,10 +45,9 @@ class NucleiMeasurement: "mean_area", "mean_intensity", ], - analysis_type="nuclei_counts", - ), + )), ), - ("segmentation_masks", materialize_segmentation_masks), + ("segmentation_masks", MaterializationSpec(ROIOptions())), ) def identify_primary_objects_gpu( image: np.ndarray, From fd1456b2e0a2f2d2d93471139e981ce7cff6dbe0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:44:32 +0000 Subject: [PATCH 06/27] Give the threshold backends one shared primitive base, not a parent chain f6e76e779 made CentrosomeNumpyThresholdPrimitiveBackendStrategy a subclass of the Numba strategy to reuse its primitives. That also handed it NumbaNumpyDefaultBackend.is_default_backend = True, since the Centrosome mixin never sets that flag. Two numpy defaults then registered, and DefaultBackendSelection raised during function-registry preparation. Every pipeline in smoke was rejected because of it. The primitives now live on NumpyThresholdPrimitives, which declares no memory type and so is never registered. Numba and Centrosome are siblings that each add only their provider mixin, the same shape morphology and watershed already use. The registry has one numpy default (Numba); Centrosome is non-default. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- .../thresholding_family/thresholding.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py b/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py index e40650cd3..6c302e0a7 100644 --- a/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py +++ b/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py @@ -1330,8 +1330,12 @@ class NumbaLogTransformConversion: log_max: float -class NumbaNumpyThresholdPrimitiveBackendStrategy(NumbaNumpyDefaultBackend, ThresholdPrimitiveBackendStrategy): - """Numba-backed threshold primitives for NumPy-memory images.""" +class NumpyThresholdPrimitives(ThresholdPrimitiveBackendStrategy): + """Threshold primitives for NumPy-memory images, shared by every NumPy provider. + + Declares no memory type, so it is not registered itself; each provider + subclass adds its own provider mixin and default flag. + """ def prepare_backend(self) -> None: values = np.linspace(0.01, 1.0, 32, dtype=np.float64) image = values[:25].reshape((5, 5)) @@ -1493,10 +1497,12 @@ def minimum_cross_entropy_threshold( return float(_li_threshold_numba(values, _li_tolerance_numba(values))) -class CentrosomeNumpyThresholdPrimitiveBackendStrategy( - CentrosomeNumpyBackend, NumbaNumpyThresholdPrimitiveBackendStrategy -): - """Compatibility provider backed by absorbed threshold primitives.""" +class NumbaNumpyThresholdPrimitiveBackendStrategy(NumbaNumpyDefaultBackend, NumpyThresholdPrimitives): + """Numba-backed threshold primitives for NumPy-memory images.""" + + +class CentrosomeNumpyThresholdPrimitiveBackendStrategy(CentrosomeNumpyBackend, NumpyThresholdPrimitives): + """Centrosome provider backed by the same absorbed threshold primitives.""" def threshold_primitives( *, backend_provider: BackendProviderInput = DEFAULT_CELLPROFILER_BACKEND_SELECTION From 8fb6dda4d4acb5c4fa1fbfef57f5c3e1b63a3b4d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:45:22 +0000 Subject: [PATCH 07/27] Same shared-base split for secondary propagation backends NativeSecondaryPropagationBackendStrategy subclassed the Numba strategy and inherited is_default_backend = True from NumbaNumpyDefaultBackend: a second numpy default, the same bug as the threshold family. The propagation code moves to NumpySecondaryPropagation (no memory type, unregistered); Numba and Native are siblings. A sweep of all 26 CellProfiler strategy families now finds no memory type with more than one default. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- .../backends/cellprofiler/secondary.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/openhcs/processing/backends/cellprofiler/secondary.py b/openhcs/processing/backends/cellprofiler/secondary.py index 41f1d726a..7fbfebedf 100644 --- a/openhcs/processing/backends/cellprofiler/secondary.py +++ b/openhcs/processing/backends/cellprofiler/secondary.py @@ -672,8 +672,12 @@ def propagate_zero_image_result( ) -class NumbaSecondaryPropagationBackendStrategy(NumbaNumpyDefaultBackend, SecondaryPropagationBackendStrategy): - """Numba implementation of regularized secondary-label propagation.""" +class NumpySecondaryPropagation(SecondaryPropagationBackendStrategy): + """Regularized secondary-label propagation shared by every NumPy provider. + + Declares no memory type, so it is not registered itself; each provider + subclass adds its own provider mixin and default flag. + """ def prepare_backend(self) -> None: image = np.arange(9, dtype=np.float64).reshape((3, 3)) labels = np.array([[1, 0, 0], [0, 0, 2], [0, 0, 0]], dtype=np.int32) @@ -747,10 +751,12 @@ def propagate_zero_image_result( return LabelPropagationResult(labels=propagated, distances=distances) -class NativeSecondaryPropagationBackendStrategy( - NativeNumpyBackend, NumbaSecondaryPropagationBackendStrategy -): - """Native compatibility key backed by absorbed propagation semantics.""" +class NumbaSecondaryPropagationBackendStrategy(NumbaNumpyDefaultBackend, NumpySecondaryPropagation): + """Numba implementation of regularized secondary-label propagation.""" + + +class NativeSecondaryPropagationBackendStrategy(NativeNumpyBackend, NumpySecondaryPropagation): + """Native provider backed by the same absorbed propagation semantics.""" def secondary_propagation_backend( *, backend_provider: BackendProviderInput = DEFAULT_CELLPROFILER_BACKEND_SELECTION From 9a7ce55cdffa59a7ab3457c906c2f6747d29eac1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:00:22 +0000 Subject: [PATCH 08/27] Put MethodKeyedStrategy before EnumKeyedStrategyMixin in every family 1047d5744 extracted MethodKeyedStrategy (__enum_member_attr__ = "method") but every family listed it after EnumKeyedStrategyMixin, whose own __enum_member_attr__ = "strategy_key" then wins in the MRO. No strategy declares strategy_key, so every concrete strategy was skipped as keyless and these 16 registries came out empty. FeatureOperationStrategy raised KeyError: 'Enhance' during function-registry preparation, which rejected every pipeline in smoke. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- .../backends/cellprofiler/feature_enhancement.py | 4 ++-- openhcs/processing/backends/cellprofiler/illumination.py | 8 ++++---- .../backends/cellprofiler/morphology_family/morphology.py | 4 ++-- openhcs/processing/backends/cellprofiler/neighbors.py | 2 +- openhcs/processing/backends/cellprofiler/secondary.py | 8 ++++---- openhcs/processing/backends/cellprofiler/smoothing.py | 2 +- .../cellprofiler/thresholding_family/thresholding.py | 2 +- openhcs/processing/backends/cellprofiler/tracking.py | 2 +- openhcs/processing/backends/processors/cupy_processor.py | 2 +- .../backends/processors/image_stack_operations.py | 4 ++-- 10 files changed, 19 insertions(+), 19 deletions(-) diff --git a/openhcs/processing/backends/cellprofiler/feature_enhancement.py b/openhcs/processing/backends/cellprofiler/feature_enhancement.py index 9c8c1a713..70316a8e2 100644 --- a/openhcs/processing/backends/cellprofiler/feature_enhancement.py +++ b/openhcs/processing/backends/cellprofiler/feature_enhancement.py @@ -212,7 +212,7 @@ class FeatureEnhancementRequest: dic_decay: float class FeatureOperationStrategy( - EnumKeyedStrategyMixin[OperationMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[OperationMethod], ABC, metaclass=AutoRegisterMeta ): """Top-level CP enhance/suppress operation semantics.""" @@ -245,7 +245,7 @@ def apply(self, request: FeatureEnhancementRequest) -> np.ndarray: return request.mask_context.restore_background(opened) class FeatureEnhanceMethodStrategy( - EnumKeyedStrategyMixin[EnhanceMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[EnhanceMethod], ABC, metaclass=AutoRegisterMeta ): """CP feature enhancement method semantics.""" diff --git a/openhcs/processing/backends/cellprofiler/illumination.py b/openhcs/processing/backends/cellprofiler/illumination.py index f04d5b67a..7ad232b88 100644 --- a/openhcs/processing/backends/cellprofiler/illumination.py +++ b/openhcs/processing/backends/cellprofiler/illumination.py @@ -610,8 +610,8 @@ def illumination_gaussian_filter( IlluminationCalculationResult = RuntimeArrayData | AlignedImageStack class IlluminationCorrectionStrategy( - EnumKeyedStrategyMixin[IlluminationCorrectionMethod], - MethodKeyedStrategy, ABC, + MethodKeyedStrategy, + EnumKeyedStrategyMixin[IlluminationCorrectionMethod], ABC, metaclass=AutoRegisterMeta, ): """Nominal correction implementation for one CellProfiler method.""" @@ -1069,7 +1069,7 @@ def correct_illumination_apply( ) class SmoothingFilterSizeStrategy( - EnumKeyedStrategyMixin[FilterSizeMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[FilterSizeMethod], ABC, metaclass=AutoRegisterMeta ): """Nominal filter-size derivation for one closed CellProfiler mode.""" @@ -1096,7 +1096,7 @@ def calculate(self, request: IlluminationCalculationRequest) -> float: return min(30.0, float(np.max(request.spatial_image_shape)) / 40.0) class SmoothingPlaneStrategy( - EnumKeyedStrategyMixin[SmoothingMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[SmoothingMethod], ABC, metaclass=AutoRegisterMeta ): """Nominal smoothing implementation for one closed CellProfiler mode.""" diff --git a/openhcs/processing/backends/cellprofiler/morphology_family/morphology.py b/openhcs/processing/backends/cellprofiler/morphology_family/morphology.py index 269932afd..81c659315 100644 --- a/openhcs/processing/backends/cellprofiler/morphology_family/morphology.py +++ b/openhcs/processing/backends/cellprofiler/morphology_family/morphology.py @@ -5234,7 +5234,7 @@ class CombineObjectsStats: class CombineObjectsStrategy( - EnumKeyedStrategyMixin[CombineObjectsMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[CombineObjectsMethod], ABC, metaclass=AutoRegisterMeta ): """Nominal object-label combination strategy.""" @@ -5557,7 +5557,7 @@ def execute(self, request: SplitOrMergeRequest) -> np.ndarray: class SplitOrMergeMergeMethodStrategy( - EnumKeyedStrategyMixin[SplitOrMergeMergeMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[SplitOrMergeMergeMethod], ABC, metaclass=AutoRegisterMeta ): """Nominal implementation for one SplitOrMergeObjects merge method.""" diff --git a/openhcs/processing/backends/cellprofiler/neighbors.py b/openhcs/processing/backends/cellprofiler/neighbors.py index 9ac788b44..8ff92b7a0 100644 --- a/openhcs/processing/backends/cellprofiler/neighbors.py +++ b/openhcs/processing/backends/cellprofiler/neighbors.py @@ -158,7 +158,7 @@ class NeighborDistancePlan: class NeighborDistancePlanner( - EnumKeyedStrategyMixin[DistanceMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[DistanceMethod], ABC, metaclass=AutoRegisterMeta ): """Prepare neighbor-distance state for one closed distance method.""" diff --git a/openhcs/processing/backends/cellprofiler/secondary.py b/openhcs/processing/backends/cellprofiler/secondary.py index 7fbfebedf..2f452fdc2 100644 --- a/openhcs/processing/backends/cellprofiler/secondary.py +++ b/openhcs/processing/backends/cellprofiler/secondary.py @@ -419,8 +419,8 @@ def image_plane(self) -> np.ndarray: class SecondarySegmentationStrategy( - EnumKeyedStrategyMixin[SecondaryMethod], - MethodKeyedStrategy, ABC, + MethodKeyedStrategy, + EnumKeyedStrategyMixin[SecondaryMethod], ABC, metaclass=AutoRegisterMeta, ): """Segmentation strategy for one closed secondary-object method.""" @@ -817,8 +817,8 @@ def object_count(self) -> int: class ThresholdCalculator( - EnumKeyedStrategyMixin[ThresholdMethod], - MethodKeyedStrategy, ABC, + MethodKeyedStrategy, + EnumKeyedStrategyMixin[ThresholdMethod], ABC, metaclass=AutoRegisterMeta, ): """Threshold strategy for one closed CellProfiler threshold method.""" diff --git a/openhcs/processing/backends/cellprofiler/smoothing.py b/openhcs/processing/backends/cellprofiler/smoothing.py index 9ec273fc0..0ec98886c 100644 --- a/openhcs/processing/backends/cellprofiler/smoothing.py +++ b/openhcs/processing/backends/cellprofiler/smoothing.py @@ -150,7 +150,7 @@ def sigma(self) -> float: class SmoothingBackendProviderPolicy( - EnumKeyedStrategyMixin[SmoothingMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[SmoothingMethod], ABC, metaclass=AutoRegisterMeta ): """Nominal SSOT for CellProfiler Smooth default backend semantics.""" diff --git a/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py b/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py index 6c302e0a7..e393a281f 100644 --- a/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py +++ b/openhcs/processing/backends/cellprofiler/thresholding_family/thresholding.py @@ -1910,7 +1910,7 @@ def _global_thresholds( class GlobalThresholdMethodStrategy( - EnumKeyedStrategyMixin[CellProfilerThresholdMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[CellProfilerThresholdMethod], ABC, metaclass=AutoRegisterMeta ): """Nominal implementation for one CellProfiler global threshold method.""" diff --git a/openhcs/processing/backends/cellprofiler/tracking.py b/openhcs/processing/backends/cellprofiler/tracking.py index 21a0cbfd3..021b24795 100644 --- a/openhcs/processing/backends/cellprofiler/tracking.py +++ b/openhcs/processing/backends/cellprofiler/tracking.py @@ -1164,7 +1164,7 @@ def _new_track_labels( class TrackObjectsMethodStrategy( - EnumKeyedStrategyMixin[TrackingMethod], MethodKeyedStrategy, ABC, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[TrackingMethod], ABC, metaclass=AutoRegisterMeta ): """Registered CellProfiler TrackObjects method behavior.""" diff --git a/openhcs/processing/backends/processors/cupy_processor.py b/openhcs/processing/backends/processors/cupy_processor.py index 8c35fb785..9dbd552c9 100644 --- a/openhcs/processing/backends/processors/cupy_processor.py +++ b/openhcs/processing/backends/processors/cupy_processor.py @@ -722,7 +722,7 @@ def sobel_components( class CupyEdgeMagnitudeStrategy( - EnumKeyedStrategyMixin[EdgeMagnitudeMethod], MethodKeyedStrategy, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[EdgeMagnitudeMethod], metaclass=AutoRegisterMeta ): @abstractmethod diff --git a/openhcs/processing/backends/processors/image_stack_operations.py b/openhcs/processing/backends/processors/image_stack_operations.py index 651504437..bbdfb2b4d 100644 --- a/openhcs/processing/backends/processors/image_stack_operations.py +++ b/openhcs/processing/backends/processors/image_stack_operations.py @@ -129,7 +129,7 @@ def min_projection(ops: ArrayOperations, stack: Any) -> Any: class StackProjection( - EnumKeyedStrategyMixin[StackProjectionMethod], MethodKeyedStrategy, metaclass=AutoRegisterMeta + MethodKeyedStrategy, EnumKeyedStrategyMixin[StackProjectionMethod], metaclass=AutoRegisterMeta ): """One leading-axis projection, keyed by its method value.""" @@ -172,7 +172,7 @@ def create_projection(ops: ArrayOperations, stack: Any, method: Any) -> Any: # ----- spatial binning (NumPy-compatible libraries) ----- -class SpatialBin(EnumKeyedStrategyMixin[SpatialBinMethod], MethodKeyedStrategy, metaclass=AutoRegisterMeta): +class SpatialBin(MethodKeyedStrategy, EnumKeyedStrategyMixin[SpatialBinMethod], metaclass=AutoRegisterMeta): """Reduction applied within each spatial bin.""" @abstractmethod From 6e658558341e5d5c51381afb29285e7688f6e5d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:09:48 +0000 Subject: [PATCH 09/27] Bare ndarrays get their spatial adapter again 98cbd690d deleted SourceSpatialDomainAdapter.for_value's bare-ndarray branch as dead. It only looked dead because PlainImagePayload had been abstract since e009fc263. Object-label relationships pass raw label arrays (identify_tertiary_objects -> object_label_parent_child_payload), so registry preparation raised "requires a registered nominal adapter for ndarray". The branch comes back as the decoder boundary. A local import of PlainImagePayload would hide a cycle, since runtime_image_values imports this module. So the family resolves its own member instead: BareArraySourceSpatialDomainAdapter declares adapts_bare_arrays, and for_value finds it through subclasses. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/payload/runtime_image_values.py | 2 ++ openhcs/core/source/source_spatial_domain.py | 22 +++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/openhcs/core/payload/runtime_image_values.py b/openhcs/core/payload/runtime_image_values.py index 730adb298..cf4bd1456 100644 --- a/openhcs/core/payload/runtime_image_values.py +++ b/openhcs/core/payload/runtime_image_values.py @@ -1903,6 +1903,8 @@ class BareArraySourceSpatialDomainAdapter( ): """Source-domain adapter for bare pixels, which declare no placement.""" + adapts_bare_arrays = True + @classmethod def for_array( cls, diff --git a/openhcs/core/source/source_spatial_domain.py b/openhcs/core/source/source_spatial_domain.py index 22de8f6e3..1127899f5 100644 --- a/openhcs/core/source/source_spatial_domain.py +++ b/openhcs/core/source/source_spatial_domain.py @@ -647,6 +647,9 @@ def spatial_adapter( class SourceSpatialDomainAdapter(ABC): """Adapter for dense XY payloads that carry source-domain coordinates.""" + adapts_bare_arrays: ClassVar[bool] = False + """True on the one member that places bare NumPy pixels at the origin.""" + @classmethod def for_value( cls, @@ -654,11 +657,28 @@ def for_value( *, source_shape_override_yx: tuple[int, int] | None = None, ) -> SourceSpatialDomainAdapter | None: - """Return the placement adapter of a spatially placed value.""" + """Return the placement adapter of a placed value or a bare NumPy array.""" + if isinstance(value, np.ndarray): + return cls.bare_array_member().for_array( + value, source_shape_override_yx=source_shape_override_yx + ) if not isinstance(value, SpatiallyPlacedValue): return None return value.spatial_adapter(source_shape_override_yx=source_shape_override_yx) + @classmethod + def bare_array_member(cls) -> type[SourceSpatialDomainAdapter]: + """Return the family member declaring ``adapts_bare_arrays``.""" + pending = list(SourceSpatialDomainAdapter.__subclasses__()) + members = [] + while pending: + member = pending.pop() + pending.extend(member.__subclasses__()) + if vars(member).get("adapts_bare_arrays"): + members.append(member) + (member,) = members + return member + @property @abstractmethod def array(self) -> Any: ... From b6dc772b7cbba79d5cd8e02b469bdcd00c8c8329 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:18:28 +0000 Subject: [PATCH 10/27] Put adopt_compiled_execution's body back under its own def 362ff2b8d extracted _validate_context_matches_source but inserted the new def directly after adopt_compiled_execution's docstring. adopt became a docstring-only method returning None, and its body became the tail of the validator. Every compiled run then raised "'NoneType' object has no attribute 'execution_id'" in _initialize_orchestrator. That was all 6 smoke failures on 6e6585583. The validator now sits after adopt, which ends in `return self` again. An AST scan of openhcs finds no other non-abstract docstring-only method with a return annotation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/orchestrator/orchestrator.py | 44 +++++++++++------------ 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/openhcs/core/orchestrator/orchestrator.py b/openhcs/core/orchestrator/orchestrator.py index 74211cc8f..2872646ae 100644 --- a/openhcs/core/orchestrator/orchestrator.py +++ b/openhcs/core/orchestrator/orchestrator.py @@ -502,28 +502,6 @@ def adopt_compiled_execution( execution_bundle: CompiledExecutionBundle, ) -> PipelineOrchestrator: """Bind an admitted compiled source domain to this fresh runtime owner.""" - - def _validate_context_matches_source( - self, - context: ExecutingContext, - source: ExecutingContext, - source_registry: Mapping, - ) -> None: - if ( - context.dataset_root != self.dataset_root - or context.input_dir != source.input_dir - or context.workspace_path != source.workspace_path - or context.microscope_handler is not source.microscope_handler - or context.filemanager is None - or context.filemanager.registry.keys() != source_registry.keys() - or any( - backend is not source_registry[name] - for name, backend in context.filemanager.registry.items() - ) - ): - raise ValueError( - "Compiled execution source domain does not match this runtime." - ) if self._initialized or self.state is not OrchestratorCreated: raise RuntimeError( "Compiled execution can only be adopted before initialization." @@ -564,6 +542,28 @@ def _validate_context_matches_source( self._state = OrchestratorReady return self + def _validate_context_matches_source( + self, + context: ExecutingContext, + source: ExecutingContext, + source_registry: Mapping, + ) -> None: + if ( + context.dataset_root != self.dataset_root + or context.input_dir != source.input_dir + or context.workspace_path != source.workspace_path + or context.microscope_handler is not source.microscope_handler + or context.filemanager is None + or context.filemanager.registry.keys() != source_registry.keys() + or any( + backend is not source_registry[name] + for name, backend in context.filemanager.registry.items() + ) + ): + raise ValueError( + "Compiled execution source domain does not match this runtime." + ) + def is_initialized(self) -> bool: return self._initialized From 56453833a6993ab304f41d2eac8b9c8dfc0ed6b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:19:20 +0000 Subject: [PATCH 11/27] Fix two runtime NameErrors: stale `request` local, missing `import zmq` function_runtime.py:720 read `request.source_binding_plan` inside PatternGroupExecutionRequest.load_input_stack, where the request is `self`. Any step with no producer records hit a NameError there. viewer_protocol.py uses zmq.Context, zmq.REQ and zmq.ZMQError but never imported zmq. The except tuple at :1837 is only evaluated when an exception is already in flight, so a real viewer-launch error became a NameError that hid it. A ruff F821 scan filtered to runtime-evaluated names (not postponed annotations) leaves only pipeline_config's runtime-generated Lazy* and global_pipeline_config globals. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/steps/function_runtime.py | 2 +- openhcs/runtime/viewer/viewer_protocol.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/openhcs/core/steps/function_runtime.py b/openhcs/core/steps/function_runtime.py index 48ea8db87..bc16c5dc4 100644 --- a/openhcs/core/steps/function_runtime.py +++ b/openhcs/core/steps/function_runtime.py @@ -717,7 +717,7 @@ def load_input_stack( ) if not producer_records: metadata = main_data_stack.metadata - domain = request.source_binding_plan.source_spatial_domain.with_source_cohort( + domain = self.source_binding_plan.source_spatial_domain.with_source_cohort( metadata.source_spatial_domain, depth=len(matching_files), ) diff --git a/openhcs/runtime/viewer/viewer_protocol.py b/openhcs/runtime/viewer/viewer_protocol.py index c9feff59f..a4b50b2f1 100644 --- a/openhcs/runtime/viewer/viewer_protocol.py +++ b/openhcs/runtime/viewer/viewer_protocol.py @@ -37,6 +37,7 @@ ViewerSettlePhase, ViewerSettleProgress, ) +import zmq from zmqruntime.process_launch import BackgroundProcessLaunchPolicy from zmqruntime.client import EndpointProcessGroup, endpoint_process from zmqruntime.config import NonBlankString, TransportMode, ZMQConfig From 4af1247d3376ef4b6c92c2939b8ad3096e999e7a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:28:27 +0000 Subject: [PATCH 12/27] Re-import the names projected dataclasses resolve at runtime 18d063493 removed "annotation-only" imports, but python_introspect's project_dataclass / validate_annotated_dataclass call get_type_hints() on these classes at runtime. BundleExecutionRequest and WorkerLaneExecutionContext lost seven names, so every compiled run raised "name 'CompiledExecutionBundle' is not defined". A scan of every dataclass python_introspect resolves (project_dataclass / validate_annotated_dataclass targets, including self-validating __post_init__) finds only these seven. Restoring all 274 removed dataclass-annotation imports instead re-closes import cycles: 261 modules failed to import. With just these seven, an import of every openhcs module shows only the 12 torch-only backends missing, and get_type_hints resolves both classes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/orchestrator/bundle_execution.py | 6 ++++++ openhcs/core/orchestrator/worker_lanes.py | 1 + 2 files changed, 7 insertions(+) diff --git a/openhcs/core/orchestrator/bundle_execution.py b/openhcs/core/orchestrator/bundle_execution.py index aca6e0d28..6f9110d9b 100644 --- a/openhcs/core/orchestrator/bundle_execution.py +++ b/openhcs/core/orchestrator/bundle_execution.py @@ -55,6 +55,12 @@ SuccessProgressStatus, ViewerSettlementProgressPhase, ) +from openhcs.core.debug.debug_runtime import DebugExecutionPolicy +from openhcs.core.execution.compiled_execution import CompiledExecutionBundle +from openhcs.core.execution.execution_visualizer import ExecutionVisualizerABC +from openhcs.core.orchestrator.execution_result import RuntimeObservationMode +from openhcs.core.orchestrator.worker_execution import PreparedForkWorkerLaneRunner +from openhcs.core.progress.types import ProgressQueue logger = logging.getLogger(__name__) diff --git a/openhcs/core/orchestrator/worker_lanes.py b/openhcs/core/orchestrator/worker_lanes.py index bbd2d9ef5..914f912b1 100644 --- a/openhcs/core/orchestrator/worker_lanes.py +++ b/openhcs/core/orchestrator/worker_lanes.py @@ -11,6 +11,7 @@ from openhcs.core.context.processing_context import CompiledContext from openhcs.core.debug.debug_runtime import DebugSinkInstallRequest from openhcs.core.progress.types import ProgressExecutionContext +from openhcs.core.debug.debug_runtime import DebugExecutionPolicy TransportAxisContexts: TypeAlias = List[tuple[str, CompiledContext]] ForkAxisContextKeys: TypeAlias = List[str] From 1bc9422a53b41db9ddc999c13ce6ce5977695808 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:29:13 +0000 Subject: [PATCH 13/27] normalize_clause_value is a classmethod, like its sibling matches SourceFilterClause.__post_init__ calls self.match_type.normalize_clause_value(self), and match_type holds the match-type class, not an instance. As an instance method the clause was bound as `self`, so every SourceFilterClause raised "missing 1 required positional argument: 'clause'". Importing openhcs.mcp.installed_demo already failed this way. The base method and TextMatchType's override are now classmethods; `matches` already was one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/source/source_bindings.py | 5 +++-- openhcs/core/source/source_metadata.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/openhcs/core/source/source_bindings.py b/openhcs/core/source/source_bindings.py index bfc354e43..4c309346c 100644 --- a/openhcs/core/source/source_bindings.py +++ b/openhcs/core/source/source_bindings.py @@ -168,10 +168,11 @@ def text_of(file_path: str) -> str: class TextMatchType(SourceFilterMatchType): """Compares the subject text with the clause's value.""" - def normalize_clause_value(self, clause: SourceFilterClause) -> None: + @classmethod + def normalize_clause_value(cls, clause: SourceFilterClause) -> None: if clause.value is None: raise ValueError( - f"SourceFilterClause.value is required for {self.name}." + f"SourceFilterClause.value is required for {cls.name}." ) object.__setattr__(clause, "value", str(clause.value)) diff --git a/openhcs/core/source/source_metadata.py b/openhcs/core/source/source_metadata.py index b8d6be31a..eac48a5da 100644 --- a/openhcs/core/source/source_metadata.py +++ b/openhcs/core/source/source_metadata.py @@ -73,7 +73,8 @@ class SourceFilterMatchType(ABC, metaclass=AutoRegisterMeta): name: ClassVar[str | None] = None """Spelling in forms and on the wire.""" - def normalize_clause_value(self, clause: SourceFilterClause) -> None: + @classmethod + def normalize_clause_value(cls, clause: SourceFilterClause) -> None: object.__setattr__(clause, "value", None) """The clause carries a comparison operand.""" From adea3ed6e4a060191756d9ad3d4b753c4fbfb58e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:35:15 +0000 Subject: [PATCH 14/27] Restore the dataclass-annotation imports that cannot close a cycle 18d063493 removed 285 "annotation-only" imports. Dataclass field annotations are resolved at runtime by get_type_hints (python_introspect projection, codecs, the metadata writer), so smoke kept failing one name at a time: CompiledExecutionBundle, then SourceProjectionRole. For every undefined name in a dataclass field annotation, this restores the exact import 18d063493 removed from that file (or the name's unique definition), but only when a static module-level import graph shows the target cannot reach the importing module: 194 names in 74 files. The 18 that would close a cycle are left for declaration moves. Restoring all of them broke 261 modules. An import of every openhcs module now fails only on the 11 torch-only backends. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLduzEngvw2qQf1Qx8mC --- openhcs/core/artifact_store/runtime_artifact_queries.py | 2 ++ openhcs/core/artifact_store/runtime_artifact_values.py | 1 + .../core/artifact_store/runtime_execution_validation.py | 1 + openhcs/core/artifact_store/runtime_stores.py | 2 ++ openhcs/core/artifacts/input_projection.py | 1 + openhcs/core/artifacts/plans.py | 4 ++++ openhcs/core/artifacts/relations.py | 1 + openhcs/core/artifacts/specs.py | 5 +++++ openhcs/core/axes/axis_filter.py | 1 + openhcs/core/axes/component_set.py | 1 + openhcs/core/callable/callable_contract.py | 1 + openhcs/core/callable/function_patterns.py | 3 +++ openhcs/core/callable/invocation_artifacts.py | 3 +++ openhcs/core/callable/runtime_adapters.py | 5 +++++ openhcs/core/callable/runtime_batch_contracts.py | 2 ++ openhcs/core/context/processing_context.py | 1 + openhcs/core/dataset_sources/openhcs_format.py | 1 + openhcs/core/debug/debug_runtime.py | 3 +++ openhcs/core/debug/debug_session_projection.py | 2 ++ openhcs/core/equivalence/keys.py | 1 + openhcs/core/equivalence/measurement_features.py | 1 + openhcs/core/equivalence/relationships.py | 2 ++ openhcs/core/execution/compiled_execution.py | 3 +++ openhcs/core/execution/compiled_step_plan.py | 4 ++++ openhcs/core/execution/runtime_pattern_cache.py | 3 +++ openhcs/core/io/viewer_streaming_service.py | 4 ++++ openhcs/core/io/virtual_workspace_metadata.py | 2 ++ openhcs/core/materialization/core.py | 5 +++++ openhcs/core/materialization/options.py | 1 + openhcs/core/measurements/measurement_feature_queries.py | 1 + openhcs/core/measurements/measurement_image_alignment.py | 2 ++ openhcs/core/measurements/runtime_measurements.py | 1 + .../core/object_labels/runtime_object_label_building.py | 4 ++++ openhcs/core/object_labels/runtime_object_labels.py | 2 ++ openhcs/core/object_labels/runtime_relationships.py | 2 ++ openhcs/core/orchestrator/bundle_execution.py | 4 ++++ openhcs/core/orchestrator/execution_result.py | 2 ++ openhcs/core/orchestrator/worker_execution.py | 5 +++++ openhcs/core/orchestrator/worker_lanes.py | 1 + openhcs/core/payload/aligned_image_payload.py | 2 ++ openhcs/core/payload/payload_axes.py | 1 + openhcs/core/payload/projected_image_output.py | 1 + openhcs/core/payload/runtime_image_loading.py | 2 ++ openhcs/core/payload/runtime_image_values.py | 2 ++ openhcs/core/payload/runtime_slice_projection.py | 1 + openhcs/core/payload/runtime_source_binding_cache.py | 4 ++++ openhcs/core/payload/runtime_stack_cache.py | 1 + openhcs/core/pipeline/artifact_declarations.py | 2 ++ openhcs/core/pipeline/artifact_planning.py | 4 ++++ openhcs/core/pipeline/compilation_session.py | 7 +++++++ openhcs/core/pipeline/compiler.py | 3 +++ openhcs/core/pipeline/materialization_flag_planner.py | 3 +++ openhcs/core/pipeline/path_planner.py | 1 + openhcs/core/plate/plate_image_inventory.py | 1 + openhcs/core/progress/debug_projection.py | 2 ++ openhcs/core/progress/live_measurements.py | 1 + openhcs/core/progress/runtime_tree.py | 2 ++ openhcs/core/source/source_binding_context.py | 1 + openhcs/core/source/source_binding_selection.py | 6 ++++++ openhcs/core/source/source_binding_workspace.py | 2 ++ openhcs/core/source/source_bindings.py | 1 + openhcs/core/source/source_bindings_preview.py | 1 + openhcs/core/source/source_matching.py | 1 + openhcs/core/source/source_metadata.py | 1 + openhcs/core/source/source_plane_alignment.py | 1 + openhcs/core/source/source_projection.py | 3 +++ openhcs/core/source/source_workspace_projection.py | 6 ++++++ openhcs/core/steps/function_artifact_materialization.py | 3 +++ openhcs/core/steps/function_output_identity.py | 4 ++++ openhcs/core/steps/function_output_manifest.py | 2 ++ openhcs/core/steps/function_outputs.py | 2 ++ openhcs/core/steps/function_runtime.py | 3 +++ openhcs/core/steps/stream_component_semantics.py | 1 + openhcs/core/util/artifact_inspection.py | 3 +++ 74 files changed, 171 insertions(+) diff --git a/openhcs/core/artifact_store/runtime_artifact_queries.py b/openhcs/core/artifact_store/runtime_artifact_queries.py index 3e62c21c1..44c9fd837 100644 --- a/openhcs/core/artifact_store/runtime_artifact_queries.py +++ b/openhcs/core/artifact_store/runtime_artifact_queries.py @@ -41,6 +41,8 @@ SpatialGrid, ) from openhcs.core.measurements.measurement_dialect import MeasurementDialect +from openhcs.core.artifact_store.runtime_stores import RuntimeValueStore +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxisProjector, RuntimePlaneAxisValueProjection class RuntimeMeasurementTablesQueryCache( diff --git a/openhcs/core/artifact_store/runtime_artifact_values.py b/openhcs/core/artifact_store/runtime_artifact_values.py index ea4ccbb9a..b23dcd6e2 100644 --- a/openhcs/core/artifact_store/runtime_artifact_values.py +++ b/openhcs/core/artifact_store/runtime_artifact_values.py @@ -8,6 +8,7 @@ from openhcs.core.artifacts.kinds import ArtifactType from openhcs.core.axes.component_group_scope import RuntimeExecutionAxisScope +from openhcs.core.payload.runtime_image_values import ImagePayloadMetadata @dataclass(frozen=True) diff --git a/openhcs/core/artifact_store/runtime_execution_validation.py b/openhcs/core/artifact_store/runtime_execution_validation.py index b637f0e1c..507b0db63 100644 --- a/openhcs/core/artifact_store/runtime_execution_validation.py +++ b/openhcs/core/artifact_store/runtime_execution_validation.py @@ -23,6 +23,7 @@ ) from openhcs.core.source.source_spatial_domain import SourceSpatialDomain from openhcs.core.steps.function_artifact_materialization import runtime_artifact_materializations_from_records +from openhcs.core.artifact_store.runtime_stores import StoredRuntimeValue RuntimeArtifactViewerComponentIdentity = tuple[tuple[str, str], ...] diff --git a/openhcs/core/artifact_store/runtime_stores.py b/openhcs/core/artifact_store/runtime_stores.py index e2985a97e..7c00be11e 100644 --- a/openhcs/core/artifact_store/runtime_stores.py +++ b/openhcs/core/artifact_store/runtime_stores.py @@ -32,6 +32,8 @@ ) from openhcs.core.source.source_bindings import CompiledSourceBindingPlan from openhcs.core.axes.axis_declarations import PartitionAxis +from openhcs.core.artifact_store.runtime_artifact_values import ArtifactKey +from openhcs.core.artifacts.kinds import ArtifactType @dataclass(frozen=True) diff --git a/openhcs/core/artifacts/input_projection.py b/openhcs/core/artifacts/input_projection.py index 3efa63912..d4ccc0091 100644 --- a/openhcs/core/artifacts/input_projection.py +++ b/openhcs/core/artifacts/input_projection.py @@ -7,6 +7,7 @@ from openhcs.core.axes.component_group_scope import ComponentGroupScope from openhcs.core.axes.component_set import ComponentSet from openhcs.core.callable.callable_declarations import FunctionStepExecutionScope +from openhcs.core.axes.axis_declarations import Axis @dataclass(frozen=True) diff --git a/openhcs/core/artifacts/plans.py b/openhcs/core/artifacts/plans.py index 128c3ff01..c2818c0aa 100644 --- a/openhcs/core/artifacts/plans.py +++ b/openhcs/core/artifacts/plans.py @@ -22,6 +22,10 @@ from openhcs.core.axes.component_group_scope import ComponentGroupScope, UngroupedScope from openhcs.core.axes.component_set import ComponentSet from openhcs.core.payload.runtime_slice_projection import RuntimeSliceProjection +from openhcs.core.artifacts.payloads import ArtifactMaterializationPayload +from openhcs.core.artifacts.sidecars import ArtifactSidecarRole +from openhcs.core.artifacts.streaming import ViewerStreaming +from openhcs.core.axes.axis_declarations import Axis AnswerT = TypeVar("AnswerT") diff --git a/openhcs/core/artifacts/relations.py b/openhcs/core/artifacts/relations.py index 77c774a20..00d0411d1 100644 --- a/openhcs/core/artifacts/relations.py +++ b/openhcs/core/artifacts/relations.py @@ -23,6 +23,7 @@ from openhcs.core.artifacts.plans import ArtifactInputPlan, ArtifactOutputPlan, ArtifactPlan from openhcs.core.measurements.runtime_measurements import MeasurementSubject from openhcs.core.measurements.runtime_measurements import MeasurementScope +from openhcs.core.artifacts.plans import ArtifactSpecRef @dataclass(frozen=True) diff --git a/openhcs/core/artifacts/specs.py b/openhcs/core/artifacts/specs.py index 442bcef4b..c2c68c9bd 100644 --- a/openhcs/core/artifacts/specs.py +++ b/openhcs/core/artifacts/specs.py @@ -16,6 +16,11 @@ from openhcs.core.artifacts.relations import AssembledStackGroupLineageSourceRelation, GroupLineageSourceRelation, SourceStackLineageSourceRelation from openhcs.core.artifacts.streaming import AutomaticStreaming from openhcs.core.measurements.runtime_measurements import RuntimeMeasurementFeatureOwner +from openhcs.core.artifacts.payloads import ArtifactMaterializationPayload +from openhcs.core.artifacts.plans import ArtifactPlan +from openhcs.core.artifacts.relations import ArtifactSpecRelation +from openhcs.core.artifacts.sidecars import ArtifactSidecarRole +from openhcs.core.artifacts.streaming import ViewerStreaming MergedT = TypeVar("MergedT") diff --git a/openhcs/core/axes/axis_filter.py b/openhcs/core/axes/axis_filter.py index 454a8f971..aa8f2f203 100644 --- a/openhcs/core/axes/axis_filter.py +++ b/openhcs/core/axes/axis_filter.py @@ -5,6 +5,7 @@ from dataclasses import dataclass from collections.abc import Mapping from typing import TypeAlias +from openhcs.core.config.pipeline_config import PartitionFilterConfig, PartitionFilterMode PartitionFilterValue: TypeAlias = list[str] | str | int | None diff --git a/openhcs/core/axes/component_set.py b/openhcs/core/axes/component_set.py index f140191b3..740ba48c2 100644 --- a/openhcs/core/axes/component_set.py +++ b/openhcs/core/axes/component_set.py @@ -6,6 +6,7 @@ from dataclasses import dataclass from openhcs.core.axes.axis_declarations import AxisFamily, PartitionAxis, is_axis +from openhcs.core.axes.axis_declarations import Axis @dataclass(slots=True) diff --git a/openhcs/core/callable/callable_contract.py b/openhcs/core/callable/callable_contract.py index 57d927df3..1fc637eb3 100644 --- a/openhcs/core/callable/callable_contract.py +++ b/openhcs/core/callable/callable_contract.py @@ -64,6 +64,7 @@ from openhcs.core.payload.runtime_slice_projection import RuntimeSliceProjection from openhcs.core.config.pipeline_config import runtime_config_parameter from openhcs.core.pipeline.annotation_checks import special_input_parameter_accepts_sequence +from openhcs.core.artifacts.plans import ArtifactSpecRef CallableNamespace = Mapping[str, Any] diff --git a/openhcs/core/callable/function_patterns.py b/openhcs/core/callable/function_patterns.py index b2cdfd741..3c4cefee3 100644 --- a/openhcs/core/callable/function_patterns.py +++ b/openhcs/core/callable/function_patterns.py @@ -37,6 +37,9 @@ from openhcs.core.callable.function_reference import FunctionReference from openhcs.core.payload.runtime_image_values import project_image_mask_to_data_domain from openhcs.core.payload.runtime_image_values import ImagePayload, owned_runtime_value +from openhcs.core.artifacts.input_projection import ArtifactInputProjectionPlan +from openhcs.core.artifacts.specs import ArtifactSpec +from openhcs.core.callable.callable_contract import CallableContract FunctionPatternCallable: TypeAlias = Callable | FunctionReference FunctionPatternSyntax: TypeAlias = Callable | tuple | list | dict diff --git a/openhcs/core/callable/invocation_artifacts.py b/openhcs/core/callable/invocation_artifacts.py index 570be5bba..6c8d07280 100644 --- a/openhcs/core/callable/invocation_artifacts.py +++ b/openhcs/core/callable/invocation_artifacts.py @@ -18,6 +18,9 @@ from openhcs.core.axes.axis_declarations import Ungrouped, is_grouping_declaration from openhcs.core.callable.function_patterns import FunctionInvocationKey from openhcs.core.pipeline.artifact_declarations import ArtifactProducer +from openhcs.core.axes.axis_declarations import GroupingDeclaration +from openhcs.core.callable.callable_contract import CallableContract +from openhcs.core.config.pipeline_config import StepSourceBindingsConfig _ClaimValue = TypeVar("_ClaimValue") diff --git a/openhcs/core/callable/runtime_adapters.py b/openhcs/core/callable/runtime_adapters.py index b2fb79cab..e5418e128 100644 --- a/openhcs/core/callable/runtime_adapters.py +++ b/openhcs/core/callable/runtime_adapters.py @@ -32,6 +32,11 @@ SourceUniverseRequest, ) from openhcs.core.payload.runtime_plane_projection import RuntimePlaneProjection +from openhcs.core.axes.axis_declarations import Axis +from openhcs.core.axes.component_group_scope import RuntimeExecutionAxisScope +from openhcs.core.context.processing_context import ExecutingContext +from openhcs.core.payload.aligned_image_payload import ImagePayloadExecutionMode +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxisValueProjection _F = TypeVar("_F", bound=Callable[..., Any]) diff --git a/openhcs/core/callable/runtime_batch_contracts.py b/openhcs/core/callable/runtime_batch_contracts.py index 3f2d51f88..289d04e08 100644 --- a/openhcs/core/callable/runtime_batch_contracts.py +++ b/openhcs/core/callable/runtime_batch_contracts.py @@ -21,6 +21,8 @@ from openhcs.core.payload.runtime_plane_projection import ( RuntimePlaneAxisValueProjection, ) +from openhcs.core.artifact_store.runtime_stores import RuntimeArtifactBatch +from openhcs.core.context.processing_context import ExecutingContext F = TypeVar("F", bound=Callable) diff --git a/openhcs/core/context/processing_context.py b/openhcs/core/context/processing_context.py index ba9a7b694..15a0fe5f2 100644 --- a/openhcs/core/context/processing_context.py +++ b/openhcs/core/context/processing_context.py @@ -36,6 +36,7 @@ from openhcs.core.context.step_execution_observation import StepExecutionObservation from openhcs.core.steps.function_output_identity import FunctionOutputIdentityCache from openhcs.runtime.zmq.zmq_config import OPENHCS_ZMQ_CONFIG +from openhcs.core.config.pipeline_config import StreamingConfig _RuntimeStepValue = TypeVar("_RuntimeStepValue") diff --git a/openhcs/core/dataset_sources/openhcs_format.py b/openhcs/core/dataset_sources/openhcs_format.py index 672e5de34..d4dcbd125 100644 --- a/openhcs/core/dataset_sources/openhcs_format.py +++ b/openhcs/core/dataset_sources/openhcs_format.py @@ -1293,6 +1293,7 @@ def _merge_component_metadata( from dataclasses import replace from pathlib import PurePosixPath from openhcs.core.source.source_projection import SourceProjectionMetadataSerializer, SourceProjectionSet +from openhcs.core.context.processing_context import ExecutingContext class OpenHCSDatasetSource(PreparedWorkspaceSource, DatasetSource): diff --git a/openhcs/core/debug/debug_runtime.py b/openhcs/core/debug/debug_runtime.py index 8507bd6f4..b935e02f5 100644 --- a/openhcs/core/debug/debug_runtime.py +++ b/openhcs/core/debug/debug_runtime.py @@ -39,6 +39,9 @@ StartedProgressStatus, SuccessProgressStatus, ) +from openhcs.core.debug.debug_view_models import DebugViewModel +from openhcs.core.payload.vfs_protocol import FileManagerLike +from openhcs.core.progress.types import ProgressExecutionContext @runtime_checkable diff --git a/openhcs/core/debug/debug_session_projection.py b/openhcs/core/debug/debug_session_projection.py index 047df8aca..592dcb057 100644 --- a/openhcs/core/debug/debug_session_projection.py +++ b/openhcs/core/debug/debug_session_projection.py @@ -9,6 +9,8 @@ from metaclass_registry import AutoRegisterMeta from openhcs.core.execution.execution_state import ExecutionCancelled, ExecutionCompleted, ExecutionFailed, parse_terminal_status +from openhcs.core.debug.debug_runtime import DebugSession, DebugSnapshot, DebugTerminalSummary +from openhcs.core.execution.execution_state import ManagerExecutionState @dataclass(frozen=True) diff --git a/openhcs/core/equivalence/keys.py b/openhcs/core/equivalence/keys.py index e8aae3a1c..69ef41873 100644 --- a/openhcs/core/equivalence/keys.py +++ b/openhcs/core/equivalence/keys.py @@ -16,6 +16,7 @@ runtime_source_name_tokens, ) from openhcs.core.measurements.runtime_measurements import MeasurementScope, MeasurementStatistic, ObjectCoreMeasurementFeature +from openhcs.core.equivalence.policy import RuntimeEquivalencePolicy @dataclass(frozen=True) diff --git a/openhcs/core/equivalence/measurement_features.py b/openhcs/core/equivalence/measurement_features.py index 74c179a93..5d6b9d621 100644 --- a/openhcs/core/equivalence/measurement_features.py +++ b/openhcs/core/equivalence/measurement_features.py @@ -45,6 +45,7 @@ ObjectIntensityFeatureMarker, ObjectLocationFeatureMarker, ) +from openhcs.core.measurements.runtime_measurements import RuntimeMeasurementFeature RuntimeMeasurementFactCounterMapping = Mapping[ RuntimeMeasurementFeatureKey, diff --git a/openhcs/core/equivalence/relationships.py b/openhcs/core/equivalence/relationships.py index 7b89e6b69..e4126e0a3 100644 --- a/openhcs/core/equivalence/relationships.py +++ b/openhcs/core/equivalence/relationships.py @@ -12,6 +12,8 @@ from openhcs.core.payload.runtime_identifier import normalize_runtime_identifier from metaclass_registry.strategies import MostDerivedContextStrategyMixin from openhcs.core.measurements.runtime_measurements import MeasurementStatistic +from openhcs.core.equivalence.keys import RuntimeMeasurementFeatureKey +from openhcs.core.measurements.measurement_dialect import MeasurementDialect @dataclass(frozen=True) class RelationshipAggregateFeatureContext: diff --git a/openhcs/core/execution/compiled_execution.py b/openhcs/core/execution/compiled_execution.py index 0a91c40c3..be5a9397b 100644 --- a/openhcs/core/execution/compiled_execution.py +++ b/openhcs/core/execution/compiled_execution.py @@ -14,6 +14,9 @@ WorkerStartExecutionFacts, resolve_worker_start_context, ) +from openhcs.core.config.pipeline_config import MultiprocessingStartMethod +from openhcs.core.context.processing_context import CompiledContext +from openhcs.core.steps.abstract import AbstractStep @dataclass(frozen=True) diff --git a/openhcs/core/execution/compiled_step_plan.py b/openhcs/core/execution/compiled_step_plan.py index b3a897c34..9ac3dc0f6 100644 --- a/openhcs/core/execution/compiled_step_plan.py +++ b/openhcs/core/execution/compiled_step_plan.py @@ -22,6 +22,10 @@ CompiledSourceUniversePlan, ) from openhcs.core.util.step_dependencies import UnresolvedStepInput +from openhcs.core.axes.axis_declarations import Axis +from openhcs.core.axes.component_group_scope import ComponentGroupScope +from openhcs.core.callable.function_patterns import CompiledFunctionPattern +from openhcs.core.util.step_dependencies import StepInputDependency StreamingConfig = Any diff --git a/openhcs/core/execution/runtime_pattern_cache.py b/openhcs/core/execution/runtime_pattern_cache.py index eb2f99478..34a289dfd 100644 --- a/openhcs/core/execution/runtime_pattern_cache.py +++ b/openhcs/core/execution/runtime_pattern_cache.py @@ -9,6 +9,9 @@ from openhcs.core.callable.function_patterns import FunctionGroupKey from openhcs.core.source.source_binding_selection import SourceCandidatePath +from openhcs.core.axes.axis_declarations import Axis, GroupingDeclaration +from openhcs.core.components.parser_metaprogramming import FilenameParseResult +from openhcs.core.dataset_sources.interfaces import FilenameParser DiscoveredPatternCollection = ( diff --git a/openhcs/core/io/viewer_streaming_service.py b/openhcs/core/io/viewer_streaming_service.py index 5321f80b4..b0424a273 100644 --- a/openhcs/core/io/viewer_streaming_service.py +++ b/openhcs/core/io/viewer_streaming_service.py @@ -47,6 +47,10 @@ ViewerLaunchContext, ) from openhcs.runtime.zmq.zmq_config import OPENHCS_ZMQ_CONFIG +from openhcs.core.config.pipeline_config import StreamingConfig +from openhcs.core.config.streaming_config_declarations import ViewerType +from openhcs.core.dataset_sources.source import DatasetSource +from openhcs.core.source.source_workspace_projection import VirtualWorkspaceSourceProjection logger = logging.getLogger(__name__) diff --git a/openhcs/core/io/virtual_workspace_metadata.py b/openhcs/core/io/virtual_workspace_metadata.py index 5a042af85..44e23c4b9 100644 --- a/openhcs/core/io/virtual_workspace_metadata.py +++ b/openhcs/core/io/virtual_workspace_metadata.py @@ -24,6 +24,8 @@ from openhcs.core.source.source_projection import OpenHCSPlaneAddress, SourceArtifactProjection, SourcePlaneProjection, SourceProjectionMetadataSerializer, SourceProjectionSet from openhcs.core.source.source_tile_geometry import SourceTileLayout from openhcs.core.axes.axis_declarations import AxisFamily, ColourAxis +from openhcs.core.source.source_metadata import SourceMetadataMapping +from openhcs.core.source.source_projection import SourceProjection @dataclass(frozen=True) diff --git a/openhcs/core/materialization/core.py b/openhcs/core/materialization/core.py index 3dfb601e3..2fd68f509 100644 --- a/openhcs/core/materialization/core.py +++ b/openhcs/core/materialization/core.py @@ -96,6 +96,11 @@ from openhcs.core.io.roi_point_metadata import ROIFractionalZ from openhcs.core.measurements.runtime_measurements import MeasurementTable from openhcs.core.measurements.measurement_row_materialization import MeasurementSparseColumnarRows, is_structural_missing_measurement_cell, ConcatenatedColumnarRows, MEASUREMENT_SPARSE_CELL +from openhcs.core.artifacts.plans import ArtifactOutputPlan +from openhcs.core.axes.axis_declarations import Axis +from openhcs.core.context.processing_context import ExecutingContext +from openhcs.core.dataset_sources.interfaces import FilenameParser +from openhcs.core.payload.runtime_tabular_values import MeasurementObjectRowIdentity logger = logging.getLogger(__name__) diff --git a/openhcs/core/materialization/options.py b/openhcs/core/materialization/options.py index c1d9bcd8e..34d5881d0 100644 --- a/openhcs/core/materialization/options.py +++ b/openhcs/core/materialization/options.py @@ -18,6 +18,7 @@ from openhcs.core.measurements.runtime_measurements import RuntimeMeasurementFeature from openhcs.core.materialization.path_scopes import SharedMaterializationRelativePathScope +from openhcs.core.materialization.path_scopes import MaterializationRelativePathScope class MaterializedFilenameIdentity(ABC, metaclass=AutoRegisterMeta): diff --git a/openhcs/core/measurements/measurement_feature_queries.py b/openhcs/core/measurements/measurement_feature_queries.py index 140b0d5ff..40acc3dfa 100644 --- a/openhcs/core/measurements/measurement_feature_queries.py +++ b/openhcs/core/measurements/measurement_feature_queries.py @@ -46,6 +46,7 @@ from openhcs.core.measurements.runtime_measurements import ( MeasurementTable, ) +from openhcs.core.measurements.measurement_dialect import MeasurementDialectLike MeasurementValueIndexResult = tuple[dict[int, float], list[float]] OptionalMeasurementValueIndexResult = MeasurementValueIndexResult | None diff --git a/openhcs/core/measurements/measurement_image_alignment.py b/openhcs/core/measurements/measurement_image_alignment.py index 1f8b3881b..f8778f8a5 100644 --- a/openhcs/core/measurements/measurement_image_alignment.py +++ b/openhcs/core/measurements/measurement_image_alignment.py @@ -21,6 +21,8 @@ from openhcs.core.source.source_spatial_domain import SourceSpatialDomainAdapter from openhcs.core.payload.runtime_image_values import ImagePayload, owned_runtime_value +from openhcs.core.object_labels.runtime_object_labels import ObjectLabelMeasurementSource +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxisProjector logger = logging.getLogger(__name__) diff --git a/openhcs/core/measurements/runtime_measurements.py b/openhcs/core/measurements/runtime_measurements.py index 75e37e01b..f7e560cad 100644 --- a/openhcs/core/measurements/runtime_measurements.py +++ b/openhcs/core/measurements/runtime_measurements.py @@ -33,6 +33,7 @@ from openhcs.core.payload.runtime_image_values import RuntimeSliceProjectionDeclarationError from openhcs.core.measurements.measurement_declarations import MeasurementScope, RuntimeMeasurementFeatureRelation, RuntimeMeasurementFeatureRelationDeclaration, RuntimeMeasurementFeatureSemanticMarker from openhcs.core.measurements.measurement_dialect import MeasurementDialect +from openhcs.core.axes.component_group_scope import RuntimeExecutionAxisScope @dataclass(kw_only=True) diff --git a/openhcs/core/object_labels/runtime_object_label_building.py b/openhcs/core/object_labels/runtime_object_label_building.py index f105bae56..86330dc22 100644 --- a/openhcs/core/object_labels/runtime_object_label_building.py +++ b/openhcs/core/object_labels/runtime_object_label_building.py @@ -15,6 +15,10 @@ from openhcs.core.source.source_spatial_domain import SourceSpatialDomain from openhcs.core.payload.runtime_array_values import array_geometry from openhcs.core.object_labels.label_declarations import ObjectLabelRepresentation +from openhcs.core.object_labels.runtime_object_label_domains import ObjectLabelDomainScope +from openhcs.core.object_labels.runtime_object_labels import ObjectLabelVariants +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxisValueProjection +from openhcs.core.source.source_metadata import SourceVoxelSpacing @dataclass(frozen=True) diff --git a/openhcs/core/object_labels/runtime_object_labels.py b/openhcs/core/object_labels/runtime_object_labels.py index c8aa564b6..25d9206c4 100644 --- a/openhcs/core/object_labels/runtime_object_labels.py +++ b/openhcs/core/object_labels/runtime_object_labels.py @@ -65,6 +65,8 @@ def _passthrough(func): from openhcs.core.memory import MemoryType, runtime_slice_stack_geometry, stack_runtime_slices from openhcs.core.payload.runtime_image_values import RuntimeSliceProjectionDeclarationError +from openhcs.core.artifacts.payloads import PayloadShape +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxis _PRESERVE_PLANE_AXIS = object() diff --git a/openhcs/core/object_labels/runtime_relationships.py b/openhcs/core/object_labels/runtime_relationships.py index 968d8b03e..78b604cd3 100644 --- a/openhcs/core/object_labels/runtime_relationships.py +++ b/openhcs/core/object_labels/runtime_relationships.py @@ -38,6 +38,8 @@ from openhcs.core.object_labels.runtime_object_labels import object_label_dense_array, object_label_storage_is_sparse_ijv, object_label_sparse_ijv_rows from openhcs.core.measurements.runtime_measurements import MeasurementRowAxisField from openhcs.core.source.source_image_provenance import SourceImageProvenance +from openhcs.core.artifacts.plans import ArtifactSpecRef +from openhcs.core.object_labels.runtime_object_labels import ObjectLabelMeasurementSource class DirectParentReferenceFeatureMarker(ObjectReferenceFeatureMarker): diff --git a/openhcs/core/orchestrator/bundle_execution.py b/openhcs/core/orchestrator/bundle_execution.py index 6f9110d9b..a7035d519 100644 --- a/openhcs/core/orchestrator/bundle_execution.py +++ b/openhcs/core/orchestrator/bundle_execution.py @@ -61,6 +61,10 @@ from openhcs.core.orchestrator.execution_result import RuntimeObservationMode from openhcs.core.orchestrator.worker_execution import PreparedForkWorkerLaneRunner from openhcs.core.progress.types import ProgressQueue +from openhcs.core.context.processing_context import CompiledContext +from openhcs.core.execution.compiled_execution import CompiledRuntimeEnvironmentPlan +from openhcs.core.steps.abstract import AbstractStep +from openhcs.runtime.viewer.viewer_contract_types import ViewerControlResponse, ViewerSettleProgress logger = logging.getLogger(__name__) diff --git a/openhcs/core/orchestrator/execution_result.py b/openhcs/core/orchestrator/execution_result.py index d38246752..d0a8f5e0a 100644 --- a/openhcs/core/orchestrator/execution_result.py +++ b/openhcs/core/orchestrator/execution_result.py @@ -19,6 +19,8 @@ from openhcs.core.progress.types import AxisErrorProgressPhase, CancelledProgressPhase, CancelledProgressStatus, ErrorProgressStatus from openhcs.core.artifact_store.runtime_stores import RuntimeArtifactQuery from openhcs.core.context.step_execution_observation import StepExecutionObservation +from openhcs.core.artifact_store.runtime_stores import StoredRuntimeValue +from openhcs.core.progress.types import ProgressPhase, ProgressStatus class RuntimeExecutionTransportSerialization: """Pickle reducers required for worker-to-parent execution results.""" diff --git a/openhcs/core/orchestrator/worker_execution.py b/openhcs/core/orchestrator/worker_execution.py index 52df42996..02a9e03bd 100644 --- a/openhcs/core/orchestrator/worker_execution.py +++ b/openhcs/core/orchestrator/worker_execution.py @@ -46,6 +46,11 @@ StepStartedProgressPhase, SuccessProgressStatus, ) +from openhcs.core.execution.compiled_execution import CompiledExecutionBundle +from openhcs.core.orchestrator.cancellation import ExecutionCancellationSignal +from openhcs.core.orchestrator.execution_result import RuntimeObservationMode +from openhcs.core.orchestrator.worker_lanes import WorkerLaneExecutionContext +from openhcs.core.progress.types import ProgressEvent logger = logging.getLogger(__name__) PIPELINE_PROGRESS_STEP_NAME = "pipeline" diff --git a/openhcs/core/orchestrator/worker_lanes.py b/openhcs/core/orchestrator/worker_lanes.py index 914f912b1..2553d97cd 100644 --- a/openhcs/core/orchestrator/worker_lanes.py +++ b/openhcs/core/orchestrator/worker_lanes.py @@ -12,6 +12,7 @@ from openhcs.core.debug.debug_runtime import DebugSinkInstallRequest from openhcs.core.progress.types import ProgressExecutionContext from openhcs.core.debug.debug_runtime import DebugExecutionPolicy +from openhcs.core.orchestrator.execution_result import RuntimeObservationMode TransportAxisContexts: TypeAlias = List[tuple[str, CompiledContext]] ForkAxisContextKeys: TypeAlias = List[str] diff --git a/openhcs/core/payload/aligned_image_payload.py b/openhcs/core/payload/aligned_image_payload.py index 64fdf5537..e85e80262 100644 --- a/openhcs/core/payload/aligned_image_payload.py +++ b/openhcs/core/payload/aligned_image_payload.py @@ -41,6 +41,8 @@ from openhcs.core.payload.runtime_slice_projection import RuntimeSliceProjection from openhcs.core.payload.runtime_slice_alignment import RuntimeSliceAlignedValues from openhcs.core.payload.runtime_image_values import RuntimeSliceProjectionDeclarationError +from openhcs.core.payload.runtime_array_values import RuntimeArrayData +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxis class ImagePayloadExecutionMode(ABC, metaclass=AutoRegisterMeta): diff --git a/openhcs/core/payload/payload_axes.py b/openhcs/core/payload/payload_axes.py index 04379f876..9a4105a60 100644 --- a/openhcs/core/payload/payload_axes.py +++ b/openhcs/core/payload/payload_axes.py @@ -21,6 +21,7 @@ from python_introspect import to_jsonable from openhcs.core.axes.axis_declarations import AxisFamily, AxisRole, ColourAxis +from openhcs.core.axes.axis_declarations import Axis class SpatialAxis(AxisRole): diff --git a/openhcs/core/payload/projected_image_output.py b/openhcs/core/payload/projected_image_output.py index cec39621e..c5dc68ef6 100644 --- a/openhcs/core/payload/projected_image_output.py +++ b/openhcs/core/payload/projected_image_output.py @@ -11,6 +11,7 @@ RuntimePlaneAxisValueProjection, RuntimeSliceInvariantValue, ) +from openhcs.core.payload.runtime_array_values import RuntimeArrayData class SourceProjectedImageOutput( diff --git a/openhcs/core/payload/runtime_image_loading.py b/openhcs/core/payload/runtime_image_loading.py index 0aa766eec..6dfc79347 100644 --- a/openhcs/core/payload/runtime_image_loading.py +++ b/openhcs/core/payload/runtime_image_loading.py @@ -20,6 +20,8 @@ from openhcs.core.source.source_image_provenance import SourceImageProvenancePlanes, SourcePlaneIndexedMetadata from openhcs.core.source.source_metadata import SourceVoxelSpacing from openhcs.core.source.source_spatial_domain import SourceSpatialDomain +from openhcs.core.payload.vfs_protocol import FileManagerLike +from openhcs.core.source.source_image_provenance import SourceImageIdentity @dataclass(frozen=True) diff --git a/openhcs/core/payload/runtime_image_values.py b/openhcs/core/payload/runtime_image_values.py index cf4bd1456..678df8bb0 100644 --- a/openhcs/core/payload/runtime_image_values.py +++ b/openhcs/core/payload/runtime_image_values.py @@ -51,6 +51,8 @@ ) from openhcs.core.axes.axis_declarations import AxisFamily, ColourAxis from openhcs.core.memory import MEMORY_TYPE_NUMPY, stack_runtime_slices +from openhcs.core.payload.runtime_array_values import RuntimeArrayData +from typing import ClassVar diff --git a/openhcs/core/payload/runtime_slice_projection.py b/openhcs/core/payload/runtime_slice_projection.py index 45e71297e..4099c8e02 100644 --- a/openhcs/core/payload/runtime_slice_projection.py +++ b/openhcs/core/payload/runtime_slice_projection.py @@ -21,6 +21,7 @@ from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxisValueProjection, RuntimeSliceProjectableValue from openhcs.core.payload.runtime_image_values import as_runtime_value +from openhcs.core.axes.axis_declarations import Axis def preserved_image_plane_projection( diff --git a/openhcs/core/payload/runtime_source_binding_cache.py b/openhcs/core/payload/runtime_source_binding_cache.py index 581789fdb..25f83fa2b 100644 --- a/openhcs/core/payload/runtime_source_binding_cache.py +++ b/openhcs/core/payload/runtime_source_binding_cache.py @@ -12,6 +12,10 @@ from openhcs.core.source.source_matching import source_component_metadata_items from openhcs.core.source.source_path_identity import source_path_identity_key from openhcs.core.source.source_binding_selection import DeclaredSourceMetadataRecord, SourceIdentityResolutionContext +from openhcs.core.axes.axis_declarations import Axis +from openhcs.core.source.source_binding_selection import SourceCandidatePathResolution, SourcePatternResolutionContext, SourceUniverseRuntimeState +from openhcs.core.source.source_metadata import MetadataExtractionRule, SourceMetadataMapping +from openhcs.core.source.source_workspace_projection import VirtualWorkspaceSourceProjection @dataclass(frozen=True) diff --git a/openhcs/core/payload/runtime_stack_cache.py b/openhcs/core/payload/runtime_stack_cache.py index d5157997b..74bc4b7b4 100644 --- a/openhcs/core/payload/runtime_stack_cache.py +++ b/openhcs/core/payload/runtime_stack_cache.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field +from openhcs.core.payload.runtime_array_values import RuntimeArrayData @dataclass(frozen=True) diff --git a/openhcs/core/pipeline/artifact_declarations.py b/openhcs/core/pipeline/artifact_declarations.py index 436387f6e..b421f4a4a 100644 --- a/openhcs/core/pipeline/artifact_declarations.py +++ b/openhcs/core/pipeline/artifact_declarations.py @@ -4,6 +4,8 @@ from typing import Optional from openhcs.core.callable.function_patterns import DEFAULT_GROUP_KEY +from openhcs.core.artifacts.specs import ArtifactSpec +from openhcs.core.callable.function_patterns import FunctionInvocationKey class MissingArtifactInputError(ValueError): diff --git a/openhcs/core/pipeline/artifact_planning.py b/openhcs/core/pipeline/artifact_planning.py index 74aae3383..72a6f4f93 100644 --- a/openhcs/core/pipeline/artifact_planning.py +++ b/openhcs/core/pipeline/artifact_planning.py @@ -43,6 +43,10 @@ from openhcs.core.callable.invocation_artifacts import ArtifactDeclarationStepContext from openhcs.core.callable.invocation_artifacts import CompositeInvocationContractProvider from openhcs.core.callable.invocation_artifacts import callable_contract_artifact_declarations +from openhcs.core.callable.function_patterns import FunctionInvocationKey, NormalizedFunctionPattern +from openhcs.core.callable.invocation_artifacts import InvocationContractPlan +from openhcs.core.util.artifact_key_selection import ArtifactPlanKeySelector +from openhcs.core.util.step_dependencies import StepInputDependency class AutomaticArtifactOutputMaterializationStrategy( diff --git a/openhcs/core/pipeline/compilation_session.py b/openhcs/core/pipeline/compilation_session.py index e31ad0d33..a63f39496 100644 --- a/openhcs/core/pipeline/compilation_session.py +++ b/openhcs/core/pipeline/compilation_session.py @@ -20,6 +20,13 @@ from openhcs.core.pipeline.artifact_planning import extract_artifact_declarations from openhcs.core.pipeline.funcstep_contract_validator import FuncStepContractValidator from openhcs.core.components.validation import GenericValidator +from openhcs.core.artifacts.plans import ArtifactSpecRef +from openhcs.core.callable.invocation_artifacts import InvocationArtifactDeclarationProviderLike +from openhcs.core.config.pipeline_config import GlobalPipelineConfig +from openhcs.core.context.processing_context import CompilingContext +from openhcs.core.execution.compiled_step_plan import CompiledStepPlan +from openhcs.core.payload.vfs_protocol import FileManagerLike +from openhcs.core.steps.abstract import AbstractStep @dataclass(frozen=True) diff --git a/openhcs/core/pipeline/compiler.py b/openhcs/core/pipeline/compiler.py index 63160e0c4..d5264a2a6 100644 --- a/openhcs/core/pipeline/compiler.py +++ b/openhcs/core/pipeline/compiler.py @@ -84,6 +84,9 @@ ) from openhcs.core.dataset_sources.openhcs_format import OpenHCSMetadataHandler from openhcs.core.debug.debug_runtime import NoOpDebugExecutionPolicy +from openhcs.core.axes.axis_filter import StepAxisFilterMap +from openhcs.core.config.pipeline_config import GlobalPipelineConfig +from openhcs.core.source.source_workspace_projection import VirtualWorkspaceSourceProjection logger = logging.getLogger(__name__) diff --git a/openhcs/core/pipeline/materialization_flag_planner.py b/openhcs/core/pipeline/materialization_flag_planner.py index f24ecb0fd..a1bb690b0 100644 --- a/openhcs/core/pipeline/materialization_flag_planner.py +++ b/openhcs/core/pipeline/materialization_flag_planner.py @@ -14,6 +14,9 @@ from openhcs.constants.constants import Backend from openhcs.core.config.partition_filter import PartitionFilterProcessor +from openhcs.core.config.pipeline_config import GlobalPipelineConfig +from openhcs.core.dataset_sources.source import DatasetSource +from openhcs.core.payload.vfs_protocol import FileManagerLike logger = logging.getLogger(__name__) diff --git a/openhcs/core/pipeline/path_planner.py b/openhcs/core/pipeline/path_planner.py index caaaf5fd4..7d992833c 100644 --- a/openhcs/core/pipeline/path_planner.py +++ b/openhcs/core/pipeline/path_planner.py @@ -54,6 +54,7 @@ from openhcs.core.pipeline.artifact_planning import ArtifactGraph from openhcs.core.artifacts.specs import ArtifactSpecCollection from openhcs.core.config.pipeline_config import EMPTY_SOURCE_BINDINGS +from openhcs.core.axes.axis_declarations import Axis logger = logging.getLogger(__name__) diff --git a/openhcs/core/plate/plate_image_inventory.py b/openhcs/core/plate/plate_image_inventory.py index 3a09785a7..3d1fe6ed6 100644 --- a/openhcs/core/plate/plate_image_inventory.py +++ b/openhcs/core/plate/plate_image_inventory.py @@ -29,6 +29,7 @@ import openhcs.core.util.numpy_jsonable # noqa: F401 (numpy values in to_jsonable) from openhcs.core.source.workspace_path_lookup import VirtualWorkspacePathLookup +from openhcs.core.source.source_projection import SourceProjection JsonLike = str | int | float | bool | None diff --git a/openhcs/core/progress/debug_projection.py b/openhcs/core/progress/debug_projection.py index 4e3024525..955b05f90 100644 --- a/openhcs/core/progress/debug_projection.py +++ b/openhcs/core/progress/debug_projection.py @@ -13,6 +13,8 @@ ExecutionRuntimeProjection, build_execution_runtime_projection, ) +from openhcs.core.debug.debug_runtime import DebugSession, DebugSnapshot, DebugTerminalSummary +from openhcs.core.progress.types import ProgressEvent @dataclass(frozen=True) diff --git a/openhcs/core/progress/live_measurements.py b/openhcs/core/progress/live_measurements.py index 7f5449580..32289d996 100644 --- a/openhcs/core/progress/live_measurements.py +++ b/openhcs/core/progress/live_measurements.py @@ -22,6 +22,7 @@ from openhcs.core.measurements.runtime_measurements import ( MeasurementTable, ) +from openhcs.core.artifact_store.runtime_stores import RuntimeArtifactLocation DEFAULT_LIVE_MEASUREMENT_ROW_LIMIT = 50 DEFAULT_LIVE_MEASUREMENT_COLUMN_LIMIT = 64 diff --git a/openhcs/core/progress/runtime_tree.py b/openhcs/core/progress/runtime_tree.py index 55e083d8d..0e8529e62 100644 --- a/openhcs/core/progress/runtime_tree.py +++ b/openhcs/core/progress/runtime_tree.py @@ -20,6 +20,8 @@ PipelineProgressStream, StepProgressStream, ) +from openhcs.core.progress.projection import ExecutionRuntimeProjection, SubjectRuntimeState +from openhcs.core.progress.types import ProgressEvent @dataclass(frozen=True) diff --git a/openhcs/core/source/source_binding_context.py b/openhcs/core/source/source_binding_context.py index 66b1ef999..42bac0229 100644 --- a/openhcs/core/source/source_binding_context.py +++ b/openhcs/core/source/source_binding_context.py @@ -8,6 +8,7 @@ from openhcs.core.config.pipeline_config import SourceBindingsConfig, StepSourceBindingsConfig from openhcs.core.source.source_bindings_preview import SourceInventory from openhcs.core.config.pipeline_config import EMPTY_SOURCE_BINDINGS +from openhcs.core.payload.vfs_protocol import FileManagerLike @dataclass(frozen=True) diff --git a/openhcs/core/source/source_binding_selection.py b/openhcs/core/source/source_binding_selection.py index 1d32ae950..a7b0788fe 100644 --- a/openhcs/core/source/source_binding_selection.py +++ b/openhcs/core/source/source_binding_selection.py @@ -34,6 +34,12 @@ from openhcs.core.execution.compiled_step_plan import CompiledStepPlan from openhcs.core.payload.runtime_image_values import ImagePayload from openhcs.core.payload.runtime_image_values import as_runtime_value +from openhcs.core.dataset_sources.interfaces import FilenameParser +from openhcs.core.source.source_bindings import NamedSourceBinding, SourceBindingOrigin, SourceSetPairing +from openhcs.core.source.source_matching import SourceImageSetIdentityPolicy +from openhcs.core.source.source_metadata import MetadataExtractionRule, SourceMetadataMapping +from openhcs.core.source.source_projection import SourceProjection +from openhcs.core.source.source_workspace_projection import VirtualWorkspaceSourceProjection SourceCandidatePath = str diff --git a/openhcs/core/source/source_binding_workspace.py b/openhcs/core/source/source_binding_workspace.py index c2e23a25f..169df6e8e 100644 --- a/openhcs/core/source/source_binding_workspace.py +++ b/openhcs/core/source/source_binding_workspace.py @@ -43,6 +43,8 @@ from openhcs.core.dataset_sources.plane_stores import SourceMetadataEnricher from openhcs.core.dataset_sources.source import DeclaredFileSource from openhcs.core.source.workspace_path_lookup import VirtualWorkspacePathLookup +from openhcs.core.source.source_bindings import ImportedMetadataTable +from openhcs.core.source.source_metadata import SourceMetadataMapping, SourceMetadataScalar @dataclass(frozen=True) diff --git a/openhcs/core/source/source_bindings.py b/openhcs/core/source/source_bindings.py index 4c309346c..86378f4d9 100644 --- a/openhcs/core/source/source_bindings.py +++ b/openhcs/core/source/source_bindings.py @@ -35,6 +35,7 @@ from openhcs.core.axes.axis_declarations import ColourAxis from openhcs.core.payload.payload_axes import PayloadAxes from openhcs.core.payload.runtime_image_values import ImagePayload, ImageUnitIntervalIntensityMetadata +from openhcs.core.source.source_metadata import SourceMetadataMapping, SourceMetadataScalar SOURCE_BINDING_ALIAS_METADATA_FIELD = "source_alias" diff --git a/openhcs/core/source/source_bindings_preview.py b/openhcs/core/source/source_bindings_preview.py index 93df5beb9..abc0b4257 100644 --- a/openhcs/core/source/source_bindings_preview.py +++ b/openhcs/core/source/source_bindings_preview.py @@ -9,6 +9,7 @@ from openhcs.core.source.source_binding_workspace import SourceSetAssembler, SourceBindingWorkspaceProjector, SourceCandidate from openhcs.core.source.source_bindings import NamedSourceBinding from openhcs.core.config.pipeline_config import EMPTY_SOURCE_BINDINGS +from openhcs.core.source.source_metadata import SourceMetadataValue def _active_source_bindings( diff --git a/openhcs/core/source/source_matching.py b/openhcs/core/source/source_matching.py index 9787e92a0..6980eefcf 100644 --- a/openhcs/core/source/source_matching.py +++ b/openhcs/core/source/source_matching.py @@ -13,6 +13,7 @@ from openhcs.core.source.source_metadata import DECLARED_SOURCE_METADATA_FIELD, SOURCE_FILTER_PATHS_METADATA_FIELD, DeclaredSourceMetadata, SourceFilterPathMetadata, SourceMetadataFields, SourceMetadataMapping, SourceMetadataScalar, normalized_path_metadata_value, source_metadata_component, source_metadata_dict, source_metadata_field_identity, source_metadata_scalar from openhcs.core.source.source_path_identity import source_path_identity_key from openhcs.core.axes.axis_declarations import AxisFamily +from openhcs.core.axes.axis_declarations import Axis def metadata_from_rules( diff --git a/openhcs/core/source/source_metadata.py b/openhcs/core/source/source_metadata.py index eac48a5da..04a090ad8 100644 --- a/openhcs/core/source/source_metadata.py +++ b/openhcs/core/source/source_metadata.py @@ -27,6 +27,7 @@ from openhcs.core.source.source_path_identity import source_path_identity_key from openhcs.core.axes.axis_declarations import AxisFamily, ColourAxis, PartitionAxis, StackAxis from openhcs.core.source.common_runtime_value import CommonRuntimeValue +from openhcs.core.axes.axis_declarations import Axis SourceBindingValue = TypeVar("SourceBindingValue") diff --git a/openhcs/core/source/source_plane_alignment.py b/openhcs/core/source/source_plane_alignment.py index 4237240d3..f328ac47a 100644 --- a/openhcs/core/source/source_plane_alignment.py +++ b/openhcs/core/source/source_plane_alignment.py @@ -6,6 +6,7 @@ from typing import ClassVar from openhcs.core.source.source_matching import SourceImageSetIdentity, SourceImageSetIdentityCompatibility +from openhcs.core.source.source_matching import SourceImageSetIdentityPairPredicate SourcePlaneIdentitySequence = tuple[frozenset[SourceImageSetIdentity], ...] diff --git a/openhcs/core/source/source_projection.py b/openhcs/core/source/source_projection.py index ff5dfe878..6b766c925 100644 --- a/openhcs/core/source/source_projection.py +++ b/openhcs/core/source/source_projection.py @@ -23,6 +23,9 @@ from python_introspect import to_jsonable from openhcs.core.source.source_path_identity import absolute_source_path, source_path_posix from openhcs.core.axes.axis_declarations import AxisFamily, PartitionAxis, StackAxis, TileAxis +from openhcs.core.axes.component_group_scope import RuntimeExecutionAxisScope +from openhcs.core.source.source_bindings import SourceProjectionRole +from openhcs.core.source.source_metadata import SourceMetadataMapping class SourceDatasetConflictError(ValueError): diff --git a/openhcs/core/source/source_workspace_projection.py b/openhcs/core/source/source_workspace_projection.py index 743cb0223..69b027ba4 100644 --- a/openhcs/core/source/source_workspace_projection.py +++ b/openhcs/core/source/source_workspace_projection.py @@ -35,6 +35,12 @@ from openhcs.core.source.workspace_path_lookup import VirtualWorkspacePathLookup +from openhcs.core.config.pipeline_config import SourceBindingsConfig +from openhcs.core.io.virtual_workspace_metadata import OpenHCSMetadataPayload +from openhcs.core.payload.runtime_image_values import ImagePayloadMetadata +from openhcs.core.source.source_metadata import SourceFilterClause, SourceMetadataMapping +from openhcs.core.source.source_projection import SourceProjection +from polystore.filemanager import FileManager LookupValueT = TypeVar("LookupValueT") diff --git a/openhcs/core/steps/function_artifact_materialization.py b/openhcs/core/steps/function_artifact_materialization.py index e80a51557..0cb03fe72 100644 --- a/openhcs/core/steps/function_artifact_materialization.py +++ b/openhcs/core/steps/function_artifact_materialization.py @@ -42,6 +42,9 @@ from openhcs.core.materialization.core import BackendKwargsAuthority, MaterializationSpec, SavedMaterializationOutputs, RawBackendKwargs, ViewerStreamBackendCallKwargs, materialization_outputs, prepare_materialization from openhcs.core.axes.axis_declarations import AxisFamily, PartitionAxis from openhcs.core.payload.runtime_image_values import as_runtime_value +from openhcs.core.artifact_store.runtime_stores import StoredRuntimeValue +from openhcs.core.artifacts.plans import ArtifactOutputPlan +from openhcs.core.materialization.core import MaterializationValue logger = logging.getLogger(__name__) diff --git a/openhcs/core/steps/function_output_identity.py b/openhcs/core/steps/function_output_identity.py index 2302d2906..566d3cbab 100644 --- a/openhcs/core/steps/function_output_identity.py +++ b/openhcs/core/steps/function_output_identity.py @@ -17,6 +17,10 @@ ) from openhcs.core.source.source_projection import OpenHCSPlaneAddress from openhcs.core.axes.axis_declarations import AxisFamily +from openhcs.core.axes.axis_declarations import Axis +from openhcs.core.dataset_sources.interfaces import FilenameParser +from openhcs.core.payload.runtime_array_values import RuntimeArrayData +from openhcs.core.source.source_image_provenance import SourceImageProvenanceIdentity ParsedFilenameValue: TypeAlias = str | int | float | bool | None FunctionOutputComponentValue: TypeAlias = str | int diff --git a/openhcs/core/steps/function_output_manifest.py b/openhcs/core/steps/function_output_manifest.py index 2105cedc7..af7a11a60 100644 --- a/openhcs/core/steps/function_output_manifest.py +++ b/openhcs/core/steps/function_output_manifest.py @@ -30,6 +30,8 @@ ) from openhcs.core.axes.axis_declarations import AxisFamily, PartitionAxis from openhcs.core.payload.runtime_image_values import ImagePayload +from openhcs.core.payload.runtime_image_values import ImagePayloadMetadata +from openhcs.core.payload.runtime_plane_projection import RuntimePlaneAxis @dataclass(frozen=True) diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index 46e372402..909339d09 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -55,6 +55,8 @@ ) from openhcs.core.io.virtual_workspace_metadata import METADATA_CONFIG, AtomicMetadataWriter, VirtualWorkspaceSourceProjectionEntries from openhcs.core.dataset_sources.openhcs_format import OpenHCSMetadataHandler +from openhcs.core.payload.runtime_slice_projection import RuntimeProjectedPayloadItem +from openhcs.core.steps.function_artifact_materialization import MaterializedRuntimeArtifact logger = logging.getLogger(__name__) diff --git a/openhcs/core/steps/function_runtime.py b/openhcs/core/steps/function_runtime.py index bc16c5dc4..badf769d8 100644 --- a/openhcs/core/steps/function_runtime.py +++ b/openhcs/core/steps/function_runtime.py @@ -112,6 +112,9 @@ BeforeInvocationDebugBoundary, ExceptionDebugBoundary, ) +from openhcs.core.axes.component_group_scope import RuntimeFixedComponentValues +from openhcs.core.callable.function_patterns import CompiledFunctionGroup, CompiledFunctionInvocation +from openhcs.core.execution.compiled_step_plan import CompiledStepPlan logger = logging.getLogger(__name__) diff --git a/openhcs/core/steps/stream_component_semantics.py b/openhcs/core/steps/stream_component_semantics.py index f6bf61293..a628551af 100644 --- a/openhcs/core/steps/stream_component_semantics.py +++ b/openhcs/core/steps/stream_component_semantics.py @@ -49,6 +49,7 @@ ) from openhcs.core.axes.axis_declarations import AxisFamily from openhcs.core.axes.axis_declarations import ColourAxis +from openhcs.core.config.streaming_config_factory import StreamingViewerSurface StreamComponentMetadata = SourceComponentMetadata | None ComponentDisplayName: TypeAlias = str | int | float | bool | None diff --git a/openhcs/core/util/artifact_inspection.py b/openhcs/core/util/artifact_inspection.py index e529d2bc4..a2499978c 100644 --- a/openhcs/core/util/artifact_inspection.py +++ b/openhcs/core/util/artifact_inspection.py @@ -7,6 +7,9 @@ from typing import Any, ClassVar from zmqruntime.messages import TypedWireMessage +from openhcs.core.artifacts.plans import ArtifactInputPlan, ArtifactOutputPlan +from openhcs.core.artifacts.specs import ArtifactSpec +from openhcs.core.callable.function_patterns import FunctionInvocationKey, InvocationArtifactInputEdgePlan @dataclass(frozen=True) From eb5ce533548423981afc44c3a33e83562a7b619d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:38:54 +0000 Subject: [PATCH 15/27] Port to the siblings' current mains: bundled copies moved forward, the planner speaks arraybridge devices Work in progress. OpenHCS dropped the caps on its sibling packages on 16 November and never followed them: arraybridge 0.5 removed MEMORY_TYPE_*, the CPU/GPU sets, array_operations and integer gpu ids. This moves the bundled copies under external/ to each sibling's latest main and ports the first two owners: - FrameworkDeviceAssignment.device_for answers an arraybridge Device (main memory for a library with no accelerators); a binding keeps its integer index and says its device. - A compiled invocation carries input_device and execution_device. Not yet ported: the payload module, the processors' ArrayOperations, constants re-exports, the objectstate, ui-theme and pyqt-reactive names. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- external/ObjectState | 2 +- external/PolyStore | 2 +- external/arraybridge | 2 +- external/formbridge | 2 +- external/metaclass-registry | 2 +- external/pyqt-reactive | 2 +- external/python-introspect | 2 +- external/zmqruntime | 2 +- openhcs/core/callable/function_patterns.py | 30 ++++++++------- openhcs/core/execution/compiled_step_plan.py | 39 ++++++++++++-------- 10 files changed, 48 insertions(+), 37 deletions(-) diff --git a/external/ObjectState b/external/ObjectState index 01f3a5dc0..fec9de1f9 160000 --- a/external/ObjectState +++ b/external/ObjectState @@ -1 +1 @@ -Subproject commit 01f3a5dc03dc466fd205d6d1a288e8ba6270665b +Subproject commit fec9de1f9cf754c0a85de9d8161f9d9a2b22fca2 diff --git a/external/PolyStore b/external/PolyStore index d9aed3787..3e85a574a 160000 --- a/external/PolyStore +++ b/external/PolyStore @@ -1 +1 @@ -Subproject commit d9aed378736bee67cbcba75cb66c0a25074b876a +Subproject commit 3e85a574a09daa11a5c9b75efa3ec3a28ddaf9fb diff --git a/external/arraybridge b/external/arraybridge index f614ab9bb..c44c93321 160000 --- a/external/arraybridge +++ b/external/arraybridge @@ -1 +1 @@ -Subproject commit f614ab9bbe8a7fb8372e548e57f0d42896bdeb2c +Subproject commit c44c93321883a375d907968c56ad6945e120fbdb diff --git a/external/formbridge b/external/formbridge index d92abbe6f..408a00f8d 160000 --- a/external/formbridge +++ b/external/formbridge @@ -1 +1 @@ -Subproject commit d92abbe6f8c34b300d4faf396c3c2c14a2381dd9 +Subproject commit 408a00f8dd105a53aa9b22a6e3219e74a487e600 diff --git a/external/metaclass-registry b/external/metaclass-registry index 957470c94..5cbe4e7d0 160000 --- a/external/metaclass-registry +++ b/external/metaclass-registry @@ -1 +1 @@ -Subproject commit 957470c948a234ece464c1877fe14dbfd17188b3 +Subproject commit 5cbe4e7d05e3579d043b6658ea119bef52098151 diff --git a/external/pyqt-reactive b/external/pyqt-reactive index 28b3a699e..d87900bde 160000 --- a/external/pyqt-reactive +++ b/external/pyqt-reactive @@ -1 +1 @@ -Subproject commit 28b3a699e99262005b3e2fdbf7a133de9893fd5b +Subproject commit d87900bdea7f91df4ae01c704519803f8b69788d diff --git a/external/python-introspect b/external/python-introspect index a88fe56f7..3a5c72ba8 160000 --- a/external/python-introspect +++ b/external/python-introspect @@ -1 +1 @@ -Subproject commit a88fe56f78b523ad5c791e3f868bb35d7d6b3f12 +Subproject commit 3a5c72ba8d74260f5e15d3d4223f16e685a1d7e6 diff --git a/external/zmqruntime b/external/zmqruntime index 1d8160b2d..54afa6a3f 160000 --- a/external/zmqruntime +++ b/external/zmqruntime @@ -1 +1 @@ -Subproject commit 1d8160b2d3ecd35d7da82648cc38c5a3fa64435d +Subproject commit 54afa6a3f3e151562ea011cf9e83132a5387c0f4 diff --git a/openhcs/core/callable/function_patterns.py b/openhcs/core/callable/function_patterns.py index b2cdfd741..12a0e868e 100644 --- a/openhcs/core/callable/function_patterns.py +++ b/openhcs/core/callable/function_patterns.py @@ -19,6 +19,8 @@ from arraybridge import MemoryType +from arraybridge.devices import HOST, Device +from arraybridge.libraries import AcceleratorDevices from formbridge.pattern_metadata import PatternScopeToken from python_introspect import Enableable @@ -481,8 +483,8 @@ class CompiledFunctionInvocation(NormalizedFunctionItem): artifact_output_plans: tuple[ArtifactOutputPlan, ...] = () artifact_input_edges: tuple[InvocationArtifactInputEdgePlan, ...] = () runtime_parameter_bindings: tuple[RuntimeParameterBinding, ...] = () - input_device_id: int | None = None - execution_device_id: int | None = None + input_device: Device = HOST + execution_device: Device | None = None runtime_callable: Callable = field( init=False, repr=False, @@ -621,17 +623,17 @@ def with_device_assignment( ) -> CompiledFunctionInvocation: """Bind this immutable invocation at the compiler's placement boundary.""" if self.contract.execution_scope is FunctionStepExecutionScope.PLATE: - input_device_id = None + input_device = HOST else: input_memory_type, _ = self.contract.require_memory_types() - input_device_id = assignment.device_id_for(MemoryType(input_memory_type)) + input_device = assignment.device_for(MemoryType(input_memory_type)) return replace( self, - input_device_id=input_device_id, - execution_device_id=( + input_device=input_device, + execution_device=( None if self._execution_memory_type is None - else assignment.device_id_for(self._execution_memory_type) + else assignment.device_for(self._execution_memory_type) ), ) @@ -648,17 +650,17 @@ def convert_input(self, payload: object, source_memory_type: str) -> object: if isinstance(payload, ImagePayloadStackComposition): return payload.compose( memory_type=self._input_memory_type.value, - device_id=self.input_device_id, + device=self.input_device, ) source = MemoryType(source_memory_type) - if source is self._input_memory_type and not source.is_gpu: + if source is self._input_memory_type and not isinstance(source.library, AcceleratorDevices): mask = payload.mask if project_image_mask_to_data_domain( mask, payload, metadata=payload.metadata ) is mask: return payload - return payload.with_pixels(source.convert_to( - payload.data, self._input_memory_type, self.input_device_id + return payload.with_pixels(source.library.convert_to( + payload.data, self._input_memory_type.library, self.input_device ),) def main_flow_call_argument(self, source_payload: object) -> object: @@ -676,13 +678,13 @@ def main_flow_output_source_payload(self, source_payload: object) -> object: def execution_device_scope(self) -> AbstractContextManager[None]: """Enter the fixed device while retaining a fresh per-call scope lifetime.""" memory_type = self._execution_memory_type - if memory_type is None or not memory_type.is_gpu: + if memory_type is None or not isinstance(memory_type.library, AcceleratorDevices): return nullcontext() - if self.execution_device_id is None: + if self.execution_device is None: raise ValueError( f"No compiled device assignment exists for {memory_type.value!r}." ) - return memory_type.device_scope(self.execution_device_id) + return memory_type.library.device_scope(self.execution_device) @property def input_memory_type(self) -> str | None: diff --git a/openhcs/core/execution/compiled_step_plan.py b/openhcs/core/execution/compiled_step_plan.py index b3a897c34..d8ed12ec7 100644 --- a/openhcs/core/execution/compiled_step_plan.py +++ b/openhcs/core/execution/compiled_step_plan.py @@ -10,7 +10,10 @@ from polystore.streaming.identity import StreamProducerIdentity -from openhcs.constants.constants import Backend, GPU_MEMORY_TYPES, MemoryType +from arraybridge.devices import HOST, AcceleratorDevice, Device +from arraybridge.libraries import AcceleratorDevices + +from openhcs.constants.constants import Backend, MemoryType from openhcs.core.artifacts.plans import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -37,7 +40,7 @@ class FrameworkDeviceBinding: device_id: int def __post_init__(self) -> None: - if self.memory_type not in GPU_MEMORY_TYPES: + if not isinstance(self.memory_type.library, AcceleratorDevices): raise ValueError( "FrameworkDeviceBinding requires a GPU memory declaration, got " f"{self.memory_type.value!r}." @@ -47,6 +50,12 @@ def __post_init__(self) -> None: "FrameworkDeviceBinding.device_id must be a non-negative integer." ) + @property + def device(self) -> AcceleratorDevice: + """The accelerator this binding names, as its library counts them.""" + + return AcceleratorDevice(self.device_id) + @dataclass(frozen=True) class FrameworkDeviceAssignment: @@ -114,14 +123,14 @@ def select( ) return type(self)(selected) - def device_id_for(self, memory_type: MemoryType) -> int | None: - """Return the declared local device, or ``None`` for CPU memory.""" + def device_for(self, memory_type: MemoryType) -> Device: + """Return the declared local device; main memory for a library with no accelerators.""" - if memory_type not in GPU_MEMORY_TYPES: - return None + if not isinstance(memory_type.library, AcceleratorDevices): + return HOST for binding in self.bindings: if binding.memory_type is memory_type: - return binding.device_id + return binding.device raise ValueError( f"No compiled device assignment exists for {memory_type.value!r}." ) @@ -135,10 +144,10 @@ def scope_for( if declaration is None: return nullcontext() memory_type = MemoryType(declaration) - device_id = self.device_id_for(memory_type) - if device_id is None: + device = self.device_for(memory_type) + if device == HOST: return nullcontext() - return memory_type.device_scope(device_id) + return memory_type.library.device_scope(device) def cleanup_loaded(self) -> None: """Release loaded allocators in this exact compiled footprint.""" @@ -146,7 +155,7 @@ def cleanup_loaded(self) -> None: failures: list[Exception] = [] for binding in self.bindings: try: - binding.memory_type.cleanup_loaded(binding.device_id) + binding.memory_type.library.cleanup_loaded(binding.device) except Exception as error: error.add_note( f"Cleanup failed for {binding.memory_type.value!r} " @@ -517,7 +526,7 @@ def gpu_memory_types(self) -> frozenset[MemoryType]: return frozenset( memory_type for memory_type in memory_types - if memory_type in GPU_MEMORY_TYPES + if isinstance(memory_type.library, AcceleratorDevices) ) @property @@ -526,12 +535,12 @@ def requires_gpu(self) -> bool: return bool(self.gpu_memory_types) - def device_id_for(self, declaration: str | None) -> int | None: + def device_for(self, declaration: str | None) -> Device: """Return the compiled framework-local device for one declaration.""" if declaration is None: - return None - return self.device_assignment.device_id_for(MemoryType(declaration)) + return HOST + return self.device_assignment.device_for(MemoryType(declaration)) def memory_device_scope( self, From a6ee961da8fcf6c12430268dd91c8e1cdd9fe1d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:41:41 +0000 Subject: [PATCH 16/27] Payloads, processors, constants and the device resolver speak arraybridge 0.5 Every call OpenHCS made on a MemoryType goes to its library; integer gpu ids that crossed into arraybridge are Device values (main memory is HOST); the removed MEMORY_TYPE_* and CPU/GPU sets are gone from openhcs.constants, with their four users asking MemoryType or the library; the processors take an ArrayLibrary where they took ArrayOperations. Work in progress: not yet run. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- openhcs/constants/__init__.py | 22 ---- openhcs/constants/constants.py | 33 ------ openhcs/core/artifacts/kinds.py | 2 - openhcs/core/equivalence/arrays.py | 12 +- openhcs/core/memory/__init__.py | 32 ++---- openhcs/core/payload/aligned_image_payload.py | 105 +++++++++--------- .../core/payload/image_file_serialization.py | 2 +- openhcs/core/payload/runtime_image_values.py | 47 ++++---- openhcs/core/steps/function_runtime.py | 6 +- .../core/util/framework_device_resolver.py | 10 +- openhcs/core/util/lazy_gpu_imports.py | 6 +- .../runtime/function_contract_execution.py | 6 +- .../backends/analysis/cell_counting_cupy.py | 12 +- .../backends/lib_registry/openhcs_registry.py | 9 +- .../backends/lib_registry/registry_service.py | 4 +- .../backends/processors/__init__.py | 2 +- .../backends/processors/cupy_processor.py | 6 +- .../processors/image_stack_operations.py | 54 ++++----- .../backends/processors/jax_processor.py | 4 +- .../backends/processors/numpy_processor.py | 4 +- .../processors/pyclesperanto_processor.py | 4 +- .../processors/tensorflow_processor.py | 4 +- .../backends/processors/torch_processor.py | 4 +- openhcs/runtime/zmq/zmq_execution_client.py | 4 +- 24 files changed, 163 insertions(+), 231 deletions(-) diff --git a/openhcs/constants/__init__.py b/openhcs/constants/__init__.py index 807e06988..7b4f4562a 100644 --- a/openhcs/constants/__init__.py +++ b/openhcs/constants/__init__.py @@ -8,24 +8,13 @@ # These imports are re-exported through __all__ from openhcs.constants.constants import ( # Backend constants; Memory constants; I/O constants; Pipeline constants; Default constants - CPU_MEMORY_TYPES, DEFAULT_BACKEND, DEFAULT_IMAGE_EXTENSIONS, LOADABLE_IMAGE_EXTENSIONS, FORCE_DISK_WRITE, - GPU_MEMORY_TYPES, - MEMORY_TYPE_CUPY, - MEMORY_TYPE_JAX, - MEMORY_TYPE_NUMPY, - MEMORY_TYPE_PYCLESPERANTO, - MEMORY_TYPE_TENSORFLOW, - MEMORY_TYPE_TORCH, READ_BACKEND, REQUIRES_DISK_READ, REQUIRES_DISK_WRITE, - SUPPORTED_MEMORY_TYPES, - VALID_GPU_MEMORY_TYPES, - VALID_MEMORY_TYPES, WRITE_BACKEND, Backend, MemoryType, @@ -42,17 +31,6 @@ "WRITE_BACKEND", # Memory "MemoryType", - "CPU_MEMORY_TYPES", - "GPU_MEMORY_TYPES", - "SUPPORTED_MEMORY_TYPES", - "MEMORY_TYPE_NUMPY", - "MEMORY_TYPE_CUPY", - "MEMORY_TYPE_TORCH", - "MEMORY_TYPE_TENSORFLOW", - "MEMORY_TYPE_JAX", - "MEMORY_TYPE_PYCLESPERANTO", - "VALID_MEMORY_TYPES", - "VALID_GPU_MEMORY_TYPES", # I/O "DEFAULT_IMAGE_EXTENSIONS", "LOADABLE_IMAGE_EXTENSIONS", diff --git a/openhcs/constants/constants.py b/openhcs/constants/constants.py index d9abf4c76..eba6253db 100644 --- a/openhcs/constants/constants.py +++ b/openhcs/constants/constants.py @@ -12,39 +12,6 @@ from metaclass_registry import AutoRegisterMeta -from arraybridge.types import ( - CPU_MEMORY_TYPES as CPU_MEMORY_TYPES, -) -from arraybridge.types import ( - GPU_MEMORY_TYPES as GPU_MEMORY_TYPES, -) -from arraybridge.types import ( - MEMORY_TYPE_CUPY as MEMORY_TYPE_CUPY, -) -from arraybridge.types import ( - MEMORY_TYPE_JAX as MEMORY_TYPE_JAX, -) -from arraybridge.types import ( - MEMORY_TYPE_NUMPY as MEMORY_TYPE_NUMPY, -) -from arraybridge.types import ( - MEMORY_TYPE_PYCLESPERANTO as MEMORY_TYPE_PYCLESPERANTO, -) -from arraybridge.types import ( - MEMORY_TYPE_TENSORFLOW as MEMORY_TYPE_TENSORFLOW, -) -from arraybridge.types import ( - MEMORY_TYPE_TORCH as MEMORY_TYPE_TORCH, -) -from arraybridge.types import ( - SUPPORTED_MEMORY_TYPES as SUPPORTED_MEMORY_TYPES, -) -from arraybridge.types import ( - VALID_GPU_MEMORY_TYPES as VALID_GPU_MEMORY_TYPES, -) -from arraybridge.types import ( - VALID_MEMORY_TYPES as VALID_MEMORY_TYPES, -) from arraybridge.types import ( MemoryType as MemoryType, ) diff --git a/openhcs/core/artifacts/kinds.py b/openhcs/core/artifacts/kinds.py index 4f629dcb9..9492ce226 100644 --- a/openhcs/core/artifacts/kinds.py +++ b/openhcs/core/artifacts/kinds.py @@ -861,8 +861,6 @@ def _stack_runtime_values( return stack_image_payloads( payloads, - memory_type=detect_memory_type(payloads[0].data), - device_id=0, metadata_mode=metadata_mode, ) diff --git a/openhcs/core/equivalence/arrays.py b/openhcs/core/equivalence/arrays.py index 9a1502315..e9c12b140 100644 --- a/openhcs/core/equivalence/arrays.py +++ b/openhcs/core/equivalence/arrays.py @@ -6,11 +6,9 @@ import numpy as np -from openhcs.core.memory import ( - MEMORY_TYPE_NUMPY, - convert_memory, - detect_memory_type, -) +from arraybridge.devices import HOST + +from openhcs.core.memory import MemoryType, convert_memory, detect_memory_type def array_memory_type(value: object) -> str | None: @@ -28,8 +26,8 @@ def canonical_numpy_array(value: object) -> np.ndarray | None: return None array = ( value - if source_type == MEMORY_TYPE_NUMPY - else convert_memory(value, source_type, MEMORY_TYPE_NUMPY, 0) + if source_type == MemoryType.NUMPY.value + else convert_memory(value, source_type, MemoryType.NUMPY.value, HOST) ) return np.ascontiguousarray(array) diff --git a/openhcs/core/memory/__init__.py b/openhcs/core/memory/__init__.py index 56f28d1c1..691335557 100644 --- a/openhcs/core/memory/__init__.py +++ b/openhcs/core/memory/__init__.py @@ -8,6 +8,7 @@ from typing import Any from arraybridge import ArrayGeometry +from arraybridge.devices import Device # Re-export from arraybridge from arraybridge import ( @@ -22,15 +23,7 @@ # Exceptions MemoryConversionError, ) -from arraybridge.types import ( - MEMORY_TYPE_CUPY, - MEMORY_TYPE_JAX, - MEMORY_TYPE_NUMPY, - MEMORY_TYPE_PYCLESPERANTO, - MEMORY_TYPE_TENSORFLOW, - MEMORY_TYPE_TORCH, - MemoryType, -) +from arraybridge.types import MemoryType # OpenHCS wraps ArrayBridge decorators to preserve compiler metadata while # leaving conversion semantics in ArrayBridge. @@ -38,7 +31,7 @@ from openhcs.core.payload.runtime_array_values import array_geometry for _memory_type in MemoryType: - _memory_type.prepare_import() + _memory_type.library.prepare_import() memory_types = decorators.memory_types for _memory_type in MemoryType: @@ -48,7 +41,7 @@ def stack_runtime_slices( slices: Sequence[Any], memory_type: str, - gpu_id: int | None, + device: Device, ) -> Any: """Stack an explicitly declared runtime-slice sequence along axis zero.""" @@ -57,11 +50,11 @@ def stack_runtime_slices( raise ValueError("Runtime-slice stacking requires at least one slice.") target = MemoryType(memory_type) prepared_slices = [ - MemoryType(detect_memory_type(value)).convert_to(value, target, gpu_id) + MemoryType(detect_memory_type(value)).library.convert_to(value, target.library, device) for value in slice_values ] runtime_slice_stack_geometry(prepared_slices) - return target.stack_arrays(prepared_slices, gpu_id) + return target.library.stack_arrays(prepared_slices, device) def runtime_slice_stack_geometry(slices: Sequence[Any]) -> ArrayGeometry: @@ -81,14 +74,14 @@ def runtime_slice_stack_geometry(slices: Sequence[Any]) -> ArrayGeometry: def unstack_runtime_slices( stack: Any, memory_type: str, - gpu_id: int | None, + device: Device, *, expected_count: int | None = None, ) -> tuple[Any, ...]: """Split an explicitly declared leading runtime-slice axis.""" - converted = MemoryType(detect_memory_type(stack)).convert_to( - stack, MemoryType(memory_type), gpu_id + converted = MemoryType(detect_memory_type(stack)).library.convert_to( + stack, MemoryType(memory_type).library, device ) shape = tuple(int(value) for value in converted.shape) if not shape: @@ -105,13 +98,6 @@ def unstack_runtime_slices( # Converters "convert_memory", "detect_memory_type", - # Memory type constants - "MEMORY_TYPE_NUMPY", - "MEMORY_TYPE_CUPY", - "MEMORY_TYPE_TORCH", - "MEMORY_TYPE_TENSORFLOW", - "MEMORY_TYPE_JAX", - "MEMORY_TYPE_PYCLESPERANTO", # Decorators "memory_types", *(memory_type.value for memory_type in MemoryType), diff --git a/openhcs/core/payload/aligned_image_payload.py b/openhcs/core/payload/aligned_image_payload.py index 64fdf5537..906db9b54 100644 --- a/openhcs/core/payload/aligned_image_payload.py +++ b/openhcs/core/payload/aligned_image_payload.py @@ -17,6 +17,7 @@ import numpy as np from arraybridge import ArrayGeometry +from arraybridge.devices import HOST, Device from openhcs.core.artifacts.plans import ArtifactOutputPlan, ArtifactSpecRef @@ -432,7 +433,7 @@ def from_loaded_images( ): main_data_stack = payloads[0].copied( memory_type=execution_plan.input_memory_type, - device_id=execution_plan.device_id_for(execution_plan.input_memory_type), + device=execution_plan.device_for(execution_plan.input_memory_type), ) else: metadata_mode = RuntimeSlicePlaneAxis @@ -456,7 +457,7 @@ def from_loaded_images( main_data_stack = stack_image_payloads( payloads, metadata_mode=metadata_mode, memory_type=execution_plan.input_memory_type, - device_id=execution_plan.device_id_for(execution_plan.input_memory_type), + device=execution_plan.device_for(execution_plan.input_memory_type), ) elif metadata_mode.one_plane_per_source_binding: main_data_stack = ImagePayloadBundleContext.from_payloads( @@ -524,26 +525,26 @@ def composition_payload_metadata( @staticmethod def composition_memory_domain( payloads: tuple[RuntimeArrayData, ...], *, - memory_type: str | None = None, device_id: int | None = None, - ) -> tuple[str, int | None]: + memory_type: str | None = None, device: Device = HOST, + ) -> tuple[str, Device]: """Resolve where a composition is placed: explicitly, else beside its first payload.""" if memory_type is not None: - return memory_type, device_id + return memory_type, device memory_type = detect_memory_type(payloads[0]) - return memory_type, MemoryType(memory_type).device_id_of(payloads[0]) + return memory_type, MemoryType(memory_type).library.device_of(payloads[0]) def compose( - self, *, memory_type: str | None = None, device_id: int | None = None, + self, *, memory_type: str | None = None, device: Device = HOST, ) -> Any: # Resolve the destination from the input payloads before reconciling intensity. - memory_type, device_id = self.composition_memory_domain( + memory_type, device = self.composition_memory_domain( tuple(payload.data for payload in self.composition_payloads), - memory_type=memory_type, device_id=device_id, + memory_type=memory_type, device=device, ) payloads = ImagePayloadMetadata.intensity_coherent_payloads(self.composition_payloads) composed = self.compose_unmasked( tuple(payload.data for payload in payloads), - memory_type=memory_type, device_id=device_id, + memory_type=memory_type, device=device, ) metadata = ImagePayloadMetadata.compose( payloads, @@ -554,13 +555,13 @@ def compose( def compose_unmasked( self, payloads: tuple[RuntimeArrayData, ...], *, - memory_type: str | None = None, device_id: int | None = None, + memory_type: str | None = None, device: Device = HOST, ) -> RuntimeArrayData: - memory_type, device_id = self.composition_memory_domain( - payloads, memory_type=memory_type, device_id=device_id, + memory_type, device = self.composition_memory_domain( + payloads, memory_type=memory_type, device=device, ) return stack_runtime_slices( - payloads, memory_type, device_id, + payloads, memory_type, device, ) def compose_mask(self, composed: Any, metadata: ImagePayloadMetadata) -> Any | None: @@ -598,12 +599,12 @@ def stack_image_payloads( *, metadata_mode: type[RuntimePlaneAxis], memory_type: str | None = None, - device_id: int | None = None, + device: Device = HOST, ) -> Any: """Stack image payloads in their declared memory domain with full context.""" return ImagePayloadStackContext(image_payloads, metadata_mode).compose( - memory_type=memory_type, device_id=device_id, + memory_type=memory_type, device=device, ) @@ -650,7 +651,7 @@ def _stack_image_payload_mask( return stack_runtime_slices( resolved_masks, detect_memory_type(stack), - MemoryType(detect_memory_type(stack)).device_id_of(stack), + MemoryType(detect_memory_type(stack)).library.device_of(stack), ) @@ -670,7 +671,7 @@ def _complete_image_payload_mask( return project_image_mask_to_data_domain( mask, payload_data, metadata=payload.metadata, ) - return MemoryType(detect_memory_type(payload_data)).ones_like( + return MemoryType(detect_memory_type(payload_data)).library.ones_like( payload_data, shape=mask_domain.default_mask_shape(), dtype=bool, ) @@ -800,9 +801,9 @@ def compose_mask( stacked = stack_runtime_slices( resolved_masks, memory_type, - memory_type_owner.device_id_of(composed), + memory_type_owner.library.device_of(composed), ) - return memory_type_owner.astype(stacked, bool) + return memory_type_owner.library.astype(stacked, bool) def combined_mask(self, composed: Any) -> RuntimeArrayData | None: masks = self.present_masks @@ -816,17 +817,17 @@ def combined_mask(self, composed: Any) -> RuntimeArrayData | None: ) data = composed memory_type = MemoryType(detect_memory_type(data)) - device_id = memory_type.device_id_of(data) + device = memory_type.library.device_of(data) prepared = tuple( - memory_type.astype( - MemoryType(detect_memory_type(mask)).convert_to(mask, memory_type, device_id), + memory_type.library.astype( + MemoryType(detect_memory_type(mask)).library.convert_to(mask, memory_type.library, device), bool, ) for mask in masks ) combined = prepared[0] for mask in prepared[1:]: - combined = memory_type.logical_and( + combined = memory_type.library.logical_and( combined, mask, ) @@ -835,11 +836,11 @@ def combined_mask(self, composed: Any) -> RuntimeArrayData | None: def compose_unmasked( self, payloads: tuple[RuntimeArrayData, ...], - *, memory_type: str | None = None, device_id: int | None = None, + *, memory_type: str | None = None, device: Device = HOST, ) -> RuntimeArrayData: """Compose image payload arrays without mask/metadata wrapping.""" - memory_type, device_id = self.composition_memory_domain( - payloads, memory_type=memory_type, device_id=device_id, + memory_type, device = self.composition_memory_domain( + payloads, memory_type=memory_type, device=device, ) channel_axes = tuple( metadata.axis_index(ColourAxis, payload) @@ -852,13 +853,13 @@ def compose_unmasked( declared_channel_count = sum(axis is not None for axis in channel_axes) if declared_channel_count in {0, len(payloads)}: return super(ImagePayloadBundleContext, self).compose_unmasked( - payloads, memory_type=memory_type, device_id=device_id, + payloads, memory_type=memory_type, device=device, ) return self.compose_mixed_channel_payloads( payloads, channel_axes=channel_axes, memory_type=memory_type, - device_id=device_id, + device=device, ) @staticmethod @@ -867,7 +868,7 @@ def compose_mixed_channel_payloads( *, channel_axes: tuple[int | None, ...], memory_type: str, - device_id: int | None, + device: Device, ) -> RuntimeArrayData: """Promote channel-free payloads using declared channel-axis semantics.""" target = MemoryType(memory_type) @@ -876,7 +877,7 @@ def compose_mixed_channel_payloads( data=payload, source_type=detect_memory_type(payload), target_type=memory_type, - gpu_id=device_id, + device=device, ) for payload in payloads ) @@ -919,8 +920,8 @@ def compose_mixed_channel_payloads( ( payload if axis is not None - else target.broadcast_to( - target.reshape( + else target.library.broadcast_to( + target.library.reshape( payload, (*payload.shape[:channel_axis], 1, *payload.shape[channel_axis:]), ), @@ -929,7 +930,7 @@ def compose_mixed_channel_payloads( ) for payload, axis in zip(prepared_payloads, channel_axes, strict=True) ) - return target.stack_arrays(list(promoted), device_id) + return target.library.stack_arrays(list(promoted), device) @dataclass(frozen=True) @@ -1218,10 +1219,10 @@ def output_stack_copy( projected_outputs: Sequence[tuple[Any, AlignedImageSliceContext | None]], *, memory_type: str, - device_id: int | None, + device: Device, ) -> RuntimeArrayData | None: return self.copy_projected_output_stack( - projected_outputs, memory_type=memory_type, device_id=device_id, + projected_outputs, memory_type=memory_type, device=device, ) def __post_init__(self) -> None: @@ -1262,12 +1263,12 @@ def with_slices(self, slices: Sequence[Any]) -> ImagePayloadSliceStack: return type(self)(tuple(slices), self.slice_contexts) def copied( - self, *, memory_type: str, device_id: int | None, + self, *, memory_type: str, device: Device, ) -> ImagePayloadSliceStack: """Retain aligned member domains while copying them into independent buffers.""" return self.with_slices( tuple( - payload.copied(memory_type=memory_type, device_id=device_id) + payload.copied(memory_type=memory_type, device=device) for payload in self.slices ) ) @@ -1289,13 +1290,13 @@ def copy_projected_output_stack( projected_outputs: Sequence[tuple[Any, AlignedImageSliceContext | None]], *, memory_type: str, - device_id: int | None, + device: Device, ) -> RuntimeArrayData | None: """Prepare an independent output buffer in this owner's declared domain.""" payloads = tuple(payload for payload, _context in projected_outputs) metadata_mode = self.projected_output_composition_mode if metadata_mode.unstacked: - return payloads[0].copied(memory_type=memory_type, device_id=device_id) + return payloads[0].copied(memory_type=memory_type, device=device) data = tuple(payload.data for payload in payloads) declared_axes = { self.plane_axis_for_output_context(context) @@ -1309,7 +1310,7 @@ def copy_projected_output_stack( ).compose() return stack_image_payloads( payloads, metadata_mode=metadata_mode, - memory_type=memory_type, device_id=device_id, + memory_type=memory_type, device=device, ) def output_values_for_artifact_specs( @@ -1531,7 +1532,7 @@ def dtype(self) -> Any: return np.result_type( *( MemoryType(detect_memory_type(payload.data)) - .canonical_dtype_name(payload.data.dtype) + .library.dtype_name(payload.data.dtype) for payload in self.slices ) ) @@ -1639,7 +1640,7 @@ def with_slices(self, slices: Sequence[Any]) -> ProducedImageStack: ) def copied( - self, *, memory_type: str, device_id: int | None, + self, *, memory_type: str, device: Device, ) -> ProducedImageStack: """Snapshot produced pixels directly into one dense buffer. @@ -1649,16 +1650,16 @@ def copied( """ data = stack_runtime_slices( tuple(payload.data for payload in self.slices), - memory_type, device_id, + memory_type, device, ) masks = tuple(payload.mask for payload in self.slices) mask = None if masks[0] is not None: shared = self._shared_image_mask(masks, self.geometry) mask = ( - stack_runtime_slices(masks, memory_type, device_id) + stack_runtime_slices(masks, memory_type, device) if shared is None else stack_runtime_slices( - (shared,), memory_type, device_id, + (shared,), memory_type, device, )[0] ) metadata = self._metadata.replace_fields() @@ -1671,13 +1672,13 @@ def copied( return copied def compose( - self, *, memory_type: str | None = None, device_id: int | None = None, + self, *, memory_type: str | None = None, device: Device = HOST, ) -> Any: with self._realization_lock: if self._composed_payload is None: data = stack_runtime_slices( tuple(payload.data for payload in self.slices), - self.memory_type, 0, + self.memory_type, MemoryType(self.memory_type).library.device_of(self.slices[0].data), ) self._composed_payload = self._metadata.payload_with( data, self._materialized_image_mask(), @@ -1688,13 +1689,13 @@ def compose( target = MemoryType(memory_type) data = self._composed_payload.data source = MemoryType(detect_memory_type(data)) - if source is target and source.device_id_of(data) == device_id: + if source is target and source.library.device_of(data) == device: return self._composed_payload mask = self._composed_payload.mask return self._metadata.payload_with( - source.convert_to(data, target, device_id), - None if mask is None else MemoryType(detect_memory_type(mask)).convert_to( - mask, target, device_id, + source.library.convert_to(data, target.library, device), + None if mask is None else MemoryType(detect_memory_type(mask)).library.convert_to( + mask, target.library, device, ), ) diff --git a/openhcs/core/payload/image_file_serialization.py b/openhcs/core/payload/image_file_serialization.py index bbb9b6be6..fe5ee6cb6 100644 --- a/openhcs/core/payload/image_file_serialization.py +++ b/openhcs/core/payload/image_file_serialization.py @@ -293,7 +293,7 @@ def prepare(self, payload: Any) -> Any: """Project runtime pixels onto the host before format-specific encoding.""" payload = ImagePayload.of(payload) pixels = payload.data - host_pixels = MemoryType(detect_memory_type(pixels)).to_numpy(pixels) + host_pixels = MemoryType(detect_memory_type(pixels)).library.to_numpy(pixels) host_payload = payload.metadata.payload_with(host_pixels) return self.prepare_host_payload(host_payload) diff --git a/openhcs/core/payload/runtime_image_values.py b/openhcs/core/payload/runtime_image_values.py index ada3bda27..166f842c2 100644 --- a/openhcs/core/payload/runtime_image_values.py +++ b/openhcs/core/payload/runtime_image_values.py @@ -17,6 +17,7 @@ import numpy as np from arraybridge import ArrayGeometry, MemoryType, detect_memory_type +from arraybridge.devices import Device from python_introspect import dataclass_from_mapping, to_jsonable from zmqruntime.viewer_protocol import ( ViewerWireField, @@ -50,7 +51,7 @@ _spatial_shape_pair as _source_spatial_shape_pair, ) from openhcs.core.axes.axis_declarations import AxisFamily, ColourAxis -from openhcs.core.memory import MEMORY_TYPE_NUMPY, stack_runtime_slices +from openhcs.core.memory import stack_runtime_slices @@ -239,13 +240,13 @@ def normalize_intensity_payload( array = payload.data memory_type = MemoryType(detect_memory_type(array)) target_dtype = self.normalization_dtype( - memory_type.canonical_dtype_name(array.dtype), dtype, + memory_type.library.dtype_name(array.dtype), dtype, ) if target_dtype is None: return payload if self.has_normalized_intensity: return self.payload_with( - memory_type.astype(array, target_dtype), payload.mask, + memory_type.library.astype(array, target_dtype), payload.mask, ) if self.has_leading_intensity_axis and self.source_plane_intensity_scales: if len(self.source_plane_intensity_scales) != len(array): @@ -253,7 +254,7 @@ def normalize_intensity_payload( "Image intensity scales must match the declared leading plane axis." ) self.require_leading_intensity_axis() - source_dtype = np.dtype(memory_type.canonical_dtype_name(array.dtype)) + source_dtype = np.dtype(memory_type.library.dtype_name(array.dtype)) scale_proofs = tuple( self.normalization_scale( source_dtype, self.intensity_scale_for_source_plane(index), @@ -266,7 +267,7 @@ def normalize_intensity_payload( ), ) return metadata.payload_with( - memory_type.normalize_planes( + memory_type.library.normalize_planes( array, target_dtype, tuple(scale for scale, _ in scale_proofs), ), payload.mask, @@ -304,11 +305,11 @@ def normalized_intensity_array( ) -> tuple[Any, int | None]: """Apply one numerical recipe without projecting image source identity.""" memory_type = MemoryType(detect_memory_type(array)) - source_dtype = np.dtype(memory_type.canonical_dtype_name(array.dtype)) + source_dtype = np.dtype(memory_type.library.dtype_name(array.dtype)) scale, proof_scale = ImagePayloadIntensityFields.normalization_scale( source_dtype, scale, ) - normalized = memory_type.astype(array, target_dtype) + normalized = memory_type.library.astype(array, target_dtype) if scale is not None: normalized = normalized / float(scale) return normalized, proof_scale @@ -581,7 +582,7 @@ def for_array_payload( """Build source metadata from an arraybridge-detectable payload.""" memory_type = detect_memory_type(array) dtype = array.dtype - if memory_type == MEMORY_TYPE_NUMPY: + if memory_type == MemoryType.NUMPY.value: intensity_scale = image_intensity_scale_for_dtype(dtype) else: intensity_scale = None @@ -1416,13 +1417,13 @@ def debug_value_facts( ) return facts, projection - def copied(self, *, memory_type: str, device_id: int | None) -> ImagePayload: + def copied(self, *, memory_type: str, device: Device) -> ImagePayload: """Copy pixels, mask and metadata into an independent buffer.""" - copied_data = stack_runtime_slices((self.data,), memory_type, device_id)[0] + copied_data = stack_runtime_slices((self.data,), memory_type, device)[0] mask = self.mask copied_mask = ( None if mask is None - else stack_runtime_slices((mask,), memory_type, device_id)[0] + else stack_runtime_slices((mask,), memory_type, device)[0] ) return self.metadata.replace_fields().payload_with(copied_data, copied_mask) @@ -1588,12 +1589,12 @@ def output_stack_copy( projected_outputs: Sequence[tuple[Any, Any]], *, memory_type: str, - device_id: int | None, + device: Device, ) -> ImagePayload | None: """Return an independent buffer for the published output stack.""" del projected_outputs if self.declares_whole_image_output: - return self.copied(memory_type=memory_type, device_id=device_id) + return self.copied(memory_type=memory_type, device=device) return self # -- derived image outputs ------------------------------------------------ @@ -2119,10 +2120,10 @@ def project_image_mask_to_data_domain( data_array = runtime_array_operand(data) candidate = mask_array(mask) target = MemoryType(detect_memory_type(data_array)) - candidate = MemoryType(detect_memory_type(candidate)).convert_to( - candidate, target, target.device_id_of(data_array), + candidate = MemoryType(detect_memory_type(candidate)).library.convert_to( + candidate, target.library, target.library.device_of(data_array), ) - candidate = target.astype(candidate, bool) + candidate = target.library.astype(candidate, bool) mask_shape = tuple(candidate.shape) mask_domain = metadata.mask_domain(data) if mask_domain.accepts(mask_shape): @@ -2557,7 +2558,7 @@ def projected_channel_mask( channel_axis: int, ) -> Any: candidate = mask_array(mask) - candidate = MemoryType(detect_memory_type(candidate)).astype(candidate, bool) + candidate = MemoryType(detect_memory_type(candidate)).library.astype(candidate, bool) if candidate.shape != array_geometry(source_data).shape: return candidate channel_mask = cls.channel_axis_slice( @@ -2567,7 +2568,7 @@ def projected_channel_mask( ) if array_geometry(channel_mask).shape == array_geometry(channel_data).shape: return channel_mask - squeezed_mask = MemoryType(detect_memory_type(channel_mask)).reshape( + squeezed_mask = MemoryType(detect_memory_type(channel_mask)).library.reshape( channel_mask, tuple( size for axis, size in enumerate(channel_mask.shape) @@ -2622,7 +2623,7 @@ def broadcast_to_data(self, mask: Any) -> Any: """Broadcast a valid mask across its declared non-spatial axes.""" candidate = mask_array(mask) memory_type = MemoryType(detect_memory_type(candidate)) - candidate = memory_type.astype(candidate, bool) + candidate = memory_type.library.astype(candidate, bool) mask_shape = tuple(candidate.shape) if mask_shape == self.data_shape: return candidate @@ -2632,8 +2633,8 @@ def broadcast_to_data(self, mask: Any) -> Any: broadcast_shape = [1] * len(self.data_shape) for mask_axis, data_axis in enumerate(self.placement_axes): broadcast_shape[data_axis] = mask_shape[mask_axis] - return memory_type.broadcast_to( - memory_type.reshape(candidate, tuple(broadcast_shape)), + return memory_type.library.broadcast_to( + memory_type.library.reshape(candidate, tuple(broadcast_shape)), self.data_shape, ) if self.undeclared_shape is None or mask_shape != self.undeclared_shape: @@ -2644,8 +2645,8 @@ def broadcast_to_data(self, mask: Any) -> Any: broadcast_shape = list(mask_shape) for axis in self.declared_axes: broadcast_shape.insert(axis, 1) - return memory_type.broadcast_to( - memory_type.reshape(candidate, tuple(broadcast_shape)), + return memory_type.library.broadcast_to( + memory_type.library.reshape(candidate, tuple(broadcast_shape)), self.data_shape, ) diff --git a/openhcs/core/steps/function_runtime.py b/openhcs/core/steps/function_runtime.py index 48ea8db87..bdd76da0b 100644 --- a/openhcs/core/steps/function_runtime.py +++ b/openhcs/core/steps/function_runtime.py @@ -1057,7 +1057,7 @@ def _unstack_main_output( return unstack_runtime_slices( processed_data, self.execution_plan.output_memory_type, - self.execution_plan.device_id_for( + self.execution_plan.device_for( self.execution_plan.output_memory_type ), expected_count=expected_count, @@ -1154,7 +1154,7 @@ def _save_outputs( stack_payload = processed_stack.output_stack_copy( projected_outputs, memory_type=plan.output_memory_type, - device_id=plan.device_id_for(plan.output_memory_type), + device=plan.device_for(plan.output_memory_type), ) RuntimeProfileLogger.log( logger, @@ -1378,7 +1378,7 @@ def load_input_stack( payloads.append( source_payload.copied( memory_type=self.execution_plan.input_memory_type, - device_id=self.execution_plan.device_id_for( + device=self.execution_plan.device_for( self.execution_plan.input_memory_type, ), ) diff --git a/openhcs/core/util/framework_device_resolver.py b/openhcs/core/util/framework_device_resolver.py index 86363cdd1..d528d9588 100644 --- a/openhcs/core/util/framework_device_resolver.py +++ b/openhcs/core/util/framework_device_resolver.py @@ -34,13 +34,15 @@ def resolve( missing_packages: list[str] = [] unavailable_devices: list[str] = [] for memory_type in sorted(memory_types, key=lambda item: item.value): - framework = memory_type.import_if_installed() + framework = memory_type.library.import_if_installed() if framework is None: - missing_packages.append(memory_type.import_name) + missing_packages.append(memory_type.library.import_name) continue - available = memory_type.available_device_ids(framework) + available = tuple( + device.index for device in memory_type.library.accelerator_devices() + ) if not available: - unavailable_devices.append(memory_type.display_name) + unavailable_devices.append(memory_type.library.display_name) continue assignments[memory_type] = ( self.preferred_device_id diff --git a/openhcs/core/util/lazy_gpu_imports.py b/openhcs/core/util/lazy_gpu_imports.py index abab10fbd..490c34b69 100644 --- a/openhcs/core/util/lazy_gpu_imports.py +++ b/openhcs/core/util/lazy_gpu_imports.py @@ -25,13 +25,13 @@ def __init__( def is_installed(self) -> bool: """Check package presence without importing the framework.""" - return self._memory_type.is_installed() + return self._memory_type.library.is_installed() def _ensure_imported(self) -> Any | None: if not self._resolved: with self._lock: if not self._resolved: - module = self._memory_type.import_if_installed() + module = self._memory_type.library.import_if_installed() for attribute in self._attribute_path: if module is None: break @@ -44,7 +44,7 @@ def __getattr__(self, name: str) -> Any: module = self._ensure_imported() if module is None: raise ImportError( - f"Module {self._memory_type.import_name!r} is not installed." + f"Module {self._memory_type.library.import_name!r} is not installed." ) return getattr(module, name) diff --git a/openhcs/interop/cellprofiler/runtime/function_contract_execution.py b/openhcs/interop/cellprofiler/runtime/function_contract_execution.py index 49307786b..dea6cfd87 100644 --- a/openhcs/interop/cellprofiler/runtime/function_contract_execution.py +++ b/openhcs/interop/cellprofiler/runtime/function_contract_execution.py @@ -9,7 +9,7 @@ from openhcs.core.payload.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.callable.callable_contract import CallableContract from openhcs.core.measurements.measurement_dialect import executing_measurement_dialect -from openhcs.core.memory import detect_memory_type, stack_slices +from openhcs.core.memory import MemoryType, detect_memory_type, stack_slices from openhcs.core.callable.processing_contracts import ( ContractCall, PlaneSplit, @@ -129,8 +129,10 @@ def validate_full_stack_kwargs(self, contract, kwargs): def stack_reduction_output(self, result): result_2d = ImagePayload.of(result) + memory_type = detect_memory_type(result_2d.data) stacked = stack_slices( - [result_2d.data], detect_memory_type(result_2d.data), 0, + [result_2d.data], memory_type, + MemoryType(memory_type).library.device_of(result_2d.data), ) return result_2d.metadata.payload_with(stacked, mask=result_2d.mask) diff --git a/openhcs/processing/backends/analysis/cell_counting_cupy.py b/openhcs/processing/backends/analysis/cell_counting_cupy.py index d81708a32..5049cdc4b 100644 --- a/openhcs/processing/backends/analysis/cell_counting_cupy.py +++ b/openhcs/processing/backends/analysis/cell_counting_cupy.py @@ -74,15 +74,13 @@ def _watershed_with_cpu_partition(image, markers, *, mask): from openhcs.constants.constants import MemoryType - device_id = MemoryType.CUPY.device_id_of(image) - if device_id is None: - raise ValueError("CuPy watershed input does not declare a GPU device.") + device = MemoryType.CUPY.library.device_of(image) labels = skimage_watershed( - MemoryType.CUPY.to_numpy(image), - MemoryType.CUPY.to_numpy(markers), - mask=MemoryType.CUPY.to_numpy(mask), + MemoryType.CUPY.library.to_numpy(image), + MemoryType.CUPY.library.to_numpy(markers), + mask=MemoryType.CUPY.library.to_numpy(mask), ) - return MemoryType.CUPY.from_numpy(labels, device_id) + return MemoryType.CUPY.library.from_numpy(labels, device) def count_cells_single_channel( diff --git a/openhcs/processing/backends/lib_registry/openhcs_registry.py b/openhcs/processing/backends/lib_registry/openhcs_registry.py index adba9c545..207339e23 100644 --- a/openhcs/processing/backends/lib_registry/openhcs_registry.py +++ b/openhcs/processing/backends/lib_registry/openhcs_registry.py @@ -29,7 +29,7 @@ from packaging.requirements import Requirement from packaging.utils import canonicalize_name -from openhcs.constants import VALID_MEMORY_TYPES, MemoryType +from openhcs.constants import MemoryType from openhcs.core.util.stated_types import require_stated_parameter_types from openhcs.core.callable.callable_contract import CallableContract from openhcs.core.callable.function_contract_metadata import FunctionContractAttribute @@ -277,7 +277,7 @@ def _allowed_openhcs_memory_types() -> frozenset[str]: part of this installation's catalog; CPU-only mode further admits NumPy only. """ installed = frozenset( - memory_type.value for memory_type in MemoryType if memory_type.is_installed() + memory_type.value for memory_type in MemoryType if memory_type.library.is_installed() ) if OpenHCSProcessEnvironment.cpu_only_mode(): return installed & {MemoryType.NUMPY.value} @@ -836,9 +836,10 @@ def declared_callable_contract(cls, func: Callable) -> CallableContract | None: ): return None + memory_type_names = {memory_type.value for memory_type in MemoryType} if not plate_scoped and ( - callable_contract.input_memory_type not in VALID_MEMORY_TYPES - or callable_contract.output_memory_type not in VALID_MEMORY_TYPES + callable_contract.input_memory_type not in memory_type_names + or callable_contract.output_memory_type not in memory_type_names ): logger.debug( "Skipping %s - invalid input/output memory declarations", diff --git a/openhcs/processing/backends/lib_registry/registry_service.py b/openhcs/processing/backends/lib_registry/registry_service.py index 8501d95e5..3ad122074 100644 --- a/openhcs/processing/backends/lib_registry/registry_service.py +++ b/openhcs/processing/backends/lib_registry/registry_service.py @@ -19,7 +19,7 @@ from concurrent.futures import CancelledError from typing import TYPE_CHECKING, Dict, Optional -from arraybridge import MemoryType +from arraybridge.libraries import ArrayLibrary from objectstate import LazyDataclassFactory from python_introspect import SignatureAnalyzer from zmqruntime.process_launch import BackgroundProcessLaunchPolicy @@ -329,7 +329,7 @@ def prepare_persistent_catalog( stdout=output, stderr=subprocess.STDOUT, text=True, - env=MemoryType.subprocess_environment(), + env=ArrayLibrary.child_environment(), **policy.popen_arguments(), ) owned_process = endpoint_process(process) diff --git a/openhcs/processing/backends/processors/__init__.py b/openhcs/processing/backends/processors/__init__.py index b9524b9dc..f8fdbb7a4 100644 --- a/openhcs/processing/backends/processors/__init__.py +++ b/openhcs/processing/backends/processors/__init__.py @@ -3,7 +3,7 @@ pyclesperanto). Operations shared by several backends are written once in -``image_stack_operations`` against arraybridge ``ArrayOperations``; each +``image_stack_operations`` against arraybridge ``ArrayLibrary``; each ``_processor`` module registers them for its memory type and keeps only the operations whose algorithm differs on that backend. """ diff --git a/openhcs/processing/backends/processors/cupy_processor.py b/openhcs/processing/backends/processors/cupy_processor.py index 8c35fb785..942bcc127 100644 --- a/openhcs/processing/backends/processors/cupy_processor.py +++ b/openhcs/processing/backends/processors/cupy_processor.py @@ -11,7 +11,7 @@ from typing import List, Optional, Tuple from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from metaclass_registry import AutoRegisterMeta from openhcs.core.artifacts.specs import ArtifactSpec @@ -32,7 +32,7 @@ cp = optional_import_placeholder("cupy") -OPERATIONS = ArrayOperations.for_memory(MemoryType.CUPY) +OPERATIONS = MemoryType.CUPY.library @cupy_func @@ -837,6 +837,6 @@ def sobel( # Always preserve input dtype (CuCIM normalizes integer inputs to [0, 1]) if result.dtype != original_dtype: - result = MemoryType.CUPY.scale_dtype(result, original_dtype) + result = MemoryType.CUPY.library.scale_dtype(result, original_dtype) return result diff --git a/openhcs/processing/backends/processors/image_stack_operations.py b/openhcs/processing/backends/processors/image_stack_operations.py index 651504437..bad8b036e 100644 --- a/openhcs/processing/backends/processors/image_stack_operations.py +++ b/openhcs/processing/backends/processors/image_stack_operations.py @@ -1,7 +1,7 @@ -"""Image-stack operations written once against arraybridge ``ArrayOperations``. +"""Image-stack operations written once against arraybridge ``ArrayLibrary``. Each backend processor module registers these operations under its own -memory type and passes its ``ArrayOperations`` leaf. A leaf supplies only the +memory type and passes its ``ArrayLibrary`` leaf. A leaf supplies only the primitives its array library does differently, so a result here equals what the backend's own library calls produce. Operations whose algorithm genuinely differs per backend stay in that backend's module. @@ -18,7 +18,7 @@ import numpy as np from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from metaclass_registry import AutoRegisterMeta from metaclass_registry.strategies import EnumKeyedStrategyMixin @@ -29,11 +29,11 @@ ) -def require_stack(ops: ArrayOperations, array: Any, name: str = "input") -> None: +def require_stack(ops: ArrayLibrary, array: Any, name: str = "input") -> None: """Require one native array of the leaf's framework with three axes.""" if not ops.accepts(array): - display_name = MemoryType(ops.memory_type).display_name + display_name = ops.display_name raise TypeError( f"{name} must be a {display_name} array, got {type(array)}. " "No automatic conversion is performed." @@ -61,7 +61,7 @@ def weight_mask_extent(shape: Any) -> tuple[int, int]: def linear_weight_mask( - ops: ArrayOperations, + ops: ArrayLibrary, height: int, width: int, margin_ratio: float, @@ -91,7 +91,7 @@ def axis_weights(length: int) -> Any: # ----- masks and projections ----- -def apply_mask(ops: ArrayOperations, image: Any, mask: Any) -> Any: +def apply_mask(ops: ArrayLibrary, image: Any, mask: Any) -> Any: """Multiply a stack by a 2-D (per plane) or 3-D mask in float32.""" require_stack(ops, image) @@ -107,21 +107,21 @@ def apply_mask(ops: ArrayOperations, image: Any, mask: Any) -> Any: return ops.astype(masked, image.dtype) -def max_projection(ops: ArrayOperations, stack: Any) -> Any: +def max_projection(ops: ArrayLibrary, stack: Any) -> Any: """Maximum over the leading axis, shaped ``(1, Y, X)``.""" require_stack(ops, stack) return ops.prepend_axis(ops.max(stack, 0)) -def mean_projection(ops: ArrayOperations, stack: Any) -> Any: +def mean_projection(ops: ArrayLibrary, stack: Any) -> Any: """Mean over the leading axis in the input dtype, shaped ``(1, Y, X)``.""" require_stack(ops, stack) return ops.prepend_axis(ops.astype(ops.mean(stack, 0), stack.dtype)) -def min_projection(ops: ArrayOperations, stack: Any) -> Any: +def min_projection(ops: ArrayLibrary, stack: Any) -> Any: """Minimum over the leading axis, shaped ``(1, Y, X)``.""" require_stack(ops, stack) @@ -134,32 +134,32 @@ class StackProjection( """One leading-axis projection, keyed by its method value.""" @abstractmethod - def project(self, ops: ArrayOperations, stack: Any) -> Any: + def project(self, ops: ArrayLibrary, stack: Any) -> Any: """Return the projection shaped ``(1, Y, X)``.""" class MaxStackProjection(StackProjection): method = StackProjectionMethod.MAX - def project(self, ops: ArrayOperations, stack: Any) -> Any: + def project(self, ops: ArrayLibrary, stack: Any) -> Any: return max_projection(ops, stack) class MeanStackProjection(StackProjection): method = StackProjectionMethod.MEAN - def project(self, ops: ArrayOperations, stack: Any) -> Any: + def project(self, ops: ArrayLibrary, stack: Any) -> Any: return mean_projection(ops, stack) class MinStackProjection(StackProjection): method = StackProjectionMethod.MIN - def project(self, ops: ArrayOperations, stack: Any) -> Any: + def project(self, ops: ArrayLibrary, stack: Any) -> Any: return min_projection(ops, stack) -def create_projection(ops: ArrayOperations, stack: Any, method: Any) -> Any: +def create_projection(ops: ArrayLibrary, stack: Any, method: Any) -> Any: """Project a stack with the method's registered projection. ``method`` is any enum whose values name ``StackProjection`` members. @@ -176,35 +176,35 @@ class SpatialBin(EnumKeyedStrategyMixin[SpatialBinMethod], MethodKeyedStrategy, """Reduction applied within each spatial bin.""" @abstractmethod - def reduce(self, ops: ArrayOperations, array: Any, axis: tuple[int, ...]) -> Any: + def reduce(self, ops: ArrayLibrary, array: Any, axis: tuple[int, ...]) -> Any: """Reduce the bin axes.""" class MeanSpatialBin(SpatialBin): method = SpatialBinMethod.MEAN - def reduce(self, ops: ArrayOperations, array: Any, axis: tuple[int, ...]) -> Any: + def reduce(self, ops: ArrayLibrary, array: Any, axis: tuple[int, ...]) -> Any: return ops.mean(array, axis) class SumSpatialBin(SpatialBin): method = SpatialBinMethod.SUM - def reduce(self, ops: ArrayOperations, array: Any, axis: tuple[int, ...]) -> Any: + def reduce(self, ops: ArrayLibrary, array: Any, axis: tuple[int, ...]) -> Any: return ops.sum(array, axis) class MaxSpatialBin(SpatialBin): method = SpatialBinMethod.MAX - def reduce(self, ops: ArrayOperations, array: Any, axis: tuple[int, ...]) -> Any: + def reduce(self, ops: ArrayLibrary, array: Any, axis: tuple[int, ...]) -> Any: return ops.max(array, axis) class MinSpatialBin(SpatialBin): method = SpatialBinMethod.MIN - def reduce(self, ops: ArrayOperations, array: Any, axis: tuple[int, ...]) -> Any: + def reduce(self, ops: ArrayLibrary, array: Any, axis: tuple[int, ...]) -> Any: return ops.min(array, axis) @@ -214,7 +214,7 @@ def _require_bin_size(bin_size: int) -> None: def spatial_bin_2d( - ops: ArrayOperations, stack: Any, bin_size: int, method: SpatialBinMethod + ops: ArrayLibrary, stack: Any, bin_size: int, method: SpatialBinMethod ) -> Any: """Bin each plane in ``bin_size`` x ``bin_size`` blocks.""" @@ -233,7 +233,7 @@ def spatial_bin_2d( def spatial_bin_3d( - ops: ArrayOperations, stack: Any, bin_size: int, method: SpatialBinMethod + ops: ArrayLibrary, stack: Any, bin_size: int, method: SpatialBinMethod ) -> Any: """Bin the stack in ``bin_size``-sided cubes.""" @@ -264,7 +264,7 @@ def spatial_bin_3d( def crop( - ops: ArrayOperations, + ops: ArrayLibrary, image: Any, start_x: int, start_y: int, @@ -298,7 +298,7 @@ def crop( def stack_equalize_histogram( - ops: ArrayOperations, stack: Any, bins: int, range_min: float, range_max: float + ops: ArrayLibrary, stack: Any, bins: int, range_min: float, range_max: float ) -> Any: """Equalize with one histogram over the whole stack.""" @@ -345,7 +345,7 @@ def _target_range( def percentile_normalize_planes( - ops: ArrayOperations, + ops: ArrayLibrary, image: Any, low_percentile: float, high_percentile: float, @@ -371,7 +371,7 @@ def percentile_normalize_planes( def percentile_normalize_stack( - ops: ArrayOperations, + ops: ArrayLibrary, stack: Any, low_percentile: float, high_percentile: float, @@ -419,7 +419,7 @@ def composite_weights(weights: Sequence[float] | None, count: int) -> list[float def weighted_composite( - ops: ArrayOperations, stack: Any, weights: Sequence[float] | None + ops: ArrayLibrary, stack: Any, weights: Sequence[float] | None ) -> Any: """Float32 weighted sum of the planes, shaped ``(1, Y, X)``, in the input dtype.""" diff --git a/openhcs/processing/backends/processors/jax_processor.py b/openhcs/processing/backends/processors/jax_processor.py index 5555bef31..932c4a09b 100644 --- a/openhcs/processing/backends/processors/jax_processor.py +++ b/openhcs/processing/backends/processors/jax_processor.py @@ -9,7 +9,7 @@ from typing import List, Optional, Tuple from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from openhcs.core.artifacts.specs import ArtifactSpec from openhcs.core.artifacts.kinds import ImageArtifactType @@ -25,7 +25,7 @@ jnp = optional_import_placeholder("jax.numpy") lax = optional_import_placeholder("jax.lax") -OPERATIONS = ArrayOperations.for_memory(MemoryType.JAX) +OPERATIONS = MemoryType.JAX.library @jax_func diff --git a/openhcs/processing/backends/processors/numpy_processor.py b/openhcs/processing/backends/processors/numpy_processor.py index c6ad31aaa..67ce1f6c7 100644 --- a/openhcs/processing/backends/processors/numpy_processor.py +++ b/openhcs/processing/backends/processors/numpy_processor.py @@ -11,7 +11,7 @@ from typing import Annotated, List, Optional, Tuple from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from metaclass_registry import AutoRegisterMeta import numpy as np from numba import njit @@ -34,7 +34,7 @@ VolumetricToSliceContract, ) -OPERATIONS = ArrayOperations.for_memory(MemoryType.NUMPY) +OPERATIONS = MemoryType.NUMPY.library @numpy_func(contract=Pure2DContract) diff --git a/openhcs/processing/backends/processors/pyclesperanto_processor.py b/openhcs/processing/backends/processors/pyclesperanto_processor.py index 1ba756fdf..fabe0d4c0 100644 --- a/openhcs/processing/backends/processors/pyclesperanto_processor.py +++ b/openhcs/processing/backends/processors/pyclesperanto_processor.py @@ -10,7 +10,7 @@ from typing import List, Optional from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from openhcs.core.artifacts.specs import ArtifactSpec from openhcs.core.artifacts.kinds import ImageArtifactType @@ -24,7 +24,7 @@ cle = optional_import_placeholder("pyclesperanto") -OPERATIONS = ArrayOperations.for_memory(MemoryType.PYCLESPERANTO) +OPERATIONS = MemoryType.PYCLESPERANTO.library def _gpu_minmax_normalize_range(image: cle.Array) -> tuple: diff --git a/openhcs/processing/backends/processors/tensorflow_processor.py b/openhcs/processing/backends/processors/tensorflow_processor.py index b735b5425..04533dc6a 100644 --- a/openhcs/processing/backends/processors/tensorflow_processor.py +++ b/openhcs/processing/backends/processors/tensorflow_processor.py @@ -9,7 +9,7 @@ from typing import List, Optional, Tuple from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from openhcs.core.artifacts.specs import ArtifactSpec from openhcs.core.artifacts.kinds import ImageArtifactType @@ -23,7 +23,7 @@ tf = optional_import_placeholder("tensorflow") -OPERATIONS = ArrayOperations.for_memory(MemoryType.TENSORFLOW) +OPERATIONS = MemoryType.TENSORFLOW.library @tensorflow_func diff --git a/openhcs/processing/backends/processors/torch_processor.py b/openhcs/processing/backends/processors/torch_processor.py index 58858108b..7107e3f19 100644 --- a/openhcs/processing/backends/processors/torch_processor.py +++ b/openhcs/processing/backends/processors/torch_processor.py @@ -10,7 +10,7 @@ from typing import List, Optional, Tuple from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations +from arraybridge.libraries import ArrayLibrary from openhcs.core.artifacts.specs import ArtifactSpec from openhcs.core.artifacts.kinds import ImageArtifactType @@ -26,7 +26,7 @@ torch = optional_import_placeholder("torch") -OPERATIONS = ArrayOperations.for_memory(MemoryType.TORCH) +OPERATIONS = MemoryType.TORCH.library def _integer_limits(dtype: torch.dtype) -> Optional["torch.iinfo"]: diff --git a/openhcs/runtime/zmq/zmq_execution_client.py b/openhcs/runtime/zmq/zmq_execution_client.py index 2d825ea2a..a4a18e1e8 100644 --- a/openhcs/runtime/zmq/zmq_execution_client.py +++ b/openhcs/runtime/zmq/zmq_execution_client.py @@ -16,7 +16,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, TypeAlias -from arraybridge import MemoryType +from arraybridge.libraries import ArrayLibrary from typing_extensions import override from zmqruntime import ( EndpointApplicationCompatibility, @@ -217,7 +217,7 @@ def spawn( stdout=log_stream, stderr=subprocess.STDOUT, cwd=self.runtime_dir, - env=MemoryType.subprocess_environment(), + env=ArrayLibrary.child_environment(), **launch_policy.popen_arguments(), ) From 0b13760eb0fec389966ce1ad4d2c04f2b0e20f0d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:43:56 +0000 Subject: [PATCH 17/27] The global config is objectstate's one holder: set_global_config, live or saved by name objectstate 4 removed ensure_global_config_context, set_global_config_for_editing, get_current_global_config and rebuild_lazy_config_with_new_global_reference. Each call now names what it meant: set the process's global config, read the live one, or read the saved one (the plate inspector asked for saved). The benchmark's 'rebuild' was a copy plus that same set; a lazy config reads the one global at resolution, so the copy is gone. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- benchmark/adapters/openhcs.py | 12 ++----- benchmark/matched_cellprofiler_batch.py | 12 +++---- benchmark/well_throughput_scaling.py | 35 +++++++++---------- .../artifact_plan_inspection_service.py | 4 +-- .../services/plate_inspection_service.py | 7 ++-- openhcs/authoring/session/session.py | 8 ++--- openhcs/core/config/config_cache.py | 4 +-- openhcs/core/config/pipeline_config.py | 6 ++-- openhcs/pyqt_gui/app.py | 12 ++----- openhcs/pyqt_gui/main.py | 4 +-- openhcs/pyqt_gui/services/window_handlers.py | 4 +-- openhcs/runtime/zmq/zmq_execution_server.py | 6 ++-- 12 files changed, 44 insertions(+), 70 deletions(-) diff --git a/benchmark/adapters/openhcs.py b/benchmark/adapters/openhcs.py index ede2c9640..57bfc6515 100644 --- a/benchmark/adapters/openhcs.py +++ b/benchmark/adapters/openhcs.py @@ -338,10 +338,7 @@ def _run_converted_cppipe_pipeline( request: OpenHCSRunRequest, ) -> BenchmarkResult: """Execute a converted CellProfiler pipeline through the OpenHCS orchestrator.""" - from objectstate.lazy_factory import ( - ensure_global_config_context, - rebuild_lazy_config_with_new_global_reference, - ) + from objectstate import set_global_config phase_timing = PhaseTimingTrace( run_id=f"{request.dataset_id}:{request.pipeline_name}:openhcs", @@ -431,12 +428,7 @@ def _run_converted_cppipe_pipeline( output_suffix=output_suffix, compilation_debug_config=compilation_debug_config, ) - ensure_global_config_context(GlobalPipelineConfig, global_config) - pipeline_config = rebuild_lazy_config_with_new_global_reference( - pipeline_config, - global_config, - GlobalPipelineConfig, - ) + set_global_config(GlobalPipelineConfig, global_config) observation_export_path = ( MeasuredPipelineRunArtifact.RUNTIME_OBSERVATION.path_in(request.output_dir) ) diff --git a/benchmark/matched_cellprofiler_batch.py b/benchmark/matched_cellprofiler_batch.py index da339c42a..4a69e9005 100644 --- a/benchmark/matched_cellprofiler_batch.py +++ b/benchmark/matched_cellprofiler_batch.py @@ -26,10 +26,7 @@ from typing import Any import openhcs -from objectstate.lazy_factory import ( - ensure_global_config_context, - rebuild_lazy_config_with_new_global_reference, -) +from objectstate import set_global_config from zmqruntime.messages import ExecutionStatusSnapshot from benchmark.adapters.cellprofiler import ( @@ -1135,9 +1132,8 @@ def _candidate_pipeline_config( output_dir_suffix="_matched_pilot", ), ) - return rebuild_lazy_config_with_new_global_reference( - pipeline_config, global_config, GlobalPipelineConfig - ) + set_global_config(GlobalPipelineConfig, global_config) + return pipeline_config def main(argv: list[str] | None = None) -> int: @@ -1660,7 +1656,7 @@ def capture_progress_event(event: Mapping[str, Any]) -> None: worker_count=args.openhcs_workers, start_method=start_method, ) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) pipeline_config = _candidate_pipeline_config( prepared.pipeline_config, global_config, output_dir, wells ) diff --git a/benchmark/well_throughput_scaling.py b/benchmark/well_throughput_scaling.py index 6c498ff26..b63f1598f 100644 --- a/benchmark/well_throughput_scaling.py +++ b/benchmark/well_throughput_scaling.py @@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Any import psutil -from objectstate.lazy_factory import rebuild_lazy_config_with_new_global_reference +from objectstate import set_global_config if TYPE_CHECKING: from benchmark.reports.cppipe_figures import BenchmarkMetricRow @@ -2098,25 +2098,22 @@ def run_case_well_throughput( analysis_consolidation_config=AnalysisConsolidationConfig(enabled=False), materialize_runtime_artifacts=False, ) - pipeline_config = rebuild_lazy_config_with_new_global_reference( - replace( - prepared.pipeline_config, - num_workers=None, - use_threading=None, - multiprocessing_start_method=None, - materialize_runtime_artifacts=False, - partition_filter_config=LazyPartitionFilterConfig(partition_filter=list(well_ids)), - path_planning_config=LazyPathPlanningConfig( - partition_filter=0, - global_output_folder=output_root, - output_dir_suffix="_well_throughput", - ), - vfs_config=LazyVFSConfig( - materialization_backend=MaterializeToDisk - ), + set_global_config(GlobalPipelineConfig, global_config) + pipeline_config = replace( + prepared.pipeline_config, + num_workers=None, + use_threading=None, + multiprocessing_start_method=None, + materialize_runtime_artifacts=False, + partition_filter_config=LazyPartitionFilterConfig(partition_filter=list(well_ids)), + path_planning_config=LazyPathPlanningConfig( + partition_filter=0, + global_output_folder=output_root, + output_dir_suffix="_well_throughput", + ), + vfs_config=LazyVFSConfig( + materialization_backend=MaterializeToDisk ), - global_config, - GlobalPipelineConfig, ) run_id = f"{case_name}-{mode.name}-{time.time_ns()}" observation_path = ( diff --git a/openhcs/agent/services/artifact_plan_inspection_service.py b/openhcs/agent/services/artifact_plan_inspection_service.py index bcb402777..755b63607 100644 --- a/openhcs/agent/services/artifact_plan_inspection_service.py +++ b/openhcs/agent/services/artifact_plan_inspection_service.py @@ -108,13 +108,13 @@ def _compile(self, request: CompileInspectionInput) -> CompileInspectionResult: class InProcessCompileInspectionGateway(CompileInspectionGatewayABC): def _compile(self, request: CompileInspectionInput) -> CompileInspectionResult: - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.core.config.pipeline_config import GlobalPipelineConfig from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator from openhcs.core.progress.types import set_progress_queue - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, request.global_pipeline_config, ) diff --git a/openhcs/agent/services/plate_inspection_service.py b/openhcs/agent/services/plate_inspection_service.py index 856995a87..0a1ae4aad 100644 --- a/openhcs/agent/services/plate_inspection_service.py +++ b/openhcs/agent/services/plate_inspection_service.py @@ -952,12 +952,9 @@ class PlateInspectionPathPlanningConfigProvider: """Resolve the saved global path-planning config used for result discovery.""" def path_planning_config(self) -> PathPlanningConfig: - from objectstate import get_current_global_config + from objectstate import get_saved_global_config - global_config = get_current_global_config( - GlobalPipelineConfig, - use_live=False, - ) + global_config = get_saved_global_config(GlobalPipelineConfig) if global_config is None: return PathPlanningConfig() return global_config.path_planning_config diff --git a/openhcs/authoring/session/session.py b/openhcs/authoring/session/session.py index 4ebc2dfb0..a92c2b7ca 100644 --- a/openhcs/authoring/session/session.py +++ b/openhcs/authoring/session/session.py @@ -23,7 +23,7 @@ from pathlib import Path from typing import TYPE_CHECKING, TypeVar -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state import ObjectState, ObjectStateRegistry from polystore.base import _create_storage_registry from formbridge.services.async_operation_executor import AsyncOperationExecutor @@ -451,7 +451,7 @@ def adopt_global_config(self, config: GlobalPipelineConfig) -> None: """A saved global config: every dataset now resolves against it.""" self.global_config = config - ensure_global_config_context(GlobalPipelineConfig, config) + set_global_config(GlobalPipelineConfig, config) for scope_id in dataset_scope_ids(): orchestrator = ObjectStateRegistry.get_object(scope_id) if orchestrator is not None: @@ -1013,7 +1013,7 @@ def mirrored_workspace(self, source_root: Path) -> InputWorkspacePreparationResu ) async def initialize_datasets(self, scope_ids: tuple[str, ...]) -> None: - ensure_global_config_context(GlobalPipelineConfig, self.global_config) + set_global_config(GlobalPipelineConfig, self.global_config) for scope_id in scope_ids: self.require_work_allowed(scope_id) self.init_pending.update(scope_ids) @@ -1038,7 +1038,7 @@ async def initialize(scope_id: str) -> None: self.publish(DatasetsChanged()) def run() -> InputWorkspacePreparationResult | None: - ensure_global_config_context(GlobalPipelineConfig, self.global_config) + set_global_config(GlobalPipelineConfig, self.global_config) workspace = scope.prepare_input_workspace() if workspace is None and not self.dataset_access.initializes_in_place( scope.root diff --git a/openhcs/core/config/config_cache.py b/openhcs/core/config/config_cache.py index 62790bedd..68303172d 100644 --- a/openhcs/core/config/config_cache.py +++ b/openhcs/core/config/config_cache.py @@ -134,9 +134,9 @@ def _fsync_directory(directory: Path) -> None: def _establish_global_pipeline_config(config: GlobalPipelineConfig) -> None: - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config - ensure_global_config_context(GlobalPipelineConfig, config) + set_global_config(GlobalPipelineConfig, config) def global_pipeline_config_cache_spec() -> ConfigCacheSpec[GlobalPipelineConfig]: diff --git a/openhcs/core/config/pipeline_config.py b/openhcs/core/config/pipeline_config.py index 447d016af..b3d600a65 100644 --- a/openhcs/core/config/pipeline_config.py +++ b/openhcs/core/config/pipeline_config.py @@ -79,7 +79,7 @@ from objectstate import auto_create_decorator, abbreviation, get_base_config_type -from objectstate.global_config import get_current_global_config +from objectstate.global_config import get_live_global_config from objectstate.lazy_factory import LazyDataclass @@ -1469,11 +1469,11 @@ def get_all_streaming_ports( base_config_type = get_base_config_type() if config is None: - config = get_current_global_config(base_config_type) + config = get_live_global_config(base_config_type) if config is None: return ports - global_config = get_current_global_config(base_config_type) + global_config = get_live_global_config(base_config_type) for streaming_config_type in tuple(StreamingConfig.__registry__.values()): port = streaming_config_type.port_from_config(config) diff --git a/openhcs/pyqt_gui/app.py b/openhcs/pyqt_gui/app.py index e82f618df..89b867138 100644 --- a/openhcs/pyqt_gui/app.py +++ b/openhcs/pyqt_gui/app.py @@ -220,8 +220,7 @@ def init_storage_registry_background(): # CRITICAL FIX: Establish global config context for lazy dataclass resolution # This was missing and caused placeholder resolution to fall back to static defaults - from objectstate.global_config import set_global_config_for_editing - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from objectstate.object_state import ( ObjectState, ObjectStateRegistry, @@ -229,13 +228,8 @@ def init_storage_registry_background(): from openhcs.core.config.pipeline_config import GlobalPipelineConfig - # Set for editing (UI placeholders) - this uses threading.local() storage - set_global_config_for_editing( - GlobalPipelineConfig, self.pipeline_runtime_config - ) - - # ALSO ensure context for orchestrator creation (required by orchestrator.__init__) - ensure_global_config_context(GlobalPipelineConfig, self.pipeline_runtime_config) + # The process's global config: UI placeholders and orchestrator creation both read it. + set_global_config(GlobalPipelineConfig, self.pipeline_runtime_config) # Register GlobalPipelineConfig ObjectState (singleton, persists for app lifetime) # This is the root of the ObjectState hierarchy diff --git a/openhcs/pyqt_gui/main.py b/openhcs/pyqt_gui/main.py index 956a32a3a..77563ff1f 100644 --- a/openhcs/pyqt_gui/main.py +++ b/openhcs/pyqt_gui/main.py @@ -1167,7 +1167,7 @@ def _on_consolidate_results(self): return try: - from objectstate.global_config import get_current_global_config + from objectstate import get_live_global_config from openhcs.core.config.pipeline_config import GlobalPipelineConfig from openhcs.processing.backends.analysis.consolidate_analysis_results import ( @@ -1175,7 +1175,7 @@ def _on_consolidate_results(self): ) # Get global config - global_config = get_current_global_config(GlobalPipelineConfig) + global_config = get_live_global_config(GlobalPipelineConfig) # Run consolidation summary_df = consolidate_analysis_results( diff --git a/openhcs/pyqt_gui/services/window_handlers.py b/openhcs/pyqt_gui/services/window_handlers.py index 24ca8a21f..00df9787b 100644 --- a/openhcs/pyqt_gui/services/window_handlers.py +++ b/openhcs/pyqt_gui/services/window_handlers.py @@ -52,7 +52,7 @@ def create_global_config_window( request: ScopeWindowCreationRequest, ) -> Optional[QWidget]: """Create GlobalPipelineConfig editor window.""" - from objectstate import ObjectStateRegistry, set_global_config_for_editing + from objectstate import ObjectStateRegistry, set_global_config from openhcs.core.config.pipeline_config import GlobalPipelineConfig from openhcs.core.config.config_cache import save_global_config_sync @@ -94,7 +94,7 @@ def handle_save(new_config: GlobalPipelineConfig) -> None: if not save_global_config_sync(new_config): raise RuntimeError("Failed to persist GlobalPipelineConfig.") if not self._emit_main_window_global_config_changed(new_config): - set_global_config_for_editing(GlobalPipelineConfig, new_config) + set_global_config(GlobalPipelineConfig, new_config) logger.info("Global config saved via window") def handle_ui_save(new_config: UIConfig) -> None: diff --git a/openhcs/runtime/zmq/zmq_execution_server.py b/openhcs/runtime/zmq/zmq_execution_server.py index 7a060eb30..e245e1284 100644 --- a/openhcs/runtime/zmq/zmq_execution_server.py +++ b/openhcs/runtime/zmq/zmq_execution_server.py @@ -894,11 +894,9 @@ def _emit_compile_failure( def _ensure_request_global_config_context( request_context: ZMQExecutionContext, ) -> None: - from objectstate.lazy_factory import ( - ensure_global_config_context, - ) + from objectstate import set_global_config - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, request_context.configs.global_pipeline, ) From 4709e13e62a345ca089f3ae290def7a3b3bf48fb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:45:34 +0000 Subject: [PATCH 18/27] An array no plan placed goes to its library's first device, said once Four callers stacked or unstacked with a bare 0 where arraybridge now takes a Device. unplanned_device(memory_type) in openhcs.core.memory owns the answer: main memory, or the first accelerator of a library that has them, which is what the integer meant. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- openhcs/core/callable/processing_contracts.py | 6 +++--- openhcs/core/memory/__init__.py | 13 ++++++++++++- openhcs/core/object_labels/runtime_object_labels.py | 4 ++-- openhcs/core/payload/aligned_image_payload.py | 5 +++-- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/openhcs/core/callable/processing_contracts.py b/openhcs/core/callable/processing_contracts.py index c41bbad2e..192ff7896 100644 --- a/openhcs/core/callable/processing_contracts.py +++ b/openhcs/core/callable/processing_contracts.py @@ -31,7 +31,7 @@ ConcatenatedColumnarRows, MeasurementRowsAxisProjection, ) -from openhcs.core.memory import stack_runtime_slices, unstack_runtime_slices +from openhcs.core.memory import stack_runtime_slices, unplanned_device, unstack_runtime_slices from openhcs.core.payload.runtime_array_values import RuntimeArrayPayload @@ -413,7 +413,7 @@ def slice_value(self, value: Any, memory_type: str) -> tuple[Any, ...]: slices = unstack_runtime_slices( data, memory_type, - 0, + unplanned_device(memory_type), expected_count=metadata.source_provenance.source_plane_count or None, ) return tuple( @@ -626,7 +626,7 @@ def aggregate_values( def stack_array_slices(self, values: list[Any], memory_type: str) -> Any: """Stack an explicitly collected dense runtime-slice sequence.""" - return stack_runtime_slices(values, memory_type, 0) + return stack_runtime_slices(values, memory_type, unplanned_device(memory_type)) class ImagePayloadPure2DAuxiliaryOutputAggregator( diff --git a/openhcs/core/memory/__init__.py b/openhcs/core/memory/__init__.py index 691335557..f06950283 100644 --- a/openhcs/core/memory/__init__.py +++ b/openhcs/core/memory/__init__.py @@ -8,7 +8,8 @@ from typing import Any from arraybridge import ArrayGeometry -from arraybridge.devices import Device +from arraybridge.devices import HOST, AcceleratorDevice, Device +from arraybridge.libraries import AcceleratorDevices # Re-export from arraybridge from arraybridge import ( @@ -38,6 +39,15 @@ globals()[_memory_type.value] = getattr(decorators, _memory_type.value) +def unplanned_device(memory_type: str) -> Device: + """Where a memory type's arrays go when no compiled plan placed them: main memory, + or the first accelerator of a library that has them.""" + + if isinstance(MemoryType(memory_type).library, AcceleratorDevices): + return AcceleratorDevice(0) + return HOST + + def stack_runtime_slices( slices: Sequence[Any], memory_type: str, @@ -106,6 +116,7 @@ def unstack_runtime_slices( "stack_slices", "unstack_slices", "stack_runtime_slices", + "unplanned_device", "unstack_runtime_slices", # Slice processing "process_slices", diff --git a/openhcs/core/object_labels/runtime_object_labels.py b/openhcs/core/object_labels/runtime_object_labels.py index c8aa564b6..20d7616e3 100644 --- a/openhcs/core/object_labels/runtime_object_labels.py +++ b/openhcs/core/object_labels/runtime_object_labels.py @@ -63,7 +63,7 @@ def _passthrough(func): SourceSpatialDomainFields, ) -from openhcs.core.memory import MemoryType, runtime_slice_stack_geometry, stack_runtime_slices +from openhcs.core.memory import MemoryType, runtime_slice_stack_geometry, stack_runtime_slices, unplanned_device from openhcs.core.payload.runtime_image_values import RuntimeSliceProjectionDeclarationError _PRESERVE_PLANE_AXIS = object() @@ -1760,7 +1760,7 @@ def stack_planes( return stack_runtime_slices( tuple(cast(np.ndarray, value) for value in labels), memory_type, - 0, + unplanned_device(memory_type), ) def validate_plane_count( diff --git a/openhcs/core/payload/aligned_image_payload.py b/openhcs/core/payload/aligned_image_payload.py index 906db9b54..e8a650940 100644 --- a/openhcs/core/payload/aligned_image_payload.py +++ b/openhcs/core/payload/aligned_image_payload.py @@ -26,6 +26,7 @@ convert_memory, detect_memory_type, stack_runtime_slices, + unplanned_device, runtime_slice_stack_geometry, ) from openhcs.core.payload.runtime_image_values import ImagePayload, ImagePayloadMetadata, ImagePayloadSliceProjector, ImagePayloadSourceSpatialDomainAdapter, project_image_mask_to_data_domain @@ -1602,7 +1603,7 @@ def _materialized_image_mask(self) -> Any | None: return None shared = self._shared_image_mask(masks, self.geometry) return shared if shared is not None else stack_runtime_slices( - masks, self.memory_type, 0, + masks, self.memory_type, unplanned_device(self.memory_type), ) def __getstate__(self) -> dict[str, Any]: @@ -1678,7 +1679,7 @@ def compose( if self._composed_payload is None: data = stack_runtime_slices( tuple(payload.data for payload in self.slices), - self.memory_type, MemoryType(self.memory_type).library.device_of(self.slices[0].data), + self.memory_type, unplanned_device(self.memory_type), ) self._composed_payload = self._metadata.payload_with( data, self._materialized_image_mask(), From eb256636e148c25376f2758217721c2dd0ce6586 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:58:26 +0000 Subject: [PATCH 19/27] Tests speak the siblings' current names: libraries, devices, the stored global config MemoryType.X.library carries the array operations, a placement is a Device value (HOST, AcceleratorDevice(n)), a child's environment is ArrayLibrary.child_environment, and the global config is set, read live or saved, and forgotten through objectstate's own functions. Fakes patch the library class that owns the method (on_every_library). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- tests/conftest.py | 36 +++++++----- .../test_cellprofiler_generated_pipeline.py | 6 +- .../test_count_cells_simple_dual_channel.py | 4 +- tests/integration/test_main.py | 4 +- .../test_neurite_outgrowth_synthetic_plate.py | 4 +- .../test_source_store_code_mode_zmq.py | 4 +- .../test_end_to_end_workflow_foundation.py | 4 +- .../agent/test_owned_runtime_bootstrap.py | 2 +- tests/unit/pyqt_gui/session_harness.py | 4 +- .../test_config_window_state_resolution.py | 4 +- .../pyqt_gui/test_enableable_function_ui.py | 4 +- tests/unit/pyqt_gui/test_image_browser.py | 4 +- .../test_image_browser_streaming_config.py | 4 +- ...est_parameter_form_manager_cross_window.py | 4 +- .../pyqt_gui/test_source_bindings_editor.py | 28 +++++----- tests/unit/pyqt_gui/test_ui_agent_bridge.py | 4 +- tests/unit/remote_sensing_witness_pipeline.py | 4 +- ...cquisition_calibration_pipeline_journey.py | 4 +- .../unit/test_aligned_image_payload_device.py | 35 ++++++------ .../test_bioformats_microscope_handler.py | 4 +- .../test_bioformats_preparation_selection.py | 6 +- tests/unit/test_callable_abi_preparation.py | 3 +- tests/unit/test_cell_counting_cupy.py | 25 +++------ ...test_cellprofiler_artifact_declarations.py | 4 +- ...ellprofiler_combineobjects_source_scope.py | 4 +- .../test_cellprofiler_export_to_database.py | 4 +- ...llprofiler_generated_pipeline_execution.py | 4 +- .../test_cellprofiler_module_execution.py | 5 +- tests/unit/test_compilation_paths.py | 4 +- tests/unit/test_compilation_session.py | 14 ++--- tests/unit/test_compiled_execution.py | 6 +- .../unit/test_czi_brain_axon_cellbody_demo.py | 4 +- tests/unit/test_debug_runtime.py | 10 ++-- tests/unit/test_family_registries_restored.py | 12 ++-- tests/unit/test_framework_device_resolver.py | 56 ++++++++++--------- tests/unit/test_framework_execution_scope.py | 11 ++-- tests/unit/test_function_artifact_outputs.py | 21 +++---- tests/unit/test_function_patterns.py | 3 +- ...test_function_runtime_source_projection.py | 8 +-- .../unit/test_function_step_execution_plan.py | 23 ++++---- tests/unit/test_image_plane_contracts.py | 14 +++-- .../test_implicit_main_flow_compilation.py | 4 +- tests/unit/test_library_registry_discovery.py | 4 +- .../test_loose_operaphenix_neurite_example.py | 4 +- ..._operaphenix_neurite_metaxpress_example.py | 4 +- ...test_materialization_filter_inheritance.py | 6 +- tests/unit/test_mcp_assay_showcase.py | 4 +- tests/unit/test_memory_type_authority.py | 24 +------- ...t_microscope_virtual_workspace_metadata.py | 4 +- tests/unit/test_neuroncyto_ii_neurite_demo.py | 8 +-- .../test_opaque_main_flow_image_domain.py | 25 +++++---- .../unit/test_path_planner_materialization.py | 6 +- ...tates_resolve_from_registered_ancestors.py | 16 ++++-- tests/unit/test_plane_store_sources.py | 6 +- tests/unit/test_primary_object_diagnostics.py | 5 +- tests/unit/test_processing_module_liveness.py | 4 +- .../test_processor_operations_written_once.py | 5 +- ...global_config_reaches_registered_states.py | 20 ++++--- tests/unit/test_routed_channel_selection.py | 4 +- tests/unit/test_routed_composite_execution.py | 4 +- tests/unit/test_source_bindings.py | 18 +++--- tests/unit/test_source_tile_geometry.py | 4 +- .../test_template_crop_pipeline_execution.py | 4 +- .../test_unified_registry_runtime_payloads.py | 10 ++-- ...test_zarr_input_conversion_subdirectory.py | 4 +- tests/unit/test_zmq_execution_server.py | 6 +- .../unit/test_zmq_execution_server_process.py | 4 +- 67 files changed, 309 insertions(+), 306 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 4c1ab71a7..f5c0f5de1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -190,21 +190,29 @@ def restored_global_configs() -> Iterator[None]: """The saved and live global config of every config type is, after a test, what it was before it.""" from objectstate import global_config - def config_types() -> set[type]: - return { - *global_config._saved_global_config_contexts, - *global_config._live_global_config_contexts, - } - - before = { - config_type: global_config.GlobalContextValues.capture(config_type) - for config_type in config_types() - } + before = dict(global_config._stored_global_configs) yield - for config_type in config_types(): - before.get( - config_type, global_config.GlobalContextValues(config_type, None, None) - ).apply() + for config_type in {*before, *global_config._stored_global_configs}: + if config_type in before: + global_config.set_global_config(config_type, before[config_type]) + else: + global_config.forget_stored_global_config(config_type) + + +@pytest.fixture +def on_every_library(monkeypatch) -> Callable[[str, object], None]: + """Replace one method on every array library's own class, for a test. + + A library may state the method itself (CuPy and torch clean up their own way), so + replacing it on the family's base would leave those untouched. + """ + from arraybridge import MemoryType + + def replace(name: str, replacement: object) -> None: + for memory_type in MemoryType: + monkeypatch.setattr(type(memory_type.library), name, replacement) + + return replace @pytest.fixture diff --git a/tests/integration/test_cellprofiler_generated_pipeline.py b/tests/integration/test_cellprofiler_generated_pipeline.py index 6c6e67d9d..1415e1686 100644 --- a/tests/integration/test_cellprofiler_generated_pipeline.py +++ b/tests/integration/test_cellprofiler_generated_pipeline.py @@ -14,7 +14,7 @@ import pytest import tifffile from objectstate import replace_raw -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from PIL import Image from polystore.base import _create_storage_registry from polystore.filemanager import FileManager @@ -169,7 +169,7 @@ def _execute_imported_cppipe_via_zmq( materialize_runtime_artifacts=materialize_runtime_artifacts, analysis_consolidation_config=AnalysisConsolidationConfig(enabled=False), ) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) pipeline_config = replace_raw( imported_config, path_planning_config=LazyPathPlanningConfig( @@ -358,7 +358,7 @@ def test_invalid_public_cellprofiler_step_fails_during_zmq_compilation( dataset_source=SourceBindingsSource, analysis_consolidation_config=AnalysisConsolidationConfig(enabled=False), ) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) pipeline_config = replace_raw( PipelineConfig( dataset_source=SourceBindingsSource, diff --git a/tests/integration/test_count_cells_simple_dual_channel.py b/tests/integration/test_count_cells_simple_dual_channel.py index ac07c7602..34025a858 100644 --- a/tests/integration/test_count_cells_simple_dual_channel.py +++ b/tests/integration/test_count_cells_simple_dual_channel.py @@ -15,7 +15,7 @@ ExecutionWaitResult, ) -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.artifacts.kinds import ( MeasurementsArtifactType, ObjectLabelsArtifactType, @@ -251,7 +251,7 @@ def persisted_special_output_probe(image): ) observation_path = tmp_path / "dual_channel_runtime_observation.pkl" - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) submission = OpenHCSExecutionSubmission( subject_id=plate_dir, pipeline_document=PipelineDocumentCodec.from_values( diff --git a/tests/integration/test_main.py b/tests/integration/test_main.py index a0bb6f495..fdaa1fdee 100644 --- a/tests/integration/test_main.py +++ b/tests/integration/test_main.py @@ -73,7 +73,7 @@ zmq_execution_mode, ) -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.config.pipeline_config import GlobalPipelineConfig, PipelineConfig from openhcs.core.axes.axis_declarations import AxisFamily, Ungrouped from openhcs.domains.microscopy.axes import Microscopy @@ -493,7 +493,7 @@ def _initialize_orchestrator( global_config = _create_pipeline_config(test_config) # Set up global context for orchestrator - legitimate test setup - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) # For OMERO: Register OMERO backend with connection omero_manager = None diff --git a/tests/integration/test_neurite_outgrowth_synthetic_plate.py b/tests/integration/test_neurite_outgrowth_synthetic_plate.py index bd44d5cf6..d4f461801 100644 --- a/tests/integration/test_neurite_outgrowth_synthetic_plate.py +++ b/tests/integration/test_neurite_outgrowth_synthetic_plate.py @@ -38,7 +38,7 @@ from zmqruntime.config import TransportMode from skimage.draw import disk, line -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.config.pipeline_config import ( GlobalPipelineConfig, LazyPathPlanningConfig, @@ -178,7 +178,7 @@ def observe_dense_output(output, components): monkeypatch.setattr(Output, "with_variable_components", observe_dense_output) try: - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) orchestrator = PipelineOrchestrator( plate_dir, pipeline_config=pipeline_config ).initialize() diff --git a/tests/integration/test_source_store_code_mode_zmq.py b/tests/integration/test_source_store_code_mode_zmq.py index 1c72a319e..2e4d2560a 100644 --- a/tests/integration/test_source_store_code_mode_zmq.py +++ b/tests/integration/test_source_store_code_mode_zmq.py @@ -8,7 +8,7 @@ import numpy as np import pytest -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from ome_zarr.format import Format from polystore.bioformats_java import BioFormatsJavaContext from zmqruntime.execution.responses import ( @@ -271,7 +271,7 @@ def test_code_mode_and_zmq_wire_preserve_mixed_store_sources( for binding in wire_pipeline_document.pipeline_config.source_bindings_config.bindings ] == list(stores) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) orchestrator = PipelineOrchestrator( dataset_root=tmp_path, pipeline_config=pipeline_config, diff --git a/tests/pyqt_gui/integration/test_end_to_end_workflow_foundation.py b/tests/pyqt_gui/integration/test_end_to_end_workflow_foundation.py index e73e362bb..b29f1fb5e 100644 --- a/tests/pyqt_gui/integration/test_end_to_end_workflow_foundation.py +++ b/tests/pyqt_gui/integration/test_end_to_end_workflow_foundation.py @@ -1268,7 +1268,7 @@ def application_lifecycle(self): """Own one real OpenHCS application for the complete workflow matrix.""" import sys - from objectstate.global_config import get_current_global_config + from objectstate.global_config import get_live_global_config from openhcs.pyqt_gui.app import OpenHCSPyQtApp @@ -1298,7 +1298,7 @@ def application_lifecycle(self): pipeline_runtime=_create_test_global_config(), ), ) - if get_current_global_config(GlobalPipelineConfig) is None: + if get_live_global_config(GlobalPipelineConfig) is None: raise AssertionError("OpenHCS did not establish its global config context.") app.create_main_window() diff --git a/tests/unit/agent/test_owned_runtime_bootstrap.py b/tests/unit/agent/test_owned_runtime_bootstrap.py index 5b70d1f67..a9337b6eb 100644 --- a/tests/unit/agent/test_owned_runtime_bootstrap.py +++ b/tests/unit/agent/test_owned_runtime_bootstrap.py @@ -160,7 +160,7 @@ def test_admitted_plan_owns_materialization_and_child_configuration( monkeypatch.setattr(module.subprocess, "Popen", launch) environment = {"PLAN_TEST": "owned"} monkeypatch.setattr( - module.MemoryType, "subprocess_environment", lambda: environment + module.ArrayLibrary, "child_environment", classmethod(lambda cls: environment) ) launch_record = EndpointLaunch.by_this_process( diff --git a/tests/unit/pyqt_gui/session_harness.py b/tests/unit/pyqt_gui/session_harness.py index 36868dd6f..43f14673b 100644 --- a/tests/unit/pyqt_gui/session_harness.py +++ b/tests/unit/pyqt_gui/session_harness.py @@ -10,7 +10,7 @@ from dataclasses import dataclass, field from pathlib import Path -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state import ObjectStateRegistry from pyqt_reactive.theming import ColorScheme @@ -69,7 +69,7 @@ def caller_session(**kwargs) -> Iterator[Session]: ObjectStateRegistry.clear() global_config = kwargs.pop("global_config", GlobalPipelineConfig()) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) persisted = kwargs.pop("persisted_scope_ids", None) if persisted is not None: write_dataset_scope_ids(list(persisted)) diff --git a/tests/unit/pyqt_gui/test_config_window_state_resolution.py b/tests/unit/pyqt_gui/test_config_window_state_resolution.py index d0ee323b1..65ea2f1d7 100644 --- a/tests/unit/pyqt_gui/test_config_window_state_resolution.py +++ b/tests/unit/pyqt_gui/test_config_window_state_resolution.py @@ -7,7 +7,7 @@ from objectstate import ( ObjectState, ObjectStateRegistry, - set_global_config_for_editing, + set_global_config, ) from pyqt_reactive.forms.parameter_form_manager import ( FormManagerConfig, @@ -760,7 +760,7 @@ def test_pipeline_streaming_enableable_placeholders_dim_after_build_and_toggle( ) -> None: """Lazy inherited streaming configs still receive enableable dimming.""" ObjectStateRegistry.clear() - set_global_config_for_editing(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="/tmp/plate") ObjectStateRegistry.register(state, _skip_snapshot=True) diff --git a/tests/unit/pyqt_gui/test_enableable_function_ui.py b/tests/unit/pyqt_gui/test_enableable_function_ui.py index 719598fc6..112484315 100644 --- a/tests/unit/pyqt_gui/test_enableable_function_ui.py +++ b/tests/unit/pyqt_gui/test_enableable_function_ui.py @@ -5,7 +5,7 @@ from PyQt6.QtTest import QTest -from objectstate.global_config import set_global_config_for_editing +from objectstate import set_global_config from objectstate.object_state import ObjectState, ObjectStateRegistry from openhcs.core.config.pipeline_config import GlobalPipelineConfig, PipelineConfig from openhcs.core.steps.function_step import FunctionStep @@ -73,7 +73,7 @@ def test_registered_function_pane_moves_only_enabled_control_to_title(qapp) -> N def test_step_lazy_enableable_contents_stay_dimmed_after_async_build(qapp) -> None: """Parent refreshes must not overwrite a nested Enableable's resolved state.""" ObjectStateRegistry.clear() - set_global_config_for_editing(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) plate_state = ObjectState(PipelineConfig(), scope_id="enableable-plate") step_state = ObjectState( FunctionStep(func=lambda image: image), diff --git a/tests/unit/pyqt_gui/test_image_browser.py b/tests/unit/pyqt_gui/test_image_browser.py index 79a66e83e..87cee06aa 100644 --- a/tests/unit/pyqt_gui/test_image_browser.py +++ b/tests/unit/pyqt_gui/test_image_browser.py @@ -7,7 +7,7 @@ import pytest from objectstate import ObjectStateRegistry -from objectstate.global_config import set_global_config_for_editing +from objectstate import set_global_config from PyQt6.QtCore import Qt from pyqt_reactive.theming import ColorScheme from pyqt_reactive.widgets.shared.record_table_browser import LabelledValue @@ -117,7 +117,7 @@ def remote_sensing() -> Iterator[type[RemoteSensing]]: def _reset_global_config() -> None: ObjectStateRegistry.clear() - set_global_config_for_editing(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) def test_microscopy_files_show_axis_columns_filters_grid_and_folders(qapp) -> None: diff --git a/tests/unit/pyqt_gui/test_image_browser_streaming_config.py b/tests/unit/pyqt_gui/test_image_browser_streaming_config.py index 3f1dfed97..c756656ac 100644 --- a/tests/unit/pyqt_gui/test_image_browser_streaming_config.py +++ b/tests/unit/pyqt_gui/test_image_browser_streaming_config.py @@ -3,7 +3,7 @@ from types import SimpleNamespace from objectstate import ObjectState, ObjectStateRegistry -from objectstate.global_config import set_global_config_for_editing +from objectstate import set_global_config from PyQt6 import sip from PyQt6.QtTest import QTest from pyqt_reactive.widgets.shared.responsive_layout_widgets import ( @@ -44,7 +44,7 @@ def test_image_browser_state_resolves_plate_then_global(tmp_path) -> None: global_config = GlobalPipelineConfig( streaming_defaults=StreamingDefaults(host="global-host"), ) - set_global_config_for_editing(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) try: global_state = ObjectState(global_config, scope_id="") ObjectStateRegistry.register(global_state, _skip_snapshot=True) diff --git a/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py b/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py index 732e9fdfc..92bb0215f 100644 --- a/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py +++ b/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py @@ -4,7 +4,7 @@ from PyQt6.QtWidgets import QApplication from objectstate import ObjectStateRegistry -from objectstate.global_config import set_global_config_for_editing +from objectstate import set_global_config from objectstate.object_state import ObjectState from openhcs.core.config.pipeline_config import GlobalPipelineConfig, PipelineConfig from pyqt_reactive.forms.parameter_form_chrome_sync import ParameterFormChromeSync @@ -447,7 +447,7 @@ def test_list_enum_placeholder_preview_refreshes_structural_child_paths() -> Non global_config = GlobalPipelineConfig() global_state = ObjectState(global_config, scope_id="") ObjectStateRegistry.register(global_state, _skip_snapshot=True) - set_global_config_for_editing(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) plate_state = ObjectState(PipelineConfig(), scope_id="/tmp/plate") ObjectStateRegistry.register(plate_state, _skip_snapshot=True) diff --git a/tests/unit/pyqt_gui/test_source_bindings_editor.py b/tests/unit/pyqt_gui/test_source_bindings_editor.py index e6e6090c4..37d6a1dfd 100644 --- a/tests/unit/pyqt_gui/test_source_bindings_editor.py +++ b/tests/unit/pyqt_gui/test_source_bindings_editor.py @@ -70,7 +70,7 @@ get_base_type_for_lazy, replace_raw, ) -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from pyqt_reactive.forms.parameter_form_manager import ( FormManagerConfig, ParameterFormManager, @@ -594,7 +594,7 @@ def test_pipeline_source_bindings_table_edits_recreate_container_and_children() def test_pipeline_source_bindings_edit_refreshes_step_lazy_preview() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) binding = NamedSourceBinding(alias="DNA") state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) @@ -658,7 +658,7 @@ def test_pipeline_source_bindings_edit_refreshes_step_lazy_preview() -> None: def test_pipeline_step_source_bindings_refresh_open_step_editor_preview() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) binding = NamedSourceBinding(alias="DNA") plate_state = ObjectState(PipelineConfig(), scope_id="plate") step_state = ObjectState( @@ -736,7 +736,7 @@ def test_pipeline_step_source_bindings_refresh_open_step_editor_preview() -> Non def test_pipeline_step_source_filter_time_travel_refreshes_open_step_editor() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) plate_state = ObjectState(PipelineConfig(), scope_id="plate") step_state = ObjectState( FunctionStep(func=lambda image: image), @@ -873,7 +873,7 @@ def test_pipeline_step_source_filter_time_travel_refreshes_open_step_editor() -> def test_source_bindings_enableable_chrome_uses_nominal_step_config() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) manager = ParameterFormManager( @@ -967,7 +967,7 @@ def test_source_bindings_enableable_chrome_uses_nominal_step_config() -> None: def test_source_bindings_enableable_reset_to_inherited_true_is_path_scoped() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( step_source_bindings_config=StepSourceBindingsConfig(enabled=True), @@ -1058,7 +1058,7 @@ def test_source_bindings_enableable_reset_from_false_to_inherited_value_is_path_ for inherited_enabled in (True, False): ObjectStateRegistry.clear() - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( step_source_bindings_config=StepSourceBindingsConfig( @@ -1137,7 +1137,7 @@ def record_set_value(value): def test_pipeline_source_bindings_preview_preserves_inherited_table_rows() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) manager = ParameterFormManager( @@ -1365,7 +1365,7 @@ def test_source_bindings_table_child_reset_restores_inherited_placeholder_rows() ): QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) manager = ParameterFormManager( @@ -1489,7 +1489,7 @@ def test_source_bindings_table_child_reset_restores_inherited_placeholder_rows() def test_source_bindings_inherited_table_combo_activation_materializes_child() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) manager = ParameterFormManager( @@ -1581,7 +1581,7 @@ def test_source_bindings_inherited_table_combo_activation_materializes_child() - def test_source_bindings_inherited_table_value_edit_undo_restores_lazy_child() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) manager = ParameterFormManager( @@ -1669,7 +1669,7 @@ def test_source_bindings_inherited_table_value_edit_undo_restores_lazy_child() - def test_source_bindings_inherited_table_edits_flash_only_changed_cell() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) state = ObjectState(PipelineConfig(), scope_id="plate") ObjectStateRegistry.register(state, _skip_snapshot=True) manager = ParameterFormManager( @@ -2306,7 +2306,7 @@ def test_source_bindings_child_reset_noops_for_already_inherited_table_preview() ): QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) inherited_filter = SourceFilterClause( SourceFileName, TextContains, @@ -2608,7 +2608,7 @@ def test_source_filters_fit_complete_rows_and_bar_inside_scoped_section() -> Non def test_step_metadata_rule_cells_show_inherited_and_local_edit_markers() -> None: QtApplicationHarness.app() ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) inherited_rule = MetadataExtractionRule( source=FromFileName, pattern=r"(?PA\d{2})_(?PDNA)\.tif", diff --git a/tests/unit/pyqt_gui/test_ui_agent_bridge.py b/tests/unit/pyqt_gui/test_ui_agent_bridge.py index fce714f53..4a55be3b6 100644 --- a/tests/unit/pyqt_gui/test_ui_agent_bridge.py +++ b/tests/unit/pyqt_gui/test_ui_agent_bridge.py @@ -6,7 +6,7 @@ from pathlib import Path import pytest -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state import ObjectState, ObjectStateRegistry from PyQt6 import sip from PyQt6.QtCore import Qt @@ -3551,7 +3551,7 @@ class BridgeSessions: @classmethod def get(cls) -> Session: if cls.current is None: - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) cls.current = Session( transport_config=OpenHCSZMQConfig( default_port=session_port(), persistent=False diff --git a/tests/unit/remote_sensing_witness_pipeline.py b/tests/unit/remote_sensing_witness_pipeline.py index af86e866d..5870887de 100644 --- a/tests/unit/remote_sensing_witness_pipeline.py +++ b/tests/unit/remote_sensing_witness_pipeline.py @@ -127,7 +127,7 @@ def run_direct(root: Path, output_root: Path) -> dict: from multiprocessing import SimpleQueue from objectstate import ObjectStateRegistry - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.core.config.pipeline_config import ( GlobalPipelineConfig, @@ -142,7 +142,7 @@ def run_direct(root: Path, output_root: Path) -> dict: queue = SimpleQueue() set_progress_queue(queue) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1, use_threading=True), ) diff --git a/tests/unit/test_acquisition_calibration_pipeline_journey.py b/tests/unit/test_acquisition_calibration_pipeline_journey.py index b86b5e0f0..bc49bd556 100644 --- a/tests/unit/test_acquisition_calibration_pipeline_journey.py +++ b/tests/unit/test_acquisition_calibration_pipeline_journey.py @@ -7,7 +7,7 @@ import numpy as np import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.config.pipeline_config import ( GlobalPipelineConfig, @@ -38,7 +38,7 @@ def test_htd_spacing_survives_gaussian_compile_execute_and_persist(tmp_path): queue = SimpleQueue() set_progress_queue(queue) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( dataset_source=ImageXpressHandler, num_workers=1, use_threading=True diff --git a/tests/unit/test_aligned_image_payload_device.py b/tests/unit/test_aligned_image_payload_device.py index f43c8cfda..870462027 100644 --- a/tests/unit/test_aligned_image_payload_device.py +++ b/tests/unit/test_aligned_image_payload_device.py @@ -1,3 +1,4 @@ +from arraybridge.devices import HOST, AcceleratorDevice from openhcs.core.payload.runtime_plane_projection import RuntimeSlicePlaneAxis, SourceBindingPlaneAxis import numpy as np import pytest @@ -126,23 +127,24 @@ def test_mixed_intensity_composition_uses_declared_memory_conversion( inputs = (raw, normalized) if raw_first else (normalized, raw) context = composition(inputs, metadata_mode=mode) kwargs = {} if destination == 'implicit' else { - 'memory_type': destination, 'device_id': 1 if destination == 'cupy' else None, + 'memory_type': destination, + 'device': AcceleratorDevice(1) if destination == 'cupy' else HOST, } result = context.compose(**kwargs) assert bool(state['downloads']) == (destination == 'numpy') output = result.data requested = 'cupy' if destination == 'implicit' else destination - owner = MemoryType(requested) + owner = MemoryType(requested).library np.testing.assert_array_equal(owner.to_numpy(output), 0.5) - assert owner.device_id_of(output) == (1 if requested == 'cupy' else None) + assert owner.device_of(output) == (AcceleratorDevice(1) if requested == 'cupy' else HOST) assert result.metadata.has_normalized_intensity mask = result.mask - mask_owner = MemoryType(aligned_image_payload.detect_memory_type(mask)) + mask_owner = MemoryType(aligned_image_payload.detect_memory_type(mask)).library masks = mask_owner.to_numpy(mask) expected = raw.mask.values if composition is ImagePayloadStackContext or not declared_spatial_extent: expected = np.stack(tuple(value.mask.values for value in inputs)) - assert mask_owner.device_id_of(mask) == owner.device_id_of(output) + assert mask_owner.device_of(mask) == owner.device_of(output) np.testing.assert_array_equal(masks, expected) assert state['downloads'] assert all(device == 1 for device in state['downloads']) @@ -163,17 +165,15 @@ def test_image_bundle_stacks_on_the_payload_framework_device(monkeypatch) -> Non lambda _payload: MemoryType.CUPY.value, ) monkeypatch.setattr( - MemoryType, - "device_id_of", - lambda memory_type, _payload, _module=None: ( - 7 if memory_type is MemoryType.CUPY else None - ), + type(MemoryType.CUPY.library), + "device_of", + lambda _library, _payload: AcceleratorDevice(7), ) monkeypatch.setattr( aligned_image_payload, "stack_runtime_slices", - lambda values, memory_type, device_id: observed.append( - (tuple(values), memory_type, device_id) + lambda values, memory_type, device: observed.append( + (tuple(values), memory_type, device) ) or "stacked", ) @@ -181,7 +181,7 @@ def test_image_bundle_stacks_on_the_payload_framework_device(monkeypatch) -> Non context = ImagePayloadBundleContext(payloads) assert context.compose_unmasked(payloads) == "stacked" - assert observed == [(payloads, MemoryType.CUPY.value, 7)] + assert observed == [(payloads, MemoryType.CUPY.value, AcceleratorDevice(7))] @pytest.mark.parametrize('mask_kind', ('full', 'channel-free', 'absent')) @@ -206,13 +206,14 @@ def test_mixed_channel_bundle_promotes_masks_in_the_output_domain( ImagePayloadMetadata().payload_with(DeviceArray(gray), DeviceArray(spatial)), ) result = ImagePayloadBundleContext.from_payloads(inputs).compose( - memory_type=destination, device_id=1 if destination == 'cupy' else None, + memory_type=destination, + device=AcceleratorDevice(1) if destination == 'cupy' else HOST, ) if destination == 'cupy': assert not state['downloads'] - owner = MemoryType(destination) + owner = MemoryType(destination).library data, mask = result.data, result.mask - assert owner.device_id_of(mask) == owner.device_id_of(data) + assert owner.device_of(mask) == owner.device_of(data) np.testing.assert_array_equal(owner.to_numpy(data), np.stack((color, color))) expected = np.stack((np.ones_like(spatial) if mask_kind == 'absent' else spatial, spatial)) if mask_kind == 'full': @@ -233,7 +234,7 @@ def test_independent_cohort_copy_retains_nested_named_bundle_domains(): context = AlignedImageSliceContext.main_flow("Canonical") named = ImageOutputBundle((payload,), (context,)) nested = AlignedImageStack((named,)) - copied = (nested).copied(memory_type="numpy", device_id=None,) + copied = (nested).copied(memory_type="numpy", device=HOST,) assert type(copied) is AlignedImageStack assert type(copied.slices[0]) is ImageOutputBundle assert copied.slices[0].slice_contexts == (context,) diff --git a/tests/unit/test_bioformats_microscope_handler.py b/tests/unit/test_bioformats_microscope_handler.py index 229314cf4..4d9c6ed40 100644 --- a/tests/unit/test_bioformats_microscope_handler.py +++ b/tests/unit/test_bioformats_microscope_handler.py @@ -5,7 +5,7 @@ import pytest from polystore.virtual_workspace import SourcePixelRef -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.constants import Backend from openhcs.core.config.pipeline_config import GlobalPipelineConfig from openhcs.core.dataset_sources.source import DatasetSourceChoice @@ -182,7 +182,7 @@ def test_orchestrator_exposes_prepared_virtual_source_workspace( tmp_path: Path, ) -> None: write_bioformats_manifest_fixture(tmp_path) - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) orchestrator = PipelineOrchestrator(dataset_root=tmp_path).initialize() diff --git a/tests/unit/test_bioformats_preparation_selection.py b/tests/unit/test_bioformats_preparation_selection.py index 1d1c0dafa..4864faeac 100644 --- a/tests/unit/test_bioformats_preparation_selection.py +++ b/tests/unit/test_bioformats_preparation_selection.py @@ -6,7 +6,7 @@ import numpy as np import pytest import tifffile -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from polystore.bioformats_java import BioFormatsJavaContext from openhcs.core.config.pipeline_config import ( @@ -99,7 +99,7 @@ def counted_open(path): assert handler.initialize_workspace(tmp_path, filemanager) == tmp_path assert opened == [names[7]] else: - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) orchestrator = PipelineOrchestrator( tmp_path, storage_registry=filemanager.registry, @@ -134,7 +134,7 @@ def counted_read(self, path): return original_read(self, path) monkeypatch.setattr(TiffImageFileFormat, "read", counted_read) - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) filemanager = bioformats_filemanager() orchestrator = PipelineOrchestrator( tmp_path, diff --git a/tests/unit/test_callable_abi_preparation.py b/tests/unit/test_callable_abi_preparation.py index 5aadc4bcf..ab8891165 100644 --- a/tests/unit/test_callable_abi_preparation.py +++ b/tests/unit/test_callable_abi_preparation.py @@ -12,6 +12,7 @@ import cloudpickle import numpy as np import pytest +from arraybridge.devices import HOST from arraybridge import ArrayPayload import openhcs.core.callable.callable_contract as contract_module @@ -448,7 +449,7 @@ def observed(value, **destination): placed.data placed.mask - assert calls == [{"memory_type": "numpy", "device_id": None}] + assert calls == [{"memory_type": "numpy", "device": HOST}] np.testing.assert_array_equal(placed.data, np.stack(pixels)) assert placed.data.shape == (2, 3, 4) assert placed.mask.shape == (2, 3, 4) diff --git a/tests/unit/test_cell_counting_cupy.py b/tests/unit/test_cell_counting_cupy.py index c72b5d4b4..3d80f709b 100644 --- a/tests/unit/test_cell_counting_cupy.py +++ b/tests/unit/test_cell_counting_cupy.py @@ -1,6 +1,7 @@ import numpy as np from arraybridge import MemoryType +from arraybridge.devices import AcceleratorDevice from openhcs.processing.backends.analysis.cell_counting_cupy import ( _watershed_with_cpu_partition, @@ -10,24 +11,14 @@ def test_watershed_partition_roundtrips_through_declared_cupy_device( monkeypatch, ) -> None: - restored_device_ids = [] + restored_devices = [] + cupy = type(MemoryType.CUPY.library) + monkeypatch.setattr(cupy, "device_of", lambda _library, _value: AcceleratorDevice(3)) + monkeypatch.setattr(cupy, "to_numpy", lambda _library, value: np.asarray(value)) monkeypatch.setattr( - MemoryType, - "device_id_of", - lambda memory_type, _value: 3 if memory_type is MemoryType.CUPY else None, - ) - monkeypatch.setattr( - MemoryType, - "to_numpy", - lambda _memory_type, value: np.asarray(value), - ) - monkeypatch.setattr( - MemoryType, + cupy, "from_numpy", - lambda _memory_type, value, device_id: ( - restored_device_ids.append(device_id), - value, - )[1], + lambda _library, value, device: (restored_devices.append(device), value)[1], ) image = np.array([[0.0, 1.0, 0.0], [1.0, 2.0, 1.0], [0.0, 1.0, 0.0]]) markers = np.array([[1, 0, 0], [0, 0, 0], [0, 0, 2]]) @@ -36,4 +27,4 @@ def test_watershed_partition_roundtrips_through_declared_cupy_device( labels = _watershed_with_cpu_partition(image, markers, mask=mask) assert labels.shape == image.shape - assert restored_device_ids == [3] + assert restored_devices == [AcceleratorDevice(3)] diff --git a/tests/unit/test_cellprofiler_artifact_declarations.py b/tests/unit/test_cellprofiler_artifact_declarations.py index 9828d18a5..f6cfd40d4 100644 --- a/tests/unit/test_cellprofiler_artifact_declarations.py +++ b/tests/unit/test_cellprofiler_artifact_declarations.py @@ -10,7 +10,7 @@ import pytest -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state import ObjectState from objectstate.object_state_registry import ObjectStateRegistry from openhcs.constants.input_source import ReadPipelineStart @@ -160,7 +160,7 @@ def _compiler_contracts( pipeline_config: PipelineConfig, ) -> tuple[CallableContract, ...]: global_config = GlobalPipelineConfig() - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) ObjectStateRegistry.clear() pipeline_state = ObjectState(pipeline_config, scope_id="pipeline") diff --git a/tests/unit/test_cellprofiler_combineobjects_source_scope.py b/tests/unit/test_cellprofiler_combineobjects_source_scope.py index 177264f6c..939f764d5 100644 --- a/tests/unit/test_cellprofiler_combineobjects_source_scope.py +++ b/tests/unit/test_cellprofiler_combineobjects_source_scope.py @@ -9,7 +9,7 @@ import numpy as np import tifffile -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.artifacts.specs import ArtifactSpec, ArtifactSpecCollection from openhcs.core.artifacts.kinds import ObjectLabelsArtifactType @@ -143,7 +143,7 @@ def test_public_combineobjects_import_compiles_source_owned_scope( assert prepared.pipeline_steps is not None assert prepared.pipeline_config is not None - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) orchestrator = PipelineOrchestrator( prepared.execution_dataset_root, pipeline_config=prepared.pipeline_config, diff --git a/tests/unit/test_cellprofiler_export_to_database.py b/tests/unit/test_cellprofiler_export_to_database.py index 75e0e19ae..871ab597e 100644 --- a/tests/unit/test_cellprofiler_export_to_database.py +++ b/tests/unit/test_cellprofiler_export_to_database.py @@ -12,7 +12,7 @@ from pycodify import Assignment, generate_python_source import openhcs.serialization.pycodify_formatters # noqa: F401 -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.artifacts.plans import ArtifactInputPlan, ArtifactOutputPlan from openhcs.core.artifacts.kinds import ( @@ -491,7 +491,7 @@ def test_quality_control_plate_invocation_is_context_independent( assert prepared.pipeline_steps is not None assert prepared.pipeline_config is not None - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) orchestrator = PipelineOrchestrator( prepared.execution_dataset_root, pipeline_config=prepared.pipeline_config, diff --git a/tests/unit/test_cellprofiler_generated_pipeline_execution.py b/tests/unit/test_cellprofiler_generated_pipeline_execution.py index 0acd19690..6678d95de 100644 --- a/tests/unit/test_cellprofiler_generated_pipeline_execution.py +++ b/tests/unit/test_cellprofiler_generated_pipeline_execution.py @@ -10,7 +10,7 @@ import pytest import tifffile -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.artifacts.plans import ArtifactInputPlan, ArtifactOutputPlan from openhcs.core.artifacts.specs import ArtifactSpec, ArtifactSpecCollection @@ -195,7 +195,7 @@ def test_compiler_derives_runtime_executor_after_generic_transport( assert not isinstance(transported_callable, CellProfilerModuleExecutor) global_config = GlobalPipelineConfig() - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) orchestrator = PipelineOrchestrator( tmp_path, pipeline_config=PipelineConfig( diff --git a/tests/unit/test_cellprofiler_module_execution.py b/tests/unit/test_cellprofiler_module_execution.py index 61c3125fb..077e2550e 100644 --- a/tests/unit/test_cellprofiler_module_execution.py +++ b/tests/unit/test_cellprofiler_module_execution.py @@ -1,3 +1,4 @@ +from arraybridge.devices import HOST from openhcs.core.payload.runtime_plane_projection import NoPlaneAxis from openhcs.core.object_labels.runtime_object_label_domains import PayloadLabelScope, PlaneLabelScope from openhcs.core.payload.runtime_plane_projection import RuntimeSlicePlaneAxis @@ -9722,7 +9723,7 @@ def test_pattern_group_runtime_unstacks_aligned_image_stack_output(): output = runtime._project_output_slices(aligned, matching_files) stack_payload = aligned.copy_projected_output_stack( - output, memory_type="numpy", device_id=None, + output, memory_type="numpy", device=HOST, ) assert [payload for payload, _context in output] == [dna_payload, rna_payload] assert stack_payload.metadata.source_plane_intensity_scales == (65535, 65535) @@ -9803,7 +9804,7 @@ def test_pattern_group_runtime_leaves_variable_shape_aligned_outputs_uncached(): for (payload, _context), pixels in zip(output, (first, second), strict=True) ) assert aligned.copy_projected_output_stack( - output, memory_type="numpy", device_id=None, + output, memory_type="numpy", device=HOST, ) is None diff --git a/tests/unit/test_compilation_paths.py b/tests/unit/test_compilation_paths.py index 42e4fa585..1f2dff542 100644 --- a/tests/unit/test_compilation_paths.py +++ b/tests/unit/test_compilation_paths.py @@ -21,7 +21,7 @@ PathPlanningConfig, PipelineConfig, ) -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.callable.function_patterns import compile_function_pattern from openhcs.core.pipeline.compilation_session import ( CompilationPathResolver, @@ -307,7 +307,7 @@ def test_compilation_debug_enabled_field_is_inherited_from_enableable() -> None: assert enabled_field.default is True assert CompilationDebugConfig().enabled is True - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( compilation_debug_config=CompilationDebugConfig(enabled=False), diff --git a/tests/unit/test_compilation_session.py b/tests/unit/test_compilation_session.py index 799f11173..c7d223743 100644 --- a/tests/unit/test_compilation_session.py +++ b/tests/unit/test_compilation_session.py @@ -4,7 +4,7 @@ from types import SimpleNamespace import pytest -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state import ObjectState from objectstate.object_state_registry import ObjectStateRegistry @@ -146,7 +146,7 @@ def full_plate_keys(component, *, resolved_config): def test_compiler_captures_scoped_worker_count(pipeline_workers, expected_workers): ObjectStateRegistry.clear() global_config = GlobalPipelineConfig(num_workers=2) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) global_state = ObjectState(global_config, scope_id="") pipeline_state = ObjectState( PipelineConfig(num_workers=pipeline_workers), @@ -164,7 +164,7 @@ def test_compiler_captures_scoped_worker_count(pipeline_workers, expected_worker assert len(assignments) == expected_workers # The compiled snapshot must not resolve again in a different context. - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=4) ) assert captured.num_workers == expected_workers @@ -526,7 +526,7 @@ def test_path_planner_source_binding_plan_comes_from_objectstate_snapshot(): components=(ComponentSelector(Microscopy.Channel, "1"),) ), ) - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) pipeline_state = ObjectState( PipelineConfig( source_bindings_config=LazySourceBindingsConfig( @@ -594,7 +594,7 @@ def test_compiler_streaming_config_snapshot_preserves_inherited_port(): persistent=False, ), ) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) global_state = ObjectState(global_config, scope_id="") pipeline_state = ObjectState( PipelineConfig(), @@ -1011,7 +1011,7 @@ def test_compiler_pipeline_scope_prevents_cross_pipeline_source_binding_inherita ObjectStateRegistry.clear() binding = NamedSourceBinding(alias="DNA") plate_path = tmp_path / "plate" - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) first_orchestrator = SimpleNamespace( dataset_root=plate_path, @@ -1041,7 +1041,7 @@ def test_compiler_pipeline_scope_prevents_cross_pipeline_source_binding_inherita def test_headless_resolution_preserves_saved_ui_ancestors_and_registrations(tmp_path): ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) plate_path = tmp_path / "plate" saved_binding = NamedSourceBinding(alias="DNA") live_binding = NamedSourceBinding(alias="Memb") diff --git a/tests/unit/test_compiled_execution.py b/tests/unit/test_compiled_execution.py index d10e823bb..b7972a446 100644 --- a/tests/unit/test_compiled_execution.py +++ b/tests/unit/test_compiled_execution.py @@ -410,6 +410,7 @@ def execute_current_run( def test_axis_teardown_preserves_execution_error_and_attempts_every_stage( monkeypatch, + on_every_library, ) -> None: cleaned = [] @@ -445,10 +446,9 @@ def fail_reset() -> None: "polystore.base.reset_memory_backend", fail_reset, ) - monkeypatch.setattr( - MemoryType, + on_every_library( "cleanup_loaded", - lambda memory_type, device_id=None: cleaned.append((memory_type, device_id)), + lambda library, device=None: cleaned.append((MemoryType(library.name), device.index)), ) with pytest.raises(RuntimeError, match="step failure"): diff --git a/tests/unit/test_czi_brain_axon_cellbody_demo.py b/tests/unit/test_czi_brain_axon_cellbody_demo.py index f6a7ce33d..7e09ae6bb 100644 --- a/tests/unit/test_czi_brain_axon_cellbody_demo.py +++ b/tests/unit/test_czi_brain_axon_cellbody_demo.py @@ -417,7 +417,7 @@ def fake_source_filemanager(source_root, workspace_root): from multiprocessing import SimpleQueue from objectstate import ObjectStateRegistry - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.core.config.pipeline_config import GlobalPipelineConfig from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator @@ -426,7 +426,7 @@ def fake_source_filemanager(source_root, workspace_root): ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1), ) diff --git a/tests/unit/test_debug_runtime.py b/tests/unit/test_debug_runtime.py index 37e2aeb1e..2ced2b70b 100644 --- a/tests/unit/test_debug_runtime.py +++ b/tests/unit/test_debug_runtime.py @@ -14,7 +14,7 @@ from openhcs.core.orchestrator.worker_lanes import WorkerLaneExecutionContext from openhcs.core.axes.alias_property import AliasProperty -from openhcs.constants.constants import MEMORY_TYPE_NUMPY +from openhcs.constants.constants import MemoryType from openhcs.core.callable.callable_contract import CallableContract from openhcs.core.axes.component_group_scope import ( ComponentGroupScope, @@ -268,8 +268,8 @@ def compiled_invocation( if resolved_contract is None: resolved_contract = replace( CallableContract.from_callable(func), - input_memory_type=MEMORY_TYPE_NUMPY, - output_memory_type=MEMORY_TYPE_NUMPY, + input_memory_type=MemoryType.NUMPY.value, + output_memory_type=MemoryType.NUMPY.value, processing_contract=Pure3DContract, runtime_adapter=runtime_adapter, runtime_context_parameter=runtime_context_parameter, @@ -330,7 +330,7 @@ def execution_plan(*, artifact_inputs, artifact_outputs) -> CompiledStepPlan: step_scope_id="plate::functionstep_3", step_name="debuggable", axis_id=DebugRuntimeFixture.AXIS_ID, - input_memory_type=MEMORY_TYPE_NUMPY, + input_memory_type=MemoryType.NUMPY.value, source_binding_plan=CompiledSourceBindingPlan(), variable_components=(), execution_group_scope=UngroupedScope(), @@ -1058,7 +1058,7 @@ def test_projection_exception_contains_complete_invocation_context_without_debug func=DebugRuntimeFixture.projection_mismatch, function_name="correct_illumination_calculate", module_name="CorrectIlluminationCalculate", - input_memory_type=MEMORY_TYPE_NUMPY, output_memory_type=MEMORY_TYPE_NUMPY, runtime_adapter=runtime_adapter, processing_contract=Pure2DContract, runtime_image_execution_mode=FullStackExecution, + input_memory_type=MemoryType.NUMPY.value, output_memory_type=MemoryType.NUMPY.value, runtime_adapter=runtime_adapter, processing_contract=Pure2DContract, runtime_image_execution_mode=FullStackExecution, ) image = ImagePayloadMetadata( source_image_names=("OrigStain1", "OrigStain2"), diff --git a/tests/unit/test_family_registries_restored.py b/tests/unit/test_family_registries_restored.py index a103ad3ac..361dfacee 100644 --- a/tests/unit/test_family_registries_restored.py +++ b/tests/unit/test_family_registries_restored.py @@ -4,8 +4,8 @@ from metaclass_registry import AutoRegisterMeta from objectstate.global_config import ( - get_current_global_config, - set_global_config_for_editing, + get_live_global_config, + set_global_config, ) from openhcs.core.config.pipeline_config import GlobalPipelineConfig @@ -58,9 +58,9 @@ def test_restore_removes_declared_members_and_returns_removed_and_replaced_ones( def test_a_global_config_set_by_a_test_is_put_back_after_it(): """Runs the fixture around a body that sets the config, as pytest does around a test.""" around_a_test = conftest.restored_global_configs.__wrapped__() - before = get_current_global_config(GlobalPipelineConfig) + before = get_live_global_config(GlobalPipelineConfig) next(around_a_test) - set_global_config_for_editing(GlobalPipelineConfig, GlobalPipelineConfig()) - assert get_current_global_config(GlobalPipelineConfig) is not before + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) + assert get_live_global_config(GlobalPipelineConfig) is not before next(around_a_test, None) - assert get_current_global_config(GlobalPipelineConfig) is before + assert get_live_global_config(GlobalPipelineConfig) is before diff --git a/tests/unit/test_framework_device_resolver.py b/tests/unit/test_framework_device_resolver.py index 09081881c..9099318ee 100644 --- a/tests/unit/test_framework_device_resolver.py +++ b/tests/unit/test_framework_device_resolver.py @@ -1,17 +1,17 @@ import pytest from arraybridge import MemoryType +from arraybridge.devices import AcceleratorDevice from openhcs.core.execution.compiled_step_plan import FrameworkDeviceAssignment from openhcs.core.util.framework_device_resolver import FrameworkDeviceResolver from openhcs.utils.environment import OpenHCSProcessEnvironment -def test_empty_footprint_does_not_import_frameworks(monkeypatch) -> None: - monkeypatch.setattr( - MemoryType, +def test_empty_footprint_does_not_import_frameworks(on_every_library) -> None: + on_every_library( "import_if_installed", - lambda _memory_type: (_ for _ in ()).throw( + lambda _library: (_ for _ in ()).throw( AssertionError("empty footprint imported a GPU runtime") ), ) @@ -19,12 +19,13 @@ def test_empty_footprint_does_not_import_frameworks(monkeypatch) -> None: assert FrameworkDeviceResolver().resolve(frozenset()).bindings == () -def test_cpu_only_authority_rejects_gpu_footprint_before_import(monkeypatch) -> None: +def test_cpu_only_authority_rejects_gpu_footprint_before_import( + monkeypatch, on_every_library, +) -> None: monkeypatch.setenv(OpenHCSProcessEnvironment.cpu_only_key, "true") - monkeypatch.setattr( - MemoryType, + on_every_library( "import_if_installed", - lambda _memory_type: (_ for _ in ()).throw( + lambda _library: (_ for _ in ()).throw( AssertionError("CPU-only resolution imported a GPU runtime") ), ) @@ -33,7 +34,9 @@ def test_cpu_only_authority_rejects_gpu_footprint_before_import(monkeypatch) -> FrameworkDeviceResolver().resolve(frozenset({MemoryType.TORCH})) -def test_framework_namespaces_receive_independent_local_devices(monkeypatch) -> None: +def test_framework_namespaces_receive_independent_local_devices( + monkeypatch, on_every_library, +) -> None: modules = { MemoryType.CUPY: object(), MemoryType.TORCH: object(), @@ -51,31 +54,30 @@ def test_framework_namespaces_receive_independent_local_devices(monkeypatch) -> OpenHCSProcessEnvironment.polystore_subprocess_no_gpu_key, raising=False, ) - monkeypatch.setattr( - MemoryType, + on_every_library( "import_if_installed", - lambda memory_type: modules[memory_type], + lambda library: modules[MemoryType(library.name)], ) - monkeypatch.setattr( - MemoryType, - "available_device_ids", - lambda memory_type, _module=None: available[memory_type], + on_every_library( + "accelerator_devices", + lambda library: tuple( + AcceleratorDevice(index) for index in available[MemoryType(library.name)] + ), ) assignment = FrameworkDeviceResolver(preferred_device_id=3).resolve( frozenset(modules) ) - assert assignment.device_id_for(MemoryType.CUPY) == 3 - assert assignment.device_id_for(MemoryType.TORCH) == 5 + assert assignment.device_for(MemoryType.CUPY) == AcceleratorDevice(3) + assert assignment.device_for(MemoryType.TORCH) == AcceleratorDevice(5) -def test_compiled_cleanup_visits_only_assigned_framework_devices(monkeypatch) -> None: +def test_compiled_cleanup_visits_only_assigned_framework_devices(on_every_library) -> None: cleaned = [] - monkeypatch.setattr( - MemoryType, + on_every_library( "cleanup_loaded", - lambda memory_type, device_id=None: cleaned.append((memory_type, device_id)), + lambda library, device=None: cleaned.append((MemoryType(library.name), device.index)), ) assignment = FrameworkDeviceAssignment.from_mapping( { @@ -93,16 +95,16 @@ def test_compiled_cleanup_visits_only_assigned_framework_devices(monkeypatch) -> def test_compiled_cleanup_attempts_every_binding_before_reporting_failures( - monkeypatch, + on_every_library, ) -> None: cleaned = [] - def cleanup(memory_type, device_id=None): - cleaned.append((memory_type, device_id)) - if memory_type is MemoryType.CUPY: + def cleanup(library, device=None): + cleaned.append((MemoryType(library.name), device.index)) + if library is MemoryType.CUPY.library: raise RuntimeError("cupy cleanup failed") - monkeypatch.setattr(MemoryType, "cleanup_loaded", cleanup) + on_every_library("cleanup_loaded", cleanup) assignment = FrameworkDeviceAssignment.from_mapping( { MemoryType.CUPY: 2, diff --git a/tests/unit/test_framework_execution_scope.py b/tests/unit/test_framework_execution_scope.py index e4b1b6c9d..ca95ffb54 100644 --- a/tests/unit/test_framework_execution_scope.py +++ b/tests/unit/test_framework_execution_scope.py @@ -4,6 +4,7 @@ import numpy as np from arraybridge import MemoryType +from arraybridge.devices import AcceleratorDevice from tests.artifact_graphs import admitted_graph from openhcs.core.execution.compiled_step_plan import FrameworkDeviceAssignment from openhcs.core.callable.function_patterns import compile_function_pattern @@ -32,13 +33,13 @@ def process(image): ) @contextmanager - def memory_device_scope(memory_type, device_id): - assert device_id == 4 - events.append(("enter", memory_type.value)) + def memory_device_scope(library, device): + assert device == AcceleratorDevice(4) + events.append(("enter", library.name)) yield - events.append(("exit", memory_type.value)) + events.append(("exit", library.name)) - monkeypatch.setattr(MemoryType, "device_scope", memory_device_scope) + monkeypatch.setattr(type(MemoryType.TORCH.library), "device_scope", memory_device_scope) executor = FunctionCoreExecutor( group_data=SimpleNamespace(), diff --git a/tests/unit/test_function_artifact_outputs.py b/tests/unit/test_function_artifact_outputs.py index 396a02c72..afa4fa8c5 100644 --- a/tests/unit/test_function_artifact_outputs.py +++ b/tests/unit/test_function_artifact_outputs.py @@ -1,3 +1,4 @@ +from arraybridge.devices import HOST from openhcs.core.payload.runtime_plane_projection import NoPlaneAxis from openhcs.core.object_labels.runtime_object_label_domains import PayloadLabelScope, PlaneLabelScope from openhcs.core.payload.runtime_plane_projection import RuntimeSlicePlaneAxis, SourceBindingPlaneAxis @@ -11,7 +12,7 @@ from tests.artifact_graphs import admitted_graph from openhcs.processing.backends.cellprofiler.crop import CropMask -from openhcs.constants.constants import MEMORY_TYPE_NUMPY +from openhcs.constants.constants import MemoryType from openhcs.core.artifacts.kinds import ( ImageArtifactType, ObjectLabelsArtifactType, @@ -220,7 +221,7 @@ def _execute_function_core(request: CoreExecutionRequest): declared_contract = compiled_invocation.contract contract = replace( declared_contract, - input_memory_type=MEMORY_TYPE_NUMPY, output_memory_type=MEMORY_TYPE_NUMPY, processing_contract=request.processing_contract, + input_memory_type=MemoryType.NUMPY.value, output_memory_type=MemoryType.NUMPY.value, processing_contract=request.processing_contract, ) invocation = replace( compiled_invocation, @@ -232,7 +233,7 @@ def _execute_function_core(request: CoreExecutionRequest): step_scope_id="test::function_step", step_name="test", axis_id=request.context.axis_id, - input_memory_type=MEMORY_TYPE_NUMPY, + input_memory_type=MemoryType.NUMPY.value, source_binding_plan=CompiledSourceBindingPlan(), variable_components=(), execution_group_scope=request.execution_group_scope, @@ -268,7 +269,7 @@ def _execute_function_core(request: CoreExecutionRequest): runtime_scope, invocation, main_data_arg=request.main_data_arg, - source_memory_type=MEMORY_TYPE_NUMPY, + source_memory_type=MemoryType.NUMPY.value, declared_source_bindings=runtime_scope.execution_plan.source_binding_plan, ).execute() @@ -1749,7 +1750,7 @@ def rgb_output(image): step_index=0, step_name="RGB output", axis_id="A01", - output_memory_type=MEMORY_TYPE_NUMPY, + output_memory_type=MemoryType.NUMPY.value, artifact_inputs={}, execution_group_scope=UngroupedScope(), artifact_outputs={ @@ -1774,8 +1775,8 @@ def rgb_output(image): ), ) - stack_payload = (scalar_output).copied(memory_type=MEMORY_TYPE_NUMPY, - device_id=None,) + stack_payload = (scalar_output).copied(memory_type=MemoryType.NUMPY.value, + device=HOST,) assert stack_payload.data.shape == (2, 3, 3) stack_metadata = stack_payload.metadata assert stack_metadata.plane_axis.unstacked @@ -1797,7 +1798,7 @@ def test_pattern_group_runtime_uses_declared_output_slice_cardinality(): step_index=0, step_name="DeclaredOutput", axis_id="A01", - output_memory_type=MEMORY_TYPE_NUMPY, + output_memory_type=MemoryType.NUMPY.value, artifact_inputs={}, execution_group_scope=UngroupedScope(), artifact_outputs={}, @@ -1848,7 +1849,7 @@ def test_pattern_group_runtime_projects_nominal_object_label_stack(): step_index=0, step_name="DeclaredObjectLabels", axis_id="A01", - output_memory_type=MEMORY_TYPE_NUMPY, + output_memory_type=MemoryType.NUMPY.value, artifact_inputs={}, execution_group_scope=UngroupedScope(), artifact_outputs={}, @@ -2942,7 +2943,7 @@ def declared_source_origin(image, *, image_to_save=None): group_key=None, plane_projection=RuntimePlaneProjection.stack(), main_data_arg=object(), - source_memory_type=MEMORY_TYPE_NUMPY, + source_memory_type=MemoryType.NUMPY.value, ) diff --git a/tests/unit/test_function_patterns.py b/tests/unit/test_function_patterns.py index 6a527b18b..ecac51ca6 100644 --- a/tests/unit/test_function_patterns.py +++ b/tests/unit/test_function_patterns.py @@ -2,6 +2,7 @@ import numpy as np import pytest +from arraybridge.devices import HOST from arraybridge.decorators import DtypeConversion, DtypeConversionConfig from tests.artifact_graphs import admitted_graph @@ -1007,7 +1008,7 @@ def consume(*, payload): (placed,) = tuple(plan.compiled_function_pattern.iter_invocations()) assert placed.input_memory_type is None assert placed.output_memory_type is None - assert placed.input_device_id is None + assert placed.input_device == HOST assert ( placed.artifact_input_edges == compiled.default_group.invocations[0].artifact_input_edges diff --git a/tests/unit/test_function_runtime_source_projection.py b/tests/unit/test_function_runtime_source_projection.py index dc3552079..e86fea102 100644 --- a/tests/unit/test_function_runtime_source_projection.py +++ b/tests/unit/test_function_runtime_source_projection.py @@ -2151,7 +2151,7 @@ def test_first_step_prepares_raw_source_anchors_under_semantic_binding_groups( import tifffile from objectstate import ObjectStateRegistry - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.core.config.pipeline_config import PipelineConfig from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator @@ -2200,7 +2200,7 @@ def test_first_step_prepares_raw_source_anchors_under_semantic_binding_groups( ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) compilation = ( PipelineOrchestrator( tmp_path, @@ -3234,7 +3234,7 @@ def test_pipeline_start_main_flow_survives_prior_producer_image_input( import tifffile from objectstate import ObjectStateRegistry - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.config.pipeline_config import ( @@ -3295,7 +3295,7 @@ def test_pipeline_start_main_flow_survives_prior_producer_image_input( ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) compilation = ( PipelineOrchestrator( tmp_path, diff --git a/tests/unit/test_function_step_execution_plan.py b/tests/unit/test_function_step_execution_plan.py index a45751e82..cb246fd30 100644 --- a/tests/unit/test_function_step_execution_plan.py +++ b/tests/unit/test_function_step_execution_plan.py @@ -4,6 +4,7 @@ from types import SimpleNamespace import pytest +from arraybridge.devices import HOST, AcceleratorDevice from tests.artifact_graphs import admitted_graph from openhcs.constants.constants import MemoryType @@ -134,7 +135,7 @@ def test_compiled_step_plan_is_the_runtime_plan_owner(): assert isinstance(plan.main_input_dependency, StepOutputInput) assert plan.main_input_dependency.source_step_scope_id == "plate::functionstep_1" assert plan.source_binding_plan == CompiledSourceBindingPlan() - assert plan.device_id_for(plan.input_memory_type) is None + assert plan.device_for(plan.input_memory_type) == HOST assert not plan.requires_gpu assert plan.gpu_memory_types == frozenset() assert plan.input_conversion is not None @@ -155,10 +156,12 @@ def test_compiled_step_plan_owns_gpu_memory_classification() -> None: assert compiled_plan.requires_gpu assert compiled_plan.gpu_memory_types == frozenset({MemoryType.CUPY}) - assert compiled_plan.device_id_for("cupy") == 2 + assert compiled_plan.device_for("cupy") == AcceleratorDevice(2) -def test_compiled_step_plan_includes_invocation_execution_memory(monkeypatch) -> None: +def test_compiled_step_plan_includes_invocation_execution_memory( + monkeypatch, on_every_library, +) -> None: def numpy_boundary_with_torch_execution(image): return image @@ -175,7 +178,7 @@ def numpy_boundary_with_torch_execution(image): ) assert compiled_plan.gpu_memory_types == frozenset({MemoryType.TORCH}) - assert compiled_plan.device_id_for("torch") == 4 + assert compiled_plan.device_for("torch") == AcceleratorDevice(4) from contextlib import contextmanager from openhcs.core.pipeline.framework_device_assignment import ( assign_framework_devices, @@ -189,18 +192,18 @@ def numpy_boundary_with_torch_execution(image): (placed_invocation,) = tuple( compiled_plan.compiled_function_pattern.iter_invocations() ) - assert placed_invocation.input_device_id is None - assert placed_invocation.execution_device_id == 4 + assert placed_invocation.input_device == HOST + assert placed_invocation.execution_device == AcceleratorDevice(4) entered = [] @contextmanager - def recorded_scope(memory_type, device_id): - entered.append((memory_type, device_id)) + def recorded_scope(library, device): + entered.append((MemoryType(library.name), device)) yield - monkeypatch.setattr(MemoryType, "device_scope", recorded_scope) + on_every_library("device_scope", recorded_scope) with placed_invocation.execution_device_scope(): - assert entered == [(MemoryType.TORCH, 4)] + assert entered == [(MemoryType.TORCH, AcceleratorDevice(4))] def test_compiled_step_plan_includes_intermediate_invocation_memory() -> None: diff --git a/tests/unit/test_image_plane_contracts.py b/tests/unit/test_image_plane_contracts.py index 2400cdce5..2d5bd0183 100644 --- a/tests/unit/test_image_plane_contracts.py +++ b/tests/unit/test_image_plane_contracts.py @@ -13,8 +13,10 @@ pack_aligned_image_outputs, stack_image_payloads, ) +from arraybridge.devices import HOST + from openhcs.core.memory import ( - MEMORY_TYPE_NUMPY, + MemoryType, stack_runtime_slices, unstack_runtime_slices, ) @@ -45,11 +47,11 @@ def test_explicit_runtime_slice_stack_round_trips_any_slice_shape( np.ones(slice_shape, dtype=np.uint16), ) - stack = stack_runtime_slices(slices, MEMORY_TYPE_NUMPY, 0) + stack = stack_runtime_slices(slices, MemoryType.NUMPY.value, HOST) unstacked = unstack_runtime_slices( stack, - MEMORY_TYPE_NUMPY, - 0, + MemoryType.NUMPY.value, + HOST, expected_count=2, ) @@ -62,8 +64,8 @@ def test_explicit_runtime_slice_stack_rejects_mismatched_slice_shapes() -> None: with pytest.raises(ValueError, match="one exact shape"): stack_runtime_slices( (np.zeros((4, 5)), np.zeros((4, 6))), - MEMORY_TYPE_NUMPY, - 0, + MemoryType.NUMPY.value, + HOST, ) diff --git a/tests/unit/test_implicit_main_flow_compilation.py b/tests/unit/test_implicit_main_flow_compilation.py index ce56d924c..f3ecaf727 100644 --- a/tests/unit/test_implicit_main_flow_compilation.py +++ b/tests/unit/test_implicit_main_flow_compilation.py @@ -6,7 +6,7 @@ from objectstate import ObjectStateRegistry import tifffile -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart, ReadPreviousStep from openhcs.core.callable.callable_contract import FunctionStepExecutionScope from openhcs.core.config.pipeline_config import ( @@ -70,7 +70,7 @@ def test_native_grouped_main_flow_compiles_into_cellprofiler_consumer(tmp_path): ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) orchestrator = PipelineOrchestrator( tmp_path, pipeline_config=PipelineConfig(), diff --git a/tests/unit/test_library_registry_discovery.py b/tests/unit/test_library_registry_discovery.py index 431415734..5aae8771d 100644 --- a/tests/unit/test_library_registry_discovery.py +++ b/tests/unit/test_library_registry_discovery.py @@ -621,9 +621,9 @@ def test_registry_preparation_uses_background_process_policy(monkeypatch) -> Non subprocess_environment = {"FRAMEWORK_IMPORTS": "prepared"} monkeypatch.setattr( registry_service, - "MemoryType", + "ArrayLibrary", SimpleNamespace( - subprocess_environment=lambda: subprocess_environment, + child_environment=lambda: subprocess_environment, ), ) diff --git a/tests/unit/test_loose_operaphenix_neurite_example.py b/tests/unit/test_loose_operaphenix_neurite_example.py index 224134e2b..be5cdd0b8 100644 --- a/tests/unit/test_loose_operaphenix_neurite_example.py +++ b/tests/unit/test_loose_operaphenix_neurite_example.py @@ -4,7 +4,7 @@ import numpy as np import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.agent.dto.knowledge import ( KnowledgeBaseDocumentRequest, @@ -185,7 +185,7 @@ def test_neurite_example_compiles_with_declared_loose_file_identities( ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1), ) diff --git a/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py b/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py index 79d2f833e..74fa1273d 100644 --- a/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py +++ b/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py @@ -5,7 +5,7 @@ import numpy as np import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.agent.dto.knowledge import KnowledgeBaseDocumentRequest from openhcs.agent.services.knowledge_base_service import KnowledgeBaseService @@ -172,7 +172,7 @@ def test_compact_example_compiles_the_full_ordered_channel_stack( ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1), ) diff --git a/tests/unit/test_materialization_filter_inheritance.py b/tests/unit/test_materialization_filter_inheritance.py index ca5edba7e..3e887ec50 100644 --- a/tests/unit/test_materialization_filter_inheritance.py +++ b/tests/unit/test_materialization_filter_inheritance.py @@ -2,7 +2,7 @@ from types import SimpleNamespace from objectstate import ObjectState -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state_registry import ObjectStateRegistry from openhcs.constants.constants import Backend from openhcs.constants.input_source import ReadPreviousStep @@ -69,7 +69,7 @@ def _resolved_checkpoint( def test_path_zero_keeps_inherited_step_checkpoint_independent(tmp_path) -> None: ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) orchestrator, effective_config, resolved, filters = _resolved_checkpoint( tmp_path / "plate" ) @@ -136,7 +136,7 @@ def test_path_zero_keeps_inherited_step_checkpoint_independent(tmp_path) -> None def test_explicit_checkpoint_filter_overrides_inherited_workload(tmp_path) -> None: ObjectStateRegistry.clear() - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) orchestrator, _effective_config, resolved, filters = _resolved_checkpoint( tmp_path / "plate", checkpoint_filter="B02", diff --git a/tests/unit/test_mcp_assay_showcase.py b/tests/unit/test_mcp_assay_showcase.py index 5ae70adb1..9e2350df0 100644 --- a/tests/unit/test_mcp_assay_showcase.py +++ b/tests/unit/test_mcp_assay_showcase.py @@ -8,7 +8,7 @@ import pytest from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from polystore.streaming.identity import StreamProducerOrigin from openhcs.core.payload.aligned_image_payload import AlignedImageSliceContext @@ -230,7 +230,7 @@ def test_colocalization_presentation_compiles_from_public_native_source( ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, namespace["global_config"], ) diff --git a/tests/unit/test_memory_type_authority.py b/tests/unit/test_memory_type_authority.py index a5cd91f9d..d1da07e67 100644 --- a/tests/unit/test_memory_type_authority.py +++ b/tests/unit/test_memory_type_authority.py @@ -2,26 +2,12 @@ import pickle -from openhcs.constants import ( - CPU_MEMORY_TYPES, - GPU_MEMORY_TYPES, - SUPPORTED_MEMORY_TYPES, - VALID_GPU_MEMORY_TYPES, - VALID_MEMORY_TYPES, - MemoryType, -) +from openhcs.constants import MemoryType from openhcs.constants.constants import MemoryType as RawConstantsMemoryType from openhcs.core.memory import MemoryType as RuntimeMemoryType from openhcs.constants.constants import MemoryType as PipelineMemoryType from arraybridge import MemoryType as ArrayBridgeMemoryType -from arraybridge.types import ( - CPU_MEMORY_TYPES as ARRAYBRIDGE_CPU_MEMORY_TYPES, - GPU_MEMORY_TYPES as ARRAYBRIDGE_GPU_MEMORY_TYPES, - SUPPORTED_MEMORY_TYPES as ARRAYBRIDGE_SUPPORTED_MEMORY_TYPES, - VALID_GPU_MEMORY_TYPES as ARRAYBRIDGE_VALID_GPU_MEMORY_TYPES, - VALID_MEMORY_TYPES as ARRAYBRIDGE_VALID_MEMORY_TYPES, -) def test_memory_type_taxonomy_has_one_cross_package_identity() -> None: @@ -31,14 +17,6 @@ def test_memory_type_taxonomy_has_one_cross_package_identity() -> None: assert PipelineMemoryType is ArrayBridgeMemoryType -def test_memory_type_sets_are_owner_reexports() -> None: - assert CPU_MEMORY_TYPES is ARRAYBRIDGE_CPU_MEMORY_TYPES - assert GPU_MEMORY_TYPES is ARRAYBRIDGE_GPU_MEMORY_TYPES - assert SUPPORTED_MEMORY_TYPES is ARRAYBRIDGE_SUPPORTED_MEMORY_TYPES - assert VALID_MEMORY_TYPES is ARRAYBRIDGE_VALID_MEMORY_TYPES - assert VALID_GPU_MEMORY_TYPES is ARRAYBRIDGE_VALID_GPU_MEMORY_TYPES - - def test_legacy_openhcs_memory_type_pickle_resolves_to_owner_identity() -> None: legacy_payload = ( b"copenhcs.constants.constants\nMemoryType\np0\n" b"(Vnumpy\np1\ntp2\nRp3\n." diff --git a/tests/unit/test_microscope_virtual_workspace_metadata.py b/tests/unit/test_microscope_virtual_workspace_metadata.py index 92f15c3ec..473ff1676 100644 --- a/tests/unit/test_microscope_virtual_workspace_metadata.py +++ b/tests/unit/test_microscope_virtual_workspace_metadata.py @@ -67,7 +67,7 @@ def test_compiler_source_queries_borrow_config_while_public_queries_stay_live( tmp_path, monkeypatch ): from unittest.mock import Mock - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.core.config.pipeline_config import GlobalPipelineConfig, PipelineConfig from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator from openhcs.core.source.source_metadata import SourceFilterClause @@ -110,7 +110,7 @@ def test_compiler_source_queries_borrow_config_while_public_queries_stay_live( ), )) held_config = GlobalPipelineConfig(source_bindings_config=source_a) - ensure_global_config_context(GlobalPipelineConfig, held_config) + set_global_config(GlobalPipelineConfig, held_config) owner = PipelineOrchestrator( tmp_path, pipeline_config=PipelineConfig( diff --git a/tests/unit/test_neuroncyto_ii_neurite_demo.py b/tests/unit/test_neuroncyto_ii_neurite_demo.py index 53603a5b4..17da6798d 100644 --- a/tests/unit/test_neuroncyto_ii_neurite_demo.py +++ b/tests/unit/test_neuroncyto_ii_neurite_demo.py @@ -8,7 +8,7 @@ import numpy as np import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.callable.callable_contract import CallableContract from openhcs.core.artifacts.streaming import AutomaticStreaming, OnDemandStreaming @@ -175,7 +175,7 @@ def test_neuroncyto_demo_compiles_exact_loose_tiff_pair(tmp_path: Path) -> None: ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1), ) @@ -249,7 +249,7 @@ def test_neuroncyto_demo_executes_numeric_biological_well_identity( progress_queue = SimpleQueue() set_progress_queue(progress_queue) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1, use_threading=True), ) @@ -382,7 +382,7 @@ def test_neuroncyto_demo_contributor_prepares_only_declared_pair( ObjectStateRegistry.clear() set_progress_queue(SimpleQueue()) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=1), ) diff --git a/tests/unit/test_opaque_main_flow_image_domain.py b/tests/unit/test_opaque_main_flow_image_domain.py index 71e48d704..d2d1db330 100644 --- a/tests/unit/test_opaque_main_flow_image_domain.py +++ b/tests/unit/test_opaque_main_flow_image_domain.py @@ -1,5 +1,6 @@ """Whole image domains survive the producer/cache/next-load handoff.""" +from arraybridge.devices import HOST from openhcs.core.payload.runtime_plane_projection import NoPlaneAxis from openhcs.core.payload.runtime_plane_projection import RuntimeSlicePlaneAxis, SourceBindingPlaneAxis from dataclasses import replace @@ -9,7 +10,7 @@ import pytest from tests.artifact_graphs import admitted_graph -from openhcs.constants.constants import MEMORY_TYPE_NUMPY +from openhcs.constants.constants import MemoryType from openhcs.core.execution.compiled_step_plan import CompiledStepPlan from openhcs.core.axes.component_group_scope import ( UngroupedScope, @@ -47,8 +48,8 @@ def _runtime(): step_index=0, step_name="WholeImage", axis_id="A01", - output_memory_type=MEMORY_TYPE_NUMPY, - input_memory_type=MEMORY_TYPE_NUMPY, + output_memory_type=MemoryType.NUMPY.value, + input_memory_type=MemoryType.NUMPY.value, variable_components=(), artifact_inputs={}, artifact_outputs={}, @@ -83,7 +84,7 @@ def test_opaque_whole_image_is_copied_without_a_new_execution_axis(shape, channe ) assert len(projected) == 1 assert projected[0][0] is payload - cached = payload.copied(memory_type=MEMORY_TYPE_NUMPY, device_id=None) + cached = payload.copied(memory_type=MemoryType.NUMPY.value, device=HOST) assert cached.data.shape == shape assert cached.metadata == metadata np.testing.assert_array_equal(cached.data, pixels) @@ -120,7 +121,7 @@ def test_nominal_alignment_owner_preserves_single_output_topology(named, axis): value = (ImageOutputBundle if named else AlignedImageStack)((payload,), (context,)) projected = _runtime()._project_output_slices(value, ["source.tif"]) stack_payload = value.copy_projected_output_stack( - projected, memory_type=MEMORY_TYPE_NUMPY, device_id=None, + projected, memory_type=MemoryType.NUMPY.value, device=HOST, ) if named and axis is not RuntimeSlicePlaneAxis: expected_shape, expected_axis = shape, axis @@ -260,7 +261,7 @@ def test_mixed_named_outputs_retain_each_original_axis_before_projection(runtime bundle = ImageOutputBundle((planes, volume), contexts) projected = _runtime()._project_output_slices(bundle, []) assert bundle.copy_projected_output_stack( - projected, memory_type=MEMORY_TYPE_NUMPY, device_id=None, + projected, memory_type=MemoryType.NUMPY.value, device=HOST, ) is None assert [bundle.plane_axis_for_output_context(context) for _payload, context in projected] == [RuntimeSlicePlaneAxis] * runtime_count + [NoPlaneAxis] @@ -366,14 +367,14 @@ def test_saved_mixed_named_cohort_rejects_joint_load_and_preserves_selected_doma # must invalidate that cache rather than leave a false joint runtime domain. old_bundle = ImageOutputBundle((planes, declared_metadata.payload_with(opaque_pixels[None])), contexts) old_records = producer._save_outputs(old_bundle, [source, source]) - assert context.runtime_image_stack_cache.get(tuple(r.output_path for r in old_records), memory_type=MEMORY_TYPE_NUMPY) is not None + assert context.runtime_image_stack_cache.get(tuple(r.output_path for r in old_records), memory_type=MemoryType.NUMPY.value) is not None bundle = ImageOutputBundle((planes, opaque), contexts) records = producer._save_outputs(bundle, [source, source]) manifest = step_output_manifest(context) manifest.record_outputs(plan, records) assert tuple(r.output_path for r in records) == tuple(r.output_path for r in old_records) assert [r.main_flow_plane_axis for r in records] == [RuntimeSlicePlaneAxis, NoPlaneAxis] - assert context.runtime_image_stack_cache.get(tuple(r.output_path for r in records), memory_type=MEMORY_TYPE_NUMPY) is None + assert context.runtime_image_stack_cache.get(tuple(r.output_path for r in records), memory_type=MemoryType.NUMPY.value) is None def consumer_for(compiled): consumer_plan = replace(plan, step_index=1, step_scope_id="mixed-consumer", input_dir=tmp_path, @@ -400,7 +401,7 @@ def consumer_for(compiled): context.runtime_image_stack_cache.clear() 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) + context.runtime_image_stack_cache.store((selected_path,), memory_type=MemoryType.NUMPY.value, stack=actual) repeated = selected.load_input_stack()[1] np.testing.assert_array_equal(repeated.data, expected) assert repeated.metadata.plane_axis is axis @@ -412,7 +413,7 @@ def test_multiple_unprojected_named_binding_domains_fail_existing_bundle_grammar np.ones((1, 4, 5), dtype=np.float32)) for _ in contexts) with pytest.raises(ValueError, match="plane axis to be projected"): bundle = ImageOutputBundle(payloads, contexts) - bundle.copy_projected_output_stack(tuple(bundle.projected_output_slices()), memory_type=MEMORY_TYPE_NUMPY, device_id=None) + bundle.copy_projected_output_stack(tuple(bundle.projected_output_slices()), memory_type=MemoryType.NUMPY.value, device=HOST) def test_opaque_named_bundle_uses_existing_same_slice_mask_composition(): @@ -425,7 +426,7 @@ def test_opaque_named_bundle_uses_existing_same_slice_mask_composition(): np.ones((4, 5), dtype=np.float32) * i, mask) for i, (name, mask) in enumerate(zip(("First", "Second"), (first_mask, second_mask), strict=True))) bundle = ImageOutputBundle(payloads, contexts) - stack_payload = bundle.copy_projected_output_stack(tuple(bundle.projected_output_slices()), memory_type=MEMORY_TYPE_NUMPY, device_id=None) + stack_payload = bundle.copy_projected_output_stack(tuple(bundle.projected_output_slices()), memory_type=MemoryType.NUMPY.value, device=HOST) expected = ImagePayloadBundleContext.from_payloads(payloads).compose() assert stack_payload.metadata.plane_axis is SourceBindingPlaneAxis np.testing.assert_array_equal(stack_payload.data, expected.data) @@ -477,7 +478,7 @@ def test_input_bundle_composition_retains_lazy_plan_device_resolution(tmp_path, def unexpected_device_resolution(self, memory_type): raise AssertionError("BUNDLE composition must retain its own memory allocation authority") - monkeypatch.setattr(CompiledStepPlan, "device_id_for", unexpected_device_resolution) + monkeypatch.setattr(CompiledStepPlan, "device_for", unexpected_device_resolution) output = ImagePayloadStackComposition.from_loaded_images( payloads, producer_records=records, diff --git a/tests/unit/test_path_planner_materialization.py b/tests/unit/test_path_planner_materialization.py index 5ae9ff909..91f5111b4 100644 --- a/tests/unit/test_path_planner_materialization.py +++ b/tests/unit/test_path_planner_materialization.py @@ -40,7 +40,7 @@ RuntimeExecutionAxisScope, UngroupedScope, ) -from openhcs.constants.constants import MEMORY_TYPE_NUMPY +from openhcs.constants.constants import MemoryType from openhcs.core.memory import numpy from openhcs.core.payload.runtime_image_values import ImagePayloadMetadata from openhcs.core.artifact_store.runtime_stores import RuntimeValueStore @@ -138,7 +138,7 @@ def _execute_compiled_metadata_pattern(compiled, input_plans=None, stored_output step_scope_id="plate::functionstep_3", step_name="metadata-consumer", axis_id="A01", - input_memory_type=MEMORY_TYPE_NUMPY, + input_memory_type=MemoryType.NUMPY.value, source_binding_plan=CompiledSourceBindingPlan(), variable_components=(), execution_group_scope=UngroupedScope(), @@ -177,7 +177,7 @@ def _execute_compiled_metadata_pattern(compiled, input_plans=None, stored_output scope, invocation, main_data_arg=ImagePayloadMetadata().payload_with(source), - source_memory_type=MEMORY_TYPE_NUMPY, + source_memory_type=MemoryType.NUMPY.value, declared_source_bindings=scope.execution_plan.source_binding_plan, ).execute() np.testing.assert_array_equal(result.data, source) diff --git a/tests/unit/test_pipeline_states_resolve_from_registered_ancestors.py b/tests/unit/test_pipeline_states_resolve_from_registered_ancestors.py index 04eca1713..191205445 100644 --- a/tests/unit/test_pipeline_states_resolve_from_registered_ancestors.py +++ b/tests/unit/test_pipeline_states_resolve_from_registered_ancestors.py @@ -17,8 +17,11 @@ from formbridge.services.pattern_data_manager import FUNC_EDITOR_PATTERN_TOKENS_META_KEY from formbridge.services.scope_token_service import ScopeTokenService from objectstate import ObjectState, ObjectStateRegistry -from objectstate.global_config import GlobalContextValues -from objectstate.lazy_factory import ensure_global_config_context +from objectstate.global_config import ( + forget_stored_global_config, + get_live_global_config, + set_global_config, +) from objectstate.scope_key import ScopeKey from openhcs.authoring.session.pipelines import PipelineObjectStateBinding @@ -55,14 +58,14 @@ def _step(name: str, dtype_conversion: DtypeConversion | None = None) -> Functio def plate_state() -> Iterator[ObjectState]: """A global config holding ``GLOBAL_VALUE`` and an empty plate config below it.""" - previous_global = GlobalContextValues.capture(GlobalPipelineConfig) + previous_global = get_live_global_config(GlobalPipelineConfig) ObjectStateRegistry.clear() ScopeTokenService.clear_scope(PLATE) global_config = dataclasses.replace( GlobalPipelineConfig(), dtype_config=DtypeConfig(default_dtype_conversion=GLOBAL_VALUE), ) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) global_state = ObjectState(object_instance=global_config, scope_id="") ObjectStateRegistry.register(global_state, _skip_snapshot=True) state = ObjectState( @@ -74,7 +77,10 @@ def plate_state() -> Iterator[ObjectState]: finally: ObjectStateRegistry.clear() ScopeTokenService.clear_scope(PLATE) - previous_global.apply() + if previous_global is None: + forget_stored_global_config(GlobalPipelineConfig) + else: + set_global_config(GlobalPipelineConfig, previous_global) def _step_and_function_states() -> list[tuple[ObjectState, list[ObjectState]]]: diff --git a/tests/unit/test_plane_store_sources.py b/tests/unit/test_plane_store_sources.py index e0838af60..e32b3ded8 100644 --- a/tests/unit/test_plane_store_sources.py +++ b/tests/unit/test_plane_store_sources.py @@ -7,7 +7,7 @@ import pytest import zarr from objectstate import ObjectState -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from ome_zarr.format import Format from polystore.base import ensure_storage_registry, storage_registry from polystore.bioformats_java import BioFormatsJavaContext @@ -362,7 +362,7 @@ def reject_editor(*args, **kwargs): "instance", classmethod(lambda cls: _NoJavaStores()), ) - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) initial_bindings = SourceBindingsConfig( bindings=tuple( _binding(alias, path.name) for alias, (path, _pixels) in stores.items() @@ -463,7 +463,7 @@ def test_mixed_plane_stores_materialize_and_reopen_with_source_identity( "instance", classmethod(lambda cls: _NoJavaStores()), ) - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) source_bindings = SourceBindingsConfig( bindings=tuple( _binding(alias, path.name) for alias, (path, _pixels) in stores.items() diff --git a/tests/unit/test_primary_object_diagnostics.py b/tests/unit/test_primary_object_diagnostics.py index 8f5428062..cc026a506 100644 --- a/tests/unit/test_primary_object_diagnostics.py +++ b/tests/unit/test_primary_object_diagnostics.py @@ -1,5 +1,6 @@ """Lightweight ownership/payload checks; these do not execute segmentation.""" +from arraybridge.devices import HOST from openhcs.core.payload.runtime_plane_projection import RuntimeSlicePlaneAxis, SourceBindingPlaneAxis import ast from openhcs.interop.cellprofiler.object_label_variants import ( @@ -238,7 +239,7 @@ def test_existing_pure2d_aggregation_retains_stage_pixels_masks_and_plane_identi reloaded = pickle.loads(pickle.dumps(value)) assert np.shares_memory(reloaded.slices[0].data, reloaded.compose().data) assert np.shares_memory(reloaded.slices[0].mask, reloaded.compose().mask) - independent = value.copied(memory_type="numpy", device_id=None) + independent = value.copied(memory_type="numpy", device=HOST) assert not np.shares_memory(independent.slices[0].data, composed.data) assert not np.shares_memory(independent.slices[0].mask, composed.mask) @@ -266,7 +267,7 @@ def test_produced_input_snapshot_owns_canonical_pixels_and_masks(shared_mask, sp ) expected = np.stack(pixels) expected_mask = first_mask.copy() if shared_mask and spatial_mask else np.stack(masks) - copied = source.copied(memory_type="numpy", device_id=None) + copied = source.copied(memory_type="numpy", device=HOST) assert source._composed_payload is None canonical = copied.compose() assert copied.compose() is canonical diff --git a/tests/unit/test_processing_module_liveness.py b/tests/unit/test_processing_module_liveness.py index 0f150abbf..5bf66ceca 100644 --- a/tests/unit/test_processing_module_liveness.py +++ b/tests/unit/test_processing_module_liveness.py @@ -14,7 +14,7 @@ from functools import cached_property from pathlib import Path -from arraybridge.types import VALID_MEMORY_TYPES +from arraybridge import MemoryType import openhcs from openhcs.processing.backends.lib_registry.openhcs_registry import ( @@ -23,7 +23,7 @@ _OPENHCS_ROOT = Path(openhcs.__file__).parent _PROCESSING_PACKAGE = "openhcs.processing" -_ALL_MEMORY_TYPES = frozenset(VALID_MEMORY_TYPES) +_ALL_MEMORY_TYPES = frozenset(memory_type.value for memory_type in MemoryType) @dataclass(frozen=True) diff --git a/tests/unit/test_processor_operations_written_once.py b/tests/unit/test_processor_operations_written_once.py index 001d7673d..f76ca8244 100644 --- a/tests/unit/test_processor_operations_written_once.py +++ b/tests/unit/test_processor_operations_written_once.py @@ -1,4 +1,4 @@ -"""Processor operations are written once against arraybridge ``ArrayOperations``. +"""Processor operations are written once against arraybridge ``ArrayLibrary``. The six backend processor modules register shared operations from ``image_stack_operations``; a backend keeps its own body only where its @@ -15,7 +15,6 @@ import numpy as np import pytest from arraybridge import MemoryType -from arraybridge.array_operations import ArrayOperations from openhcs.core.callable.callable_contract import CallableContract from openhcs.core.callable.processing_contracts import VolumetricToSliceContract @@ -72,7 +71,7 @@ def _calls_shared_operation(function: ast.FunctionDef) -> bool: def test_each_backend_module_registers_with_its_own_leaf() -> None: for backend in BACKENDS: leaf = _processor_module(backend).OPERATIONS - assert leaf is ArrayOperations.for_memory(MemoryType(backend)) + assert leaf is MemoryType(backend).library def test_operations_shared_by_two_backends_are_written_once() -> None: diff --git a/tests/unit/test_replaced_global_config_reaches_registered_states.py b/tests/unit/test_replaced_global_config_reaches_registered_states.py index 6d99c99d5..c7820a3d3 100644 --- a/tests/unit/test_replaced_global_config_reaches_registered_states.py +++ b/tests/unit/test_replaced_global_config_reaches_registered_states.py @@ -14,8 +14,11 @@ import pytest from arraybridge.decorators import DtypeConversion from objectstate import ObjectState, ObjectStateRegistry -from objectstate.global_config import GlobalContextValues -from objectstate.lazy_factory import ensure_global_config_context +from objectstate.global_config import ( + forget_stored_global_config, + get_live_global_config, + set_global_config, +) from pyqt_reactive.windows.config_window import ConfigSaveParticipant, ConfigWindowTabSpec from openhcs.authoring.session.pipelines import PipelineObjectStateBinding @@ -61,13 +64,16 @@ def _states_below(scope_id: str) -> list[ObjectState]: @pytest.fixture def empty_registry() -> Iterator[None]: - previous_global = GlobalContextValues.capture(GlobalPipelineConfig) + previous_global = get_live_global_config(GlobalPipelineConfig) ObjectStateRegistry.clear() try: yield finally: ObjectStateRegistry.clear() - previous_global.apply() + if previous_global is None: + forget_stored_global_config(GlobalPipelineConfig) + else: + set_global_config(GlobalPipelineConfig, previous_global) def test_headless_session_global_config_reaches_existing_step_states( @@ -76,7 +82,7 @@ def test_headless_session_global_config_reaches_existing_step_states( """The MCP server's session has no GUI to register the global state for it.""" before = _global_config(BEFORE) - ensure_global_config_context(GlobalPipelineConfig, before) + set_global_config(GlobalPipelineConfig, before) session = Session( transport_config=OpenHCSZMQConfig(default_port=29873, persistent=False), global_config=before, @@ -117,7 +123,7 @@ def test_saved_global_config_reaches_saved_values_of_existing_step_states( plate = "/isolated/global-save-plate" before = _global_config(BEFORE) - ensure_global_config_context(GlobalPipelineConfig, before) + set_global_config(GlobalPipelineConfig, before) global_state = ObjectState(before, scope_id="") ObjectStateRegistry.register(global_state, _skip_snapshot=True) ObjectStateRegistry.register( @@ -132,7 +138,7 @@ def test_saved_global_config_reaches_saved_values_of_existing_step_states( ConfigWindowTabSpec( state=global_state, save_participant=ConfigSaveParticipant( - apply=lambda config: ensure_global_config_context( + apply=lambda config: set_global_config( GlobalPipelineConfig, config ), rollback=lambda config: None, diff --git a/tests/unit/test_routed_channel_selection.py b/tests/unit/test_routed_channel_selection.py index 5af24466c..06f3422a9 100644 --- a/tests/unit/test_routed_channel_selection.py +++ b/tests/unit/test_routed_channel_selection.py @@ -7,7 +7,7 @@ import pytest import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart, ReadPreviousStep from openhcs.core.config.pipeline_config import ( @@ -42,7 +42,7 @@ def channel_plate(tmp_path): def _execute_steps(plate, steps, output_root): ObjectStateRegistry.clear() - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( dataset_source=ImageXpressHandler, num_workers=1, use_threading=True diff --git a/tests/unit/test_routed_composite_execution.py b/tests/unit/test_routed_composite_execution.py index 1fba3b659..01c217931 100644 --- a/tests/unit/test_routed_composite_execution.py +++ b/tests/unit/test_routed_composite_execution.py @@ -7,7 +7,7 @@ import pytest import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.config.pipeline_config import ( @@ -119,7 +119,7 @@ def test_reduced_channel_stack_is_the_next_steps_only_input( ) ) ObjectStateRegistry.clear() - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( dataset_source=ImageXpressHandler, num_workers=1, use_threading=True diff --git a/tests/unit/test_source_bindings.py b/tests/unit/test_source_bindings.py index 7b763aa26..754fdcc99 100644 --- a/tests/unit/test_source_bindings.py +++ b/tests/unit/test_source_bindings.py @@ -7,7 +7,7 @@ from types import SimpleNamespace import pytest -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from objectstate.object_state import ObjectState from objectstate.object_state_registry import ObjectStateRegistry from polystore.virtual_workspace import SourcePixelRef @@ -197,7 +197,7 @@ def test_step_source_bindings_reject_duplicate_aliases(): def test_step_source_bindings_global_config_merge_resolves_lazy_default(): - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) merged = ObjectState(PipelineConfig()).to_saved_resolved_object() assert isinstance(merged, GlobalPipelineConfig) @@ -390,7 +390,7 @@ def test_step_source_bindings_inherit_plate_source_bindings_for_snapshot(): ObjectStateRegistry.clear() binding = NamedSourceBinding(alias="DNA") metadata_fields = (FieldSpec("Dose", float, required=False),) - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) pipeline_state = ObjectState( PipelineConfig( source_bindings_config=LazySourceBindingsConfig( @@ -468,7 +468,7 @@ def test_compiled_source_bindings_include_realized_original_metadata_schema(): def test_enabled_step_source_bindings_compile_inherited_bindings(): ObjectStateRegistry.clear() binding = NamedSourceBinding(alias="DNA") - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) pipeline_state = ObjectState( PipelineConfig( source_bindings_config=LazySourceBindingsConfig(bindings=(binding,)), @@ -500,7 +500,7 @@ def test_enabled_step_source_bindings_compile_inherited_bindings(): def test_pipeline_step_source_bindings_enabled_inherits_to_function_steps(): ObjectStateRegistry.clear() binding = NamedSourceBinding(alias="DNA") - ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) + set_global_config(GlobalPipelineConfig, GlobalPipelineConfig()) pipeline_state = ObjectState( PipelineConfig( step_source_bindings_config=LazyStepSourceBindingsConfig( @@ -633,7 +633,7 @@ def test_source_lineage_projection_preserves_declaration_order() -> None: def test_saved_resolved_pipeline_config_preserves_scalar_override(): - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(dataset_source=AutoDetectedSource, num_workers=7), ) @@ -653,7 +653,7 @@ def test_orchestrator_microscope_init_uses_saved_resolved_pipeline_config( ): from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(dataset_source=AutoDetectedSource), ) @@ -685,12 +685,12 @@ def test_admitted_request_config_survives_next_live_global_context( ) authored = PipelineConfig(dataset_source=OpenHCSDatasetSource) - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=2, auto_add_output_dataset=True), ) admitted = ObjectState(authored).to_saved_resolved_object() - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig(num_workers=4, auto_add_output_dataset=False), ) diff --git a/tests/unit/test_source_tile_geometry.py b/tests/unit/test_source_tile_geometry.py index e6528bb97..45dc48c41 100644 --- a/tests/unit/test_source_tile_geometry.py +++ b/tests/unit/test_source_tile_geometry.py @@ -469,7 +469,7 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired tmp_path, embedded, assembly_backend, storage_backend ): from objectstate import ObjectStateRegistry - from objectstate.lazy_factory import ensure_global_config_context + from objectstate import set_global_config from openhcs.constants.input_source import ReadPipelineStart, ReadPreviousStep @@ -538,7 +538,7 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired use_threading=True, analysis_consolidation_config=AnalysisConsolidationConfig(enabled=False), ) - ensure_global_config_context(GlobalPipelineConfig, global_config) + set_global_config(GlobalPipelineConfig, global_config) config = PipelineConfig( source_bindings_config=LazySourceBindingsConfig.from_config(_config()), vfs_config=LazyVFSConfig( diff --git a/tests/unit/test_template_crop_pipeline_execution.py b/tests/unit/test_template_crop_pipeline_execution.py index b607794bf..e0dc93e20 100644 --- a/tests/unit/test_template_crop_pipeline_execution.py +++ b/tests/unit/test_template_crop_pipeline_execution.py @@ -8,7 +8,7 @@ import pytest import tifffile from objectstate import ObjectStateRegistry -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.core.config.pipeline_config import ( GlobalPipelineConfig, @@ -91,7 +91,7 @@ def test_template_crop_persists_each_source_channel( queue = SimpleQueue() set_progress_queue(queue) try: - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( dataset_source=ImageXpressHandler, num_workers=1, use_threading=True diff --git a/tests/unit/test_unified_registry_runtime_payloads.py b/tests/unit/test_unified_registry_runtime_payloads.py index f0f81cdc6..b6d1202ae 100644 --- a/tests/unit/test_unified_registry_runtime_payloads.py +++ b/tests/unit/test_unified_registry_runtime_payloads.py @@ -23,7 +23,7 @@ from openhcs.core.callable.callable_contract import CallableContract, callable_request from openhcs.core.config.pipeline_config import LazyDtypeConfig from openhcs.core.callable.function_patterns import compile_function_pattern -from openhcs.core.memory import MEMORY_TYPE_NUMPY +from openhcs.core.memory import MemoryType from openhcs.core.memory.decorators import numpy from openhcs.core.payload.runtime_array_values import RuntimeArrayPayload from openhcs.core.payload.runtime_image_values import ( @@ -66,7 +66,7 @@ class MinimalRegistry(LibraryRegistryBase): MODULES_TO_SCAN = [] - MEMORY_TYPE = MEMORY_TYPE_NUMPY + MEMORY_TYPE = MemoryType.NUMPY.value FLOAT_DTYPE = np.float32 def get_library_version(self) -> str: @@ -211,7 +211,7 @@ def add_one(image: ImageMetadataPayload) -> ImageMetadataPayload: seen_paths.append(image.metadata.source_path) return image.with_pixels(image.data + 1) - add_one.output_memory_type = MEMORY_TYPE_NUMPY + add_one.output_memory_type = MemoryType.NUMPY.value result = Pure2DContract.execute( LibraryContractCall(add_one, ()), @@ -338,7 +338,7 @@ def apply_mask( seen_true_indices.append((int(true_y), int(true_x))) return image.with_pixels(np.where(mask_data, image_data + 100, image_data),) - apply_mask.output_memory_type = MEMORY_TYPE_NUMPY + apply_mask.output_memory_type = MemoryType.NUMPY.value result = Pure2DContract.execute( LibraryContractCall(apply_mask, ()), @@ -393,7 +393,7 @@ def consume_labels( seen_label_shapes.append(labels.labels.shape) return image - consume_labels.output_memory_type = MEMORY_TYPE_NUMPY + consume_labels.output_memory_type = MemoryType.NUMPY.value result = Pure2DContract.execute( LibraryContractCall(consume_labels, ()), diff --git a/tests/unit/test_zarr_input_conversion_subdirectory.py b/tests/unit/test_zarr_input_conversion_subdirectory.py index 581491e68..e541914e9 100644 --- a/tests/unit/test_zarr_input_conversion_subdirectory.py +++ b/tests/unit/test_zarr_input_conversion_subdirectory.py @@ -8,7 +8,7 @@ import queue from pathlib import Path -from objectstate.lazy_factory import ensure_global_config_context +from objectstate import set_global_config from openhcs.constants.constants import Backend from openhcs.core.config.pipeline_config import ( @@ -50,7 +50,7 @@ def _prepared_workspace_plate(root: Path) -> Path: def test_zarr_conversion_keys_store_outputs_by_plate_relative_virtual_path(tmp_path): """Store paths are relative to the source subdirectory; virtual paths are not.""" plate = _prepared_workspace_plate(tmp_path / "plate") - ensure_global_config_context( + set_global_config( GlobalPipelineConfig, GlobalPipelineConfig( num_workers=1, diff --git a/tests/unit/test_zmq_execution_server.py b/tests/unit/test_zmq_execution_server.py index f6e8e2399..f61c302cf 100644 --- a/tests/unit/test_zmq_execution_server.py +++ b/tests/unit/test_zmq_execution_server.py @@ -6,7 +6,7 @@ from types import ModuleType, SimpleNamespace import pytest -from objectstate import get_current_global_config +from objectstate import get_live_global_config, get_saved_global_config from zmqruntime.execution import ExecutionServer from zmqruntime.messages import ( ExecuteRequest, @@ -95,7 +95,7 @@ def test_zmq_execution_context_seeds_saved_global_config_for_compilation() -> No ZMQExecutionServer._ensure_request_global_config_context(context) - saved_global_config = get_current_global_config( + saved_global_config = get_live_global_config( GlobalPipelineConfig, use_live=False, ) @@ -836,4 +836,4 @@ def reject_resolution(*args, **kwargs): assert initialized[0]["resolved_config"] is None assert compilations[0]["resolved_config"] is None assert compilations[0]["partition_values"] == ["A01"] - assert get_current_global_config(GlobalPipelineConfig, use_live=False) is global_config + assert get_saved_global_config(GlobalPipelineConfig) is global_config diff --git a/tests/unit/test_zmq_execution_server_process.py b/tests/unit/test_zmq_execution_server_process.py index f487f444a..6c31c071e 100644 --- a/tests/unit/test_zmq_execution_server_process.py +++ b/tests/unit/test_zmq_execution_server_process.py @@ -72,9 +72,9 @@ def current(cls, *, detached=False): subprocess_environment = {"FRAMEWORK_IMPORTS": "prepared"} monkeypatch.setattr( zmq_execution_client, - "MemoryType", + "ArrayLibrary", SimpleNamespace( - subprocess_environment=lambda: subprocess_environment, + child_environment=lambda: subprocess_environment, ), ) From ef407d9056735c51aeedd85fa8bb1e2b8381acc0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:07:01 +0000 Subject: [PATCH 20/27] Sibling floors say what the code was ported against; three leftovers that only running shows pyproject names the sibling releases this code runs on (arraybridge 0.5.2, objectstate 5.0.1, formbridge 0.2.1, ...): a stale environment now fails at install, not at import. formbridge's dispatcher shuts down with close_dispatch (close is the widget's): the MCP server listed its tools and then died stopping. Six call sites. MeasurementSparseColumnarRows had fields and a __post_init__ and no @dataclass, so it took no arguments. ProducedImageStack lost slots=True, so its memory_type field ran into the image payload's read-only property; its parent is a slots dataclass and its __post_init__ already spells super() the way slots needs. Two tests named modules by their pre-move paths; one read the saved global config through the live reader. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- .../measurement_row_materialization.py | 1 + openhcs/core/payload/aligned_image_payload.py | 2 +- openhcs/mcp/execution.py | 2 +- openhcs/pyqt_gui/services/service_adapter.py | 2 +- pyproject.toml | 16 ++++++++-------- tests/pyqt_gui/test_session_gui_journey.py | 2 +- .../agent/test_mcp_affine_inspection_progress.py | 4 ++-- tests/unit/pyqt_gui/test_plate_manager_widget.py | 2 +- tests/unit/test_compiled_execution.py | 2 +- tests/unit/test_zmq_execution_server.py | 7 ++----- 10 files changed, 19 insertions(+), 21 deletions(-) diff --git a/openhcs/core/measurements/measurement_row_materialization.py b/openhcs/core/measurements/measurement_row_materialization.py index 8be9cd18e..a8c053943 100644 --- a/openhcs/core/measurements/measurement_row_materialization.py +++ b/openhcs/core/measurements/measurement_row_materialization.py @@ -593,6 +593,7 @@ def _batch_aligns_with_segment( ) +@dataclass(frozen=True, slots=True) class MeasurementSparseColumnarRows(ColumnarRows): """Columnar measurement rows whose missing cells are structural, not values.""" diff --git a/openhcs/core/payload/aligned_image_payload.py b/openhcs/core/payload/aligned_image_payload.py index 0c234d207..7164534aa 100644 --- a/openhcs/core/payload/aligned_image_payload.py +++ b/openhcs/core/payload/aligned_image_payload.py @@ -1467,7 +1467,7 @@ def composition_payload_metadata( ) -@dataclass(kw_only=True) +@dataclass(kw_only=True, slots=True) class ProducedImageStack(ImagePayloadSliceStack): """Borrowed produced image slices, composed once into one dense buffer. diff --git a/openhcs/mcp/execution.py b/openhcs/mcp/execution.py index 6a2758e01..2bd50edf4 100644 --- a/openhcs/mcp/execution.py +++ b/openhcs/mcp/execution.py @@ -102,7 +102,7 @@ def close(self) -> None: if self._closed: return try: - self.dispatcher.close() + self.dispatcher.close_dispatch() finally: try: super().close() diff --git a/openhcs/pyqt_gui/services/service_adapter.py b/openhcs/pyqt_gui/services/service_adapter.py index 8b67096b9..5028a42c5 100644 --- a/openhcs/pyqt_gui/services/service_adapter.py +++ b/openhcs/pyqt_gui/services/service_adapter.py @@ -74,7 +74,7 @@ def log_failure(completed) -> None: def close(self): """Fence UI dispatch and retire the owned async-operation executor.""" - self.ui_dispatcher.close() + self.ui_dispatcher.close_dispatch() self._async_operations.close() def create_message_box( diff --git a/pyproject.toml b/pyproject.toml index ac996a5f5..08584487f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -102,15 +102,15 @@ dependencies = [ "psutil>=5.9.0", # External dependencies (PyPI versions for production builds) - "zmqruntime>=0.6.4", + "zmqruntime>=0.6.6", "pycodify>=0.2.1", - "objectstate>=3.0.4", - "python-introspect>=0.2.8", - "metaclass-registry>=0.4.0", - "arraybridge>=0.4.1", - "polystore>=0.6.2", - "formbridge>=0.1.3", - "pyqt-reactive>=0.7.2", + "objectstate>=5.0.1", + "python-introspect>=0.4.0", + "metaclass-registry>=0.5.0", + "arraybridge>=0.5.2", + "polystore>=0.6.3", + "formbridge>=0.2.1", + "pyqt-reactive>=0.10.0", ] [project.optional-dependencies] diff --git a/tests/pyqt_gui/test_session_gui_journey.py b/tests/pyqt_gui/test_session_gui_journey.py index 4cbf574a9..36b23490f 100644 --- a/tests/pyqt_gui/test_session_gui_journey.py +++ b/tests/pyqt_gui/test_session_gui_journey.py @@ -115,4 +115,4 @@ def wait_until(condition, label) -> None: manager.close() release_widgets(application, manager) session.close() - dispatcher.close() + dispatcher.close_dispatch() diff --git a/tests/unit/agent/test_mcp_affine_inspection_progress.py b/tests/unit/agent/test_mcp_affine_inspection_progress.py index 41b387ee5..cb181dd64 100644 --- a/tests/unit/agent/test_mcp_affine_inspection_progress.py +++ b/tests/unit/agent/test_mcp_affine_inspection_progress.py @@ -257,7 +257,7 @@ async def exercise(): def test_closed_dispatcher_rejects_without_invocation(): executor = McpTransportExecutor() calls = [] - executor.dispatcher.close() + executor.dispatcher.close_dispatch() async def exercise(): with pytest.raises(MainThreadDispatcherClosedError): @@ -285,7 +285,7 @@ async def exercise(): assert calls == [] assert dispatcher.call(lambda: "original-main") == "original-main" finally: - dispatcher.close() + dispatcher.close_dispatch() def test_transport_rejects_worker_start_without_affinity_claim(): diff --git a/tests/unit/pyqt_gui/test_plate_manager_widget.py b/tests/unit/pyqt_gui/test_plate_manager_widget.py index 70ec1e139..b0f1118a4 100644 --- a/tests/unit/pyqt_gui/test_plate_manager_widget.py +++ b/tests/unit/pyqt_gui/test_plate_manager_widget.py @@ -865,7 +865,7 @@ def test_progress_from_a_worker_thread_reaches_the_live_row(tmp_path) -> None: live = gui.plate_manager._format_item_content(row, 0, None) assert "Executing 25.0%" in live.layout.status_prefix finally: - dispatcher.close() + dispatcher.close_dispatch() # --------------------------------------------------------------------------- diff --git a/tests/unit/test_compiled_execution.py b/tests/unit/test_compiled_execution.py index b7972a446..39d72196b 100644 --- a/tests/unit/test_compiled_execution.py +++ b/tests/unit/test_compiled_execution.py @@ -83,7 +83,7 @@ def resolve_for_transport(contexts): return {"A01": resolved_context} monkeypatch.setattr( - "openhcs.core.compiled_execution.resolve_lazy_configurations_for_serialization", + "openhcs.core.execution.compiled_execution.resolve_lazy_configurations_for_serialization", resolve_for_transport, ) diff --git a/tests/unit/test_zmq_execution_server.py b/tests/unit/test_zmq_execution_server.py index f61c302cf..b7e43036e 100644 --- a/tests/unit/test_zmq_execution_server.py +++ b/tests/unit/test_zmq_execution_server.py @@ -95,10 +95,7 @@ def test_zmq_execution_context_seeds_saved_global_config_for_compilation() -> No ZMQExecutionServer._ensure_request_global_config_context(context) - saved_global_config = get_live_global_config( - GlobalPipelineConfig, - use_live=False, - ) + saved_global_config = get_saved_global_config(GlobalPipelineConfig) assert saved_global_config is global_config assert saved_global_config.processing_config.group_by is Microscopy.Channel @@ -320,7 +317,7 @@ def test_server_exports_outcomes_without_projecting_compiled_values( output_dataset=SimpleNamespace(output_dataset_root=tmp_path), ) monkeypatch.setattr( - "openhcs.core.runtime_execution_validation.runtime_output_roots", + "openhcs.core.artifact_store.runtime_execution_validation.runtime_output_roots", lambda contexts, root: (root,), ) From db9e83bc3bc97fda79f21028f561d4156d3bf614 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:14:20 +0000 Subject: [PATCH 21/27] An axis is written to JSON as its boundary name, as its family already says GroupingDeclaration's docstring declares it ("a declaration's boundary name is its JSON spelling") and the family decodes it (AxisFamily.grouping_named), but nothing told the serializer. Axis classes share AutoRegisterMeta with the registered families and hold no registry key, so python-introspect asked Site for a __registry_key__ it never had and every pipeline run died on its first axis. Seen: test_count_cells_simple_dual_channel (a two-well synthetic plate through the execution server) and the callable-authoring page's code blocks, 2 passed. The page imported runtime_stores from its pre-move package. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- docs/source/development/callable_artifact_authoring.rst | 2 +- openhcs/core/axes/axis_declarations.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/source/development/callable_artifact_authoring.rst b/docs/source/development/callable_artifact_authoring.rst index 8eced7f89..63f97dd46 100644 --- a/docs/source/development/callable_artifact_authoring.rst +++ b/docs/source/development/callable_artifact_authoring.rst @@ -511,7 +511,7 @@ runtime axis, not biological object counts or an inferred well identity: artifact_inputs, artifact_outputs, execution_scope, runtime_bound_parameters, ) from openhcs.core.measurements.runtime_measurements import MeasurementTable - from openhcs.core.runtime_store.runtime_stores import RuntimeArtifactBatch + from openhcs.core.artifact_store.runtime_stores import RuntimeArtifactBatch from openhcs.core.materialization.core import MaterializationSpec from openhcs.core.materialization.options import CsvOptions diff --git a/openhcs/core/axes/axis_declarations.py b/openhcs/core/axes/axis_declarations.py index fae268ada..0007f4e88 100644 --- a/openhcs/core/axes/axis_declarations.py +++ b/openhcs/core/axes/axis_declarations.py @@ -20,6 +20,7 @@ from typing import ClassVar, TypeGuard from metaclass_registry import AutoRegisterMeta +from python_introspect import to_jsonable class AxisDeclarationMeta(AutoRegisterMeta): @@ -311,6 +312,13 @@ def grouping_axes(cls) -> tuple[type[Axis], ...]: """The axes whose values partition an assembled value (empty: none).""" +@to_jsonable.register(AxisDeclarationMeta) +def _boundary_name(declaration: type[GroupingDeclaration]) -> str: + """A grouping declaration's JSON spelling is its boundary ``name``.""" + + return declaration.name + + class Axis(GroupingDeclaration): """One declared axis. Subclasses are nested in an :class:`AxisFamily`.""" From 1bbc0c62d93e3fc7cf4a18b7a50cd8960c01b370 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:37:19 +0000 Subject: [PATCH 22/27] Open plain TIFF folders without Java; fix the run command's second run; teach live names in the source-binding docs - BioFormatsJavaAdapter.discover_stores asked for the Java context before looking at any file, so an install without the bioformats extra could not open a folder of plain TIFFs. The context is now asked for only by a path that needs Java, through the conversion _declares_path already owned. - dev_client_session.run_source unpacked the scope ids add_datasets returned; a resident session that already holds the folder adds nothing, and the ValueError was reported as a transport failure. The run now finds the dataset by its root. - image_sources.rst and quick_start.rst taught enum members that became classes (SourceFilterSubject.FILE, SourceFilterMatchType.EQUALS, MetadataSource.FILE_NAME, InputSource.PIPELINE_START). Their code blocks now run. - test_source_binding_path_admission read two files at paths they moved from. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- docs/source/architecture/quick_start.rst | 23 +++++++++++-------- .../guide_for_biologists/image_sources.rst | 12 +++++----- openhcs/mcp/dev_client_session.py | 23 +++++++++++++++---- openhcs/microscopes/bioformats_adapter.py | 11 +++++---- .../test_source_binding_path_admission.py | 4 ++-- 5 files changed, 46 insertions(+), 27 deletions(-) diff --git a/docs/source/architecture/quick_start.rst b/docs/source/architecture/quick_start.rst index 7445c3b8c..e9bfd2579 100644 --- a/docs/source/architecture/quick_start.rst +++ b/docs/source/architecture/quick_start.rst @@ -56,7 +56,7 @@ A minimal declaration uses an ordinary registered callable: .. code-block:: python from openhcs.core.memory.decorators import numpy - from openhcs.constants.input_source import InputSource + from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.config.pipeline_config import ( LazyProcessingConfig, LazyStepSourceBindingsConfig, @@ -221,6 +221,7 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: .. code-block:: python + from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.config.pipeline_config import ( LazyProcessingConfig, LazySourceBindingsConfig, @@ -229,13 +230,15 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: ) from openhcs.core.source.source_bindings import ( ComponentSelector, + FromFileName, MetadataExtractionRule, - MetadataSource, NamedSourceBinding, + PathIsImage, + SourceExtension, + SourceFileName, SourceFilterClause, - SourceFilterMatchType, - SourceFilterSubject, SourceSelector, + TextContains, ) from openhcs.core.steps.function_step import FunctionStep from openhcs.domains.microscopy.axes import Microscopy @@ -249,8 +252,8 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: selector=SourceSelector( filters=( SourceFilterClause( - subject=SourceFilterSubject.FILE, - match_type=SourceFilterMatchType.CONTAINS, + subject=SourceFileName, + match_type=TextContains, value=token, ), ), @@ -264,13 +267,13 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: source_bindings_config=LazySourceBindingsConfig( source_filters=( SourceFilterClause( - subject=SourceFilterSubject.EXTENSION, - match_type=SourceFilterMatchType.IS_IMAGE, + subject=SourceExtension, + match_type=PathIsImage, ), ), metadata_rules=( MetadataExtractionRule( - source=MetadataSource.FILE_NAME, + source=FromFileName, pattern=( r"^(?P[A-H][0-9]{2})_" r"s(?P[0-9]+)_(?P[^.]+)" @@ -289,7 +292,7 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: name="Normalize DNA", func=stack_percentile_normalize, processing_config=LazyProcessingConfig( - input_source=InputSource.PIPELINE_START, + input_source=ReadPipelineStart, ), source_bindings=LazyStepSourceBindingsConfig( enabled=True, diff --git a/docs/source/guide_for_biologists/image_sources.rst b/docs/source/guide_for_biologists/image_sources.rst index 830cf0d53..beb01083a 100644 --- a/docs/source/guide_for_biologists/image_sources.rst +++ b/docs/source/guide_for_biologists/image_sources.rst @@ -296,7 +296,7 @@ source-binding semantics; do not pass that concrete class to this lazy field. .. code-block:: python - from openhcs.constants.input_source import InputSource + from openhcs.constants.input_source import ReadPipelineStart from openhcs.core.config.pipeline_config import ( LazyProcessingConfig, LazySourceBindingsConfig, @@ -305,10 +305,10 @@ source-binding semantics; do not pass that concrete class to this lazy field. ) from openhcs.core.source.source_bindings import ( NamedSourceBinding, + SourceFileName, SourceFilterClause, - SourceFilterMatchType, - SourceFilterSubject, SourceSelector, + TextEquals, ) from openhcs.core.steps.function_step import FunctionStep from openhcs.processing.backends.processors.numpy_processor import ( @@ -322,8 +322,8 @@ source-binding semantics; do not pass that concrete class to this lazy field. selector=SourceSelector( filters=( SourceFilterClause( - subject=SourceFilterSubject.FILE, - match_type=SourceFilterMatchType.EQUALS, + subject=SourceFileName, + match_type=TextEquals, value=filename, ), ), @@ -375,7 +375,7 @@ source-binding semantics; do not pass that concrete class to this lazy field. name="Normalize DNA", func=stack_percentile_normalize, processing_config=LazyProcessingConfig( - input_source=InputSource.PIPELINE_START, + input_source=ReadPipelineStart, ), source_bindings=LazyStepSourceBindingsConfig( enabled=True, diff --git a/openhcs/mcp/dev_client_session.py b/openhcs/mcp/dev_client_session.py index dce170fbb..587568860 100644 --- a/openhcs/mcp/dev_client_session.py +++ b/openhcs/mcp/dev_client_session.py @@ -10,6 +10,7 @@ import time from abc import ABC, abstractmethod from dataclasses import dataclass +from pathlib import Path from typing import ClassVar from python_introspect import JsonValue @@ -100,7 +101,9 @@ async def call(self, capability, arguments: dict[str, JsonValue]) -> McpDevToolR self.results.append(result) return result - async def dataset_row(self, scope_id: str) -> DatasetRowState | None: + async def dataset_rows(self) -> tuple[DatasetRowState, ...]: + """The session's dataset rows, in the order they were added.""" + result = await call_mcp_tool( self.session, McpDevToolCall(agent_capabilities.session_datasets.name, {}), @@ -108,8 +111,14 @@ async def dataset_row(self, scope_id: str) -> DatasetRowState | None: ) state = result.first_decoded_payload() if not isinstance(state, DatasetListState): - return None - return next((row for row in state.rows if row.scope_id == scope_id), None) + return () + return tuple(state.rows) + + async def dataset_row(self, scope_id: str) -> DatasetRowState | None: + return next( + (row for row in await self.dataset_rows() if row.scope_id == scope_id), + None, + ) async def wait_for( self, @@ -164,7 +173,13 @@ async def run_source( added = await self.call(agent_capabilities.add_datasets, {"roots": [root]}) if _rejected(added): return - (scope_id, *_rest) = added.first_decoded_payload().target_scope_ids + # A resident session may already hold ``root``; adding it again adds nothing. + dataset_root = Path(root).resolve() + (scope_id, *_rest) = ( + row.scope_id + for row in await self.dataset_rows() + if Path(row.root).resolve() == dataset_root + ) piped = await self.call( agent_capabilities.set_dataset_pipeline, {"scope_id": scope_id, "pipeline_source": pipeline_source}, diff --git a/openhcs/microscopes/bioformats_adapter.py b/openhcs/microscopes/bioformats_adapter.py index 639bfe98d..783ccec95 100644 --- a/openhcs/microscopes/bioformats_adapter.py +++ b/openhcs/microscopes/bioformats_adapter.py @@ -656,7 +656,6 @@ class BioFormatsJavaAdapter(SourcePlaneStoreAdapter): registry_key = "java" def discover_stores(self, root: Path) -> tuple[SourcePlaneDataset, ...]: - context = BioFormatsJavaContext.instance() datasets: list[SourcePlaneDataset] = [] exclusions: list[BioFormatsPackedRgbSeriesExclusion] = [] claimed_paths: set[Path] = set() @@ -664,11 +663,11 @@ def discover_stores(self, root: Path) -> tuple[SourcePlaneDataset, ...]: for source_path in candidate_source_paths(root): if absolute_source_path(source_path) in claimed_paths: continue - if not self._declares_path(context, source_path): + if not self._declares_path(source_path): continue if not self.source_bindings.discovery_path_matches( root, source_path - ) and context.is_single_file(source_path): + ) and BioFormatsJavaContext.instance().is_single_file(source_path): continue try: dataset = self._discover_container(root, source_path) @@ -704,13 +703,15 @@ def discover_stores(self, root: Path) -> tuple[SourcePlaneDataset, ...]: return tuple(datasets) @staticmethod - def _declares_path(context: BioFormatsJavaContext, path: Path) -> bool: + def _declares_path(path: Path) -> bool: + """Whether Java claims ``path``; a plain image file never asks Java.""" + if ImageFileFormat.is_image_path(path): image_format = ImageFileFormat.require_path(path) if not image_format.requires_plane_store_decoder(path): return False try: - return context.declares_path(path) + return BioFormatsJavaContext.instance().declares_path(path) except BioFormatsJavaUnavailableError as exc: raise PlaneStoreUnavailableError(str(exc)) from exc diff --git a/tests/unit/test_source_binding_path_admission.py b/tests/unit/test_source_binding_path_admission.py index be19dba12..9117fa358 100644 --- a/tests/unit/test_source_binding_path_admission.py +++ b/tests/unit/test_source_binding_path_admission.py @@ -202,14 +202,14 @@ def test_preparation_consumers_cannot_reauthor_binding_or_java_lifetime(): root = Path(__file__).resolve().parents[2] for path, class_name, method_name, owner_call, forbidden in ( ( - "openhcs/core/config.py", + "openhcs/core/config/pipeline_config.py", "SourceBindingsConfig", "discovery_path_matches", "physical_path_matches", {"explicit_source", "selector"}, ), ( - "openhcs/core/source_binding_workspace.py", + "openhcs/core/source/source_binding_workspace.py", "SourceBindingWorkspaceProjector", "candidate_matches_binding", "physical_path_matches", From efeb830f471a19c68167360540f9ef326aa3ffce Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:49:14 +0000 Subject: [PATCH 23/27] The run command says why a stage failed A failed initialize or compile printed its status and nothing else: the reason is published as a session event, which run_source read while waiting and threw away. Each stage now says where its failure is explained: initialize and compile put the events since the stage started into the journey, and a finished run's error is printed from its dataset row, which already carried it. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- openhcs/mcp/dev_client_renderers/pipeline.py | 5 +++++ openhcs/mcp/dev_client_session.py | 17 ++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/openhcs/mcp/dev_client_renderers/pipeline.py b/openhcs/mcp/dev_client_renderers/pipeline.py index 9d3c449c2..c6c331f0c 100644 --- a/openhcs/mcp/dev_client_renderers/pipeline.py +++ b/openhcs/mcp/dev_client_renderers/pipeline.py @@ -406,6 +406,11 @@ def render_payload( f"initialized={row.initialized} compiled={row.compiled} " f"terminal={McpDevOutputRenderer.text(row.terminal_status)} " f"scope={row.scope_id}" + + ( + f"\n error: {row.finished_execution_error}" + if row.finished_execution_error + else "" + ) for row in payload.rows ) return "\n".join(lines) diff --git a/openhcs/mcp/dev_client_session.py b/openhcs/mcp/dev_client_session.py index 587568860..678305f5e 100644 --- a/openhcs/mcp/dev_client_session.py +++ b/openhcs/mcp/dev_client_session.py @@ -43,6 +43,15 @@ def finished(cls, row: DatasetRowState) -> bool: ... @abstractmethod def succeeded(cls, row: DatasetRowState) -> bool: ... + @classmethod + async def explain_failure(cls, journey: SessionJourney, started_sequence: int) -> None: + """Put why the stage failed into the journey: the session publishes it as an event.""" + + await journey.call( + agent_capabilities.session_events, + {"after_sequence": started_sequence, "timeout_seconds": 0.0}, + ) + class InitializeStage(DatasetStage): capability = agent_capabilities.initialize_datasets @@ -83,6 +92,10 @@ def finished(cls, row: DatasetRowState) -> bool: def succeeded(cls, row: DatasetRowState) -> bool: return row.terminal_status == "complete" + @classmethod + async def explain_failure(cls, journey: SessionJourney, started_sequence: int) -> None: + """A finished run's error is on its dataset row.""" + @dataclass(slots=True) class SessionJourney: @@ -192,13 +205,15 @@ async def run_source( return if stage is RunStage and not wait_for_run: return + started_sequence = started.first_decoded_payload().event_sequence row = await self.wait_for( stage, scope_id, - after_sequence=started.first_decoded_payload().event_sequence, + after_sequence=started_sequence, timeout_seconds=stage_timeout_seconds, ) if row is None or not stage.succeeded(row): + await stage.explain_failure(self, started_sequence) break await self.call(agent_capabilities.session_datasets, {}) From 1c92caba9a86019c19390c165d01f3ddd56e04d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:18:58 +0000 Subject: [PATCH 24/27] The agent benchmark checks a task from the plate a run wrote python -m benchmark.agent_validation check TASK_ROOT reads the one output plate beside a blind task's inputs, takes each case's planes by the site OpenHCS's own plane filenames give, and makes the task's held-out assertions on them: one JSON line an assertion, exit 0 only when every one passes. A case is a site in one place now, where inputs are written and results read. It reads image planes, so the two number tasks and the table task fail here until their results have a plane to be read from. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- benchmark/agent_validation/__main__.py | 13 ++++ benchmark/agent_validation/corpus.py | 63 ++++++++++++++++++- .../benchmark/test_agent_validation_corpus.py | 35 +++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/benchmark/agent_validation/__main__.py b/benchmark/agent_validation/__main__.py index 2fc1db8cb..73730006a 100644 --- a/benchmark/agent_validation/__main__.py +++ b/benchmark/agent_validation/__main__.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import json from pathlib import Path from benchmark.agent_validation.corpus import AgentValidationCorpus @@ -28,6 +29,12 @@ def _parser() -> argparse.ArgumentParser: help="Verify a pinned human-eval-bia checkout without executing it.", ) verify.add_argument("checkout", type=Path) + check = subparsers.add_parser( + "check", + help="Check the plate an OpenHCS run wrote beside one task's inputs against " + "the task's held-out cases.", + ) + check.add_argument("task_root", type=Path) return parser @@ -45,6 +52,12 @@ def main(argv: list[str] | None = None) -> int: probe_ids = AgentValidationCorpus.build_diagnostic_bundle(args.output_root) print(f"Wrote {len(probe_ids)} diagnostic probes to {args.output_root}") return 0 + if args.command == "check": + assertions = AgentValidationCorpus.check_output_plate(args.task_root) + for assertion in assertions: + print(json.dumps({"name": assertion.name, "passed": assertion.passed, + "detail": assertion.detail}, sort_keys=True)) + return 0 if assertions and all(assertion.passed for assertion in assertions) else 1 results = verify_upstream_checkout(args.checkout) for result in results: print( diff --git a/benchmark/agent_validation/corpus.py b/benchmark/agent_validation/corpus.py index 993c1dce1..390cf392f 100644 --- a/benchmark/agent_validation/corpus.py +++ b/benchmark/agent_validation/corpus.py @@ -31,6 +31,7 @@ from benchmark.agent_validation.perturbations import DiagnosticPerturbationDeclaration from benchmark.agent_validation.scoring import AttemptJournalScorer from openhcs.core.io.pipeline_document import PipelineDocumentCodec +from openhcs.core.source.source_projection import OpenHCSPlaneAddress from python_introspect import to_jsonable @@ -189,13 +190,73 @@ def score( lifecycle_passed=journal.lifecycle_passed, ) + @classmethod + def check_output_plate(cls, task_root: Path) -> tuple[AssertionResult, ...]: + """Check the plate an OpenHCS run wrote beside one blind task's inputs. + + A case is a site of the input plate, so its result is the planes the run wrote for + that site: one plane as written, several as a stack in z order. Every held-out + assertion of the task is made on it. A case with no plane fails by name; this reads + image planes, so a task whose result is a table or a number fails here until its + result has a plane to be read from. + """ + + bundle = json.loads((task_root / "task.json").read_text(encoding="utf-8")) + declaration = ValidationTaskDeclaration.get(bundle["spec"]["task_id"]) + planes = cls._output_planes(task_root, task_root / bundle["spec"]["input_root"]) + results: list[AssertionResult] = [] + for site, case in cls._sited_cases(declaration): + written = [path for _, path in sorted(planes.get(site, ()))] + if not written: + results.append(AssertionResult( + f"{case.case_id}.output", False, + f"no output plane for site {site} in a plate beside the inputs")) + continue + stack = [tifffile.imread(path) for path in written] + actual = stack[0] if len(stack) == 1 else np.stack(stack) + results.extend( + AssertionResult(f"{case.case_id}.{assertion.name}", assertion.passed, + assertion.detail) + for assertion in declaration.assert_case(case, actual)) + return tuple(results) + @staticmethod + def _output_planes(task_root: Path, input_root: Path) -> dict[int, list[tuple[int, Path]]]: + """Each site's planes, as (z, file), in the one plate a run wrote beside the inputs: + a directory OpenHCS left its metadata in that is not the inputs.""" + + plates = sorted( + metadata.parent for metadata in task_root.glob("*/openhcs_metadata.json") + if metadata.parent.resolve() != input_root.resolve()) + if len(plates) != 1: + raise ValueError( + f"{task_root} holds {len(plates)} output plates beside its inputs; " + "a check reads exactly one.") + planes: dict[int, list[tuple[int, Path]]] = {} + for path in sorted(plates[0].rglob("*.tif")): + parsed = OpenHCSPlaneAddress.from_filename(path.name) + if parsed is None: + continue + address = parsed.address.as_component_metadata() + planes.setdefault(int(address["site"]), []).append((int(address["z_index"]), path)) + return planes + + @staticmethod + def _sited_cases( + declaration: type[ValidationTaskDeclaration], + ) -> tuple[tuple[int, ScoringCase], ...]: + """Each scoring case and the site of the plate it is written to and read from.""" + + return tuple(enumerate(declaration.scoring_cases(), start=1)) + + @classmethod def _write_inputs( + cls, declaration: type[ValidationTaskDeclaration], input_root: Path, ) -> tuple[TaskCaseRecord, ...]: rows = [] - for site, case in enumerate(declaration.scoring_cases(), start=1): + for site, case in cls._sited_cases(declaration): files: list[InputFileRecord] = [] for input_value in case.inputs: array = np.asarray(input_value.array) diff --git a/tests/unit/benchmark/test_agent_validation_corpus.py b/tests/unit/benchmark/test_agent_validation_corpus.py index 562b6ae75..f7884d36e 100644 --- a/tests/unit/benchmark/test_agent_validation_corpus.py +++ b/tests/unit/benchmark/test_agent_validation_corpus.py @@ -336,3 +336,38 @@ def _reference_result(task_id: str, case) -> object: ) image = inputs["image"] return np.asarray(measure.label(image > image.mean()).max()) + + +def test_a_task_is_checked_from_the_plate_a_run_wrote_beside_its_inputs(tmp_path: Path) -> None: + import tifffile + + from openhcs.core.source.source_projection import OpenHCSPlaneAddress + + AgentValidationCorpus.build_authoring_bundle(tmp_path / "bundle") + task_root = tmp_path / "bundle" / "human_eval_bia.binary_closing" + (case,) = ValidationTaskDeclaration.get("human_eval_bia.binary_closing").scoring_cases() + + # Nothing has run: there is no plate to read, and the check says so rather than fail a case. + with pytest.raises(ValueError, match="0 output plates"): + AgentValidationCorpus.check_output_plate(task_root) + + (source,) = (task_root / "inputs").glob("*.tif") + plane = OpenHCSPlaneAddress.from_filename(source.name).address.filename() + written = task_root / "inputs_openhcs" / "images" / plane + written.parent.mkdir(parents=True) + (task_root / "inputs_openhcs" / "openhcs_metadata.json").write_text("{}", encoding="utf-8") + + tifffile.imwrite(written, np.asarray(case.expected)) + assert [(result.name, result.passed) + for result in AgentValidationCorpus.check_output_plate(task_root)] \ + == [("case-1.array_equal", True)] + + wrong = np.asarray(case.expected).copy() + wrong[3, 3] = 0 + tifffile.imwrite(written, wrong) + (result,) = AgentValidationCorpus.check_output_plate(task_root) + assert not result.passed and "mismatch_count=1" in result.detail + + written.unlink() + (result,) = AgentValidationCorpus.check_output_plate(task_root) + assert (result.name, result.passed) == ("case-1.output", False) From ec7755f1561b1ccbd4cea7a69c8f0b4af147d7e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:20:37 +0000 Subject: [PATCH 25/27] The agent benchmark writes one task a check can read build-task TASK_ROOT --pick N writes one blind task whose result is image planes: of those, in declaration order, the one N lands on. Whoever runs attempts picks by number and keeps no list of this benchmark's tasks. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- benchmark/agent_validation/__main__.py | 10 +++++++ benchmark/agent_validation/contracts.py | 5 ++++ benchmark/agent_validation/corpus.py | 30 ++++++++++++++----- .../benchmark/test_agent_validation_corpus.py | 9 ++++-- 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/benchmark/agent_validation/__main__.py b/benchmark/agent_validation/__main__.py index 73730006a..cd892db5e 100644 --- a/benchmark/agent_validation/__main__.py +++ b/benchmark/agent_validation/__main__.py @@ -29,6 +29,13 @@ def _parser() -> argparse.ArgumentParser: help="Verify a pinned human-eval-bia checkout without executing it.", ) verify.add_argument("checkout", type=Path) + one = subparsers.add_parser( + "build-task", + help="Write one blind task that `check` can read the result of.", + ) + one.add_argument("task_root", type=Path) + one.add_argument("--pick", type=int, required=True, + help="which of those tasks, counted around in declaration order") check = subparsers.add_parser( "check", help="Check the plate an OpenHCS run wrote beside one task's inputs against " @@ -52,6 +59,9 @@ def main(argv: list[str] | None = None) -> int: probe_ids = AgentValidationCorpus.build_diagnostic_bundle(args.output_root) print(f"Wrote {len(probe_ids)} diagnostic probes to {args.output_root}") return 0 + if args.command == "build-task": + print(AgentValidationCorpus.build_task(args.task_root, args.pick).task_id) + return 0 if args.command == "check": assertions = AgentValidationCorpus.check_output_plate(args.task_root) for assertion in assertions: diff --git a/benchmark/agent_validation/contracts.py b/benchmark/agent_validation/contracts.py index a04a806ff..4ab94eacf 100644 --- a/benchmark/agent_validation/contracts.py +++ b/benchmark/agent_validation/contracts.py @@ -36,6 +36,11 @@ class OutputKind(Enum): SCALAR = "scalar" TABLE = "table" + @property + def written_as_planes(self) -> bool: + """Whether a run's result of this kind is image planes in its output plate.""" + return self in (OutputKind.ARRAY, OutputKind.LABEL_IMAGE) + class FunctionAvailabilityExpectation(Enum): """Expected catalogue decision before a pipeline is authored.""" diff --git a/benchmark/agent_validation/corpus.py b/benchmark/agent_validation/corpus.py index 390cf392f..a93bb6aa5 100644 --- a/benchmark/agent_validation/corpus.py +++ b/benchmark/agent_validation/corpus.py @@ -73,19 +73,35 @@ def build_authoring_bundle(cls, output_root: Path) -> tuple[TaskAuthoringSpec, . output_root.mkdir(parents=True, exist_ok=False) specs = [] for declaration in cls.task_declarations(): - task_root = output_root / declaration.task_id - input_root = task_root / "inputs" - input_root.mkdir(parents=True) - case_rows = cls._write_inputs(declaration, input_root) - spec = declaration.authoring_spec(Path("inputs")) - specs.append(spec) - _write_json(task_root / "task.json", TaskBundleRecord(spec, case_rows)) + specs.append(cls._write_task(declaration, output_root / declaration.task_id)) _write_json( output_root / "corpus.json", CorpusBundleRecord(tuple(spec.task_id for spec in specs)), ) return tuple(specs) + @classmethod + def build_task(cls, task_root: Path, pick: int) -> TaskAuthoringSpec: + """Write one blind task whose result `check_output_plate` reads: of those, in + declaration order, the one `pick` lands on.""" + + checked = tuple(declaration for declaration in cls.task_declarations() + if declaration.output_kind.written_as_planes) + return cls._write_task(checked[pick % len(checked)], task_root) + + @classmethod + def _write_task( + cls, declaration: type[ValidationTaskDeclaration], task_root: Path, + ) -> TaskAuthoringSpec: + """One task's answer-free prompt, provenance and source images.""" + + input_root = task_root / "inputs" + input_root.mkdir(parents=True) + spec = declaration.authoring_spec(Path("inputs")) + _write_json(task_root / "task.json", + TaskBundleRecord(spec, cls._write_inputs(declaration, input_root))) + return spec + @classmethod def build_diagnostic_bundle(cls, output_root: Path) -> tuple[str, ...]: """Write opaque flawed candidates without revealing their failure class.""" diff --git a/tests/unit/benchmark/test_agent_validation_corpus.py b/tests/unit/benchmark/test_agent_validation_corpus.py index f7884d36e..1674287d7 100644 --- a/tests/unit/benchmark/test_agent_validation_corpus.py +++ b/tests/unit/benchmark/test_agent_validation_corpus.py @@ -343,8 +343,13 @@ def test_a_task_is_checked_from_the_plate_a_run_wrote_beside_its_inputs(tmp_path from openhcs.core.source.source_projection import OpenHCSPlaneAddress - AgentValidationCorpus.build_authoring_bundle(tmp_path / "bundle") - task_root = tmp_path / "bundle" / "human_eval_bia.binary_closing" + # One task is built alone, and only a task whose result is planes is ever picked. + picked = {AgentValidationCorpus.build_task(tmp_path / str(pick), pick).task_id + for pick in range(8)} + assert picked == {declaration.task_id for declaration in AgentValidationCorpus.task_declarations() + if declaration.output_kind.written_as_planes} + task_root = next(tmp_path / str(pick) for pick in range(8) + if "binary_closing" in (tmp_path / str(pick) / "task.json").read_text()) (case,) = ValidationTaskDeclaration.get("human_eval_bia.binary_closing").scoring_cases() # Nothing has run: there is no plate to read, and the check says so rather than fail a case. From 01e56e0da4280e8cdc21e16ad12a0a9cf130e204 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:40:43 +0000 Subject: [PATCH 26/27] The agent benchmark builds a task by its id and has its own command A runner that owns one task and how it is done names the task; a position in declaration order was a second copy of that order. build-task takes the id and refuses one whose result is not checked as a plate, naming those that are. openhcs-agent-validation is the benchmark's command on PATH. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- benchmark/agent_validation/__main__.py | 5 ++--- benchmark/agent_validation/corpus.py | 17 ++++++++++------- pyproject.toml | 1 + .../benchmark/test_agent_validation_corpus.py | 14 +++++++------- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/benchmark/agent_validation/__main__.py b/benchmark/agent_validation/__main__.py index cd892db5e..6260daa21 100644 --- a/benchmark/agent_validation/__main__.py +++ b/benchmark/agent_validation/__main__.py @@ -34,8 +34,7 @@ def _parser() -> argparse.ArgumentParser: help="Write one blind task that `check` can read the result of.", ) one.add_argument("task_root", type=Path) - one.add_argument("--pick", type=int, required=True, - help="which of those tasks, counted around in declaration order") + one.add_argument("task_id", help="the task's id, as `list` prints it") check = subparsers.add_parser( "check", help="Check the plate an OpenHCS run wrote beside one task's inputs against " @@ -60,7 +59,7 @@ def main(argv: list[str] | None = None) -> int: print(f"Wrote {len(probe_ids)} diagnostic probes to {args.output_root}") return 0 if args.command == "build-task": - print(AgentValidationCorpus.build_task(args.task_root, args.pick).task_id) + print(AgentValidationCorpus.build_task(args.task_root, args.task_id).task_id) return 0 if args.command == "check": assertions = AgentValidationCorpus.check_output_plate(args.task_root) diff --git a/benchmark/agent_validation/corpus.py b/benchmark/agent_validation/corpus.py index a93bb6aa5..73ab103da 100644 --- a/benchmark/agent_validation/corpus.py +++ b/benchmark/agent_validation/corpus.py @@ -81,13 +81,16 @@ def build_authoring_bundle(cls, output_root: Path) -> tuple[TaskAuthoringSpec, . return tuple(specs) @classmethod - def build_task(cls, task_root: Path, pick: int) -> TaskAuthoringSpec: - """Write one blind task whose result `check_output_plate` reads: of those, in - declaration order, the one `pick` lands on.""" - - checked = tuple(declaration for declaration in cls.task_declarations() - if declaration.output_kind.written_as_planes) - return cls._write_task(checked[pick % len(checked)], task_root) + def build_task(cls, task_root: Path, task_id: str) -> TaskAuthoringSpec: + """Write the blind task named `task_id`, one whose result `check_output_plate` + reads.""" + + checked = {declaration.task_id: declaration for declaration in cls.task_declarations() + if declaration.output_kind.written_as_planes} + if task_id not in checked: + raise ValueError(f"{task_id} is not a task whose result is checked as a plate: " + f"{', '.join(checked)}") + return cls._write_task(checked[task_id], task_root) @classmethod def _write_task( diff --git a/pyproject.toml b/pyproject.toml index 08584487f..19ab8b5f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -311,6 +311,7 @@ openhcs-mcp-http = "openhcs.mcp.http:main" openhcs-mcp-dev = "openhcs.mcp.dev_client:main" openhcs-mcp-demo = "openhcs.mcp.installed_demo:main" openhcs-benchmark = "benchmark.cellprofiler_benchmark_cli:main" +openhcs-agent-validation = "benchmark.agent_validation.__main__:main" [project.gui-scripts] openhcs-gui = "openhcs.pyqt_gui.__main__:main" diff --git a/tests/unit/benchmark/test_agent_validation_corpus.py b/tests/unit/benchmark/test_agent_validation_corpus.py index 1674287d7..674928813 100644 --- a/tests/unit/benchmark/test_agent_validation_corpus.py +++ b/tests/unit/benchmark/test_agent_validation_corpus.py @@ -343,13 +343,13 @@ def test_a_task_is_checked_from_the_plate_a_run_wrote_beside_its_inputs(tmp_path from openhcs.core.source.source_projection import OpenHCSPlaneAddress - # One task is built alone, and only a task whose result is planes is ever picked. - picked = {AgentValidationCorpus.build_task(tmp_path / str(pick), pick).task_id - for pick in range(8)} - assert picked == {declaration.task_id for declaration in AgentValidationCorpus.task_declarations() - if declaration.output_kind.written_as_planes} - task_root = next(tmp_path / str(pick) for pick in range(8) - if "binary_closing" in (tmp_path / str(pick) / "task.json").read_text()) + # One task is built alone, by its id, and only one whose result is planes. + with pytest.raises(ValueError, match="not a task whose result is checked as a plate"): + AgentValidationCorpus.build_task(tmp_path / "scalar", + "human_eval_bia.otsu_positive_pixel_count") + task_root = tmp_path / "closing" + assert AgentValidationCorpus.build_task( + task_root, "human_eval_bia.binary_closing").task_id == "human_eval_bia.binary_closing" (case,) = ValidationTaskDeclaration.get("human_eval_bia.binary_closing").scoring_cases() # Nothing has run: there is no plate to read, and the check says so rather than fail a case. From 695fcfc270c94c369c9e674567e1dd391dcb94d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:21:06 +0000 Subject: [PATCH 27/27] The projection task's planes are images, and its answer is one plane stack_axis wrote each plane as a bare row (6,), so six planes assembled to a (6,6) array, and OpenHCS refuses an image payload with no leading plane axis (runtime_image_values.py: _leading_plane_count). A plane is written at least 2-D, and the task's answer is the one plane the projection leaves, (1, 6). The registry's own max_projection now passes the benchmark's check on the declared source. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- benchmark/agent_validation/corpus.py | 2 +- benchmark/agent_validation/tasks.py | 2 +- tests/unit/benchmark/test_agent_validation_corpus.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/benchmark/agent_validation/corpus.py b/benchmark/agent_validation/corpus.py index 73ab103da..606698930 100644 --- a/benchmark/agent_validation/corpus.py +++ b/benchmark/agent_validation/corpus.py @@ -292,7 +292,7 @@ def _write_inputs( f"z{z_index:03d}_t001.tif" ) path = input_root / filename - tifffile.imwrite(path, np.asarray(plane)) + tifffile.imwrite(path, np.atleast_2d(plane)) files.append( InputFileRecord( input_name=input_value.name, diff --git a/benchmark/agent_validation/tasks.py b/benchmark/agent_validation/tasks.py index 5ed5adc7d..e4d21aad2 100644 --- a/benchmark/agent_validation/tasks.py +++ b/benchmark/agent_validation/tasks.py @@ -407,7 +407,7 @@ def scoring_cases(cls) -> tuple[ScoringCase, ...]: ScoringCase( "case-1", (TaskInput("image", image, stack_axis=0),), - np.asarray([0, 4, 0, 0, 3, 0]), + np.asarray([[0, 4, 0, 0, 3, 0]]), ), ) diff --git a/tests/unit/benchmark/test_agent_validation_corpus.py b/tests/unit/benchmark/test_agent_validation_corpus.py index 674928813..02503287b 100644 --- a/tests/unit/benchmark/test_agent_validation_corpus.py +++ b/tests/unit/benchmark/test_agent_validation_corpus.py @@ -325,7 +325,7 @@ def _reference_result(task_id: str, case) -> object: inputs["label_image"], distance=parameters["radius"] ) if task_id.endswith("maximum_intensity_projection"): - return inputs["image"].max(axis=0) + return inputs["image"].max(axis=0, keepdims=True) if task_id.endswith("measure_properties_of_regions"): return pd.DataFrame( measure.regionprops_table(