Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions openhcs/core/context/processing_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ def __init__(
self.runtime_pattern_discovery_cache = RuntimePatternDiscoveryCache()
self.runtime_source_binding_context_cache = RuntimeSourceBindingContextCache()
self._runtime_step_values: dict[type[object], object] | None = None
from openhcs.core.steps.abstract import StepExecutionObservation

self.completed_step_outputs = StepExecutionObservation.empty()
self.runtime_source_workspace_projection_cache = (
VirtualWorkspaceSourceProjectionCache()
)
Expand Down Expand Up @@ -194,6 +197,25 @@ def bind_execution_runtime(
"""Bind worker-owned execution identity after compilation freeze."""

self.execution_runtime = runtime
self.reset_completed_step_outputs()

def reset_completed_step_outputs(self) -> None:
"""Start an execution's saved-output facts without retaining old payloads."""
from openhcs.core.steps.abstract import StepExecutionObservation

self.completed_step_outputs = StepExecutionObservation.empty()

def record_completed_step_outputs(
self, observation: "StepExecutionObservation"
) -> None:
"""Own completed persisted facts across step cleanup and worker transfer."""
from openhcs.core.steps.abstract import StepExecutionObservation

if observation is self.completed_step_outputs:
return
self.completed_step_outputs = StepExecutionObservation.combine(
(self.completed_step_outputs, observation)
)

def release_execution_image_cache(self) -> None:
"""Release image reuse storage without discarding runtime observations."""
Expand Down
136 changes: 71 additions & 65 deletions openhcs/core/orchestrator/compiled_plate_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ def execute_compiled_plate_request(
raise

set_progress_queue(validated.progress_queue)
for context in validated.compiled_contexts.values():
context.reset_completed_step_outputs()
try:
orchestrator._state = OrchestratorState.EXECUTING
logger.info(
Expand All @@ -229,53 +231,63 @@ def execute_compiled_plate_request(
execution_bundle = request.execution_bundle
worker_assignments = request.worker_assignments_for()

executor_resources.install_execution_bundle(execution_bundle)
orchestrator._executor = executor_resources.executor
execution_results: Dict[str, ExecutionResult] = {}
plate_runtime_observation = RuntimeExecutionObservation()
try:
with executor_resources.execution_context():
worker_assignment_plan = executor_resources.plan_worker_lanes(
actual_max_workers=validated.actual_max_workers,
execution_bundle=execution_bundle,
worker_assignments=worker_assignments,
executor_resources.install_execution_bundle(execution_bundle)
orchestrator._executor = executor_resources.executor
try:
with executor_resources.execution_context():
worker_assignment_plan = executor_resources.plan_worker_lanes(
actual_max_workers=validated.actual_max_workers,
execution_bundle=execution_bundle,
worker_assignments=worker_assignments,
)
worker_lane_execution_plan = validated.worker_lane_execution_plan(
request=request,
worker_assignment_plan=worker_assignment_plan,
)
execution_results = executor_resources.run_worker_lanes(
pipeline_definition=validated.pipeline_definition,
worker_lane_execution_plan=worker_lane_execution_plan,
parent_contexts=validated.compiled_contexts,
)
if any(result.is_cancelled() for result in execution_results.values()):
raise ExecutionCancelledError("Execution cancelled during worker execution")
cancellation.raise_if_requested("after worker execution")
executor_resources.shutdown_executor()
except BrokenProcessPool as exc:
logger.warning(
"ORCHESTRATOR: Executor context exit failed due to broken process "
f"pool (workers were killed externally): {exc}"
)
worker_lane_execution_plan = validated.worker_lane_execution_plan(
request=request,
worker_assignment_plan=worker_assignment_plan,
if not execution_results:
raise
finally:
executor_resources.clear_execution_bundle()
executor_resources.release_parent_runtime_resources(execution_bundle)

if all(result.is_success() for result in execution_results.values()):
plate_runtime_observation = execute_plate_scoped_steps(
validated.compiled_contexts,
progress_queue=validated.progress_queue,
progress_context=validated,
)
execution_results = executor_resources.run_worker_lanes(
pipeline_definition=validated.pipeline_definition,
worker_lane_execution_plan=worker_lane_execution_plan,
parent_contexts=validated.compiled_contexts,
consolidate_analysis_outputs(
validated.compiled_contexts,
execution_results,
plate_runtime_observation=plate_runtime_observation,
)
cancellation.raise_if_requested("after worker execution")
executor_resources.shutdown_executor()
except BrokenProcessPool as exc:
logger.warning(
"ORCHESTRATOR: Executor context exit failed due to broken process "
f"pool (workers were killed externally): {exc}"
)
if not execution_results:
raise
finally:
executor_resources.clear_execution_bundle()
executor_resources.release_parent_runtime_resources(execution_bundle)

plate_runtime_observation = RuntimeExecutionObservation()
if all(result.is_success() for result in execution_results.values()):
plate_runtime_observation = execute_plate_scoped_steps(
validated.compiled_contexts,
progress_queue=validated.progress_queue,
progress_context=validated,
)
consolidate_analysis_outputs(
validated.compiled_contexts,
execution_results,
plate_runtime_observation=plate_runtime_observation,
)
OpenHCSMetadataTarget.finalize_completed_plate(
validated.compiled_contexts,
runtime_observations=(
RuntimeExecutionObservation.from_completed_outputs(
validated.compiled_contexts
),
),
)
if all(result.is_success() for result in execution_results.values()):
viewer_states_by_port = settle_viewer_state(
visualizers,
progress_queue=validated.progress_queue,
Expand Down Expand Up @@ -545,7 +557,7 @@ def execute_plate_scoped_steps(
owner_context,
owner_plan.require_function_execution_ready(),
)
OpenHCSMetadataTarget.write_for_step(
projection_entries = OpenHCSMetadataTarget.observe_for_step(
owner_context,
owner_plan.require_function_execution_ready(),
artifact_materializations=materializations,
Expand All @@ -555,12 +567,18 @@ def execute_plate_scoped_steps(
for key, context in compiled_contexts.items()
if context is owner_context
)
observations_by_context[owner_context_key].append(
observation = StepExecutionObservation.combine((
StepExecutionObservation.combine(
item.observation(owner_plan, owner_context)
for item in materializations
)
)
),
StepExecutionObservation(
materialized_locations_by_address=MappingProxyType({}),
source_projection_entries_by_target=projection_entries,
),
))
owner_context.record_completed_step_outputs(observation)
observations_by_context[owner_context_key].append(observation)
_emit_execution_progress(
progress_queue=progress_queue,
progress_context=progress_context,
Expand Down Expand Up @@ -813,30 +831,18 @@ def _plate_artifact_batch(
if input_ref not in selected_input_edges:
continue
input_edge = selected_input_edges[input_ref]
input_plan = input_edge.storage_plan
projection = input_edge.projection
if input_plan is None or projection is None:
raise RuntimeError(
"Selected plate artifact input lost its storage plan."
)
for group_key in projection.producer_selection_scope.keys:
query = RuntimeArtifactQuery.from_input_plan(
input_plan,
axis_id=axis_id,
backend=Backend.MEMORY.value,
group_key=group_key,
)
matches = tuple(
record
for record in records_by_axis.get(axis_id, ())
if query.matches(record)
matches = RuntimeArtifactQuery.records_for_input_edge(
input_edge,
records_by_axis.get(axis_id, ()),
axis_id=axis_id,
backend=Backend.MEMORY.value,
)
for record in matches:
selected[axis_id].setdefault(
(record.key, record.location),
record,
)
for record in matches:
selected[axis_id].setdefault(
(record.key, record.location),
record,
)
selected_for_spec += len(matches)
selected_for_spec += len(matches)
if input_spec.required and selected_for_spec == 0:
raise ValueError(
f"Plate-scoped callable {contract.function_name!r} is missing required "
Expand Down
80 changes: 71 additions & 9 deletions openhcs/core/orchestrator/execution_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
from types import MappingProxyType
from typing import TYPE_CHECKING, Mapping, Optional

from openhcs.constants.constants import Backend
from openhcs.core.context.processing_context import ProcessingContext
from openhcs.core.runtime_stores import StoredRuntimeValue
from openhcs.core.runtime_stores import RuntimeArtifactQuery, StoredRuntimeValue
from openhcs.core.steps.abstract import StepExecutionObservation

if TYPE_CHECKING:
Expand Down Expand Up @@ -86,12 +87,28 @@ class RuntimeExecutionObservation:

contexts: tuple[RuntimeContextObservation, ...] = field(default_factory=tuple)

@classmethod
def from_completed_outputs(
cls, contexts: Mapping[str, ProcessingContext]
) -> "RuntimeExecutionObservation":
"""Project saved facts independently of retained runtime pixel records."""
return cls(contexts=tuple(
RuntimeContextObservation(
context_key=context_key,
records=(),
outputs=context.completed_step_outputs,
)
for context_key, context in contexts.items()
if not context.completed_step_outputs.is_empty
))

def merge_into(self, execution_contexts: Mapping[str, ProcessingContext]) -> None:
"""Merge returned runtime records into parent-owned compiled contexts."""
for context_observation in self.contexts:
context = execution_contexts[context_observation.context_key]
store = context.runtime_value_store
store.merge_observed_values(context_observation.records)
context.record_completed_step_outputs(context_observation.outputs)


class RuntimeObservationMode(Enum):
Expand Down Expand Up @@ -140,15 +157,33 @@ def retain_records(
return ()
if self is RuntimeObservationMode.MERGE_INTO_PARENT:
return records
required_types = {
spec.artifact_type
for plan in context.step_plans.values()
if plan.execution_scope.requires_parent_runtime_observation
for invocation in plan.compiled_function_pattern.default_group.invocations
for spec in invocation.contract.artifact_inputs
}
selected_addresses = set()
for plan in context.step_plans.values():
if not plan.execution_scope.requires_parent_runtime_observation:
continue
for invocation in plan.compiled_function_pattern.default_group.invocations:
input_edges = {
edge.spec.ref(): edge
for edge in invocation.select_inputs(plan.artifact_inputs).values()
if edge.storage_plan is not None
}
for spec in invocation.contract.artifact_inputs:
edge = input_edges.get(spec.ref())
if edge is None:
continue
selected_addresses.update(
(record.key, record.location)
for record in RuntimeArtifactQuery.records_for_input_edge(
edge,
records,
axis_id=context.require_axis_id(),
backend=Backend.MEMORY.value,
)
)
return tuple(
record for record in records if record.key.artifact_type in required_types
record
for record in records
if (record.key, record.location) in selected_addresses
)


Expand Down Expand Up @@ -183,6 +218,9 @@ def is_error(self) -> bool:
"""Check if execution failed."""
return self.status == ExecutionStatus.ERROR

def is_cancelled(self) -> bool:
return self.status == ExecutionStatus.CANCELLED

@classmethod
def success(
cls,
Expand All @@ -202,11 +240,35 @@ def error(
axis_id: str,
failed_combination: Optional[str] = None,
error_message: Optional[str] = None,
runtime_observation: RuntimeExecutionObservation | None = None,
) -> "ExecutionResult":
"""Create an error execution result."""
return cls(
status=ExecutionStatus.ERROR,
axis_id=axis_id,
failed_combination=failed_combination,
error_message=error_message,
runtime_observation=(
RuntimeExecutionObservation()
if runtime_observation is None else runtime_observation
),
)

@classmethod
def cancelled(
cls,
axis_id: str,
*,
error_message: str,
runtime_observation: RuntimeExecutionObservation | None = None,
) -> "ExecutionResult":
"""Return completed outputs from a cooperative cancellation boundary."""
return cls(
status=ExecutionStatus.CANCELLED,
axis_id=axis_id,
error_message=error_message,
runtime_observation=(
RuntimeExecutionObservation()
if runtime_observation is None else runtime_observation
),
)
Loading
Loading