From e3af24189f9df3277d57ec3976322df84350d892 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 29 Sep 2026 15:42:46 -0400 Subject: [PATCH 1/9] Expose same-run primary segmentation diagnostic artifacts (#214) --- ...ntation_diagnostics_checkpoint_20260929.md | 112 +++++++++ .../primary_object_diagnostics.py | 191 +++++++++++++++ .../backends/cellprofiler/primary_objects.py | 74 +++++- ...rimary_segmentation_diagnostics_journey.py | 176 ++++++++++++++ ...t_cellprofiler_adaptive_guide_threshold.py | 4 +- .../unit/test_cellprofiler_library_loading.py | 4 +- ...iler_primary_object_performance_kernels.py | 2 +- tests/unit/test_primary_object_diagnostics.py | 227 ++++++++++++++++++ 8 files changed, 776 insertions(+), 14 deletions(-) create mode 100644 docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md create mode 100644 openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py create mode 100644 tests/integration/test_primary_segmentation_diagnostics_journey.py create mode 100644 tests/unit/test_primary_object_diagnostics.py diff --git a/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md b/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md new file mode 100644 index 0000000000..072d74a6f1 --- /dev/null +++ b/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md @@ -0,0 +1,112 @@ +# Primary-segmentation diagnostics (#214) + +Implementation owner: Singer. Base audited: `a0263e82a1b3296f34f8c5cdd50ffae5c33ef7dd`. +Worktree: `/home/ts/wt/openhcs-primary-segmentation-diagnostics-20260929`. +Issue: https://github.com/OpenHCSDev/openhcs/issues/214. + +## Contract and ownership + +The final mask alone cannot locate a loss in threshold support, peak suppression, +watershed or filtering. IPO now captures the actual threshold support before +hole filling and connected components before declumping. It returns exact +maxima-response, maxima and marker arrays from the existing execution, followed +by image projections of the canonical unedited/small-removed label variants. +There is no second segmentation, fixture-capture dependency or biological verdict. + +`PrimaryObjectDiagnosticPlanes` owns stage names, order and slot types. The +module's existing cooperative `finalize_artifact_contract_outputs` hook appends +image `QA_CHECKPOINT` sidecars with source-stack and exact object-output relations. +Their names are `__qa_checkpoint__`. Source address, group/plane +coordinates and compiled producer remain owned by the existing artifact path. +The first three ordinary return values are preserved, including ordinary +ArrayBridge main-output dtype handling; seven typed image values follow them. +Direct tuple-unpacking tests are migrated, not supported by an old-return alias. + +These are not new object sets, do not alter measurement subjects, do not enter +main flow and use `ON_DEMAND` viewer streaming. Normal runtime artifact persistence +still applies by default. Declumping-disabled and no-foreground executions have +wholly invalid response/seed masks and NaN response pixels: absent evidence is +not represented as a measured zero. Pipeline settings and threshold support +distinguish disabled from empty execution. Diagnostic intensity metadata describes +the stage's pixels, not the acquisition's uint16 scale. + +Evidence is bounded to seven planes per IPO plane. Only threshold support and +initial components are snapshotted to protect their pre-transform stage identity. +Executed response/seed arrays and payload variant arrays are referenced, not +rerun or cloned. Source validity is decoded once and shared across stages; +unexecuted stages share one invalid mask. No input or private benchmark was read. + +## Actual focused checks + +Seven lightweight tests passed in 1.74 seconds, using the prescribed project +Python 3.12 environment, this worktree and all eight recorded submodule source +directories on `PYTHONPATH`, with `OPENHCS_CPU_ONLY=true`, thread limits of one, +`PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` and: + +``` +python -B -m pytest -q --confcutdir=tests/unit tests/unit/test_primary_object_diagnostics.py +``` + +Two unrelated pytest async-config warnings remain because plugins are disabled. +Verified import paths are under this worktree and its recorded submodules. +The first test iterations exposed incorrect fixture assumptions about source +spatial-domain construction and the payload's count owner; those fixtures now +use `SourceSpatialDomain` and `objects.domain.declared_object_count` directly. + +This is a focused source/AST audit, not a complete NRA scan: + +- IMPL-1/2/3/7: actual new diagnostic source has no string/type/kind dispatcher; + executed and unexecuted evidence own their behavior under an ABC. +- MEMB-1/3: artifact projection reads the typed record's `_fields`; no parallel + stage roster or handler registry. ABI slot types derive from the same annotations. +- BOUND-1/2/7: no string-key raw record reads, duck-typed fallback access or bypass + of `ObjectLabelPayload` variant ownership in the new source. One source decode + precedes all stage projections. +- IDEN-5/6: exact input-source and object-output relations are exercised; projections + retain coordinates and share the authoritative arrays rather than reconstructing + filtering evidence or inventing a competing object identity. +- Actual AST comparison against the pinned baseline confirms the segmentation + body is unchanged except evidence captures and the augmented return. +- The real image-output contextualizer preserves absent-stage masks and numeric + pixels, provenance and stage intensity semantics. +- New-case experiment: one added nominal record field is picked up by the actual + artifact projection without a catalog/dispatcher edit. A real new computed + stage requires its field plus its same-execution producer argument (two sites); + output names, slot annotation and consumers derive without extra maintenance. + +## Remaining acceptance and scheduling + +The new worktree cannot yet import IPO because main's newly required native +`_granularity_reconstruct` extension is not built here. No native build, algorithm, +MCP, JVM or GUI has been started. Build the extension only in this worktree +(`python setup.py build_ext --inplace --parallel 1`) after explicit slot handoff. +Do not install or change the running baseline. + +`tests/integration/test_primary_segmentation_diagnostics_journey.py` is prepared +but NOT run. It covers real registered IPO on a small synthetic close-pair/faint +field (empty, disabled, intensity and shape declumping), then source-document +roundtrip, normal compiled execution, secondary binding and persisted review +through the existing runtime/filemanager. Native parity, these real journeys, +fresh MCP discovery, persisted MCP result review and isolated-display same-coordinate +raw/intermediate/final viewer inspection remain required. Passing metadata tests +does not prove them or biological QA. + +Parent takes the first released slot for #151/#212. Wait for the parent's explicit +handoff, then acquire `/home/ts/wt/openhcs-issue-batch-20260929/validation.lock` +nonblocking, run the resource guard and retain at least 8 GiB RAM. Use a single +worker and owned disposable test output under +`/home/ts/.cache/agent-scratch/openhcs-primary-diagnostics-20260929`, retain receipts, +then clean disposable output. Do not poll the lock or start a GUI without display +allocation. + +Core artifact/runtime/adapter files owned by Zeno are unchanged. This bus has no +verified Zeno route, and the parent cannot relay; obtain a direct route before any +shared-file changes or manual adapter-fixture migration. One existing hand-written +IPO executor fixture still declares only the previous two artifact slots; it must +derive the new diagnostics before its native suite is run. Normal compiled contracts +already use the module hook. + +Independent draft PR #207 / issue #138 remains at its published polymorphism +checkpoint, with 51 provider-free tests and prior existing-environment lifecycle +evidence. Its authorized bounded fresh bootstrap creation/native validation is +still pending the explicit serialized slot. It is not abandoned or closed. diff --git a/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py b/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py new file mode 100644 index 0000000000..e77942419e --- /dev/null +++ b/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py @@ -0,0 +1,191 @@ +"""Source-aligned evidence from one IdentifyPrimaryObjects execution. + +These are review images, not new object sets. In particular the filtering +planes project the existing ObjectLabelPayload variants without changing their +identity domain or reconstructing rejected objects. +""" + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import NamedTuple, Tuple, get_type_hints + +import numpy as np + +from openhcs.core.artifacts import ( + ArtifactSidecarRole, + ArtifactSidecarSourceRelation, + ArtifactSpec, + ArtifactViewerStreaming, + ImageArtifactType, + SourceStackLineageSourceRelation, +) +from openhcs.core.measurement_row_materialization import DataclassMeasurementColumnarRows +from openhcs.core.runtime_image_values import ( + ImagePayloadMetadata, + MaskedImagePayload, + image_payload_data, + image_payload_mask, + image_payload_metadata, +) +from openhcs.core.runtime_object_labels import ObjectLabelPayload, ObjectLabelVariant + + +@dataclass(frozen=True, slots=True) +class DiagnosticPlaneSource: + """Decode source identity and validity once, sharing one mask across stages.""" + + metadata: ImagePayloadMetadata + validity_mask: np.ndarray + + @classmethod + def from_image(cls, image: object) -> "DiagnosticPlaneSource": + source_mask = image_payload_mask(image) + return cls( + image_payload_metadata(image), + np.ones(np.asarray(image_payload_data(image)).shape, dtype=bool) + if source_mask is None else np.asarray(source_mask, dtype=bool), + ) + + def plane( + self, pixels: np.ndarray, *, validity_mask: np.ndarray | None = None + ) -> MaskedImagePayload: + """Attach source coordinates, but keep the stage's intensity semantics.""" + + return MaskedImagePayload( + data=pixels, + mask=self.validity_mask if validity_mask is None else validity_mask, + # Do not interpret a normalized response using its acquisition's + # uint16 scale. Source address/coordinates remain untouched. + metadata=self.metadata.replace_fields( + intensity_scale=None, + source_dtype=str(pixels.dtype), + unit_interval_intensity=None, + source_plane_intensity_scales=(), + source_plane_dtypes=(), + ), + ) + + +class DeclumpingEvidence(ABC): + """Declumping owns whether its intermediate pixels were actually produced.""" + + @abstractmethod + def planes( + self, source: DiagnosticPlaneSource + ) -> tuple[MaskedImagePayload, MaskedImagePayload, MaskedImagePayload]: + """Return response, maxima and labeled seeds in source coordinates.""" + + +@dataclass(frozen=True, slots=True) +class ExecutedDeclumpingEvidence(DeclumpingEvidence): + """The exact response and seeds used by this execution's watershed.""" + + response: np.ndarray + maxima: np.ndarray + markers: np.ndarray + + def planes( + self, source: DiagnosticPlaneSource + ) -> tuple[MaskedImagePayload, MaskedImagePayload, MaskedImagePayload]: + return ( + source.plane(self.response), + source.plane(self.maxima), + source.plane(self.markers), + ) + + +class UnexecutedDeclumpingEvidence(DeclumpingEvidence): + """Disabled declumping or no foreground: no response/seed evidence exists. + + A wholly invalid plane means NOT EXECUTED, not a measured zero response. + NaN response pixels make that distinction survive ordinary image export + even where a reader does not expose the validity mask. + """ + + def planes( + self, source: DiagnosticPlaneSource + ) -> tuple[MaskedImagePayload, MaskedImagePayload, MaskedImagePayload]: + shape = source.validity_mask.shape + invalid = np.zeros(shape, dtype=bool) + return ( + source.plane(np.full(shape, np.nan), validity_mask=invalid), + source.plane(np.zeros(shape, dtype=bool), validity_mask=invalid), + source.plane(np.zeros(shape, dtype=np.int32), validity_mask=invalid), + ) + + +class PrimaryObjectDiagnosticPlanes(NamedTuple): + """Fixed, bounded stage planes, in acquisition pixel coordinates. + + Field declarations own artifact names, order and return-slot types. + Threshold support is captured BEFORE hole filling. Initial components are + captured AFTER pre-declump filling. Unedited and small-removed are the + canonical payload variants after final identity remapping, not extra seeds. + """ + + threshold_support: MaskedImagePayload + initial_components: MaskedImagePayload + declump_response: MaskedImagePayload + seed_maxima: MaskedImagePayload + seed_markers: MaskedImagePayload + unedited_objects: MaskedImagePayload + small_removed_objects: MaskedImagePayload + + @classmethod + def from_execution( + cls, + *, + image: object, + threshold_support: np.ndarray, + initial_components: np.ndarray, + declumping: DeclumpingEvidence, + objects: ObjectLabelPayload, + ) -> "PrimaryObjectDiagnosticPlanes": + source = DiagnosticPlaneSource.from_image(image) + response, maxima, markers = declumping.planes(source) + return cls( + source.plane(threshold_support), + source.plane(initial_components), + response, + maxima, + markers, + source.plane( + objects.variant_data.labels_for_variant(ObjectLabelVariant.UNEDITED), + ), + source.plane( + objects.variant_data.labels_for_variant(ObjectLabelVariant.SMALL_REMOVED), + ), + ) + + @classmethod + def artifact_specs( + cls, *, source_image: ArtifactSpec, objects: ArtifactSpec + ) -> tuple[ArtifactSpec, ...]: + """Project stage declarations into the ordinary image-sidecar contract.""" + + prefix = ArtifactSidecarRole.QA_CHECKPOINT.name_for(objects.name) + return tuple( + ArtifactSpec.output( + f"{prefix}__{stage}", + ImageArtifactType, + sidecar_role=ArtifactSidecarRole.QA_CHECKPOINT, + viewer_streaming=ArtifactViewerStreaming.ON_DEMAND, + relations=( + SourceStackLineageSourceRelation(source=source_image.ref()), + ArtifactSidecarSourceRelation(source=objects.ref()), + ), + ) + for stage in cls._fields + ) + + +# The callable ABI is a projection of the same typed plane declaration, not a +# second hand-written stage roster. The first three ordinary slots stay intact. +PrimaryObjectsRuntimeTuple = Tuple[ + ( + np.ndarray, + DataclassMeasurementColumnarRows, + ObjectLabelPayload, + *get_type_hints(PrimaryObjectDiagnosticPlanes).values(), + ) +] diff --git a/openhcs/processing/backends/cellprofiler/primary_objects.py b/openhcs/processing/backends/cellprofiler/primary_objects.py index 4196aa2c8d..673e58a75e 100644 --- a/openhcs/processing/backends/cellprofiler/primary_objects.py +++ b/openhcs/processing/backends/cellprofiler/primary_objects.py @@ -3,12 +3,9 @@ import logging import numpy as np import time -from typing import TYPE_CHECKING, Tuple +from typing import TYPE_CHECKING from enum import Enum from openhcs.core.memory import numpy -from openhcs.core.measurement_row_materialization import ( - DataclassMeasurementColumnarRows, -) from openhcs.core.public_api import public_names_from_objects from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, @@ -16,7 +13,6 @@ image_payload_mask, image_payload_metadata, ) -from openhcs.core.runtime_object_labels import ObjectLabelPayload from openhcs.core.runtime_object_label_building import ( SourceImageObjectLabelBuildRequest, ) @@ -61,6 +57,12 @@ unit_interval_scale_for_threshold_selection, ) from openhcs.processing.backends.cellprofiler.perf_fixtures import capture_array_fixture +from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import ( + ExecutedDeclumpingEvidence, + PrimaryObjectDiagnosticPlanes, + PrimaryObjectsRuntimeTuple, + UnexecutedDeclumpingEvidence, +) from openhcs.processing.backends.cellprofiler.watershed import ( cellprofiler_legacy_watershed, ) @@ -85,7 +87,11 @@ from openhcs.processing.backends.cellprofiler.enum_attributes import ( CellProfilerEnumAttributeMixin, ) -from openhcs.core.artifacts import ImageArtifactType, ObjectLabelsArtifactType +from openhcs.core.artifacts import ( + ArtifactSpecCollection, + ImageArtifactType, + ObjectLabelsArtifactType, +) if TYPE_CHECKING: from openhcs.interop.cellprofiler.parser import ModuleBlock @@ -150,7 +156,7 @@ def identify_primary_objects( morphology_backend_provider: BackendProviderInput = DEFAULT_CELLPROFILER_BACKEND_SELECTION, watershed_backend_provider: BackendProviderInput = DEFAULT_CELLPROFILER_BACKEND_SELECTION, respect_source_border_metadata: bool = False, -) -> Tuple[np.ndarray, DataclassMeasurementColumnarRows, ObjectLabelPayload]: +) -> PrimaryObjectsRuntimeTuple: """ Segment primary objects, such as fluorescent nuclei, in a grayscale image. @@ -212,7 +218,12 @@ def identify_primary_objects( current image plane border. Returns: - Tuple of (original image, object statistics, labeled image)""" + Original image, threshold measurements and object-label payload followed + by the seven source-aligned PrimaryObjectDiagnosticPlanes fields. These + QA checkpoint sidecars do not change main flow or object identity. An + entirely invalid declump response/seed plane means that stage did not + execute (disabled declumping or no foreground), not a measured zero. + """ from openhcs.processing.backends.cellprofiler.morphology import ( MorphologyBackendStrategy, ) @@ -277,6 +288,8 @@ def identify_primary_objects( proven_unit_interval_scale=proven_unit_interval_scale, ).calculate() binary = threshold.mask + threshold_support = binary.copy() + declumping = UnexecutedDeclumpingEvidence() capture_array_fixture( "ipo_threshold", image=img, @@ -314,6 +327,7 @@ def identify_primary_objects( labeled_image, object_count = morphology.connected_components( binary, connectivity=2 ) + initial_components = labeled_image.copy() declump_backend_method = CellProfilerDeclumpMethod.SHAPE runtime_profiler.log( "ipo_initial_label", @@ -414,6 +428,7 @@ def identify_primary_objects( ) phase_started_at = time.perf_counter() markers, object_count = morphology.connected_components(maxima, connectivity=2) + declumping = ExecutedDeclumpingEvidence(maxima_image, maxima, markers) runtime_profiler.log( "ipo_declump_marker_label", time.perf_counter() - phase_started_at, @@ -546,7 +561,14 @@ def identify_primary_objects( time.perf_counter() - profile_total_started_at, function="identify_primary_objects", ) - return (image, threshold_measurements, label_payload) + diagnostics = PrimaryObjectDiagnosticPlanes.from_execution( + image=image, + threshold_support=threshold_support, + initial_components=initial_components, + declumping=declumping, + objects=label_payload, + ) + return (image, threshold_measurements, label_payload, *diagnostics) def _remap_object_label_variant_after_final_relabel( @@ -601,6 +623,40 @@ class IdentifyPrimaryObjectsModule( validated = True confidence = 1.0 + @classmethod + def finalize_artifact_contract_outputs( + cls, + module, + *, + invocation_key, + step_context, + artifact_inputs: ArtifactSpecCollection, + artifact_outputs: ArtifactSpecCollection, + ): + """Declare same-run QA planes without new object or main-flow outputs.""" + + outputs = super().finalize_artifact_contract_outputs( + module, + invocation_key=invocation_key, + step_context=step_context, + artifact_inputs=artifact_inputs, + artifact_outputs=artifact_outputs, + ) + source = cls.primary_image_inputs( + cls.require_callable(invocation_key.function_name), artifact_inputs.specs + ) + if len(source) != 1: + raise ValueError("IdentifyPrimaryObjects diagnostics require one source image.") + objects = ArtifactSpecCollection(outputs).of_artifact_type(ObjectLabelsArtifactType) + if len(objects) != 1: + raise ValueError("IdentifyPrimaryObjects diagnostics require one object output.") + return ( + *outputs, + *PrimaryObjectDiagnosticPlanes.artifact_specs( + source_image=source[0], objects=objects[0] + ), + ) + include_threshold_advanced_setting = True input_image_setting = SettingNameFamily( "Select the input image", diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py new file mode 100644 index 0000000000..bbe26ca5f0 --- /dev/null +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -0,0 +1,176 @@ +"""Real IPO/secondary authoring -> compile -> execute -> persisted artifacts. + +Run only in the coordinator's serialized native-validation slot. There is no +private plate, segmentation replacement, mocked runtime or biological verdict. +""" + +import numpy as np +import pytest + + +def _field(empty=False): + yy, xx = np.mgrid[:32, :40] + image = ( + 0.8 * np.exp(-((yy - 14) ** 2 + (xx - 14) ** 2) / 14) + + 0.7 * np.exp(-((yy - 14) ** 2 + (xx - 20) ** 2) / 14) + + 0.25 * np.exp(-((yy - 24) ** 2 + (xx - 30) ** 2) / 8) + ).astype(np.float32) + return np.zeros_like(image) if empty else image + + +@pytest.mark.parametrize("mode", ["empty", "disabled", "intensity", "shape"]) +def test_real_registered_ipo_returns_same_run_stage_pixels(mode): + from openhcs.core.config import DtypeConfig + from openhcs.core.runtime_image_values import image_payload_data + from openhcs.interop.cellprofiler.module_declarations import CellProfilerModule + from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import PrimaryObjectDiagnosticPlanes + from openhcs.processing.backends.cellprofiler.primary_objects import UnclumpMethod, WatershedMethod + from openhcs.processing.backends.cellprofiler.morphology import FillHolesOption + from openhcs.processing.backends.cellprofiler.thresholding import CellProfilerThresholdMethod + + image = _field(mode == "empty") + method = UnclumpMethod.NONE if mode == "disabled" else ( + UnclumpMethod.SHAPE if mode == "shape" else UnclumpMethod.INTENSITY + ) + func = CellProfilerModule.require_module("IdentifyPrimaryObjects").require_callable() + original, measurements, objects, *planes = func( + image, min_diameter=2, max_diameter=20, + exclude_size=False, exclude_border_objects=False, + unclump_method=method, watershed_method=WatershedMethod.INTENSITY, + threshold_method=CellProfilerThresholdMethod.MANUAL, manual_threshold=0.2, + threshold_smoothing_scale=0.0, fill_holes=FillHolesOption.NEVER, + automatic_smoothing=False, smoothing_filter_size=1, + automatic_suppression=False, maxima_suppression_size=2, + low_res_maxima=False, dtype_config=DtypeConfig(), + ) + diagnostics = PrimaryObjectDiagnosticPlanes(*planes) + np.testing.assert_array_equal(image_payload_data(original), image) + np.testing.assert_array_equal(diagnostics.threshold_support.data, image > 0.2) + np.testing.assert_array_equal(diagnostics.unedited_objects.data, objects.unedited_labels) + np.testing.assert_array_equal(diagnostics.small_removed_objects.data, objects.small_removed_labels) + assert measurements.row_count > 0 + if mode in ("empty", "disabled"): + assert not diagnostics.declump_response.mask.any() + assert np.isnan(diagnostics.declump_response.data).all() + assert not diagnostics.seed_markers.data.any() + else: + assert diagnostics.declump_response.mask.all() + assert diagnostics.seed_markers.data.max() > 0 + np.testing.assert_array_equal(diagnostics.seed_markers.data > 0, diagnostics.seed_maxima.data) + if mode == "empty": + assert not objects.labels.any() + + +def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_binding(tmp_path): + import tifffile + from openhcs.agent.services.execution_session_service import ( + AgentProgressQueue, CompileInspectionInput, InProcessCompileInspectionGateway, + ) + from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents + from openhcs.constants.input_source import InputSource + from openhcs.core.artifacts import ArtifactInputPlan, ArtifactOutputPlan, ImageArtifactType, ObjectLabelsArtifactType + from openhcs.core.config import GlobalPipelineConfig, LazyProcessingConfig, LazySourceBindingsConfig, PipelineConfig + from openhcs.core.orchestrator.execution_result import RuntimeObservationMode + from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator + from openhcs.core.pipeline_document import PipelineDocumentAuthority + from openhcs.core.runtime_image_values import image_payload_data, image_payload_metadata + from openhcs.core.runtime_object_labels import object_label_dense_array + from openhcs.core.source_bindings import ( + ComponentSelector, NamedSourceBinding, SourceFilterClause, SourceFilterMatchType, + SourceFilterSubject, SourceSelector, StepSourceBindingsConfig, + ) + from openhcs.core.steps.function_step import FunctionStep + from openhcs.processing.backends.cellprofiler.primary_objects import ( + IdentifyPrimaryObjectsModule, UnclumpMethod, WatershedMethod, identify_primary_objects, + ) + from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import PrimaryObjectDiagnosticPlanes + from openhcs.processing.backends.cellprofiler.secondary import ( + IdentifySecondaryObjectsModule, SecondaryMethod, identify_secondary_objects, + ) + from openhcs.processing.backends.cellprofiler.thresholding import CellProfilerThresholdMethod + + def binding(module, plan_type, artifact_type): + (declared,) = module.declared_artifact_bindings(plan_type=plan_type, artifact_type=artifact_type) + return declared.require_parameter_name() + + def step(func, name, kwargs): + return FunctionStep( + func=(func, kwargs), name=name, + processing_config=LazyProcessingConfig( + variable_components=[VariableComponents.SITE], group_by=GroupBy.NONE, + input_source=InputSource.PIPELINE_START, + ), + source_bindings=StepSourceBindingsConfig(enabled=True), + ) + + image = _field() + tifffile.imwrite(tmp_path / "A01_s001_DNA.tif", image) + primary = step(identify_primary_objects, "Primary", { + binding(IdentifyPrimaryObjectsModule, ArtifactInputPlan, ImageArtifactType): "DNA", + binding(IdentifyPrimaryObjectsModule, ArtifactOutputPlan, ObjectLabelsArtifactType): "Nuclei", + "exclude_size": False, "exclude_border_objects": False, + "min_diameter": 2, "max_diameter": 20, + "unclump_method": UnclumpMethod.INTENSITY, + "watershed_method": WatershedMethod.INTENSITY, + "threshold_method": CellProfilerThresholdMethod.MANUAL, + "manual_threshold": 0.2, "threshold_smoothing_scale": 0.0, + }) + secondary = step(identify_secondary_objects, "Secondary", { + binding(IdentifySecondaryObjectsModule, ArtifactInputPlan, ImageArtifactType): "DNA", + binding(IdentifySecondaryObjectsModule, ArtifactInputPlan, ObjectLabelsArtifactType): "Nuclei", + IdentifySecondaryObjectsModule.secondary_output_binding.require_parameter_name(): "Cells", + "method": SecondaryMethod.DISTANCE_N, "distance_to_dilate": 2, + }) + document = PipelineDocumentAuthority.from_values( + pipeline_config=PipelineConfig( + microscope=Microscope.SOURCE_BINDINGS, + source_bindings_config=LazySourceBindingsConfig(bindings=(NamedSourceBinding( + alias="DNA", selector=SourceSelector(filters=(SourceFilterClause( + subject=SourceFilterSubject.FILE, match_type=SourceFilterMatchType.CONTAINS, + value="DNA", + ),)), component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + ),)), + ), pipeline_steps=[primary, secondary], + ) + document = PipelineDocumentAuthority.from_source(PipelineDocumentAuthority.render(document)) + bundle = InProcessCompileInspectionGateway().compile(CompileInspectionInput( + plate=tmp_path, pipeline_document=document, axis_filter=("A01",), + global_pipeline_config=GlobalPipelineConfig(num_workers=1, use_threading=True), + progress_queue=AgentProgressQueue(), + )).execution_bundle + context = bundle.runtime_contexts["A01"] + primary_invocation = next(context.step_plans[0].compiled_function_pattern.iter_invocations()) + secondary_invocation = next(context.step_plans[1].compiled_function_pattern.iter_invocations()) + (edge,) = (edge for edge in secondary_invocation.artifact_input_edges + if edge.spec.artifact_type is ObjectLabelsArtifactType) + assert edge.spec.name == "Nuclei" + assert edge.storage_plan.source_step_id == 0 + assert len(primary_invocation.contract.artifact_outputs.of_artifact_type(ObjectLabelsArtifactType)) == 1 + + orchestrator = PipelineOrchestrator(tmp_path, pipeline_config=document.pipeline_config).initialize() + results = orchestrator.execute_compiled_plate( + execution_bundle=bundle, max_workers=1, + runtime_observation_mode=RuntimeObservationMode.MERGE_INTO_PARENT, + progress_queue=AgentProgressQueue(), progress_context={ + "execution_id": "primary-diagnostics-synthetic", "plate_id": str(tmp_path), "axis_id": "", + }, + ) + assert results["A01"].is_success(), results["A01"].error_message + store = context.runtime_value_store + (primary_record,) = store.find(name="Nuclei", axis_id="A01") + (secondary_record,) = store.find(name="Cells", axis_id="A01") + assert np.count_nonzero(object_label_dense_array(secondary_record.value.data)) >= np.count_nonzero( + object_label_dense_array(primary_record.value.data)) > 0 + diagnostic_specs = tuple(spec for spec in primary_invocation.contract.artifact_outputs + if spec.sidecar_role is not None) + assert len(diagnostic_specs) == len(PrimaryObjectDiagnosticPlanes._fields) + persisted = [] + for spec in diagnostic_specs: + (record,) = store.find(name=spec.name, artifact_type=ImageArtifactType, axis_id="A01") + reloaded = orchestrator.filemanager.load(record.path, record.backend) + np.testing.assert_array_equal(image_payload_data(reloaded), image_payload_data(record.value.data)) + assert image_payload_metadata(record.value.data).source_path.endswith("A01_s001_DNA.tif") + persisted.append(record.value.data) + diagnostics = PrimaryObjectDiagnosticPlanes(*persisted) + np.testing.assert_array_equal(diagnostics.unedited_objects.data, primary_record.value.data.unedited_labels) + np.testing.assert_array_equal(diagnostics.small_removed_objects.data, primary_record.value.data.small_removed_labels) diff --git a/tests/unit/test_cellprofiler_adaptive_guide_threshold.py b/tests/unit/test_cellprofiler_adaptive_guide_threshold.py index 44104ce298..f502cbbfb1 100644 --- a/tests/unit/test_cellprofiler_adaptive_guide_threshold.py +++ b/tests/unit/test_cellprofiler_adaptive_guide_threshold.py @@ -304,12 +304,12 @@ def test_identify_primary_objects_runtime_uses_scope_owned_threshold_rows( "dtype_config": DtypeConfig(), } - _image, global_rows, _labels = identify_primary_objects( + _image, global_rows, _labels, *_diagnostics = identify_primary_objects( image, threshold_scope=CellProfilerThresholdScope.GLOBAL, **runtime_kwargs, ) - _image, adaptive_rows, _labels = identify_primary_objects( + _image, adaptive_rows, _labels, *_diagnostics = identify_primary_objects( image, threshold_scope=CellProfilerThresholdScope.ADAPTIVE, **runtime_kwargs, diff --git a/tests/unit/test_cellprofiler_library_loading.py b/tests/unit/test_cellprofiler_library_loading.py index 3e79f567e7..d8b8f750d7 100644 --- a/tests/unit/test_cellprofiler_library_loading.py +++ b/tests/unit/test_cellprofiler_library_loading.py @@ -1897,7 +1897,7 @@ def fake_threshold_tuple(self, **_kwargs): def test_identify_primary_objects_accepts_nominal_options_directly(): image = np.zeros((8, 8), dtype=np.float32) image[2:6, 2:6] = 1.0 - _image, _measurements, labels = identify_primary_objects( + _image, _measurements, labels, *_diagnostics = identify_primary_objects( image, min_diameter=2, max_diameter=8, @@ -1960,7 +1960,7 @@ def test_identify_primary_objects_does_not_size_filter_after_hole_fill() -> None image[1:6, 5] = 1.0 image[1, 1:6] = 1.0 image[5, 1:6] = 1.0 - _image, _measurements, labels = identify_primary_objects( + _image, _measurements, labels, *_diagnostics = identify_primary_objects( image, min_diameter=1, max_diameter=5, diff --git a/tests/unit/test_cellprofiler_primary_object_performance_kernels.py b/tests/unit/test_cellprofiler_primary_object_performance_kernels.py index 466a9d4d7c..18404e3399 100644 --- a/tests/unit/test_cellprofiler_primary_object_performance_kernels.py +++ b/tests/unit/test_cellprofiler_primary_object_performance_kernels.py @@ -217,7 +217,7 @@ def test_primary_object_border_filter_preserves_unedited_variant() -> None: image[0, :2] = 1.0 image[3:5, 3:5] = 1.0 - _image, _measurements, labels = identify_primary_objects( + _image, _measurements, labels, *_diagnostics = identify_primary_objects( image, min_diameter=1, max_diameter=20, diff --git a/tests/unit/test_primary_object_diagnostics.py b/tests/unit/test_primary_object_diagnostics.py new file mode 100644 index 0000000000..8afcfbbc4b --- /dev/null +++ b/tests/unit/test_primary_object_diagnostics.py @@ -0,0 +1,227 @@ +"""Lightweight ownership/payload checks; these do not execute segmentation.""" + +import ast +from pathlib import Path +import subprocess +from typing import NamedTuple, get_args + +import numpy as np +import pytest + +from openhcs.core.artifacts import ( + ArtifactSidecarRole, + ArtifactSidecarSourceRelation, + ArtifactSpec, + ArtifactViewerStreaming, + ImageArtifactType, + ObjectLabelsArtifactType, +) +from openhcs.core.runtime_image_values import ImagePayloadMetadata, MaskedImagePayload +from openhcs.core.runtime_object_label_building import SourceImageObjectLabelBuildRequest +from openhcs.core.source_spatial_domain import SourceSpatialDomain +from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import ( + ExecutedDeclumpingEvidence, + PrimaryObjectDiagnosticPlanes, + PrimaryObjectsRuntimeTuple, + UnexecutedDeclumpingEvidence, +) + + +def _source(): + image = np.arange(30, dtype=np.float32).reshape(5, 6) + mask = np.ones_like(image, dtype=bool) + mask[0] = False + return MaskedImagePayload( + image, + mask, + ImagePayloadMetadata( + source_path="/synthetic/A01_s001_DNA.tif", + source_image_names=("DNA",), + source_spatial_domain=SourceSpatialDomain( + origin_yx=(40, 80), source_shape_yx=(100, 120) + ), + intensity_scale=65535, + ), + ) + + +def _objects(source): + labels = np.zeros(source.data.shape, dtype=np.int32) + labels[2, 3] = 1 + unedited = labels.copy() + unedited[1, 1] = 2 + small_removed = unedited.copy() + small_removed[1, 1] = 0 + return SourceImageObjectLabelBuildRequest( + image=source, + labels=labels, + unedited_labels=unedited, + small_removed_labels=small_removed, + declared_object_count=1, + ).payload() + + +@pytest.mark.parametrize("executed", [False, True]) +def test_planes_preserve_exact_source_coordinates_and_owned_variants(executed): + source = _source() + objects = _objects(source) + response = source.data.copy() + maxima = response > 20 + markers = maxima.astype(np.int32) + evidence = ( + ExecutedDeclumpingEvidence(response, maxima, markers) + if executed else UnexecutedDeclumpingEvidence() + ) + threshold_support = source.data > 15 + initial_components = objects.labels.copy() + diagnostics = PrimaryObjectDiagnosticPlanes.from_execution( + image=source, + threshold_support=threshold_support, + initial_components=initial_components, + declumping=evidence, + objects=objects, + ) + assert len(diagnostics) == 7 + for plane in diagnostics: + assert plane.data.shape == source.data.shape + assert plane.metadata.source_provenance == source.metadata.source_provenance + assert plane.metadata.source_path == source.metadata.source_path + assert plane.metadata.spatial_origin_yx == (40, 80) + assert plane.metadata.intensity_scale is None + assert plane.metadata.source_dtype == str(plane.data.dtype) + assert source.metadata.intensity_scale == 65535 + assert diagnostics.threshold_support.data is threshold_support + assert diagnostics.initial_components.data is initial_components + assert diagnostics.unedited_objects.data is objects.unedited_labels + assert diagnostics.small_removed_objects.data is objects.small_removed_labels + assert objects.domain.declared_object_count == 1 + assert diagnostics.threshold_support.mask is diagnostics.initial_components.mask + assert diagnostics.unedited_objects.mask is diagnostics.small_removed_objects.mask + if executed: + assert diagnostics.declump_response.data is response + assert diagnostics.seed_maxima.data is maxima + assert diagnostics.seed_markers.data is markers + assert diagnostics.declump_response.mask is source.mask + else: + assert np.isnan(diagnostics.declump_response.data).all() + assert not diagnostics.seed_markers.data.any() + assert not diagnostics.seed_maxima.data.any() + assert not diagnostics.declump_response.mask.any() + assert not diagnostics.seed_maxima.mask.any() + assert not diagnostics.seed_markers.mask.any() + + +def test_diagnostic_contract_has_source_producer_stage_identity_not_new_objects(): + source = ArtifactSpec.input("DNA", ImageArtifactType) + objects = ArtifactSpec.output("Nuclei", ObjectLabelsArtifactType) + specs = PrimaryObjectDiagnosticPlanes.artifact_specs(source_image=source, objects=objects) + assert len(specs) == len(PrimaryObjectDiagnosticPlanes._fields) + for field, spec in zip(PrimaryObjectDiagnosticPlanes._fields, specs, strict=True): + assert spec.name.endswith(f"__{field}") + assert spec.artifact_type is ImageArtifactType + assert spec.sidecar_role is ArtifactSidecarRole.QA_CHECKPOINT + assert not spec.participates_in_main_flow + assert spec.viewer_streaming is ArtifactViewerStreaming.ON_DEMAND + assert spec.source_context_sources() == (source.ref(),) + assert ArtifactSidecarSourceRelation(source=objects.ref()) in spec.relations + assert len(get_args(PrimaryObjectsRuntimeTuple)) == 3 + len(specs) + assert get_args(PrimaryObjectsRuntimeTuple)[3:] == (MaskedImagePayload,) * len(specs) + + +def test_ordinary_image_contextualization_preserves_unexecuted_masks(): + from openhcs.core.artifacts import ArtifactOutputPlan + from openhcs.core.steps.function_runtime import FunctionOutputContextStrategy + + source = _source() + objects = _objects(source) + diagnostics = PrimaryObjectDiagnosticPlanes.from_execution( + image=source, threshold_support=source.data > 15, + initial_components=objects.labels, + declumping=UnexecutedDeclumpingEvidence(), objects=objects, + ) + specs = PrimaryObjectDiagnosticPlanes.artifact_specs( + source_image=ArtifactSpec.input("DNA", ImageArtifactType), + objects=ArtifactSpec.output("Nuclei", ObjectLabelsArtifactType), + ) + for spec, plane in zip(specs, diagnostics, strict=True): + plan = ArtifactOutputPlan( + name=spec.name, path=f"/memory/{spec.name}.pkl", + artifact_type=spec.artifact_type, sidecar_role=spec.sidecar_role, + relations=spec.relations, + ) + value = FunctionOutputContextStrategy.for_output_plan(plan).contextualize( + source, plane, plan, None + ) + np.testing.assert_array_equal(value.mask, plane.mask) + np.testing.assert_array_equal(value.data, plane.data) + assert value.metadata.source_provenance == source.metadata.source_provenance + assert value.metadata.intensity_scale is None + + +def test_new_stage_declaration_needs_no_catalog_or_dispatch_edit(): + # Run the actual declaration projection with a new nominal record field. + class ExtendedPlanes(NamedTuple): + additional_stage: MaskedImagePayload + + specs = PrimaryObjectDiagnosticPlanes.artifact_specs.__func__( + ExtendedPlanes, + source_image=ArtifactSpec.input("DNA", ImageArtifactType), + objects=ArtifactSpec.output("Nuclei", ObjectLabelsArtifactType), + ) + assert len(specs) == 1 + assert specs[0].name.endswith("__additional_stage") + + +def test_focused_real_source_antipattern_guards(): + root = Path(__file__).resolve().parents[2] + source = root / "openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py" + tree = ast.parse(source.read_text()) + # IMPL-1/2/3/7 and BOUND-1/2/7: evidence owners have no kind/type + # dispatcher, raw string-key consumers or duck-typed fallback readers. + assert not any(isinstance(node, ast.Match) for node in ast.walk(tree)) + assert not any( + isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id in {"isinstance", "getattr", "hasattr", "eval", "exec"} + for node in ast.walk(tree) + ) + assert not any( + isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Constant) + and isinstance(node.slice.value, str) + for node in ast.walk(tree) + ) + projection = next( + node for node in ast.walk(tree) + if isinstance(node, ast.FunctionDef) and node.name == "artifact_specs" + ) + # MEMB-1/3: no hand-maintained roster alongside the typed stage record. + assert not any(isinstance(node, (ast.List, ast.Set, ast.Dict)) for node in ast.walk(projection)) + assert any( + isinstance(node, ast.Attribute) and node.attr == "_fields" + for node in ast.walk(projection) + ) + + +def test_processing_body_is_unchanged_except_same_run_evidence_capture(): + root = Path(__file__).resolve().parents[2] + relative = "openhcs/processing/backends/cellprofiler/primary_objects.py" + baseline = subprocess.run( + ["git", "show", f"a0263e82a1b3296f34f8c5cdd50ffae5c33ef7dd:{relative}"], + cwd=root, check=True, capture_output=True, text=True, + ).stdout + before = next(n for n in ast.parse(baseline).body if isinstance(n, ast.FunctionDef) + and n.name == "identify_primary_objects") + after = next(n for n in ast.parse((root / relative).read_text()).body + if isinstance(n, ast.FunctionDef) and n.name == before.name) + + class RemoveEvidence(ast.NodeTransformer): + def visit_Assign(self, node): + if any(isinstance(target, ast.Name) and target.id in { + "threshold_support", "initial_components", "declumping", "diagnostics" + } for target in node.targets): + return None + return self.generic_visit(node) + + after = RemoveEvidence().visit(after) + # Compare the original algorithm, not docstring, signature or output ABI. + assert ast.dump(ast.Module(body=before.body[1:-1], type_ignores=[])) == ast.dump( + ast.Module(body=after.body[1:-1], type_ignores=[])) From 51218d5a1a9a66a7e899c4185766fccfe9460d00 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 29 Sep 2026 15:46:49 -0400 Subject: [PATCH 2/9] Verify existing stage aggregation and serialized payload boundaries --- ...ntation_diagnostics_checkpoint_20260929.md | 6 ++- tests/unit/test_primary_object_diagnostics.py | 40 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md b/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md index 072d74a6f1..de53906681 100644 --- a/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md +++ b/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md @@ -3,6 +3,7 @@ Implementation owner: Singer. Base audited: `a0263e82a1b3296f34f8c5cdd50ffae5c33ef7dd`. Worktree: `/home/ts/wt/openhcs-primary-segmentation-diagnostics-20260929`. Issue: https://github.com/OpenHCSDev/openhcs/issues/214. +Draft implementation: https://github.com/OpenHCSDev/openhcs/pull/215. ## Contract and ownership @@ -38,7 +39,7 @@ unexecuted stages share one invalid mask. No input or private benchmark was read ## Actual focused checks -Seven lightweight tests passed in 1.74 seconds, using the prescribed project +Nine lightweight tests passed in 1.79 seconds, using the prescribed project Python 3.12 environment, this worktree and all eight recorded submodule source directories on `PYTHONPATH`, with `OPENHCS_CPU_ONLY=true`, thread limits of one, `PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` and: @@ -69,6 +70,9 @@ This is a focused source/AST audit, not a complete NRA scan: body is unchanged except evidence captures and the augmented return. - The real image-output contextualizer preserves absent-stage masks and numeric pixels, provenance and stage intensity semantics. +- The existing PURE_2D auxiliary aggregator preserves stage pixels, independent + masks and two-plane source provenance. A small pickle boundary roundtrip + preserves typed planes; this is not persisted MCP/result-review acceptance. - New-case experiment: one added nominal record field is picked up by the actual artifact projection without a catalog/dispatcher edit. A real new computed stage requires its field plus its same-execution producer argument (two sites); diff --git a/tests/unit/test_primary_object_diagnostics.py b/tests/unit/test_primary_object_diagnostics.py index 8afcfbbc4b..08ae437981 100644 --- a/tests/unit/test_primary_object_diagnostics.py +++ b/tests/unit/test_primary_object_diagnostics.py @@ -158,6 +158,46 @@ def test_ordinary_image_contextualization_preserves_unexecuted_masks(): assert value.metadata.intensity_scale is None +def test_existing_pure2d_aggregation_retains_stage_pixels_masks_and_plane_identity(): + from openhcs.core.runtime_plane_projection import RuntimePlaneAxis + from openhcs.processing.backends.lib_registry.unified_registry import Pure2DAuxiliaryOutputAggregator + from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import DiagnosticPlaneSource + + first = _source() + second = MaskedImagePayload( + first.data + 10, ~first.mask, + ImagePayloadMetadata( + source_path="/synthetic/A01_s002_DNA.tif", source_image_names=("DNA",), + source_spatial_domain=first.metadata.source_spatial_domain, + ), + ) + planes = [DiagnosticPlaneSource.from_image(source).plane(source.data) + for source in (first, second)] + value = Pure2DAuxiliaryOutputAggregator.aggregate( + planes, "numpy", plane_axis=RuntimePlaneAxis.RUNTIME_SLICE + ) + np.testing.assert_array_equal(value.data, np.stack([first.data, second.data])) + np.testing.assert_array_equal(value.mask, np.stack([first.mask, second.mask])) + assert value.metadata.plane_axis is RuntimePlaneAxis.RUNTIME_SLICE + assert value.metadata.source_provenance.source_plane_count == 2 + + +def test_typed_stage_payloads_roundtrip_existing_pickle_boundary(): + import pickle + + source = _source() + diagnostics = PrimaryObjectDiagnosticPlanes.from_execution( + image=source, threshold_support=source.data > 15, + initial_components=_objects(source).labels, + declumping=UnexecutedDeclumpingEvidence(), objects=_objects(source), + ) + reloaded = pickle.loads(pickle.dumps(diagnostics)) + for before, after in zip(diagnostics, reloaded, strict=True): + np.testing.assert_array_equal(before.data, after.data) + np.testing.assert_array_equal(before.mask, after.mask) + assert before.metadata == after.metadata + + def test_new_stage_declaration_needs_no_catalog_or_dispatch_edit(): # Run the actual declaration projection with a new nominal record field. class ExtendedPlanes(NamedTuple): From c4b7dc029e9620469e1a6bfa9a70b22be0485a03 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 29 Sep 2026 16:10:58 -0400 Subject: [PATCH 3/9] Bound absent-stage evidence and align IPO executor fixture (#214) --- ...ntation_diagnostics_checkpoint_20260929.md | 48 ++++++++++++------- .../primary_object_diagnostics.py | 2 +- ...rimary_segmentation_diagnostics_journey.py | 8 ++-- .../unit/test_cellprofiler_runtime_adapter.py | 18 +++++-- tests/unit/test_primary_object_diagnostics.py | 3 ++ 5 files changed, 55 insertions(+), 24 deletions(-) diff --git a/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md b/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md index de53906681..0685e77642 100644 --- a/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md +++ b/docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md @@ -35,11 +35,13 @@ Evidence is bounded to seven planes per IPO plane. Only threshold support and initial components are snapshotted to protect their pre-transform stage identity. Executed response/seed arrays and payload variant arrays are referenced, not rerun or cloned. Source validity is decoded once and shared across stages; -unexecuted stages share one invalid mask. No input or private benchmark was read. +unexecuted stages share one invalid mask and use float32 NaN response pixels, +halving the absent response allocation compared with NumPy's default float64. +No input or private benchmark was read. ## Actual focused checks -Nine lightweight tests passed in 1.79 seconds, using the prescribed project +Nine lightweight tests passed in 1.76 seconds, using the prescribed project Python 3.12 environment, this worktree and all eight recorded submodule source directories on `PYTHONPATH`, with `OPENHCS_CPU_ONLY=true`, thread limits of one, `PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` and: @@ -49,7 +51,13 @@ python -B -m pytest -q --confcutdir=tests/unit tests/unit/test_primary_object_di ``` Two unrelated pytest async-config warnings remain because plugins are disabled. -Verified import paths are under this worktree and its recorded submodules. +Verified import paths are under this worktree and its recorded submodules, +including all eight dependency modules. This explicit source authority matters: +the shared environment's default imports now resolve to the clean installed +harness, not this feature tree. Latest remote main +`283b21275553c54261cf9aeedb7374c113d07f2b` was merged normally into this branch +as `e6b2addc8c9e626d045742ef7d2f18c8b29e2b4a`; its installed package/skill remains +frozen and unchanged. The first test iterations exposed incorrect fixture assumptions about source spatial-domain construction and the payload's count owner; those fixtures now use `SourceSpatialDomain` and `objects.domain.declared_object_count` directly. @@ -88,29 +96,37 @@ Do not install or change the running baseline. `tests/integration/test_primary_segmentation_diagnostics_journey.py` is prepared but NOT run. It covers real registered IPO on a small synthetic close-pair/faint -field (empty, disabled, intensity and shape declumping), then source-document +field (empty, unclumping disabled, watershed disabled, intensity and shape +declumping), then source-document roundtrip, normal compiled execution, secondary binding and persisted review through the existing runtime/filemanager. Native parity, these real journeys, fresh MCP discovery, persisted MCP result review and isolated-display same-coordinate raw/intermediate/final viewer inspection remain required. Passing metadata tests does not prove them or biological QA. -Parent takes the first released slot for #151/#212. Wait for the parent's explicit -handoff, then acquire `/home/ts/wt/openhcs-issue-batch-20260929/validation.lock` +Parent's #151/#212 acceptance is merged and installed. Confucius owns the current +heavy slot using that frozen harness. Wait for the parent's explicit handoff, +then acquire `/home/ts/wt/openhcs-issue-batch-20260929/validation.lock` nonblocking, run the resource guard and retain at least 8 GiB RAM. Use a single worker and owned disposable test output under `/home/ts/.cache/agent-scratch/openhcs-primary-diagnostics-20260929`, retain receipts, then clean disposable output. Do not poll the lock or start a GUI without display allocation. -Core artifact/runtime/adapter files owned by Zeno are unchanged. This bus has no -verified Zeno route, and the parent cannot relay; obtain a direct route before any -shared-file changes or manual adapter-fixture migration. One existing hand-written -IPO executor fixture still declares only the previous two artifact slots; it must -derive the new diagnostics before its native suite is run. Normal compiled contracts -already use the module hook. - -Independent draft PR #207 / issue #138 remains at its published polymorphism -checkpoint, with 51 provider-free tests and prior existing-environment lifecycle -evidence. Its authorized bounded fresh bootstrap creation/native validation is +Core artifact/runtime/adapter implementation files owned by Zeno are unchanged. +The IPO-specific fixture in `tests/unit/test_cellprofiler_runtime_adapter.py` +previously declared only the old measurement/object slots. PR #205 and Zeno's +worktree had no conflicting edits to that file at the scope check. The fixture +now derives appended diagnostic specs from `PrimaryObjectDiagnosticPlanes`, +preserving its original main/label/persistence assertions and adapter bindings. +This fixture migration is source-only; its native test has NOT run. Normal +compiled contracts already use the module hook. Any future shared implementation +change still requires direct coordination with Zeno; no comms route is required +for independent source work. + +Independent draft PR #207 / issue #138 now includes the independent MI discovery +correction at `bd164a94f0a42b90b45d7f8e43d09314d5fcaccf`, with 53 provider-free +tests and actual Python3.9 standalone diamond-command/stage evidence. Its prior +existing-environment lifecycle receipts do not certify that current revision. +Authorized bounded fresh bootstrap creation/native validation is still pending the explicit serialized slot. It is not abandoned or closed. diff --git a/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py b/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py index e77942419e..57b93882e5 100644 --- a/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py +++ b/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py @@ -108,7 +108,7 @@ def planes( shape = source.validity_mask.shape invalid = np.zeros(shape, dtype=bool) return ( - source.plane(np.full(shape, np.nan), validity_mask=invalid), + source.plane(np.full(shape, np.nan, dtype=np.float32), validity_mask=invalid), source.plane(np.zeros(shape, dtype=bool), validity_mask=invalid), source.plane(np.zeros(shape, dtype=np.int32), validity_mask=invalid), ) diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index bbe26ca5f0..9012e144ed 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -18,7 +18,7 @@ def _field(empty=False): return np.zeros_like(image) if empty else image -@pytest.mark.parametrize("mode", ["empty", "disabled", "intensity", "shape"]) +@pytest.mark.parametrize("mode", ["empty", "disabled", "watershed-disabled", "intensity", "shape"]) def test_real_registered_ipo_returns_same_run_stage_pixels(mode): from openhcs.core.config import DtypeConfig from openhcs.core.runtime_image_values import image_payload_data @@ -36,7 +36,9 @@ def test_real_registered_ipo_returns_same_run_stage_pixels(mode): original, measurements, objects, *planes = func( image, min_diameter=2, max_diameter=20, exclude_size=False, exclude_border_objects=False, - unclump_method=method, watershed_method=WatershedMethod.INTENSITY, + unclump_method=method, + watershed_method=(WatershedMethod.NONE if mode == "watershed-disabled" + else WatershedMethod.INTENSITY), threshold_method=CellProfilerThresholdMethod.MANUAL, manual_threshold=0.2, threshold_smoothing_scale=0.0, fill_holes=FillHolesOption.NEVER, automatic_smoothing=False, smoothing_filter_size=1, @@ -49,7 +51,7 @@ def test_real_registered_ipo_returns_same_run_stage_pixels(mode): np.testing.assert_array_equal(diagnostics.unedited_objects.data, objects.unedited_labels) np.testing.assert_array_equal(diagnostics.small_removed_objects.data, objects.small_removed_labels) assert measurements.row_count > 0 - if mode in ("empty", "disabled"): + if mode in ("empty", "disabled", "watershed-disabled"): assert not diagnostics.declump_response.mask.any() assert np.isnan(diagnostics.declump_response.data).all() assert not diagnostics.seed_markers.data.any() diff --git a/tests/unit/test_cellprofiler_runtime_adapter.py b/tests/unit/test_cellprofiler_runtime_adapter.py index e07c457645..c5a86f3d1b 100644 --- a/tests/unit/test_cellprofiler_runtime_adapter.py +++ b/tests/unit/test_cellprofiler_runtime_adapter.py @@ -6007,6 +6007,10 @@ def test_core_cellprofiler_functions_resolve_with_numpy_memory_contract(module_n def test_cellprofiler_module_executor_runs_resolved_identify_primary_objects(): + from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import ( + PrimaryObjectDiagnosticPlanes, + ) + adapter, filemanager = _adapter( ( _output_binding( @@ -6027,15 +6031,21 @@ def test_cellprofiler_module_executor_runs_resolved_identify_primary_objects(): identify_primary_objects = CellProfilerModule.require_module( IDENTIFY_PRIMARY_OBJECTS ).require_callable() + source_image = ArtifactSpec.input(DNA_IMAGE, ImageArtifactType) + object_output = ArtifactSpec.output_inheriting_group_scope( + NUCLEI, + ObjectLabelsArtifactType, + source_image, + ) executor = _executor( identify_primary_objects, adapter, ( ArtifactSpec.output(MEASUREMENTS, MeasurementsArtifactType), - ArtifactSpec.output_inheriting_group_scope( - NUCLEI, - ObjectLabelsArtifactType, - ArtifactSpec.input(DNA_IMAGE, ImageArtifactType), + object_output, + *PrimaryObjectDiagnosticPlanes.artifact_specs( + source_image=source_image, + objects=object_output, ), ), ) diff --git a/tests/unit/test_primary_object_diagnostics.py b/tests/unit/test_primary_object_diagnostics.py index 08ae437981..648736ed82 100644 --- a/tests/unit/test_primary_object_diagnostics.py +++ b/tests/unit/test_primary_object_diagnostics.py @@ -103,12 +103,15 @@ def test_planes_preserve_exact_source_coordinates_and_owned_variants(executed): assert diagnostics.seed_markers.data is markers assert diagnostics.declump_response.mask is source.mask else: + assert diagnostics.declump_response.data.dtype == np.float32 assert np.isnan(diagnostics.declump_response.data).all() assert not diagnostics.seed_markers.data.any() assert not diagnostics.seed_maxima.data.any() assert not diagnostics.declump_response.mask.any() assert not diagnostics.seed_maxima.mask.any() assert not diagnostics.seed_markers.mask.any() + assert diagnostics.declump_response.mask is diagnostics.seed_maxima.mask + assert diagnostics.seed_maxima.mask is diagnostics.seed_markers.mask def test_diagnostic_contract_has_source_producer_stage_identity_not_new_objects(): From 1bc80d6e02b80796c77794051cfea7415afd3842 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 11:17:20 -0400 Subject: [PATCH 4/9] docs: record current-main primary diagnostics source checkpoint --- ...mary_diagnostics_current_main_20260930.rst | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 docs/validation/primary_diagnostics_current_main_20260930.rst diff --git a/docs/validation/primary_diagnostics_current_main_20260930.rst b/docs/validation/primary_diagnostics_current_main_20260930.rst new file mode 100644 index 0000000000..5769260416 --- /dev/null +++ b/docs/validation/primary_diagnostics_current_main_20260930.rst @@ -0,0 +1,57 @@ +Primary object diagnostics current-main checkpoint +================================================= + +Parent integration owns existing PR215. Reviewed featurec4b7dc02 merged +normally with mainc42d9bf5 into3048eda2. Original author source is untouched; +no rebase, force push, second diagnostic registry or competing implementation. +This sparse persistent worktree is not the installed editable source. + +The seven stages are declared by PrimaryObjectDiagnosticPlanes. Artifact names, +order and callable return-slot types derive from that same declaration. Executed +and unexecuted declumping evidence own their different plane projections; no +consumer dispatch decides their semantics. Object variants remain owned by +ObjectLabelPayload. QA planes use existing image-sidecar/output contextualizing +and PURE_2D aggregation mechanisms, not another segmentation algorithm. + +Executed source validation +-------------------------- + +First pytest collection failed: local _tabular_native had not been built in +the new source checkout. Original XML is preserved in the parent ledger as +primary-diagnostics-current-main-unit-original-20260930.xml. Zero cases ran. + +Standard setup.py build_ext --inplace --parallel1 built both existing declared +native extensions in3.60s, exit0, peak146620KiB. No binary copied from another +checkout, package installation, dependency download or source-path shim. +Compiler scratch is tracked in the parent integration ledger. + +Subsequent actual source test command used existing Python3.12.3, this checkout +as PYTHONPATH, native threads1, pytest plugin autoload disabled and timeout60: + +.. code-block:: text + + python -m pytest tests/unit/test_primary_object_diagnostics.py -q + +Nine cases PASS1.26s, process1.68s, peak89020KiB. Two async config warnings +come from disabled plugin autoload. XML is preserved as +primary-diagnostics-current-main-unit-after-build-20260930.xml in parent ledger. +Checks exercise source/coordinate and canonical variant identity, wholly-invalid +unexecuted stages, existing real output contextualization and plane aggregation, +typed pickle boundary, declaration extension without catalog changes, focused +new-source antipattern guards, and original algorithm AST preservation apart +from same-run capture. They are not full-package NRA or scientific acceptance. + +Remaining live acceptance +------------------------- + +Actual registered IPO modes, normal compiled primary-to-secondary identity, +persisted sidecar readback and MCP/viewer raw/intermediate/final inspection +remain unexecuted at this checkpoint. Synthetic continuity tests are present +in tests/integration/test_primary_segmentation_diagnostics_journey.py; a +prepared test is not executed evidence. No issue closure or main merge claimed. + +Fermat holds the sole scientific runtime admission/frozen installed c42d +contract. This source checkpoint does not alter that application, managed +skill or biological analysis. Run native/live acceptance only after its +terminal cleanup and fresh admission, then integrate this same existing PR +without waiting for optional hosted CI. Whole owner ZIP scope remains open. From fe6c84ed20737b5b9cdd4b3a5ebc29a412686021 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 11:30:59 -0400 Subject: [PATCH 5/9] docs: retain primary diagnostics packaged guard result --- .../primary_diagnostics_current_main_20260930.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/validation/primary_diagnostics_current_main_20260930.rst b/docs/validation/primary_diagnostics_current_main_20260930.rst index 5769260416..59d001483c 100644 --- a/docs/validation/primary_diagnostics_current_main_20260930.rst +++ b/docs/validation/primary_diagnostics_current_main_20260930.rst @@ -41,6 +41,14 @@ typed pickle boundary, declaration extension without catalog changes, focused new-source antipattern guards, and original algorithm AST preservation apart from same-run capture. They are not full-package NRA or scientific acceptance. +Required structural screen also ran using the existing packaged agent-comms +ratchet, authenticated byte-identical to pinned3b03785 by SHA256e323c94d49c2b72d9524a5169f123e64b4a6e46a41035ca9fb4497e49b6ca562. +Basec42d9bf5 to published1bc80d6e: PASS5114 metrics, zero nonzero or positive +deltas,12.84s/86528KiB/exit0. Two changed production paths are the diagnostics +owner and primary_objects. Complete JSON lives in the parent persistent ledger +as primary-diagnostics-packaged-ratchet-20260930.json. This screen does not +replace complete NRA/R1, module parity or live acceptance. + Remaining live acceptance ------------------------- From c02108c98a08a9722b4c6c95c85eb85353935547 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 11:58:54 -0400 Subject: [PATCH 6/9] Persist primary diagnostic stages as distinct artifact-owned TIFFs --- ...mary_diagnostics_current_main_20260930.rst | 63 ++++++++++++++----- .../primary_object_diagnostics.py | 11 ++++ ...rimary_segmentation_diagnostics_journey.py | 32 ++++++++-- .../PRIMARY-DIAGNOSTICS-20260930.rst | 16 +++++ tests/unit/test_primary_object_diagnostics.py | 10 +++ 5 files changed, 114 insertions(+), 18 deletions(-) create mode 100644 tests/runtime_diagnostics/PRIMARY-DIAGNOSTICS-20260930.rst diff --git a/docs/validation/primary_diagnostics_current_main_20260930.rst b/docs/validation/primary_diagnostics_current_main_20260930.rst index 59d001483c..fd266fee34 100644 --- a/docs/validation/primary_diagnostics_current_main_20260930.rst +++ b/docs/validation/primary_diagnostics_current_main_20260930.rst @@ -49,17 +49,52 @@ owner and primary_objects. Complete JSON lives in the parent persistent ledger as primary-diagnostics-packaged-ratchet-20260930.json. This screen does not replace complete NRA/R1, module parity or live acceptance. -Remaining live acceptance -------------------------- - -Actual registered IPO modes, normal compiled primary-to-secondary identity, -persisted sidecar readback and MCP/viewer raw/intermediate/final inspection -remain unexecuted at this checkpoint. Synthetic continuity tests are present -in tests/integration/test_primary_segmentation_diagnostics_journey.py; a -prepared test is not executed evidence. No issue closure or main merge claimed. - -Fermat holds the sole scientific runtime admission/frozen installed c42d -contract. This source checkpoint does not alter that application, managed -skill or biological analysis. Run native/live acceptance only after its -terminal cleanup and fresh admission, then integrate this same existing PR -without waiting for optional hosted CI. Whole owner ZIP scope remains open. +Continuous native acceptance +---------------------------- + +Following the scientific worker's verified terminal cleanup, the parent used +the released validation lock for the real synthetic primary/secondary journey. +No biological inputs, held-out data, extra environment or Fiji download. + +The originally unexecuted fixture had three API/semantic mistakes: row_count +is a method; memory records belong to RuntimeValueStore, not an unrelated +FileManager; source-binding identities are virtual addresses, not necessarily +physical input filenames. Readback now compares ordinary persisted TIFFs with +the existing writer's declared runtime-plane projection. Source identity and +pixel contributors are checked through their nominal authorities; a sidecar's +own runtime alias is not incorrectly required to equal the DNA alias. + +Native execution exposed a product defect: all seven diagnostic stages used +the same source-derived filename. The diagnostic declaration now requests the +existing artifact-name TIFF materialization, preserving each stage separately. +No second writer, routing registry or serialization fallback was introduced. +The first explicit declaration lacked its required .tif suffix; that failed +attempt is retained rather than hidden by an inferred serialization format. + +Final command, with one CPU and native threads1, existing Python3.12 and this +source checkout as PYTHONPATH: + +.. code-block:: text + + python -m pytest tests/unit/test_primary_object_diagnostics.py \ + tests/integration/test_primary_segmentation_diagnostics_journey.py -q + +Actual result:15PASS7.05s; process10.55s, peak463732KiB, exit0. The five real +registered IPO modes include empty, declumping-disabled, watershed-disabled, +intensity and shape. The continuous PipelineDocument roundtrip -> compile -> +execute -> persist journey checks all seven distinct stage TIFFs pixel-exactly, +source address and contributors, canonical unedited/small-removed label +variants, primary-to-secondary label identity and containment of each own seed. +All earlier failures and the final XML are retained in the parent ledger as +primary-diagnostics-native-{first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,final}-20260930.xml. + +Remaining installed acceptance +------------------------------ + +The affected installed MCP/viewer raw/intermediate/final journey remains +unexecuted for this PR. Neither a main merge nor biological acceptance is +claimed. The previous scientific run is frozen ABSTENTION_RESOURCE_GUARD, +zeroof4 candidates; its clock, inputs and prior failures are unchanged. +The parent owns the released integration slot. Publish this same existing PR +and complete installed acceptance without waiting for optional hosted CI. +Whole owner ZIP scope remains open. diff --git a/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py b/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py index 57b93882e5..253aac98d3 100644 --- a/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py +++ b/openhcs/processing/backends/cellprofiler/primary_object_diagnostics.py @@ -28,6 +28,11 @@ image_payload_metadata, ) from openhcs.core.runtime_object_labels import ObjectLabelPayload, ObjectLabelVariant +from openhcs.processing.materialization import ( + ImageFileOptions, + MaterializationSpec, + MaterializedFilenameIdentity, +) @dataclass(frozen=True, slots=True) @@ -170,6 +175,12 @@ def artifact_specs( ImageArtifactType, sidecar_role=ArtifactSidecarRole.QA_CHECKPOINT, viewer_streaming=ArtifactViewerStreaming.ON_DEMAND, + materialization=MaterializationSpec( + ImageFileOptions( + filename_suffix=".tif", + filename_identity=MaterializedFilenameIdentity.ARTIFACT_NAME, + ) + ), relations=( SourceStackLineageSourceRelation(source=source_image.ref()), ArtifactSidecarSourceRelation(source=objects.ref()), diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index 9012e144ed..352abb8d0f 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -50,7 +50,7 @@ def test_real_registered_ipo_returns_same_run_stage_pixels(mode): np.testing.assert_array_equal(diagnostics.threshold_support.data, image > 0.2) np.testing.assert_array_equal(diagnostics.unedited_objects.data, objects.unedited_labels) np.testing.assert_array_equal(diagnostics.small_removed_objects.data, objects.small_removed_labels) - assert measurements.row_count > 0 + assert measurements.row_count() > 0 if mode in ("empty", "disabled", "watershed-disabled"): assert not diagnostics.declump_response.mask.any() assert np.isnan(diagnostics.declump_response.data).all() @@ -65,6 +65,7 @@ def test_real_registered_ipo_returns_same_run_stage_pixels(mode): def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_binding(tmp_path): import tifffile + from openhcs.processing.materialization.core import MaterializationInput from openhcs.agent.services.execution_session_service import ( AgentProgressQueue, CompileInspectionInput, InProcessCompileInspectionGateway, ) @@ -161,17 +162,40 @@ def step(func, name, kwargs): store = context.runtime_value_store (primary_record,) = store.find(name="Nuclei", axis_id="A01") (secondary_record,) = store.find(name="Cells", axis_id="A01") + source_metadata = primary_record.value.data.metadata assert np.count_nonzero(object_label_dense_array(secondary_record.value.data)) >= np.count_nonzero( object_label_dense_array(primary_record.value.data)) > 0 + primary_labels = object_label_dense_array(primary_record.value.data) + secondary_labels = object_label_dense_array(secondary_record.value.data) + np.testing.assert_array_equal(np.unique(primary_labels), np.unique(secondary_labels)) + np.testing.assert_array_equal( + secondary_labels[primary_labels > 0], primary_labels[primary_labels > 0] + ) diagnostic_specs = tuple(spec for spec in primary_invocation.contract.artifact_outputs if spec.sidecar_role is not None) assert len(diagnostic_specs) == len(PrimaryObjectDiagnosticPlanes._fields) persisted = [] for spec in diagnostic_specs: (record,) = store.find(name=spec.name, artifact_type=ImageArtifactType, axis_id="A01") - reloaded = orchestrator.filemanager.load(record.path, record.backend) - np.testing.assert_array_equal(image_payload_data(reloaded), image_payload_data(record.value.data)) - assert image_payload_metadata(record.value.data).source_path.endswith("A01_s001_DNA.tif") + (saved_path,) = context.step_plans[0].artifact_analysis_output_dir.glob( + f"*_{spec.name}_step0.tif" + ) + (options,) = spec.materialization.outputs + (plane,) = MaterializationInput.from_runtime_slice_projected_value( + record.value.data, options + ).items + np.testing.assert_array_equal( + tifffile.imread(saved_path), plane.data + ) + metadata = image_payload_metadata(record.value.data) + # Sidecars have their own runtime alias, retaining the same source + # address and pixel contributors as the primary object payload. + assert metadata.source_provenance.scalar_source_identity == ( + source_metadata.source_provenance.scalar_source_identity + ) + assert metadata.source_image_provenance_planes.as_contributors().identity == ( + source_metadata.source_image_provenance_planes.as_contributors().identity + ) persisted.append(record.value.data) diagnostics = PrimaryObjectDiagnosticPlanes(*persisted) np.testing.assert_array_equal(diagnostics.unedited_objects.data, primary_record.value.data.unedited_labels) diff --git a/tests/runtime_diagnostics/PRIMARY-DIAGNOSTICS-20260930.rst b/tests/runtime_diagnostics/PRIMARY-DIAGNOSTICS-20260930.rst new file mode 100644 index 0000000000..da4be6d581 --- /dev/null +++ b/tests/runtime_diagnostics/PRIMARY-DIAGNOSTICS-20260930.rst @@ -0,0 +1,16 @@ +Primary diagnostics native acceptance artifacts +=============================================== + +Parent-owned synthetic primary/secondary continuous runtime fixtures only. +No biological inputs or held-out answers. First attempt preserved XML at +parent ledger primary-diagnostics-native-first-20260930.xml: five cases fail +because the unrun fixture used the ColumnarRows.row_count method as a property; +compiled case cannot create its basetemp because this sparse checkout omitted +the parent runtime_diagnostics directory. Actual IPO calls completed through +pixel/variant assertions before that API misuse, not five product failures. + +Correction uses original declared row_count() without weakening >0 assertion +or any pixel/identity expectation. This persistent parent directory now exists +and later attempt basetemp paths are unique; never erase prior attempt files. +Preserve native fixture images, output artifacts and failed receipts through +integration acceptance. Only purely disposable compiler output may be retired. diff --git a/tests/unit/test_primary_object_diagnostics.py b/tests/unit/test_primary_object_diagnostics.py index 648736ed82..55534f1546 100644 --- a/tests/unit/test_primary_object_diagnostics.py +++ b/tests/unit/test_primary_object_diagnostics.py @@ -25,6 +25,10 @@ PrimaryObjectsRuntimeTuple, UnexecutedDeclumpingEvidence, ) +from openhcs.processing.materialization import ( + ImageFileOptions, + MaterializedFilenameIdentity, +) def _source(): @@ -125,6 +129,12 @@ def test_diagnostic_contract_has_source_producer_stage_identity_not_new_objects( assert spec.sidecar_role is ArtifactSidecarRole.QA_CHECKPOINT assert not spec.participates_in_main_flow assert spec.viewer_streaming is ArtifactViewerStreaming.ON_DEMAND + assert spec.materialization.outputs == ( + ImageFileOptions( + filename_suffix=".tif", + filename_identity=MaterializedFilenameIdentity.ARTIFACT_NAME, + ), + ) assert spec.source_context_sources() == (source.ref(),) assert ArtifactSidecarSourceRelation(source=objects.ref()) in spec.relations assert len(get_args(PrimaryObjectsRuntimeTuple)) == 3 + len(specs) From cba1c90df2e2d7e5f6d54bd68edceca339ddeb71 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 12:40:45 -0400 Subject: [PATCH 7/9] Publish independently persisted artifact source metadata through declared targets --- ...mary_diagnostics_current_main_20260930.rst | 57 ++- openhcs/core/steps/function_outputs.py | 277 ++++++++----- ...rimary_segmentation_diagnostics_journey.py | 369 ++++++++++++++---- tests/unit/test_function_outputs.py | 32 +- 4 files changed, 537 insertions(+), 198 deletions(-) diff --git a/docs/validation/primary_diagnostics_current_main_20260930.rst b/docs/validation/primary_diagnostics_current_main_20260930.rst index fd266fee34..668552dda8 100644 --- a/docs/validation/primary_diagnostics_current_main_20260930.rst +++ b/docs/validation/primary_diagnostics_current_main_20260930.rst @@ -88,13 +88,50 @@ variants, primary-to-secondary label identity and containment of each own seed. All earlier failures and the final XML are retained in the parent ledger as primary-diagnostics-native-{first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,final}-20260930.xml. -Remaining installed acceptance ------------------------------- - -The affected installed MCP/viewer raw/intermediate/final journey remains -unexecuted for this PR. Neither a main merge nor biological acceptance is -claimed. The previous scientific run is frozen ABSTENTION_RESOURCE_GUARD, -zeroof4 candidates; its clock, inputs and prior failures are unchanged. -The parent owns the released integration slot. Publish this same existing PR -and complete installed acceptance without waiting for optional hosted CI. -Whole owner ZIP scope remains open. +Installed reopening defect and ownership cutover +------------------------------------------------ + +Ordinary editable imports at candidate97195 passed15 cases7.09s with PYTHONPATH +unset. Actual fresh installed MCP then opened and streamed the raw synthetic +image on isolated:91/5992. Reopening its persisted threshold-support TIFF +failed StorageResolutionError. The viewer was closed explicitly through MCP, +the shell exited1 after the failed command, and the ports and lock were freed. +The original terminal transcript and failed fixture remain in the parent ledger. + +Correction to the initial diagnosis: the second step did not overwrite early +diagnostic metadata. The first step's main-flow backend was memory and its +checkpoint was absent. Both manually enumerated metadata targets were absent, +although the independent artifact materialization target saved all stage TIFFs. +AtomicMetadataWriter already retains those projections across later steps. + +The existing OutputTarget now owns an AutoRegisterMeta declaration family. +Primary images and explicit checkpoints compose their shared produced-image +capability by MI. RuntimeArtifactMetadataTarget resolves the independently +compiled artifact destination and publishes its typed projections, including +when main flow is memory. Shared serialization and AtomicMetadataWriter remain +the only writer. The old primary/materialized constructors, repeated consumer +rosters and is_main-based target dispatch are deleted, not retained as aliases. +is_main is now a declaration fact consumed only by the external metadata format. + +MEMB-2, IMPL-4/5 and IDEN-1 witnesses: the old two-member tuples in write and +finalize omitted artifact persistence; produced_projection_metadata dispatched +through is_main. The new-case guard declares an additional target and proves +automatic discovery for execution and reconciliation without changing either +consumer. The native journey checks seven persistent stage source entries and +both Nuclei/Cells label entries after secondary execution and reconciliation. +Source identities after persistence are compared through the canonical JSON +codec, which normalizes nested mapping keys; this is separate from the existing +native sidecar/source identity and pixel-contributor equality checks. + +First combined run:72PASS/2FAIL9.57s. One real table-only publication regression +was repaired by the primary declaration's execution admission hook; the other +assertion incorrectly compared in-memory mapping keys with serialized JSON +identities. Original XML retained. Second combined run:74PASS9.89s. The final +family-discovery guard passed in the final75PASS8.64s run. Installed reopening +still requires execution. +These are focused source/native proofs, not complete NRA or biological QA. + +The parent owns this same PR215 and issue214, with no competing implementation. +Complete the affected installed path before merge; do not wait for optional CI. +The frozen scientific abstention, held-out boundary and full ZIP scope remain +unchanged. Owner clarification:20GiB is a warning margin, not a hard disk limit. diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index c1ba7c6962..085152b926 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -4,11 +4,18 @@ import logging import time +from abc import ABC, abstractmethod from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path +from typing import ClassVar import numpy as np +from metaclass_registry import ( + AutoRegisterMeta, + RegistryFamily, + extract_key_from_class_name, +) from polystore.streaming.identity import StreamProducerIdentity from polystore.streaming.viewer_transport import ViewerStreamProducer from polystore.virtual_workspace import SourcePixelRef @@ -666,69 +673,70 @@ def stream_outputs( class OpenHCSMetadataWriter: - """Writes OpenHCS metadata sidecars for primary and materialized outputs.""" + """Publish the declared storage targets' durable source projections.""" - @dataclass(frozen=True, slots=True) - class OutputTarget: + @dataclass(frozen=True) + class OutputTarget(ABC, metaclass=AutoRegisterMeta): """One compiled output location projected into OpenHCS metadata.""" + __registry_family__ = RegistryFamily("declaration_key") + __key_extractor__ = staticmethod(extract_key_from_class_name) + declaration_key: ClassVar[str | None] = None + is_main: ClassVar[bool] = False + output_dir: Path backend: str - is_main: bool plate_root: str sub_dir: str results_dir: str | None @classmethod - def primary( + @abstractmethod + def from_plan( cls, plan: CompiledStepPlan ) -> OpenHCSMetadataWriter.OutputTarget | None: - if plan.write_backend in [Backend.OMERO_LOCAL.value, Backend.MEMORY.value]: - return None - if plan.write_backend is None: - raise ValueError( - f"Step {plan.step_index} ({plan.step_name}) has no write backend." - ) - if plan.output_dir is None: - raise ValueError( - f"Step {plan.step_index} ({plan.step_name}) has no output directory." - ) - if plan.output_plate_root is None or plan.sub_dir is None: - raise ValueError( - f"Step {plan.step_index} ({plan.step_name}) has incomplete " - "OpenHCS metadata output identity." - ) - return cls( - output_dir=plan.output_dir, - backend=plan.write_backend, - is_main=True, - plate_root=plan.output_plate_root, - sub_dir=plan.sub_dir, - results_dir=plan.analysis_results_dir, + """Resolve this declaration's independently compiled storage target.""" + + @classmethod + def for_plan( + cls, plan: CompiledStepPlan + ) -> tuple[OpenHCSMetadataWriter.OutputTarget, ...]: + """Derive targets from their declarations, without a consumer roster.""" + return tuple( + target + for declaration in cls.__registry__.values() + if (target := declaration.from_plan(plan)) is not None ) @classmethod - def materialized( - cls, - plan: CompiledStepPlan, + def from_execution( + cls, context: ProcessingContext, plan: CompiledStepPlan ) -> OpenHCSMetadataWriter.OutputTarget | None: - materialized_output = plan.materialized_output - if materialized_output is None: - return None - if materialized_output.backend in [ - Backend.OMERO_LOCAL.value, - Backend.MEMORY.value, - ]: - return None - return cls( - output_dir=materialized_output.output_dir, - backend=materialized_output.backend, - is_main=False, - plate_root=materialized_output.plate_root, - sub_dir=materialized_output.sub_dir, - results_dir=materialized_output.analysis_results_dir, + """Resolve the target participating in this step's publication.""" + return cls.from_plan(plan) + + @classmethod + def for_execution( + cls, context: ProcessingContext, plan: CompiledStepPlan + ) -> tuple[OpenHCSMetadataWriter.OutputTarget, ...]: + return tuple( + target + for declaration in cls.__registry__.values() + if (target := declaration.from_execution(context, plan)) is not None ) + def produced_records( + self, context: ProcessingContext, plan: CompiledStepPlan + ) -> tuple[ProducedOutputSemantics, ...]: + """Targets without main-flow image storage have no produced records.""" + return () + + def runtime_artifact_projection_paths( + self, context: ProcessingContext, plan: CompiledStepPlan + ) -> tuple[tuple[SourceArtifactProjection, str], ...]: + """Only runtime-artifact targets own persisted artifact projections.""" + return () + def contains_images(self, context: ProcessingContext) -> bool: """Return whether the completed target contains image outputs.""" @@ -754,11 +762,15 @@ def write( if context.filemanager is None: raise ValueError("OpenHCS metadata requires a file manager.") if context.metadata_cache is None: - raise ValueError("Produced metadata requires declared component labels.") + raise ValueError( + "Produced metadata requires declared component labels." + ) structured_metadata = self.produced_projection_metadata( context, produced_plan ) - parser_context = FunctionOutputParserContext.from_processing_context(context) + parser_context = FunctionOutputParserContext.from_processing_context( + context + ) saved_image_paths = tuple( str(Path(path).relative_to(self.plate_root)) for path in context.filemanager.list_image_files( @@ -789,16 +801,12 @@ def produced_projection_metadata( return None # Plate reconciliation must not reload cleaned step memory. if context.filemanager is None: raise ValueError("OpenHCS metadata requires a file manager.") - target = self.primary(plan) if self.is_main else self.materialized(plan) + target = type(self).from_plan(plan) if target != self: raise ValueError( "Produced metadata plan does not own this output target." ) - records = tuple( - record - for record in step_output_manifest(context).produced_records_for(plan) - if record.is_image_payload - ) + records = self.produced_records(context, plan) payloads = ( context.filemanager.load_batch( [ @@ -876,26 +884,13 @@ def produced_projection_metadata( projection_paths=tuple(projection_paths), ) - def runtime_artifact_projection_paths( + def project_runtime_artifacts( self, context: ProcessingContext, plan: CompiledStepPlan, ) -> tuple[tuple[SourceArtifactProjection, str], ...]: """Project persisted image artifacts into the target source authority.""" - if not plan.runtime_artifact_materialization.has_persistent_target: - return () - artifact_target = self.materialized(plan) or self.primary(plan) - if artifact_target != self: - return () - if ( - plan.runtime_artifact_materialization.require_persistent_backend() - != self.backend - ): - raise ValueError( - "Runtime artifact backend does not match its materialized " - "metadata target." - ) projection_paths = [] for materialization in runtime_artifact_materializations(plan, context): if ( @@ -991,13 +986,8 @@ def write( context: ProcessingContext, plan: CompiledStepPlan, ) -> None: - if not plan.create_openhcs_metadata: - for target in ( - cls.OutputTarget.primary(plan), - cls.OutputTarget.materialized(plan), - ): - if target is None: - continue + for target in cls.OutputTarget.for_execution(context, plan): + if not plan.create_openhcs_metadata: structured_metadata = target.produced_projection_metadata(context, plan) if structured_metadata is None: continue @@ -1006,9 +996,8 @@ def write( target.sub_dir, structured_metadata, ) - return - cls.write_primary_metadata(context, plan) - cls.write_materialized_metadata(context, plan) + else: + target.write(context, produced_plan=plan) @classmethod def finalize_completed_plate( @@ -1024,38 +1013,122 @@ def finalize_completed_plate( for plan in context.step_plans.values(): if not plan.create_openhcs_metadata: continue - for target in ( - cls.OutputTarget.primary(plan), - cls.OutputTarget.materialized(plan), - ): - if target is not None: - target_contexts.setdefault(target, context) + for target in cls.OutputTarget.for_plan(plan): + target_contexts.setdefault(target, context) for target, context in target_contexts.items(): if target.contains_images(context): target.write(context) - @staticmethod - def write_primary_metadata( - context: ProcessingContext, - plan: CompiledStepPlan, - ) -> None: + +class ProducedImageMetadataCapability: + """Main-flow and checkpoint targets share the typed image-record projection.""" + + def produced_records( + self, context: ProcessingContext, plan: CompiledStepPlan + ) -> tuple[ProducedOutputSemantics, ...]: + return tuple( + record + for record in step_output_manifest(context).produced_records_for(plan) + if record.is_image_payload + ) + + +class PrimaryImageMetadataTarget( + ProducedImageMetadataCapability, OpenHCSMetadataWriter.OutputTarget +): + """The persistent main-flow image directory owns primary plate identity.""" + + is_main = True + + @classmethod + def from_execution( + cls, context: ProcessingContext, plan: CompiledStepPlan + ) -> PrimaryImageMetadataTarget | None: if not ProducedMemoryPathsAuthority.paths(context, plan): - return - target = OpenHCSMetadataWriter.OutputTarget.primary(plan) - if target is None: - return - target.write(context, produced_plan=plan) + return None + return cls.from_plan(plan) - @staticmethod - def write_materialized_metadata( - context: ProcessingContext, - plan: CompiledStepPlan, - ) -> None: - target = OpenHCSMetadataWriter.OutputTarget.materialized(plan) - if target is None: - return - target.write(context, produced_plan=plan) + @classmethod + def from_plan(cls, plan: CompiledStepPlan) -> PrimaryImageMetadataTarget | None: + if plan.write_backend in (Backend.OMERO_LOCAL.value, Backend.MEMORY.value): + return None + if plan.write_backend is None: + raise ValueError( + f"Step {plan.step_index} ({plan.step_name}) has no write backend." + ) + if plan.output_dir is None: + raise ValueError( + f"Step {plan.step_index} ({plan.step_name}) has no output directory." + ) + if plan.output_plate_root is None or plan.sub_dir is None: + raise ValueError( + f"Step {plan.step_index} ({plan.step_name}) has incomplete " + "OpenHCS metadata output identity." + ) + return cls( + output_dir=plan.output_dir, + backend=plan.write_backend, + plate_root=plan.output_plate_root, + sub_dir=plan.sub_dir, + results_dir=plan.analysis_results_dir, + ) + + +class MaterializedImageMetadataTarget( + ProducedImageMetadataCapability, OpenHCSMetadataWriter.OutputTarget +): + """Explicit main-flow checkpoints retain their own compiled storage identity.""" + + @classmethod + def from_plan( + cls, plan: CompiledStepPlan + ) -> MaterializedImageMetadataTarget | None: + output = plan.materialized_output + if output is None or output.backend in ( + Backend.OMERO_LOCAL.value, + Backend.MEMORY.value, + ): + return None + return cls( + output_dir=output.output_dir, + backend=output.backend, + plate_root=output.plate_root, + sub_dir=output.sub_dir, + results_dir=output.analysis_results_dir, + ) + + +class RuntimeArtifactMetadataTarget(OpenHCSMetadataWriter.OutputTarget): + """Image artifacts persist independently of main-flow image/checkpoint storage.""" + + @classmethod + def from_plan(cls, plan: CompiledStepPlan) -> RuntimeArtifactMetadataTarget | None: + materialization = plan.runtime_artifact_materialization + if not materialization.has_persistent_target: + return None + output_dir = plan.artifact_analysis_output_dir + plate_root = ( + plan.materialized_output.plate_root + if plan.materialized_output is not None + else plan.output_plate_root + ) + if plate_root is None: + raise ValueError( + "Persistent image artifacts require a compiled output plate root." + ) + return cls( + output_dir=output_dir, + backend=materialization.require_persistent_backend(), + plate_root=plate_root, + sub_dir=str(output_dir.relative_to(plate_root)), + results_dir=None, + ) + + def runtime_artifact_projection_paths( + self, context: ProcessingContext, plan: CompiledStepPlan + ) -> tuple[tuple[SourceArtifactProjection, str], ...]: + return self.project_runtime_artifacts(context, plan) class RuntimeArtifactMaterializationAuthority: diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index 352abb8d0f..eb48e67859 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -18,38 +18,66 @@ def _field(empty=False): return np.zeros_like(image) if empty else image -@pytest.mark.parametrize("mode", ["empty", "disabled", "watershed-disabled", "intensity", "shape"]) +@pytest.mark.parametrize( + "mode", ["empty", "disabled", "watershed-disabled", "intensity", "shape"] +) def test_real_registered_ipo_returns_same_run_stage_pixels(mode): from openhcs.core.config import DtypeConfig from openhcs.core.runtime_image_values import image_payload_data from openhcs.interop.cellprofiler.module_declarations import CellProfilerModule - from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import PrimaryObjectDiagnosticPlanes - from openhcs.processing.backends.cellprofiler.primary_objects import UnclumpMethod, WatershedMethod from openhcs.processing.backends.cellprofiler.morphology import FillHolesOption - from openhcs.processing.backends.cellprofiler.thresholding import CellProfilerThresholdMethod + from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import ( + PrimaryObjectDiagnosticPlanes, + ) + from openhcs.processing.backends.cellprofiler.primary_objects import ( + UnclumpMethod, + WatershedMethod, + ) + from openhcs.processing.backends.cellprofiler.thresholding import ( + CellProfilerThresholdMethod, + ) image = _field(mode == "empty") - method = UnclumpMethod.NONE if mode == "disabled" else ( - UnclumpMethod.SHAPE if mode == "shape" else UnclumpMethod.INTENSITY + method = ( + UnclumpMethod.NONE + if mode == "disabled" + else (UnclumpMethod.SHAPE if mode == "shape" else UnclumpMethod.INTENSITY) ) - func = CellProfilerModule.require_module("IdentifyPrimaryObjects").require_callable() + func = CellProfilerModule.require_module( + "IdentifyPrimaryObjects" + ).require_callable() original, measurements, objects, *planes = func( - image, min_diameter=2, max_diameter=20, - exclude_size=False, exclude_border_objects=False, + image, + min_diameter=2, + max_diameter=20, + exclude_size=False, + exclude_border_objects=False, unclump_method=method, - watershed_method=(WatershedMethod.NONE if mode == "watershed-disabled" - else WatershedMethod.INTENSITY), - threshold_method=CellProfilerThresholdMethod.MANUAL, manual_threshold=0.2, - threshold_smoothing_scale=0.0, fill_holes=FillHolesOption.NEVER, - automatic_smoothing=False, smoothing_filter_size=1, - automatic_suppression=False, maxima_suppression_size=2, - low_res_maxima=False, dtype_config=DtypeConfig(), + watershed_method=( + WatershedMethod.NONE + if mode == "watershed-disabled" + else WatershedMethod.INTENSITY + ), + threshold_method=CellProfilerThresholdMethod.MANUAL, + manual_threshold=0.2, + threshold_smoothing_scale=0.0, + fill_holes=FillHolesOption.NEVER, + automatic_smoothing=False, + smoothing_filter_size=1, + automatic_suppression=False, + maxima_suppression_size=2, + low_res_maxima=False, + dtype_config=DtypeConfig(), ) diagnostics = PrimaryObjectDiagnosticPlanes(*planes) np.testing.assert_array_equal(image_payload_data(original), image) np.testing.assert_array_equal(diagnostics.threshold_support.data, image > 0.2) - np.testing.assert_array_equal(diagnostics.unedited_objects.data, objects.unedited_labels) - np.testing.assert_array_equal(diagnostics.small_removed_objects.data, objects.small_removed_labels) + np.testing.assert_array_equal( + diagnostics.unedited_objects.data, objects.unedited_labels + ) + np.testing.assert_array_equal( + diagnostics.small_removed_objects.data, objects.small_removed_labels + ) assert measurements.row_count() > 0 if mode in ("empty", "disabled", "watershed-disabled"): assert not diagnostics.declump_response.mask.any() @@ -58,49 +86,96 @@ def test_real_registered_ipo_returns_same_run_stage_pixels(mode): else: assert diagnostics.declump_response.mask.all() assert diagnostics.seed_markers.data.max() > 0 - np.testing.assert_array_equal(diagnostics.seed_markers.data > 0, diagnostics.seed_maxima.data) + np.testing.assert_array_equal( + diagnostics.seed_markers.data > 0, diagnostics.seed_maxima.data + ) if mode == "empty": assert not objects.labels.any() -def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_binding(tmp_path): +def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_binding( + tmp_path, +): + import json + import tifffile - from openhcs.processing.materialization.core import MaterializationInput + from openhcs.agent.services.execution_session_service import ( - AgentProgressQueue, CompileInspectionInput, InProcessCompileInspectionGateway, + AgentProgressQueue, + CompileInspectionInput, + InProcessCompileInspectionGateway, ) from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents from openhcs.constants.input_source import InputSource - from openhcs.core.artifacts import ArtifactInputPlan, ArtifactOutputPlan, ImageArtifactType, ObjectLabelsArtifactType - from openhcs.core.config import GlobalPipelineConfig, LazyProcessingConfig, LazySourceBindingsConfig, PipelineConfig + from openhcs.core.artifacts import ( + ArtifactInputPlan, + ArtifactOutputPlan, + ImageArtifactType, + ObjectLabelsArtifactType, + ) + from openhcs.core.config import ( + GlobalPipelineConfig, + LazyProcessingConfig, + LazySourceBindingsConfig, + PipelineConfig, + ) from openhcs.core.orchestrator.execution_result import RuntimeObservationMode from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator from openhcs.core.pipeline_document import PipelineDocumentAuthority - from openhcs.core.runtime_image_values import image_payload_data, image_payload_metadata + from openhcs.core.runtime_image_values import ( + image_payload_metadata, + ) from openhcs.core.runtime_object_labels import object_label_dense_array from openhcs.core.source_bindings import ( - ComponentSelector, NamedSourceBinding, SourceFilterClause, SourceFilterMatchType, - SourceFilterSubject, SourceSelector, StepSourceBindingsConfig, + ComponentSelector, + NamedSourceBinding, + SourceFilterClause, + SourceFilterMatchType, + SourceFilterSubject, + SourceSelector, + StepSourceBindingsConfig, ) + from openhcs.core.source_image_provenance import SourceImageProvenance + from openhcs.core.steps.function_outputs import OpenHCSMetadataWriter from openhcs.core.steps.function_step import FunctionStep + from openhcs.core.virtual_workspace_metadata import ( + FIELDS, + METADATA_CONFIG, + VirtualWorkspaceSourceProjectionEntries, + ) + from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import ( + PrimaryObjectDiagnosticPlanes, + ) from openhcs.processing.backends.cellprofiler.primary_objects import ( - IdentifyPrimaryObjectsModule, UnclumpMethod, WatershedMethod, identify_primary_objects, + IdentifyPrimaryObjectsModule, + UnclumpMethod, + WatershedMethod, + identify_primary_objects, ) - from openhcs.processing.backends.cellprofiler.primary_object_diagnostics import PrimaryObjectDiagnosticPlanes from openhcs.processing.backends.cellprofiler.secondary import ( - IdentifySecondaryObjectsModule, SecondaryMethod, identify_secondary_objects, + IdentifySecondaryObjectsModule, + SecondaryMethod, + identify_secondary_objects, ) - from openhcs.processing.backends.cellprofiler.thresholding import CellProfilerThresholdMethod + from openhcs.processing.backends.cellprofiler.thresholding import ( + CellProfilerThresholdMethod, + ) + from openhcs.processing.materialization.core import MaterializationInput + from openhcs.serialization.json import to_jsonable def binding(module, plan_type, artifact_type): - (declared,) = module.declared_artifact_bindings(plan_type=plan_type, artifact_type=artifact_type) + (declared,) = module.declared_artifact_bindings( + plan_type=plan_type, artifact_type=artifact_type + ) return declared.require_parameter_name() def step(func, name, kwargs): return FunctionStep( - func=(func, kwargs), name=name, + func=(func, kwargs), + name=name, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.SITE], group_by=GroupBy.NONE, + variable_components=[VariableComponents.SITE], + group_by=GroupBy.NONE, input_source=InputSource.PIPELINE_START, ), source_bindings=StepSourceBindingsConfig(enabled=True), @@ -108,54 +183,124 @@ def step(func, name, kwargs): image = _field() tifffile.imwrite(tmp_path / "A01_s001_DNA.tif", image) - primary = step(identify_primary_objects, "Primary", { - binding(IdentifyPrimaryObjectsModule, ArtifactInputPlan, ImageArtifactType): "DNA", - binding(IdentifyPrimaryObjectsModule, ArtifactOutputPlan, ObjectLabelsArtifactType): "Nuclei", - "exclude_size": False, "exclude_border_objects": False, - "min_diameter": 2, "max_diameter": 20, - "unclump_method": UnclumpMethod.INTENSITY, - "watershed_method": WatershedMethod.INTENSITY, - "threshold_method": CellProfilerThresholdMethod.MANUAL, - "manual_threshold": 0.2, "threshold_smoothing_scale": 0.0, - }) - secondary = step(identify_secondary_objects, "Secondary", { - binding(IdentifySecondaryObjectsModule, ArtifactInputPlan, ImageArtifactType): "DNA", - binding(IdentifySecondaryObjectsModule, ArtifactInputPlan, ObjectLabelsArtifactType): "Nuclei", - IdentifySecondaryObjectsModule.secondary_output_binding.require_parameter_name(): "Cells", - "method": SecondaryMethod.DISTANCE_N, "distance_to_dilate": 2, - }) + primary = step( + identify_primary_objects, + "Primary", + { + binding( + IdentifyPrimaryObjectsModule, ArtifactInputPlan, ImageArtifactType + ): "DNA", + binding( + IdentifyPrimaryObjectsModule, + ArtifactOutputPlan, + ObjectLabelsArtifactType, + ): "Nuclei", + "exclude_size": False, + "exclude_border_objects": False, + "min_diameter": 2, + "max_diameter": 20, + "unclump_method": UnclumpMethod.INTENSITY, + "watershed_method": WatershedMethod.INTENSITY, + "threshold_method": CellProfilerThresholdMethod.MANUAL, + "manual_threshold": 0.2, + "threshold_smoothing_scale": 0.0, + }, + ) + secondary = step( + identify_secondary_objects, + "Secondary", + { + binding( + IdentifySecondaryObjectsModule, ArtifactInputPlan, ImageArtifactType + ): "DNA", + binding( + IdentifySecondaryObjectsModule, + ArtifactInputPlan, + ObjectLabelsArtifactType, + ): "Nuclei", + IdentifySecondaryObjectsModule.secondary_output_binding.require_parameter_name(): "Cells", + "method": SecondaryMethod.DISTANCE_N, + "distance_to_dilate": 2, + }, + ) document = PipelineDocumentAuthority.from_values( pipeline_config=PipelineConfig( microscope=Microscope.SOURCE_BINDINGS, - source_bindings_config=LazySourceBindingsConfig(bindings=(NamedSourceBinding( - alias="DNA", selector=SourceSelector(filters=(SourceFilterClause( - subject=SourceFilterSubject.FILE, match_type=SourceFilterMatchType.CONTAINS, - value="DNA", - ),)), component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), - ),)), - ), pipeline_steps=[primary, secondary], - ) - document = PipelineDocumentAuthority.from_source(PipelineDocumentAuthority.render(document)) - bundle = InProcessCompileInspectionGateway().compile(CompileInspectionInput( - plate=tmp_path, pipeline_document=document, axis_filter=("A01",), - global_pipeline_config=GlobalPipelineConfig(num_workers=1, use_threading=True), - progress_queue=AgentProgressQueue(), - )).execution_bundle + source_bindings_config=LazySourceBindingsConfig( + bindings=( + NamedSourceBinding( + alias="DNA", + selector=SourceSelector( + filters=( + SourceFilterClause( + subject=SourceFilterSubject.FILE, + match_type=SourceFilterMatchType.CONTAINS, + value="DNA", + ), + ) + ), + component_identity=( + ComponentSelector(AllComponents.CHANNEL, "1"), + ), + ), + ) + ), + ), + pipeline_steps=[primary, secondary], + ) + document = PipelineDocumentAuthority.from_source( + PipelineDocumentAuthority.render(document) + ) + bundle = ( + InProcessCompileInspectionGateway() + .compile( + CompileInspectionInput( + plate=tmp_path, + pipeline_document=document, + axis_filter=("A01",), + global_pipeline_config=GlobalPipelineConfig( + num_workers=1, use_threading=True + ), + progress_queue=AgentProgressQueue(), + ) + ) + .execution_bundle + ) context = bundle.runtime_contexts["A01"] - primary_invocation = next(context.step_plans[0].compiled_function_pattern.iter_invocations()) - secondary_invocation = next(context.step_plans[1].compiled_function_pattern.iter_invocations()) - (edge,) = (edge for edge in secondary_invocation.artifact_input_edges - if edge.spec.artifact_type is ObjectLabelsArtifactType) + primary_invocation = next( + context.step_plans[0].compiled_function_pattern.iter_invocations() + ) + secondary_invocation = next( + context.step_plans[1].compiled_function_pattern.iter_invocations() + ) + (edge,) = ( + edge + for edge in secondary_invocation.artifact_input_edges + if edge.spec.artifact_type is ObjectLabelsArtifactType + ) assert edge.spec.name == "Nuclei" assert edge.storage_plan.source_step_id == 0 - assert len(primary_invocation.contract.artifact_outputs.of_artifact_type(ObjectLabelsArtifactType)) == 1 + assert ( + len( + primary_invocation.contract.artifact_outputs.of_artifact_type( + ObjectLabelsArtifactType + ) + ) + == 1 + ) - orchestrator = PipelineOrchestrator(tmp_path, pipeline_config=document.pipeline_config).initialize() + orchestrator = PipelineOrchestrator( + tmp_path, pipeline_config=document.pipeline_config + ).initialize() results = orchestrator.execute_compiled_plate( - execution_bundle=bundle, max_workers=1, + execution_bundle=bundle, + max_workers=1, runtime_observation_mode=RuntimeObservationMode.MERGE_INTO_PARENT, - progress_queue=AgentProgressQueue(), progress_context={ - "execution_id": "primary-diagnostics-synthetic", "plate_id": str(tmp_path), "axis_id": "", + progress_queue=AgentProgressQueue(), + progress_context={ + "execution_id": "primary-diagnostics-synthetic", + "plate_id": str(tmp_path), + "axis_id": "", }, ) assert results["A01"].is_success(), results["A01"].error_message @@ -163,20 +308,30 @@ def step(func, name, kwargs): (primary_record,) = store.find(name="Nuclei", axis_id="A01") (secondary_record,) = store.find(name="Cells", axis_id="A01") source_metadata = primary_record.value.data.metadata - assert np.count_nonzero(object_label_dense_array(secondary_record.value.data)) >= np.count_nonzero( - object_label_dense_array(primary_record.value.data)) > 0 + assert ( + np.count_nonzero(object_label_dense_array(secondary_record.value.data)) + >= np.count_nonzero(object_label_dense_array(primary_record.value.data)) + > 0 + ) primary_labels = object_label_dense_array(primary_record.value.data) secondary_labels = object_label_dense_array(secondary_record.value.data) - np.testing.assert_array_equal(np.unique(primary_labels), np.unique(secondary_labels)) + np.testing.assert_array_equal( + np.unique(primary_labels), np.unique(secondary_labels) + ) np.testing.assert_array_equal( secondary_labels[primary_labels > 0], primary_labels[primary_labels > 0] ) - diagnostic_specs = tuple(spec for spec in primary_invocation.contract.artifact_outputs - if spec.sidecar_role is not None) + diagnostic_specs = tuple( + spec + for spec in primary_invocation.contract.artifact_outputs + if spec.sidecar_role is not None + ) assert len(diagnostic_specs) == len(PrimaryObjectDiagnosticPlanes._fields) persisted = [] for spec in diagnostic_specs: - (record,) = store.find(name=spec.name, artifact_type=ImageArtifactType, axis_id="A01") + (record,) = store.find( + name=spec.name, artifact_type=ImageArtifactType, axis_id="A01" + ) (saved_path,) = context.step_plans[0].artifact_analysis_output_dir.glob( f"*_{spec.name}_step0.tif" ) @@ -184,9 +339,7 @@ def step(func, name, kwargs): (plane,) = MaterializationInput.from_runtime_slice_projected_value( record.value.data, options ).items - np.testing.assert_array_equal( - tifffile.imread(saved_path), plane.data - ) + np.testing.assert_array_equal(tifffile.imread(saved_path), plane.data) metadata = image_payload_metadata(record.value.data) # Sidecars have their own runtime alias, retaining the same source # address and pixel contributors as the primary object payload. @@ -198,5 +351,53 @@ def step(func, name, kwargs): ) persisted.append(record.value.data) diagnostics = PrimaryObjectDiagnosticPlanes(*persisted) - np.testing.assert_array_equal(diagnostics.unedited_objects.data, primary_record.value.data.unedited_labels) - np.testing.assert_array_equal(diagnostics.small_removed_objects.data, primary_record.value.data.small_removed_labels) + np.testing.assert_array_equal( + diagnostics.unedited_objects.data, primary_record.value.data.unedited_labels + ) + np.testing.assert_array_equal( + diagnostics.small_removed_objects.data, + primary_record.value.data.small_removed_labels, + ) + + # A memory-backed first step still owns persistent image artifacts. Later + # steps and reconciliation must retain their durable reopening authority. + primary_plan = context.step_plans[0] + assert primary_plan.write_backend == "memory" + assert primary_plan.materialized_output is None + OpenHCSMetadataWriter.finalize_completed_plate(bundle.runtime_contexts) + metadata_path = METADATA_CONFIG.metadata_path(primary_plan.output_plate_root) + metadata_document = json.loads(metadata_path.read_text()) + persisted_source_provenance = SourceImageProvenance.from_mapping( + json.loads(json.dumps(to_jsonable(source_metadata.source_provenance))) + ) + entries = { + path: projection + for subdirectory in metadata_document[FIELDS.SUBDIRECTORIES].values() + for path, projection in VirtualWorkspaceSourceProjectionEntries.from_subdirectory( + subdirectory + ).entries.items() + } + for spec in diagnostic_specs: + (saved_path,) = primary_plan.artifact_analysis_output_dir.glob( + f"*_{spec.name}_step0.tif" + ) + relative_path = str(saved_path.relative_to(primary_plan.output_plate_root)) + projection = entries[relative_path] + assert projection.source_alias == spec.name + assert projection.artifact_kind is ImageArtifactType + assert projection.image_metadata is not None + assert projection.image_metadata.source_dtype == str( + tifffile.imread(saved_path).dtype + ) + assert projection.image_metadata.source_provenance.scalar_source_identity == ( + persisted_source_provenance.scalar_source_identity + ) + for alias, plan in (("Nuclei", primary_plan), ("Cells", context.step_plans[1])): + (saved_path,) = plan.artifact_analysis_output_dir.glob( + f"*_{alias}_step*.labels.tif" + ) + projection = entries[ + str(saved_path.relative_to(primary_plan.output_plate_root)) + ] + assert projection.source_alias == alias + assert projection.artifact_kind is ObjectLabelsArtifactType diff --git a/tests/unit/test_function_outputs.py b/tests/unit/test_function_outputs.py index 97051b212e..88d9d747a1 100644 --- a/tests/unit/test_function_outputs.py +++ b/tests/unit/test_function_outputs.py @@ -69,6 +69,7 @@ OpenHCSMetadataWriter, ProducedMemoryPathsAuthority, RuntimeArtifactMaterializationAuthority, + RuntimeArtifactMetadataTarget, StreamOutputsAuthority, finalize_function_step_outputs, ) @@ -1362,6 +1363,33 @@ def test_image_persistence_skips_object_label_main_flow_payloads(): assert ProducedMemoryPathsAuthority.paths(context, plan) == [] +def test_metadata_target_family_discovers_new_declaration_without_consumer_edits(tmp_path): + registry = OpenHCSMetadataWriter.OutputTarget.__registry__ + original_keys = set(registry) + try: + class SupplementalImageMetadataTarget(OpenHCSMetadataWriter.OutputTarget): + @classmethod + def from_plan(cls, plan): + return cls( + output_dir=tmp_path, + backend=Backend.DISK.value, + plate_root=str(tmp_path), + sub_dir="supplemental", + results_dir=None, + ) + + plan = function_step_plan("memory-only") + plan.write_backend = Backend.MEMORY.value + context = context_stub(FileManagerStub({})) + (target,) = OpenHCSMetadataWriter.OutputTarget.for_plan(plan) + assert type(target) is SupplementalImageMetadataTarget + assert OpenHCSMetadataWriter.OutputTarget.for_execution(context, plan) == (target,) + assert target.produced_projection_metadata(context, plan) is None + finally: + for key in set(registry) - original_keys: + del registry[key] + + def test_metadata_writer_skips_owner_without_image_outputs(): path = "/tmp/output/A01_s1_w1.tif" filemanager = FileManagerStub({path: object()}) @@ -1607,7 +1635,7 @@ def test_runtime_image_artifact_projects_persisted_source_binding( lambda _plan, _context: (materialization,), ) - target = OpenHCSMetadataWriter.OutputTarget.materialized(plan) + target = RuntimeArtifactMetadataTarget.from_plan(plan) assert target is not None [(projection, virtual_path)] = target.runtime_artifact_projection_paths( context, plan @@ -1720,7 +1748,7 @@ def test_runtime_multiplane_label_artifact_projects_persisted_source_binding( lambda _plan, _context: (materialization,), ) - target = OpenHCSMetadataWriter.OutputTarget.materialized(plan) + target = RuntimeArtifactMetadataTarget.from_plan(plan) assert target is not None [(projection, virtual_path)] = target.runtime_artifact_projection_paths( context, plan From 2ae8f0b95e11255fddceea28389593d4dc759b47 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 12:58:42 -0400 Subject: [PATCH 8/9] Retain canonical image bindings when reopening persisted result artifacts --- ...mary_diagnostics_current_main_20260930.rst | 32 +++++++++++++++++ openhcs/core/compiled_step_plan.py | 12 +++++++ openhcs/core/plate_image_inventory.py | 31 +++++++++++----- openhcs/core/steps/function_outputs.py | 10 +----- openhcs/microscopes/microscope_interfaces.py | 35 ++++++++++++++++++- openhcs/microscopes/openhcs.py | 31 +++++++--------- ...rimary_segmentation_diagnostics_journey.py | 21 +++++++++++ tests/unit/test_plate_image_inventory.py | 16 +++++++++ 8 files changed, 150 insertions(+), 38 deletions(-) diff --git a/docs/validation/primary_diagnostics_current_main_20260930.rst b/docs/validation/primary_diagnostics_current_main_20260930.rst index 668552dda8..3beee30d96 100644 --- a/docs/validation/primary_diagnostics_current_main_20260930.rst +++ b/docs/validation/primary_diagnostics_current_main_20260930.rst @@ -135,3 +135,35 @@ The parent owns this same PR215 and issue214, with no competing implementation. Complete the affected installed path before merge; do not wait for optional CI. The frozen scientific abstention, held-out boundary and full ZIP scope remain unchanged. Owner clarification:20GiB is a warning margin, not a hard disk limit. + +Result inventory continuation +---------------------------- + +Installed candidatecba1c90df with the75-case metadata fix still failed diagnostic +reopening. The exact native viewer rejection was ``No component metadata +available for path``. Its full log and terminal transcript are retained at +primary-diagnostics-viewer-reopen-20260930; viewer/MCP were explicitly closed, +the shell exited1, and ports5992/6792/6992 and validation.lock were freed. +An attempted capture_scope=canvas was rejected at the boundary, so no bitmap +inspection is claimed for that attempt. + +The result-directory owner now carries its existing typed source authority +from OpenHCSMetadataHandler through PlateResultFileRecord to PlateFileRecord. +The canonical projection/ref and acquisition components survive selecting a +native TIFF as a result, not just as an image. Ordered inventory merging keeps +the handler declaration ahead of path-only duplicate discoveries. There is no +new JSON reader, filename-derived source identity or reconstructed source +receipt. Generic external result directories still have genuinely optional +source bindings; absence is handled by their nominal directory owner. + +The compiled plan owns artifact output plate-root resolution beside its two +existing artifact directory properties. This removes the newly introduced +foreign absence probe flagged by the original packaged ratchet. Its original +exit1 JSON remains preserved; no baseline or guard was weakened. + +Four focused target/compiled-root cases PASS1.40s. Expanded inventory/native +run97PASS/1FAIL20.84s: the new fixture used address.items instead of the declared +component_values().items accessor. The original failed XML is retained. Final +expanded run:98PASS18.82s. Directory existence/type admission is now owned by +AnalysisResultDirectory, rather than growing OpenHCSMetadataHandler. Its focused +guard and corrected installed viewer acceptance remain pending. diff --git a/openhcs/core/compiled_step_plan.py b/openhcs/core/compiled_step_plan.py index 3f6f4bc3ca..33fa62b487 100644 --- a/openhcs/core/compiled_step_plan.py +++ b/openhcs/core/compiled_step_plan.py @@ -445,6 +445,18 @@ def execution_group_value(self) -> str | None: component = self.execution_group_scope.component return None if component is None else component.value + @property + def artifact_output_plate_root(self) -> str: + """Resolve artifact plate identity alongside its compiled directories.""" + plate_root = self.output_plate_root + if self.materialized_output is not None: + plate_root = self.materialized_output.plate_root + if plate_root is None: + raise ValueError( + f"Step {self.step_index} ({self.step_name}) has no artifact output plate root." + ) + return plate_root + @property def artifact_analysis_output_dir(self) -> Path: output_dir = self.analysis_results_dir diff --git a/openhcs/core/plate_image_inventory.py b/openhcs/core/plate_image_inventory.py index b64bf7b0e8..9d65a9c9a5 100644 --- a/openhcs/core/plate_image_inventory.py +++ b/openhcs/core/plate_image_inventory.py @@ -322,6 +322,7 @@ class PlateResultFileRecord: file_format: FileFormat metadata: Mapping[str, JsonValue] = field(default_factory=dict) source_ref: SourcePixelRef | None = None + source_projection: "SourceProjection | None" = None @property def full_path_obj(self) -> Path: @@ -396,6 +397,7 @@ def from_result(cls, record: PlateResultFileRecord) -> "PlateFileRecord": full_path=record.full_path, file_format=record.file_format, source_ref=record.source_ref, + source_projection=record.source_projection, ) def matches(self, query: "PlateFileInventoryQuery") -> bool: @@ -781,9 +783,10 @@ def _merged( scanned_file_count = 0 for inventory in inventories: scanned_file_count += inventory.scanned_file_count - records_by_path.update( - (record.full_path, record) for record in inventory.records - ) + # The handler's declared inventory precedes path-only projections. + # Do not discard its typed source binding on duplicate discovery. + for record in inventory.records: + records_by_path.setdefault(record.full_path, record) return PlateResultFileInventory( plate_path=plate_path, records=tuple( @@ -892,6 +895,9 @@ def from_directory_files( if file_format is None: continue relative_path = file_path.relative_to(plate_path) + projection = result_directory.source_binding_for( + str(relative_path), str(file_path) + ) metadata: dict[str, JsonValue] = { "filename": str(relative_path), "type": file_format.name, @@ -900,7 +906,9 @@ def from_directory_files( "result_subdirectory": result_directory.subdirectory_name, "full_path": str(file_path), } - if parser is not None: + if projection is not None: + metadata.update(projection.source_metadata) + elif parser is not None: parsed = parser.parse_filename(file_path.name) if parsed: metadata.update(parsed.wire_mapping()) @@ -910,13 +918,18 @@ def from_directory_files( full_path=str(file_path), file_format=file_format, metadata=metadata, + source_projection=projection, source_ref=( - SourcePixelRef( - backend=Backend.DISK.value, - backend_address=str(file_path), + projection.ref + if projection is not None + else ( + SourcePixelRef( + backend=Backend.DISK.value, + backend_address=str(file_path), + ) + if ImageFileFormat.is_image_path(file_path) + else None ) - if ImageFileFormat.is_image_path(file_path) - else None ), ) ) diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index 085152b926..1fc608ad60 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -1108,15 +1108,7 @@ def from_plan(cls, plan: CompiledStepPlan) -> RuntimeArtifactMetadataTarget | No if not materialization.has_persistent_target: return None output_dir = plan.artifact_analysis_output_dir - plate_root = ( - plan.materialized_output.plate_root - if plan.materialized_output is not None - else plan.output_plate_root - ) - if plate_root is None: - raise ValueError( - "Persistent image artifacts require a compiled output plate root." - ) + plate_root = plan.artifact_output_plate_root return cls( output_dir=output_dir, backend=materialization.require_persistent_backend(), diff --git a/openhcs/microscopes/microscope_interfaces.py b/openhcs/microscopes/microscope_interfaces.py index de2d0121e9..f3b4bd702a 100644 --- a/openhcs/microscopes/microscope_interfaces.py +++ b/openhcs/microscopes/microscope_interfaces.py @@ -27,7 +27,10 @@ from polystore.filemanager import FileManager if TYPE_CHECKING: - from openhcs.core.source_projection import SourcePlaneDataset + from openhcs.core.source_projection import SourcePlaneDataset, SourceProjection + from openhcs.core.source_workspace_projection import ( + VirtualWorkspaceSourceProjection, + ) from openhcs.microscopes.openhcs import OpenHCSMetadata @@ -127,6 +130,36 @@ class AnalysisResultDirectory: subdirectory_name: str path: Path + source_projection: VirtualWorkspaceSourceProjection | None = None + + @classmethod + def from_declared_path( + cls, + subdirectory_name: str, + path: Path, + source_projection: VirtualWorkspaceSourceProjection | None = None, + ) -> AnalysisResultDirectory | None: + """Admit existing declared directories without inventing missing results.""" + if not path.exists(): + return None + if not path.is_dir(): + raise NotADirectoryError( + f"Analysis metadata subdirectory {subdirectory_name!r} " + f"declares a non-directory results path: {path}" + ) + return cls(subdirectory_name, path, source_projection) + + def source_binding_for( + self, virtual_path: str, full_path: str + ) -> SourceProjection | None: + """Resolve a file through this directory's metadata-owned source authority.""" + if self.source_projection is None: + return None + from openhcs.core.source_workspace_projection import VirtualWorkspacePathLookup + + return self.source_projection.source_projection_for( + VirtualWorkspacePathLookup.from_paths(virtual_path, full_path) + ) class MetadataArtifactProvider(ABC, metaclass=AutoRegisterMeta): diff --git a/openhcs/microscopes/openhcs.py b/openhcs/microscopes/openhcs.py index da4428de20..09f2b77e65 100644 --- a/openhcs/microscopes/openhcs.py +++ b/openhcs/microscopes/openhcs.py @@ -29,6 +29,7 @@ SourceComponentProjectionStrategy, SourceVoxelSpacing, ) +from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection from metaclass_registry import AutoRegisterMeta from polystore.exceptions import MetadataNotFoundError from polystore.filemanager import FileManager @@ -398,6 +399,11 @@ def analysis_result_directories( plate_root = Path(plate_path) metadata_document = self.load_metadata_document(plate_root) subdirectories = self._metadata_subdirectories(metadata_document, plate_root) + source_projection = ( + VirtualWorkspaceSourceProjection.from_openhcs_metadata_if_available( + plate_root, metadata_document + ) + ) result_directories = [] for subdirectory_name, subdirectory_data in subdirectories.items(): @@ -409,26 +415,13 @@ def analysis_result_directories( f"OpenHCS metadata subdirectory {subdirectory_name!r} " "results_dir must be a non-empty string when declared." ) - result_path = plate_root / result_dir_name - if not result_path.exists(): - logger.debug( - "OpenHCS metadata subdirectory %r declares missing results " - "directory %s; treating it as no result artifacts.", - subdirectory_name, - result_path, - ) - continue - if not result_path.is_dir(): - raise NotADirectoryError( - f"OpenHCS metadata subdirectory {subdirectory_name!r} " - f"declares a non-directory results path: {result_path}" - ) - result_directories.append( - AnalysisResultDirectory( - subdirectory_name=subdirectory_name, - path=result_path, - ) + result_directory = AnalysisResultDirectory.from_declared_path( + subdirectory_name=subdirectory_name, + path=plate_root / result_dir_name, + source_projection=source_projection, ) + if result_directory is not None: + result_directories.append(result_directory) return tuple(result_directories) def _metadata_projection( diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index eb48e67859..c73c3577a2 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -377,12 +377,33 @@ def step(func, name, kwargs): subdirectory ).entries.items() } + from openhcs.core.plate_image_inventory import ( + PlateFileRecord, + PlateResultFileInventory, + ) + from openhcs.microscopes.openhcs import OpenHCSMetadataHandler + + result_inventory = PlateResultFileInventory.from_handler_and_configured_output_root( + plate_path=metadata_path.parent, + metadata_handler=OpenHCSMetadataHandler(context.filemanager), + parser=context.microscope_handler.parser, + path_config=orchestrator.get_effective_config().path_planning_config, + ) + result_records = { + record.relative_path: PlateFileRecord.from_result(record) + for record in result_inventory.records + } for spec in diagnostic_specs: (saved_path,) = primary_plan.artifact_analysis_output_dir.glob( f"*_{spec.name}_step0.tif" ) relative_path = str(saved_path.relative_to(primary_plan.output_plate_root)) projection = entries[relative_path] + result_record = result_records[relative_path] + assert result_record.source_projection == projection + assert result_record.require_image_source_ref() == projection.ref + for component, value in projection.address.component_values().items(): + assert str(result_record.metadata[component.value]) == value assert projection.source_alias == spec.name assert projection.artifact_kind is ImageArtifactType assert projection.image_metadata is not None diff --git a/tests/unit/test_plate_image_inventory.py b/tests/unit/test_plate_image_inventory.py index 5fc0606800..fabf48fe17 100644 --- a/tests/unit/test_plate_image_inventory.py +++ b/tests/unit/test_plate_image_inventory.py @@ -30,6 +30,22 @@ from polystore.virtual_workspace import SourcePixelRef +@pytest.mark.parametrize("kind", ("absent", "file", "directory")) +def test_declared_result_directory_admits_only_existing_directories(tmp_path, kind): + path = tmp_path / "results" + if kind == "file": + path.write_bytes(b"not a directory") + with pytest.raises(NotADirectoryError, match="non-directory results path"): + AnalysisResultDirectory.from_declared_path("images", path) + elif kind == "directory": + path.mkdir() + assert AnalysisResultDirectory.from_declared_path("images", path) == ( + AnalysisResultDirectory("images", path) + ) + else: + assert AnalysisResultDirectory.from_declared_path("images", path) is None + + class _ImageBrowserOrchestrator: def __init__(self, plate_path: Path, microscope_handler, filemanager: FileManager): self.plate_path = plate_path From 47c2e8296e168d7346c29a912e983917f1914ef7 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 13:07:21 -0400 Subject: [PATCH 9/9] Record installed diagnostic reopening and latest-main integration acceptance --- ...mary_diagnostics_current_main_20260930.rst | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/validation/primary_diagnostics_current_main_20260930.rst b/docs/validation/primary_diagnostics_current_main_20260930.rst index 3beee30d96..6a65fd57b8 100644 --- a/docs/validation/primary_diagnostics_current_main_20260930.rst +++ b/docs/validation/primary_diagnostics_current_main_20260930.rst @@ -167,3 +167,31 @@ component_values().items accessor. The original failed XML is retained. Final expanded run:98PASS18.82s. Directory existence/type admission is now owned by AnalysisResultDirectory, rather than growing OpenHCSMetadataHandler. Its focused guard and corrected installed viewer acceptance remain pending. + +Installed live result +--------------------- + +Directory owner suite7PASS2.86s and explicit absent/file/directory guard3PASS1.92s. +Original packaged ratchet againstmain616 at2ae8f0b95:PASS5154 metrics, no positive +deltas, OpenHCSMetadataHandler excess reduced8. Original failed screen retained. + +Actual installed MCP at2ae8f0b95, ordinary editable imports with PYTHONPATH unset, +successfully reopened raw, threshold-support TIFF selected as result, and the +primary ROI archive on isolated:91/5992. Parent personally opened raw-only, +result-only, combined and diagnostic-only PNGs. All have nativecanvas953x470, +XY orientation, point[0,0,0,0,0,15,19]; camera center[0,15.5,19.5],zoom11.1625, +unit native scale and zero translation. Raw contrast approximately[0,.862224], +gamma1, stage[0,1]. Two ROI polygons align with bright/dim synthetic support; +the binary diagnostic shows their two foreground components. Technical +reopening/visibility/alignment PASS, not biological segmentation acceptance. +Full terminal inputs/responses, exact PNG hashes and evidence are retained in +the parent ledger's primary-diagnostics-viewer-binding-20260930/ACCEPTANCE.rst. +Explicit MCP close succeeded and the shell terminated normallyexit0. + +New main7b169084 SaveImages binding fix is normally integrated atd556afb8 in +the isolated source tree. No dependency gitlink changes or competing patch. +Latest-main combined suite171PASS22.22s, including the real compiled persistence +journey, inventory/streaming/metadata families and the updated function artifact +binding suite. Original packaged ratchet against7b169084:PASS5155 metrics, zero +positive deltas. Installed activation of this integrated source remains next; +the live result above specifically identifies2ae8, not unexecuted later code.