diff --git a/docs/validation/execution-axis-outcome1005/OWNER-CHECKPOINT.rst b/docs/validation/execution-axis-outcome1005/OWNER-CHECKPOINT.rst new file mode 100644 index 0000000000..40b6d7c3ba --- /dev/null +++ b/docs/validation/execution-axis-outcome1005/OWNER-CHECKPOINT.rst @@ -0,0 +1,90 @@ +Execution axis outcome and terminal status (#1005) +================================================= + +Source boundary +--------------- + +Reviewed main 4d8c9c1 and the immutable H003fresh26 receipt0134. +The receipt contains an ERROR axis, partial nuclei artifacts, and a COMPLETE +transport record. No original scientific execution was replayed. + +ExecutionResult owns each axis's status, error message and returned observations. +CompiledPlateExecutionResults owns the collection and parent diagnostics. +Previously four orchestration decisions independently recomputed aggregate +success. ZMQ ExecutionServer.run_execution independently treated normal return +from execute_task as success, without querying OpenHCS axis results. This is +IDEN-4 (completion name disagrees with outcome) and IMPL-5 (repeated decision). + +The collection now owns is_success and require_success. Orchestration consumes +is_success; the OpenHCS server consumes require_success after runtime exports. +The original ZMQ lifecycle handles the resulting exception and publishes FAILED. +No competing error flag, UI status, result store or protocol format is added. +Successful axes and partial artifacts remain intact. Compile-only bypasses the +execution aggregate, as before. Empty-result semantics remain unchanged. + +Consumer closure +---------------- + +Worker lanes return ExecutionResult values. Compiled plate execution derives +plate-step admission, viewer settling, progress success and orchestrator state +from the collection. The OpenHCS server exports observations before qualifying +terminal success. ZMQ lifecycle owns the terminal record; its status poller, +OpenHCS execution job service and GUI completion service consume that record. +Those views do not need local failed-axis overrides. + +The existing audit.measures.measure_source parsed 64 files in orchestrator, +runtime, progress and vendored ZMQ execution before edits, with zero omissions. +This is scoped AST evidence, not a completed global NRA proof. After migration, +the expanded family (including agent and actual pyqt_gui roots) parsed 215 files +with zero omissions. Source reads confirmed ExecutionJobRecord.status derives +status/errors from the terminal response; the GUI completion callback parses +that same terminal status into TerminalExecutionStatus.completion_payload. + +Crossings and acceptance +------------------------ + +#140 / draft PR160 addresses a fork-worker exception whose waiter did not +terminate. That documentation-only investigation is not this implementation. +Both share the existing lifecycle publication path; no lifecycle source is +changed here. PR981 Gaussian axes and PR1004 neurite rooting are disjoint. +Planck explicitly confirmed no outcome/status claim on #1005. + +The initial source pytest collection could not import TiffPhotometric from the +foreign PolyStore checkout. The reused interpreter's baseline installed wheel +also lacks it. Neither package nor dirty submodule has been changed. + +Focused checks passed 62 tests in 6.60 seconds using the existing receiving26 +dependency target and reused interpreter. Source package search includes this +branch; dependency imports use the qualified installed target, not the foreign +externals. Tests cover original server run_execution and terminal publication +for failed/all-success aggregates, export ordering, and retained successful +axis results. Controlled worker responses are not installed public-MCP proof. + +Pending: a +distinct tiny registered public MCP failing-axis and all-success pair on an +owned reused engineering route coordinated with Dewey. Original science, +UNKNOWN inputs and active blind-author packages remain untouched. Hosted CI +is deferred. Do not merge or close #1005 as live-verified yet. + +Installed acceptance preparation +-------------------------------- + +Dewey confirmed exact receiving26 native and MCP closure and released the :95 +engineering successor route. He owns one next ordinary candidate combining +published production1007 d89a114fe with final981 f9c09b3dd. This worker retains +source custody; no second client, server, environment or target mutation. + +The committed axis_outcome_probe1005.py source passes the existing custom +function syntax/import validator with no errors or warnings. Actual native +registration and reflected callable admission remain pending on that route. +mixed_axes_pipeline.py and all_success_pipeline.py are distinct documents: +both persist the first-step pixels, then only the mixed case rejects A02. +The callable observes pixel values, never filenames or scientific state. + +Generated once: /run/media/ts/hdd/openhcs-engineering/execution-axis1005-20261006/input. +Two 32x32 float32 planes, A01=0.2 and A02=0.8. Their TIFF hashes are +54fb29ebdff37c5c5b5fc71fb95b587afde1af79718c92c737cf01f4f4323342 and +43714da601538fd95515e0a9f32be1c06e792d39b9befb35488df7b4eebfceb4. +These tiny input files are owned retained acceptance evidence, not disposable +scientific scratch. Never rerun create_inputs.py over that existing directory. +No installed success/failure outcome is claimed by fixture validation. diff --git a/docs/validation/execution-axis-outcome1005/all_success_pipeline.py b/docs/validation/execution-axis-outcome1005/all_success_pipeline.py new file mode 100644 index 0000000000..24f7cc1579 --- /dev/null +++ b/docs/validation/execution-axis-outcome1005/all_success_pipeline.py @@ -0,0 +1,41 @@ +from pathlib import Path + +from openhcs.core.config import ( + LazyPathPlanningConfig, + LazySourceBindingsConfig, + LazyStepMaterializationConfig, + PipelineConfig, +) +from openhcs.core.source_bindings import ( + MetadataExtractionRule, + MetadataSource, + NamedSourceBinding, +) +from openhcs.core.steps.function_step import FunctionStep +from openhcs.processing.custom_functions.axis_outcome_probe1005 import axis_outcome_probe1005 + +pipeline_config = PipelineConfig( + num_workers=2, + source_bindings_config=LazySourceBindingsConfig( + bindings=(NamedSourceBinding(alias="ProbeImage"),), + metadata_rules=(MetadataExtractionRule( + source=MetadataSource.FILE_NAME, + pattern=r"probe_(?PA0[12])_s(?P1)_w(?P1)\.tif$", + ),), + ), + path_planning_config=LazyPathPlanningConfig( + global_output_folder=Path("/run/media/ts/hdd/openhcs-engineering/execution-axis1005-20261006/all-success"), + output_dir_suffix="_all_success", + ), +) +pipeline_steps = [ + FunctionStep( + name="PersistBeforeFailure", + func=(axis_outcome_probe1005, {"fail_above": 2.0}), + step_materialization_config=LazyStepMaterializationConfig(enabled=True), + ), + FunctionStep( + name="QualifySyntheticAxis", + func=(axis_outcome_probe1005, {"fail_above": 2.0}), + ), +] diff --git a/docs/validation/execution-axis-outcome1005/axis_outcome_probe1005.py b/docs/validation/execution-axis-outcome1005/axis_outcome_probe1005.py new file mode 100644 index 0000000000..d70464be8d --- /dev/null +++ b/docs/validation/execution-axis-outcome1005/axis_outcome_probe1005.py @@ -0,0 +1,13 @@ +"""Synthetic execution failure probe; no scientific data or external effects.""" + +import numpy as np + +from openhcs.core.memory import numpy + + +@numpy +def axis_outcome_probe1005(image, fail_above: float = 2.0): + """Preserve pixels, or fail deterministically for the high-valued axis.""" + if float(np.mean(image)) > fail_above: + raise RuntimeError("SYNTHETIC_AXIS_1005: high-valued axis rejected") + return image.copy() diff --git a/docs/validation/execution-axis-outcome1005/create_inputs.py b/docs/validation/execution-axis-outcome1005/create_inputs.py new file mode 100644 index 0000000000..9b8fe40dae --- /dev/null +++ b/docs/validation/execution-axis-outcome1005/create_inputs.py @@ -0,0 +1,27 @@ +"""Generate two tiny deterministic TIFF planes, never read scientific images.""" + +import hashlib +import json +from pathlib import Path + +import numpy as np +import tifffile + + +def main() -> None: + root = Path("/run/media/ts/hdd/openhcs-engineering/execution-axis1005-20261006/input") + root.mkdir(parents=True, exist_ok=False) + receipts = [] + for well, value in (("A01", 0.2), ("A02", 0.8)): + image = np.full((32, 32), value, dtype=np.float32) + path = root / f"probe_{well}_s1_w1.tif" + tifffile.imwrite(path, image, photometric="minisblack") + receipts.append({ + "path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "shape": list(image.shape), "dtype": str(image.dtype), "value": float(image[0, 0]), + }) + print(json.dumps(receipts, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/docs/validation/execution-axis-outcome1005/mixed_axes_pipeline.py b/docs/validation/execution-axis-outcome1005/mixed_axes_pipeline.py new file mode 100644 index 0000000000..7431ab33e6 --- /dev/null +++ b/docs/validation/execution-axis-outcome1005/mixed_axes_pipeline.py @@ -0,0 +1,41 @@ +from pathlib import Path + +from openhcs.core.config import ( + LazyPathPlanningConfig, + LazySourceBindingsConfig, + LazyStepMaterializationConfig, + PipelineConfig, +) +from openhcs.core.source_bindings import ( + MetadataExtractionRule, + MetadataSource, + NamedSourceBinding, +) +from openhcs.core.steps.function_step import FunctionStep +from openhcs.processing.custom_functions.axis_outcome_probe1005 import axis_outcome_probe1005 + +pipeline_config = PipelineConfig( + num_workers=2, + source_bindings_config=LazySourceBindingsConfig( + bindings=(NamedSourceBinding(alias="ProbeImage"),), + metadata_rules=(MetadataExtractionRule( + source=MetadataSource.FILE_NAME, + pattern=r"probe_(?PA0[12])_s(?P1)_w(?P1)\.tif$", + ),), + ), + path_planning_config=LazyPathPlanningConfig( + global_output_folder=Path("/run/media/ts/hdd/openhcs-engineering/execution-axis1005-20261006/mixed"), + output_dir_suffix="_mixed", + ), +) +pipeline_steps = [ + FunctionStep( + name="PersistBeforeFailure", + func=(axis_outcome_probe1005, {"fail_above": 2.0}), + step_materialization_config=LazyStepMaterializationConfig(enabled=True), + ), + FunctionStep( + name="QualifySyntheticAxis", + func=(axis_outcome_probe1005, {"fail_above": 0.5}), + ), +] diff --git a/openhcs/core/orchestrator/compiled_plate_execution.py b/openhcs/core/orchestrator/compiled_plate_execution.py index e530455c7f..a093ca3681 100644 --- a/openhcs/core/orchestrator/compiled_plate_execution.py +++ b/openhcs/core/orchestrator/compiled_plate_execution.py @@ -126,6 +126,20 @@ def __init__( viewer_states_by_port=MappingProxyType({}) ) + def is_success(self) -> bool: + """Whether every returned axis completed successfully.""" + return all(result.is_success() for result in self.values()) + + def require_success(self) -> None: + """Reject failed axes at terminal boundaries without dropping their outputs.""" + failures = [ + f"{axis_id}: {result.status.value}: {result.error_message or 'no error detail'}" + for axis_id, result in self.items() + if not result.is_success() + ] + if failures: + raise RuntimeError("Unsuccessful execution axes: " + "; ".join(failures)) + @property def runtime_observations(self) -> tuple[RuntimeExecutionObservation, ...]: return ( @@ -231,7 +245,7 @@ def execute_compiled_plate_request( execution_bundle = request.execution_bundle worker_assignments = request.worker_assignments_for() - execution_results: Dict[str, ExecutionResult] = {} + execution_results = CompiledPlateExecutionResults() plate_runtime_observation = RuntimeExecutionObservation() try: executor_resources.install_execution_bundle(execution_bundle) @@ -247,10 +261,12 @@ def execute_compiled_plate_request( request=request, worker_assignment_plan=worker_assignment_plan, ) - execution_results = executor_resources.run_worker_lanes( - pipeline_definition=validated.pipeline_definition, - worker_lane_execution_plan=worker_lane_execution_plan, - parent_contexts=validated.compiled_contexts, + execution_results = CompiledPlateExecutionResults( + executor_resources.run_worker_lanes( + pipeline_definition=validated.pipeline_definition, + worker_lane_execution_plan=worker_lane_execution_plan, + parent_contexts=validated.compiled_contexts, + ) ) if any(result.is_cancelled() for result in execution_results.values()): raise ExecutionCancelledError("Execution cancelled during worker execution") @@ -267,7 +283,7 @@ def execute_compiled_plate_request( executor_resources.clear_execution_bundle() executor_resources.release_parent_runtime_resources(execution_bundle) - if all(result.is_success() for result in execution_results.values()): + if execution_results.is_success(): plate_runtime_observation = execute_plate_scoped_steps( validated.compiled_contexts, progress_queue=validated.progress_queue, @@ -287,7 +303,7 @@ def execute_compiled_plate_request( ), ), ) - if all(result.is_success() for result in execution_results.values()): + if execution_results.is_success(): viewer_states_by_port = settle_viewer_state( visualizers, progress_queue=validated.progress_queue, @@ -296,7 +312,7 @@ def execute_compiled_plate_request( else: viewer_states_by_port = MappingProxyType({}) project_execution_state(orchestrator, execution_results) - if all(result.is_success() for result in execution_results.values()): + if execution_results.is_success(): _emit_execution_progress( progress_queue=validated.progress_queue, progress_context=validated, @@ -1191,11 +1207,11 @@ def stop_execution_visualizers(visualizers: list[ExecutionVisualizerABC]) -> Non def project_execution_state( orchestrator: "PipelineOrchestrator", - execution_results: Mapping[str, ExecutionResult], + execution_results: CompiledPlateExecutionResults, ) -> None: """Project worker-lane results back into orchestrator lifecycle state.""" - if all(result.is_success() for result in execution_results.values()): + if execution_results.is_success(): orchestrator._state = OrchestratorState.COMPLETED else: orchestrator._state = OrchestratorState.EXEC_FAILED diff --git a/openhcs/runtime/zmq_execution_server.py b/openhcs/runtime/zmq_execution_server.py index 7f01617fe8..4d635b0f8d 100644 --- a/openhcs/runtime/zmq_execution_server.py +++ b/openhcs/runtime/zmq_execution_server.py @@ -788,6 +788,7 @@ def _finish_compilation_or_execute( compilation=compilation, execution_results=execution_results, ) + execution_results.require_success() return execution_results def _export_runtime_observation( diff --git a/tests/unit/test_orchestrator_execution_result.py b/tests/unit/test_orchestrator_execution_result.py index 465670c00e..1e851e2ba6 100644 --- a/tests/unit/test_orchestrator_execution_result.py +++ b/tests/unit/test_orchestrator_execution_result.py @@ -3,6 +3,12 @@ import pickle from types import MappingProxyType +import pytest + +from openhcs.core.orchestrator.compiled_plate_execution import ( + CompiledPlateExecutionResults, +) + from openhcs.core.orchestrator.execution_result import ExecutionResult @@ -15,3 +21,22 @@ def test_execution_result_transport_preserves_mapping_proxy_metadata() -> None: assert restored["result"].is_success() assert restored["metadata"] == {"well": "W001"} assert isinstance(restored["metadata"], MappingProxyType) + + +@pytest.mark.parametrize("failed", [False, True]) +def test_plate_terminal_outcome_preserves_individual_axes(failed: bool) -> None: + successful = ExecutionResult.success("A01") + other = ( + ExecutionResult.error("A02", error_message="producer lineage missing") + if failed + else ExecutionResult.success("A02") + ) + results = CompiledPlateExecutionResults({"A01": successful, "A02": other}) + assert results.is_success() is not failed + if failed: + with pytest.raises(RuntimeError, match="A02: error: producer lineage missing"): + results.require_success() + else: + results.require_success() + assert results["A01"] is successful + assert results["A02"] is other diff --git a/tests/unit/test_orchestrator_lane_planning.py b/tests/unit/test_orchestrator_lane_planning.py index e3ef381fc1..e3108449b0 100644 --- a/tests/unit/test_orchestrator_lane_planning.py +++ b/tests/unit/test_orchestrator_lane_planning.py @@ -947,10 +947,16 @@ def test_analysis_consolidation_propagates_runtime_failures(monkeypatch): def test_execution_state_projector_maps_success_and_failure(): orchestrator = SimpleNamespace(_state=None) - project_execution_state(orchestrator, {"A01": ExecutionResult.success("A01")}) + project_execution_state( + orchestrator, + CompiledPlateExecutionResults({"A01": ExecutionResult.success("A01")}), + ) assert orchestrator._state is orchestrator_module.OrchestratorState.COMPLETED - project_execution_state(orchestrator, {"A01": ExecutionResult.error("A01")}) + project_execution_state( + orchestrator, + CompiledPlateExecutionResults({"A01": ExecutionResult.error("A01")}), + ) assert orchestrator._state is orchestrator_module.OrchestratorState.EXEC_FAILED diff --git a/tests/unit/test_zmq_execution_server.py b/tests/unit/test_zmq_execution_server.py index e2cf851ada..402fdb5ac4 100644 --- a/tests/unit/test_zmq_execution_server.py +++ b/tests/unit/test_zmq_execution_server.py @@ -99,6 +99,76 @@ def test_zmq_execution_context_seeds_saved_global_config_for_compilation() -> No assert saved_global_config.processing_config.group_by is GroupBy.CHANNEL +@pytest.mark.parametrize("failed", [False, True]) +def test_axis_outcomes_qualify_server_terminal_after_export(monkeypatch, failed): + server = ZMQExecutionServer(port=5555) + record = ExecutionRecord( + execution_id="axis-outcome-check", + plate_id="/tmp/plate", + client_address=None, + status=ExecutionStatus.QUEUED.value, + ) + server._lifecycle.enqueue(record) + results = CompiledPlateExecutionResults( + { + "A01": ExecutionResult.success("A01"), + "A02": ( + ExecutionResult.error("A02", error_message="producer lineage missing") + if failed + else ExecutionResult.success("A02") + ), + } + ) + exported = [] + monkeypatch.setattr( + zmq_execution_server_module, + "ZMQWorkerExecutionRequest", + lambda **kwargs: SimpleNamespace(execute=lambda: results), + ) + monkeypatch.setattr( + server, + "_export_runtime_observation", + lambda **kwargs: exported.append(kwargs["execution_results"]), + ) + context = SimpleNamespace( + compile_only=False, + execution_id=record.execution_id, + auxiliary_params=SimpleNamespace( + runtime_observation_mode_for=lambda bundle: RuntimeObservationMode.OMIT + ), + ) + monkeypatch.setattr( + server, + "execute_task", + lambda execution_id, request: server._finish_compilation_or_execute( + request_context=context, + orchestrator=None, + compilation=SimpleNamespace(execution_bundle=object()), + progress_context={}, + debug_execution_policy=None, + ), + ) + monkeypatch.setattr(server, "_kill_worker_processes", lambda: 0) + server.run_execution( + record.execution_id, + ExecuteRequest(plate_id=record.plate_id, pipeline_code="pass"), + record, + ) + terminal = server.progress_queue.get_nowait()[MessageFields.EXECUTION] + assert terminal[MessageFields.STATUS] == ( + ExecutionStatus.FAILED.value if failed else ExecutionStatus.COMPLETE.value + ) + assert exported == [results] + assert results["A01"].is_success() + if failed: + assert "A02: error: producer lineage missing" in terminal[MessageFields.ERROR] + else: + assert terminal[MessageFields.RESULTS_SUMMARY][MessageFields.WELLS] == [ + "A01", + "A02", + ] + + @pytest.mark.parametrize("invalid_output_metadata", (False, True)) def test_terminal_notification_contains_openhcs_summary_before_cleanup( monkeypatch, caplog, invalid_output_metadata