diff --git a/docs/validation/step-input-image-artifact-origin-20261004.rst b/docs/validation/step-input-image-artifact-origin-20261004.rst new file mode 100644 index 0000000000..d73cb73401 --- /dev/null +++ b/docs/validation/step-input-image-artifact-origin-20261004.rst @@ -0,0 +1,277 @@ +STEP_INPUT named-image artifact origin after ordinary preprocessing +================================================================== + +Owner repair installed in an isolated qualified wheel; public synthetic MCP +acceptance is verified below, together with411 installed controls. The initial281 focused installed controls passed; the +wider CP family exposed the follow-up consumer and fixture boundaries recorded +below. No frozen biological execution is replayed. +Reviewed main e1400cb9f278149fea7056b8fc8319d1ebd6ca69 and the retained +installed source0b3ead24459954829986e2e0763a886bb4d0fef6 exhibit the same +source-artifact resolution route. Frozen analysis and all originals remain +unchanged; no reference, scientific correction or parameter advice is supplied. + +Observed public workflow +------------------------- + +A source-bound image enters two ordinary registered NumPy processing steps. +The following CellProfiler primary-object step declares PREVIOUS_STEP and an +image alias with origin STEP_INPUT. With a new alias the invocation raises +``Source-bound artifact ... resolved no workspace members``. With the original +raw alias the invocation completes, but its threshold support is inconsistent +with the separately measured processed image. That second pixel-origin inference +is not a demonstrated full-array equality. Zero surviving objects does not +prove absence of biological objects or identify the underlying gate by itself. + +The complete frozen source uses normal PipelineDocument/FunctionStep/source +binding declarations. The original raw and measured processed arrays are uint8; +the manual threshold is expressed in the existing CellProfiler normalized +domain. No independent normalization defect has been established. + +Determining owners and consumers +-------------------------------- + +* ``SourceAssignmentBase.origin`` in core/source_bindings.py explicitly defines + selection from prior-step input versus pipeline-start sources. The existing + CompiledSourceUniversePlan also models that distinction; it is not a new flag + to invent at the adapter. +* PathPlanner's advance_artifact_context_after_compiled_pattern creates an + implicit unnamed image artifact for ordinary unlabelled NumPy returns. + The previous source alias is consequently not the current main-flow artifact + name merely because its spatial provenance remains attached. +* InvocationArtifactInputEdgePlan.source_projection in function_patterns.py + assigns a main-flow projection only when the exact artifact ref is in BOTH + current main-flow artifacts and the invocation's group-scope sources. +* PathPlanner.compile_invocation_input_edges compiles unstored named source + edges from those declarations. Its separate process_artifact_inputs omits + storage plans for exact declared source bindings. +* CP RuntimeInputBindingRequest.artifact_value (artifact_binding.py300--365) + sends a source-only edge to RuntimeAdapterRequest.source_artifact_payload. +* RuntimeAdapterRequest.source_artifact_payload (runtime_adapters.py251--366) + unconditionally resolves members through VirtualWorkspaceSourceProjection + and loads Backend.VIRTUAL_WORKSPACE. It does not consult binding.origin. + A new alias cannot match the original workspace source; an existing alias + can load its original pixels despite declaring STEP_INPUT. +* FunctionCoreExecutor.declared_source_payload is the other direct consumer of + that same resolver. A CP-only special case would leave the authority split. + +Existing refactor-audit Package AST parsing covered200 current-main modules in +core and CP runtime with zero parse omissions. The resolver has exactly two +direct call sites in that scope: FunctionCoreExecutor and CP artifact binding. +This is targeted source evidence, not an NRA semantic proof or a complete +dependency/selector migration census. The initial file-root Package invocation +parsed zero modules; it was corrected to actual directory roots, not reported +as coverage. + +The applicable ownership failure is IDEN-5 (declared source origin versus a +different pixel authority at consumption), with IMPL-13 as the repair risk if +another adapter-specific origin mechanism is added. The correct change must +extend the existing origin/source projection owner and migrate both consumers, +not add aliases, a second workspace, a reader fallback or a string dispatch. + +Ownership and acceptance +------------------------- + +Popper owns the binding investigation. Singer's626 change owns automatic/named +publication metadata only and is semantically separate. PR630 crosses execution, +runtime and output identity; coordinate its integration owner before changing +those files. This checkpoint deliberately contains no competing runtime hunk. + +Use a modest synthetic scalar image and the existing registered processing/CP +pipeline entrypoint, not the frozen retinal field. Retain an original raw alias, +apply an ordinary operation that produces distinguishable pixels, then select +an explicit STEP_INPUT alias at primary objects and measure the original alias +with PIPELINE_START in a separate downstream step. Acceptance must demonstrate: + +* new and reused STEP_INPUT aliases select the actual processed pixels; +* PIPELINE_START retains raw pixels and source identity; +* exact component/plane selectors work for a multi-channel or multi-plane + processed carrier, including a supported companion source-artifact input; +* a genuinely absent/ambiguous selection still fails through its original owner; +* current main-flow/named artifact producers and both resolver consumers use + one consistent authority, with replaced decisions removed; +* the existing installed public MCP compile/execute/measurement path confirms + the result after the coherent implementation, not only mocked adapter tests. + +No synthetic execution, native launch, source installation or acceptance result +is claimed by this initial checkpoint. The frozen foreground observation does +not by itself prove the precise consumed array; source/runtime reproduction is +the next engineering step, kept separate from assisted science development. + +Further interface/630 audit +---------------------------- + +PR630 head0ded58b36b92acf3bf7c26dc68989509b66a9a77 leaves the AST of +source_artifact_payload, source_projection, from_source_declarations and CP +artifact_value unchanged versus reviewed main. Its reorganized +FunctionCoreExecutor retains a consumer of source_artifact_payload. The shared +runtime defect is therefore not already repaired by that owner refactor. +Coordination was posted once at PR630 issuecomment5981114085. + +SourceProjection.matches_binding matches projection role, alias and artifact +kind, not origin. This makes the new-alias failure versus existing-alias raw +reload source-backed without treating spatial provenance as processed pixel +identity. NamedSourceBinding.apply_loaded_payload already owns naming selected +payload provenance and channel normalization; ImagePayloadMetadata owns exact +plane/channel projection. Reuse those owners for selection and assignment, +rather than adding an alias reader or projecting a new alias through a cache +that only represents original workspace names. + +The existing SourceUniverseRequest family and CompiledSourceUniversePlan model +pipeline-start versus step-input file universes. They must not be copied into +another resolver hierarchy. Scope matters: a companion SOURCE_ARTIFACT, a +stack-selected primary plane and a pipeline-start raw measurement are distinct +admitted contracts, so simply returning the whole current array for every +STEP_INPUT declaration is not an adequate family repair. + +The CP image-normalization entrypoint delegates to the original metadata-owned +normalize_image_payload_intensity recipe. No independent denominator change is +indicated by the reviewed uint8/normalized manual-threshold declarations. +Precise frame-wide consumed pixel equality and installed synthetic acceptance +remain unproved, not inferred from a label count or copied biological parameters. + +Proposed owner repair +---------------------- + +The published implementation now extends the existing registered +SourceUniverseRequest family: StepInputSourceUniverseRequest projects primary +images from current pixels, and PipelineStartSourceUniverseRequest inherits the +original workspace loader. Companion SOURCE_ARTIFACT inputs retain that loader. +RuntimeAdapterRequest deletes its unconditional loading procedure and delegates +to the declared origin owner. No new adapter, registry or origin store is added. + +SourceSelector owns metadata matching for both candidate paths and current +provenance; the replaced candidate and realized-metadata loops are deleted. +NamedSourceBinding owns assignment after selection, and ImagePayloadMetadata +owns the shared plane/channel pixel projection. A new alias names selected +processed pixels rather than demanding an original-workspace alias. + +CP's unstored source-binding edge now uses the same origin resolver even when +an exact main-flow name is also present. This prevents a PIPELINE_START binding +from accidentally consuming processed pixels through CP's primary-input path. +FunctionCoreExecutor already delegates source bindings to the same resolver. +No function_runtime or PR630 checkout edit is needed. + +Before editing, Package AST parsed176 core and24 CP runtime modules, plus6 +metaclass-registry,12 python-introspect,17 arraybridge and63 PolyStore modules: +zero unparsed files. Dependencies were read from their own repositories after +the initial parent-gitlink scan correctly yielded zero dependency modules. +This is relevant-family AST evidence, not a complete NRA semantic proof. +PR630 head48656092 leaves all five changed production files unchanged against +the reviewed main. Source checks and installed acceptance are still pending. + +Validation checkpoint +---------------------- + +All five changed production modules and the focused source-origin controls +parse successfully; git diff --check passes. The initial six-file source test +batch did not run: global conftest could not import AckReturnRoute from the +preserved dirty zmqruntime checkout. A unit-only collection then independently +failed importing TiffPhotometric from the preserved dirty PolyStore checkout. +Neither error is counted as a passed test or attributed to the new resolver. +No dependency checkout was reset, installed or overwritten. + +The matching qualified offline builder is being obtained from its existing +owner. Engineering88 is currently assigned to Singer626; no client/server or +SCI endpoint was borrowed. Dewey owns the eventual exact88 successor after +typed closure. Independent source selection/consumer checks continue without +waiting for the absent630 owner thread. + +The qualified whole wheel at dfe961555 passed the existing complete byte/RECORD +verifier:912 entries,812 source matches including789 Python modules and13 +skill files. The initial verifier wrapper wrongly retained the historical +source path; all checks were preserved while retargeting that comparison to +the actual pinned archive. Source, wheel, target and Git bytes agreed for the +determining adapter before qualification. All281 focused installed tests passed. + +Additional CP consumer checks found an incomplete migration: a public module +invocation can carry current_image while the originally constructed adapter +request has no source_payload. The three observed failures were not interpreted +as scientific failure. RuntimeInputBindingRequest now derives the resolver +request from its actual current_image rather than a nullable earlier snapshot. +The source origin still has one resolver; no alternate loader is introduced. +This follow-up requires a newly pinned whole wheel and final CP checks before +installed/public acceptance is claimed. + +The wider installed batch passed405 checks before three explicit PIPELINE_START +measurement fixtures failed: their minimal context had neither canonical source +workspace caches nor plate metadata, because they previously consumed a supplied +raw stack through the main-flow branch. The fixture now supplies those existing +nominal services and builds its workspace metadata through SourceProjectionSet, +leaving all intensity/object assertions unchanged. Production does not silently +substitute current processed pixels when original raw pixels were requested. + +Consumer-complete installed validation +-------------------------------------- + +Whole-wheel source ee9d9e37ed123a0d1382bcdc6ec6b9705d6c16c8 passed the original +byte/RECORD verifier, including789 Python source matches and13 managed skill +files. With the completed workspace fixture, all411 installed controls passed +in32.26s across source bindings, function IO/projection/artifacts and CP runtime. +The installed package location was printed before collection, avoiding the +preserved dirty checkout's dependency bootstrap. Actual log: +engineering-step-input-origin-633-20261004/receiving02/installed-controls.log. +Later branch changes contain documentation/test fixtures only; packaged +production and knowledge bytes remain unchanged from that qualified source. + +The public88 packet contains three complete synthetic PipelineDocuments: +new STEP_INPUT alias, reused STEP_INPUT alias, and original PIPELINE_START raw +admission, all retaining a separate raw-intensity measurement. A32x32 synthetic +TIFF is on the declared HDD artifact root, not copied from any scientific run. +Its acquisition SHA and expected distinct raw/response intensity domains are +recorded in public88/SYNTHETIC-INPUT.json. No public result is claimed yet. + +Dewey retired the positively closed626 route and published the633 successor +without changing the active SCI members. The first633 startup admission exited77 +before client creation because actual memory full PSI was elevated; there was +no633 client/native launch or UNKNOWN execution. That refusal is preserved. +After installed checks completed, memory pressure was observed to have fallen; +any startup needs a distinct passing admission, not a replay of the refused one. + +Public installed acceptance and custody +---------------------------------------- + +The fresh ``popper633_public88_start01`` admission passed with10.146GiB RAM +available and full memory PSI0.00/0.01/0.15. The earlier pre-client exit77 remains +unchanged. One recorded client (invocation f629a3526ae543e9974ccdd1af8c3b68) +imported the qualified receiving02 wheel at ee9d9e37. The normal owned runtime +handle identified PID1560544/create_time1791127634.59 on6020; startup progress +was retained through kernel/catalog preparation. A catalog-preparation request +before the execution endpoint was ready was rejected without delivery; after +the same handle became ready, all three public sessions compiled and executed. + +The normal MCP entrypoint executed the new-name and reused-name STEP_INPUT +pipelines and the opposing explicit PIPELINE_START control. Existing canonical +runtime observation exports validate all three executions. Exported full32x32 +labels and threshold-support arrays match exactly: both processed cases have +zero support/objects; the raw control has the expected36-pixel single object. +The separate PIPELINE_START measurement in every case retains raw mean +0.5174019932746887, minimum128/255 and maximum240/255 within float32 tolerance. +Two public32x32 image samples exactly reproduce the processed output (2048 +pixels checked), and acquisition identity/channel/spacing remain attached. +The original synthetic input SHA remains unchanged. + +The reader initially assumed all identities used absolute paths. The third +control correctly retained an acquisition-relative workspace identity, unlike +the absolute current-carrier identities. The receipt resolves that original +relative identity against the same acquisition and also verifies the original +absolute filter path. The initial failed assertion is preserved; no production +fallback or selector weakening was introduced. Final acceptance receipt is +``engineering-step-input-origin-633-20261004/public88/verify-public02.stdout``; +the verifier reuses the existing public reply reader and native export owner. +This proves the synthetic public workflow, not full-array equality for any +frozen scientific run or biological accuracy. Multi-plane/missing-selection +and companion-source contracts remain covered by the411 installed controls, +not claimed as three-channel public acceptance here. + +The exact owned runtime acknowledged close, terminated its endpoint and exited +successfully. The client then ended with exit1 due to the retained earlier +catalog request error; its three scientific execution jobs were complete and +the error is not hidden as a zero-exit client. Original recorder journals are +closed and the client scope is inactive/not-found. No633 runtime is retained. +``public88/OWNER-633-TERMINAL.rst`` records the closed journal hashes. + +Main626 was integrated normally at branch2d9860e93. Its separate output-identity +hunk does not modify these five source-selection files; the installed public +target stays pinned to ee9d9e37 rather than being falsely described as a rebuilt +post-merge wheel. Eight dirty dependency checkouts and four diagnostic +directories remain unchanged. Frozen science was never replayed or coached. diff --git a/openhcs/core/runtime_adapters.py b/openhcs/core/runtime_adapters.py index 8cc4b817c5..a22d5cf889 100644 --- a/openhcs/core/runtime_adapters.py +++ b/openhcs/core/runtime_adapters.py @@ -16,7 +16,6 @@ ) from openhcs.core.aligned_image_payload import ( ImagePayloadExecutionMode, - stack_image_payloads, ) from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -30,32 +29,18 @@ InvocationArtifactInputEdgePlan, InvocationArtifactInputProjectionKey, ) -from openhcs.core.runtime_image_loading import ImagePayloadSourceMetadataContext -from openhcs.core.runtime_image_values import ( - ImagePayloadMetadataCompositionMode, - image_payload_metadata, -) from openhcs.core.source_bindings import ( CompiledSourceBindingPlan, NamedSourceBinding, ) from openhcs.core.source_binding_selection import ( - SourceBindingMatchedImageSet, -) -from openhcs.core.source_image_provenance import ( - SourceImageIdentity, - SourceImageProvenance, + SourceUniverseRequest, ) from openhcs.core.source_load_plan import SourceLoadPlan from openhcs.core.runtime_plane_projection import ( - RuntimePlaneAxis, RuntimePlaneAxisValueProjection, RuntimePlaneProjection, ) -from openhcs.core.source_workspace_projection import ( - VirtualWorkspacePathLookup, - VirtualWorkspaceSourceProjectionAuthority, -) if TYPE_CHECKING: from openhcs.core.callable_contract import CallableContract @@ -249,121 +234,10 @@ def runtime_artifact_input( ) def source_artifact_payload(self, ref: ArtifactSpecRef) -> object: - """Resolve one source-bound artifact through workspace matching and VFS.""" - + """Resolve a named input through its existing source-origin owner.""" binding = self.source_binding_for_artifact_ref(ref) - source_payload = self.source_payload - source_provenance = ( - None - if source_payload is None - else image_payload_metadata(source_payload).source_provenance - ) - if source_provenance is not None and not source_provenance.has_values: - raise ValueError( - f"Source-bound artifact {ref!r} requires main-flow source provenance." - ) - - cache = self.context.runtime_source_workspace_projection_cache - projection = VirtualWorkspaceSourceProjectionAuthority.from_context( - self.context, - cache=cache, - ).projection_if_available() - if projection is None: - raise ValueError( - f"Source-bound artifact {ref!r} requires a virtual-workspace " - "source projection." - ) - projection = cache.filtered_by_axis( - projection, - axis_id=self.axis_scope.axis_id, - ) - source_context = ( - self.context.runtime_source_binding_context_cache.source_pattern_context( - parser=self.context.microscope_handler.parser, - projection=projection, - metadata_rules=self.source_binding_plan.metadata_rules, - ) - ) - matched_set = SourceBindingMatchedImageSet.from_plan( - bindings=self.source_binding_plan.binding_declarations, - match_plan=self.source_binding_plan.match_plan, - source_context=source_context, - identity_policy=self.context.source_image_set_identity_policy, - ) - source_universe = tuple( - dict.fromkeys( - source_path - for declared_binding in self.source_binding_plan.binding_declarations - for source_path in projection.files_for_projection_role( - declared_binding.projection_role, - axis_id=self.axis_scope.axis_id, - ) - ) - ) - members = matched_set.members_for_binding( - binding, - anchor_provenance=( - source_provenance - if source_provenance is not None - else SourceImageProvenance() - ), - source_universe=source_universe, - ) - if not members: - raise ValueError( - f"Source-bound artifact {ref!r} resolved no workspace members." - ) - - payloads = self.context.filemanager.load_batch( - list(members), - Backend.VIRTUAL_WORKSPACE.value, - ) - if len(payloads) != len(members): - raise ValueError( - f"Source-bound artifact {ref!r} loaded {len(payloads)} payloads " - f"for {len(members)} workspace members." - ) - projected_payloads = [] - for member, payload in zip(members, payloads, strict=True): - lookup = VirtualWorkspacePathLookup.from_paths(member, member) - source_projection = projection.require_source_projection_for(lookup) - if not source_projection.matches_binding(binding): - raise ValueError( - f"Workspace projection for {member!r} does not match compiled " - f"source artifact {ref!r}." - ) - projected = projection.project_payload(lookup, payload) - projected_payloads.append( - binding.apply_loaded_payload( - projected, - ImagePayloadSourceMetadataContext( - SourceImageIdentity( - member, - projection.source_metadata_for(lookup), - ), - source_projection.ref.backend, - self.context.filemanager, - source_projection.ref.backend_address, - ), - ) - ) - payload = ( - projected_payloads[0] - if len(projected_payloads) == 1 - and image_payload_metadata(projected_payloads[0]).persists_whole_image() - else stack_image_payloads( - projected_payloads, - metadata_mode=ImagePayloadMetadataCompositionMode.for_plane_axis( - RuntimePlaneAxis.RUNTIME_SLICE - ), - ) - ) - metadata = image_payload_metadata(payload) - domain = self.source_binding_plan.source_spatial_domain.admit_source_cohort( - metadata.source_spatial_domain, - depth=len(members), - ) - return metadata.replace_fields(source_spatial_domain=domain).attach_to(payload) + owner = SourceUniverseRequest.for_binding(binding) + return owner.source_artifact_payload(self, binding) RuntimeAdapterFactory = Callable[[RuntimeAdapterRequest], object] diff --git a/openhcs/core/runtime_image_values.py b/openhcs/core/runtime_image_values.py index 98b295d453..345ba17f71 100644 --- a/openhcs/core/runtime_image_values.py +++ b/openhcs/core/runtime_image_values.py @@ -947,6 +947,14 @@ def project_declared_source_image( "with provenance planes " f"{self.source_image_provenance_planes.identity!r}." ) + return self.project_source_planes(payload, source_plane_selection) + + def project_source_planes( + self, + payload: RuntimeArrayData, + source_plane_selection: tuple[int, ...], + ) -> RuntimeArrayData: + """Project selected provenance planes through their declared pixel axis.""" if not source_plane_selection: return self.attach_to(payload) complete_source_axis = tuple(range(self.source_provenance.source_plane_count)) @@ -959,7 +967,7 @@ def project_declared_source_image( raise ValueError( "Declared source-image channel projection requires exactly " f"one channel; got source planes {source_plane_selection!r} " - f"for {source_image_name!r}." + "for the requested source selection." ) return self.project_channel_payload( payload, diff --git a/openhcs/core/source_binding_selection.py b/openhcs/core/source_binding_selection.py index 0ad194721e..54332fb687 100644 --- a/openhcs/core/source_binding_selection.py +++ b/openhcs/core/source_binding_selection.py @@ -22,6 +22,7 @@ SourceBindingMatchMethod, SourceBindingMatchPlan, SourceSetRole, + SourceProjectionRole, ) from openhcs.core.source_image_provenance import ( SourceImageIdentity, @@ -53,13 +54,24 @@ source_paths_equal, ) from openhcs.core.source_projection import SourceProjection -from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection +from openhcs.core.source_workspace_projection import ( + VirtualWorkspacePathLookup, + VirtualWorkspaceSourceProjection, + VirtualWorkspaceSourceProjectionAuthority, +) +from openhcs.core.aligned_image_payload import stack_image_payloads +from openhcs.core.runtime_image_values import ( + ImagePayloadMetadataCompositionMode, + image_payload_metadata, +) +from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.steps.function_io import get_all_image_paths from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_loading import ImagePayloadSourceMetadataContext from openhcs.core.compiled_step_plan import CompiledStepPlan if TYPE_CHECKING: + from openhcs.core.runtime_adapters import RuntimeAdapterRequest from polystore.filemanager import FileManager from openhcs.core.context.processing_context import ProcessingContext from openhcs.microscopes.microscope_interfaces import FilenameParser @@ -543,33 +555,7 @@ def matches( if not selector.components and not selector.metadata: return True - metadata_candidates = source_context.candidate_metadata(candidate) - for component_selector in selector.components: - if not any( - source_metadata_values_equal(value, str(component_selector.value)) - for metadata in metadata_candidates - for value in source_component_metadata_values( - metadata, - component_selector.component, - ) - ): - return False - - for metadata_selector in selector.metadata: - if not any( - value is not None - and source_metadata_values_equal(value, metadata_selector.value) - for metadata in metadata_candidates - for value in ( - semantic_source_metadata_value( - metadata, - metadata_selector.field, - ), - ) - ): - return False - - return True + return selector.metadata_candidates_match(source_context.candidate_metadata(candidate)) @classmethod def compatible_candidates( @@ -1655,6 +1641,131 @@ def from_context( source_projection=source_projection, ) + @classmethod + def source_artifact_payload( + cls, request: RuntimeAdapterRequest, binding: NamedSourceBinding, + ) -> object: + """Resolve original source pixels in this origin's workspace universe.""" + + ref = binding.input_spec().ref() + source_payload = request.source_payload + source_provenance = ( + None + if source_payload is None + else image_payload_metadata(source_payload).source_provenance + ) + if source_provenance is not None and not source_provenance.has_values: + raise ValueError( + f"Source-bound artifact {ref!r} requires main-flow source provenance." + ) + + cache = request.context.runtime_source_workspace_projection_cache + projection = VirtualWorkspaceSourceProjectionAuthority.from_context( + request.context, + cache=cache, + ).projection_if_available() + if projection is None: + raise ValueError( + f"Source-bound artifact {ref!r} requires a virtual-workspace " + "source projection." + ) + projection = cache.filtered_by_axis( + projection, + axis_id=request.axis_scope.axis_id, + ) + source_context = ( + request.context.runtime_source_binding_context_cache.source_pattern_context( + parser=request.context.microscope_handler.parser, + projection=projection, + metadata_rules=request.source_binding_plan.metadata_rules, + ) + ) + matched_set = SourceBindingMatchedImageSet.from_plan( + bindings=request.source_binding_plan.binding_declarations, + match_plan=request.source_binding_plan.match_plan, + source_context=source_context, + identity_policy=request.context.source_image_set_identity_policy, + ) + source_universe = tuple( + dict.fromkeys( + source_path + for declared_binding in request.source_binding_plan.binding_declarations + for source_path in projection.files_for_projection_role( + declared_binding.projection_role, + axis_id=request.axis_scope.axis_id, + ) + ) + ) + members = matched_set.members_for_binding( + binding, + anchor_provenance=( + source_provenance + if source_provenance is not None + else SourceImageProvenance() + ), + source_universe=source_universe, + ) + if not members: + raise ValueError( + f"Source-bound artifact {ref!r} resolved no workspace members." + ) + + payloads = request.context.filemanager.load_batch( + list(members), + Backend.VIRTUAL_WORKSPACE.value, + ) + if len(payloads) != len(members): + raise ValueError( + f"Source-bound artifact {ref!r} loaded {len(payloads)} payloads " + f"for {len(members)} workspace members." + ) + projected_payloads = [] + for member, payload in zip(members, payloads, strict=True): + lookup = VirtualWorkspacePathLookup.from_paths(member, member) + source_projection = projection.require_source_projection_for(lookup) + if not source_projection.matches_binding(binding): + raise ValueError( + f"Workspace projection for {member!r} does not match compiled " + f"source artifact {ref!r}." + ) + projected = projection.project_payload(lookup, payload) + projected_payloads.append( + binding.apply_loaded_payload( + projected, + ImagePayloadSourceMetadataContext( + SourceImageIdentity( + member, + projection.source_metadata_for(lookup), + ), + source_projection.ref.backend, + request.context.filemanager, + source_projection.ref.backend_address, + ), + ) + ) + payload = ( + projected_payloads[0] + if len(projected_payloads) == 1 + and image_payload_metadata(projected_payloads[0]).persists_whole_image() + else stack_image_payloads( + projected_payloads, + metadata_mode=ImagePayloadMetadataCompositionMode.for_plane_axis( + RuntimePlaneAxis.RUNTIME_SLICE + ), + ) + ) + metadata = image_payload_metadata(payload) + domain = request.source_binding_plan.source_spatial_domain.admit_source_cohort( + metadata.source_spatial_domain, + depth=len(members), + ) + return metadata.replace_fields(source_spatial_domain=domain).attach_to(payload) + + @classmethod + def for_binding(cls, binding: NamedSourceBinding) -> type[SourceUniverseRequest]: + """Select the already registered owner of a binding's origin.""" + return cls.__registry__[binding.origin.value] + def runtime_universe_state(self) -> SourceUniverseRuntimeState: """Return cached source-universe state for this request.""" cache = self.context.runtime_source_binding_context_cache @@ -1814,6 +1925,17 @@ class StepInputSourceUniverseRequest(SourceUniverseRequest): universe_request_kind = "step_input" + @classmethod + def source_artifact_payload( + cls, request: RuntimeAdapterRequest, binding: NamedSourceBinding, + ) -> object: + """Resolve primary planes from current pixels; companions from source.""" + if binding.projection_role is SourceProjectionRole.SOURCE_ARTIFACT: + return SourceUniverseRequest.source_artifact_payload(request, binding) + if request.source_payload is None: + raise ValueError(f"STEP_INPUT binding {binding.alias!r} requires current pixels.") + return binding.project_step_input_payload(request.source_payload) + def source_universe(self) -> SourceFileUniverse: """Expand source selectors; otherwise retain the selected pattern files.""" if not self.requires_step_input_selector_resolution: diff --git a/openhcs/core/source_bindings.py b/openhcs/core/source_bindings.py index 96dd16d3ad..f96123b185 100644 --- a/openhcs/core/source_bindings.py +++ b/openhcs/core/source_bindings.py @@ -54,6 +54,7 @@ from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_loading import ImagePayloadSourceMetadataContext from openhcs.core.runtime_image_values import ImagePayloadMetadata + from openhcs.core.source_image_provenance import SourceImageProvenance SOURCE_ALIAS_PART_SEPARATOR = "__" SOURCE_BINDING_ALIAS_METADATA_FIELD = "source_alias" @@ -691,6 +692,46 @@ def path_filters_match(self, identities: tuple[str, ...]) -> bool: return any(source_filters_match(path, self.filters) for path in identities) + def metadata_candidates_match( + self, + candidates: Iterable[SourceMetadataMapping], + ) -> bool: + """Match declared coordinates in store or current-payload metadata.""" + from openhcs.core.source_matching import ( + semantic_source_metadata_value, + source_component_metadata_values, + source_metadata_values_equal, + ) + + candidates = tuple(candidates) + return all( + any( + source_metadata_values_equal(value, selector.value) + for metadata in candidates + for value in source_component_metadata_values(metadata, selector.component) + ) + for selector in self.components + ) and all( + any( + value is not None and source_metadata_values_equal(value, selector.value) + for metadata in candidates + for value in (semantic_source_metadata_value(metadata, selector.field),) + ) + for selector in self.metadata + ) + + def matches_provenance(self, provenance: SourceImageProvenance) -> bool: + """Apply the same selectors to identities carried by current pixels.""" + identities = provenance.represented_source_identities + return ( + (not self.filters or self.path_filters_match( + tuple(identity.path for identity in identities if identity.path is not None) + )) + and self.metadata_candidates_match( + tuple(identity.component_metadata or {} for identity in identities) + ) + ) + def source_alias_measurement_names(alias: str) -> tuple[str, ...]: """Return measurement source-name tokens represented by a source alias.""" @@ -850,7 +891,8 @@ class NamedSourceBinding(SourceAssignmentBase): """Name selected image planes and their optional component identity. ``alias`` is the source name presented to pipeline functions and user - interfaces. The selected planes retain their exact store-backed pixel identity. + interfaces. ``origin`` selects current-step pixels or original store pixels; + both retain their declared acquisition provenance. ``component_identity`` authoritatively assigns biological coordinates after selector resolution, replacing coordinates merely inferred by a source store. """ @@ -1077,6 +1119,33 @@ def apply_loaded_payload( metadata = metadata.replace_fields(source_channel_axis=source_channel_axis) return metadata.payload_with(data, image_payload_mask(payload)) + def project_step_input_payload(self, payload: RuntimeArrayData) -> RuntimeArrayData: + """Select current pixels by provenance, then assign this binding's name. + + The requested alias names the selection; it need not be an alias on the + input carrier. Provenance coordinates select planes, not original pixels. + """ + from openhcs.core.runtime_image_values import image_payload_metadata + + metadata = image_payload_metadata(payload) + provenance = metadata.source_provenance + if not provenance.has_values: + raise ValueError(f"STEP_INPUT binding {self.alias!r} requires source provenance.") + + if not provenance.source_plane_count: + if not self.selector.matches_provenance(provenance): + raise ValueError(f"STEP_INPUT binding {self.alias!r} selects no current planes.") + selected = payload + else: + selection = tuple( + index for index in range(provenance.source_plane_count) + if self.selector.matches_provenance(provenance.for_source_plane(index)) + ) + if not selection: + raise ValueError(f"STEP_INPUT binding {self.alias!r} selects no current planes.") + selected = metadata.project_source_planes(payload, selection) + return self.apply_loaded_payload(selected, source_context=None) + @staticmethod def _monochrome_source_data( data: RuntimeArrayData, @@ -1156,27 +1225,7 @@ def matches_realized_source_metadata( if normalized_alias is not None: return str(normalized_alias) == self.alias - from openhcs.core.source_matching import ( - semantic_source_metadata_value, - source_component_metadata_values, - source_metadata_values_equal, - ) - - return all( - any( - source_metadata_values_equal(value, selector.value) - for value in source_component_metadata_values( - metadata, - selector.component, - ) - ) - for selector in self.selector.components - ) and all( - (value := semantic_source_metadata_value(metadata, selector.field)) - is not None - and source_metadata_values_equal(value, selector.value) - for selector in self.selector.metadata - ) + return self.selector.metadata_candidates_match((metadata,)) def input_plan( self, diff --git a/openhcs/interop/cellprofiler/runtime/artifact_binding.py b/openhcs/interop/cellprofiler/runtime/artifact_binding.py index b09760303e..edec7a6fc8 100644 --- a/openhcs/interop/cellprofiler/runtime/artifact_binding.py +++ b/openhcs/interop/cellprofiler/runtime/artifact_binding.py @@ -311,12 +311,14 @@ def artifact_value( ) source_plan = self.adapter.request.source_binding_plan source_binding = source_plan.binding_for_artifact_ref(spec.ref()) - primary_projection = edge.main_flow_projection source_artifact_binding = ( source_binding - if edge.storage_plan is None and primary_projection is None + if edge.storage_plan is None else None ) + primary_projection = ( + edge.main_flow_projection if source_artifact_binding is None else None + ) runtime_edge = ( edge if edge.storage_plan is not None and primary_projection is None else None ) @@ -336,7 +338,9 @@ def artifact_value( if source_artifact_binding is not None: value = cast( RuntimeCallableArgument, - self.adapter.request.source_artifact_payload(spec.ref()), + replace( + self.adapter.request, source_payload=self.current_image, + ).source_artifact_payload(spec.ref()), ) elif runtime_edge is not None: runtime_input = self.adapter.request.runtime_artifact_input( diff --git a/tests/unit/cellprofiler_runtime_test_support.py b/tests/unit/cellprofiler_runtime_test_support.py index f5bcb02e8f..436492fa98 100644 --- a/tests/unit/cellprofiler_runtime_test_support.py +++ b/tests/unit/cellprofiler_runtime_test_support.py @@ -4,6 +4,7 @@ from collections.abc import Iterable from dataclasses import dataclass, field +from pathlib import Path from types import SimpleNamespace from typing import Any @@ -27,6 +28,8 @@ from openhcs.core.runtime_stores import RuntimeValueStore from openhcs.core.runtime_measurements import MeasurementTable from openhcs.core.source_matching import SourceImageSetIdentityPolicy +from openhcs.core.runtime_source_binding_cache import RuntimeSourceBindingContextCache +from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjectionCache from openhcs.core.steps.function_output_identity import FunctionOutputIdentityCache from openhcs.interop.cellprofiler.runtime.adapter import CellProfilerRuntimeAdapter from openhcs.core.measurement_feature_queries import ( @@ -43,6 +46,13 @@ class CellProfilerRuntimeTestContext: filemanager: object | None microscope_handler: object source_image_set_identity_policy: SourceImageSetIdentityPolicy + plate_path: Path = Path('/plate/Images') + runtime_source_binding_context_cache: RuntimeSourceBindingContextCache = field( + default_factory=RuntimeSourceBindingContextCache, + ) + runtime_source_workspace_projection_cache: VirtualWorkspaceSourceProjectionCache = field( + default_factory=VirtualWorkspaceSourceProjectionCache, + ) runtime_function_output_identity_cache: FunctionOutputIdentityCache = field( default_factory=FunctionOutputIdentityCache ) diff --git a/tests/unit/test_cellprofiler_runtime_adapter.py b/tests/unit/test_cellprofiler_runtime_adapter.py index 64112d5905..97f01752af 100644 --- a/tests/unit/test_cellprofiler_runtime_adapter.py +++ b/tests/unit/test_cellprofiler_runtime_adapter.py @@ -1,6 +1,7 @@ import importlib from collections.abc import Callable, Mapping from dataclasses import dataclass, replace +from pathlib import Path from types import SimpleNamespace from typing import Annotated, ClassVar @@ -687,10 +688,49 @@ def _pipeline_start_contains_binding(alias): def _source_bound_image_adapter(output_bindings, images): + from polystore.virtual_workspace import SourcePixelRef + from openhcs.core.source_projection import ( + OpenHCSPlaneAddress, SourcePlaneProjection, SourceProjectionSet, + ) + from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection + from openhcs.microscopes.source_schema import SourceSchemaFilenameParser + filemanager = FileManagerStub() for alias, image in images.items(): filemanager.saved[("memory", f"/src/{alias}.tif")] = image context = ContextStub(filemanager) + projections = SourceProjectionSet(tuple( + SourcePlaneProjection( + address=OpenHCSPlaneAddress.from_values('A01', '1', str(index), '1', '1'), + ref=SourcePixelRef('memory', f'/src/{alias}.tif'), + source_alias=alias, + ) + for index, alias in enumerate(images, start=1) + )) + subdirectory = projections.metadata_dict( + parser=SourceSchemaFilenameParser(), + microscope_handler_name='SourceBindingsHandler', + source_filename_parser_name='SourceSchemaFilenameParser', + grid_dimensions=[1, 1], pixel_size=1., + ) + document = {'subdirectories': {'.': subdirectory}} + context.microscope_handler.metadata_handler = SimpleNamespace( + source_workspace_metadata_document=lambda _plate: document, + ) + workspace = VirtualWorkspaceSourceProjection.from_openhcs_metadata( + Path(context.input_dir), document, + ) + for path, projection in workspace.source_projections_by_virtual_path.items(): + pixels = images[projection.source_alias] + payload = ImagePayloadMetadata( + source_path=projection.ref.backend_address, + source_image_names=(projection.source_alias,), + source_spatial_domain=SourceSpatialDomain( + origin_yx=(0, 0), source_shape_yx=pixels.shape[-2:], + ), + ).payload_with(pixels) + filemanager.saved[('virtual_workspace', path)] = payload + filemanager.saved[('virtual_workspace', str(Path(context.input_dir) / path))] = payload return cellprofiler_runtime_adapter_for_test( runtime_value_store=RuntimeValueStore(), axis_scope=runtime_axis_scope(AXIS_ID), diff --git a/tests/unit/test_step_input_artifact_origin.py b/tests/unit/test_step_input_artifact_origin.py new file mode 100644 index 0000000000..5ccc73cd8c --- /dev/null +++ b/tests/unit/test_step_input_artifact_origin.py @@ -0,0 +1,87 @@ +"""Named source origins select pixel authority, not just a provenance alias.""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from openhcs.constants.constants import AllComponents +from openhcs.core.component_group_scope import RuntimeExecutionAxisScope +from openhcs.core.runtime_adapters import RuntimeAdapterRequest +from openhcs.core.runtime_image_values import ( + ImagePayloadMetadata, + image_payload_data, + image_payload_metadata, +) +from openhcs.core.runtime_plane_projection import RuntimePlaneAxis +from openhcs.core.source_binding_selection import ( + PipelineStartSourceUniverseRequest, + SourceUniverseRequest, + StepInputSourceUniverseRequest, +) +from openhcs.core.source_bindings import ( + CompiledSourceBindingPlan, + ComponentSelector, + NamedSourceBinding, + SourceBindingOrigin, + SourceSelector, +) +from openhcs.core.source_image_provenance import SourceImageProvenancePlanes + + +@pytest.mark.parametrize("alias", ("Raw", "Response")) +def test_step_input_names_current_pixels_without_loading_workspace(alias): + data = np.arange(20, dtype=np.uint8).reshape(4, 5) + payload = ImagePayloadMetadata( + source_path="/synthetic/raw.tif", + source_component_metadata={"channel": "1"}, + source_image_names=("Raw",), + ).payload_with(data) + binding = NamedSourceBinding(alias=alias) + request = RuntimeAdapterRequest( + context=SimpleNamespace(), + source_payload=payload, + source_binding_plan=CompiledSourceBindingPlan(bindings=(binding,)), + axis_scope=RuntimeExecutionAxisScope("A01"), + ) + + result = request.source_artifact_payload(binding.input_spec().ref()) + + assert image_payload_data(result) is data + assert image_payload_metadata(result).source_image_names == (alias,) + assert image_payload_metadata(result).source_path == "/synthetic/raw.tif" + + +def test_step_input_selects_current_component_planes_not_original_aliases(): + data = np.stack((np.full((4, 5), 7), np.full((4, 5), 91))) + payload = ImagePayloadMetadata( + plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, + source_image_names=("Raw1", "Raw2"), + source_image_provenance_planes=SourceImageProvenancePlanes.from_components( + paths=("/synthetic/ch1.tif", "/synthetic/ch2.tif"), + component_metadata=({"channel": "1"}, {"channel": "2"}), + ), + ).payload_with(data) + binding = NamedSourceBinding( + alias="Processed2", + selector=SourceSelector(components=(ComponentSelector(AllComponents.CHANNEL, "2"),)), + ) + + result = binding.project_step_input_payload(payload) + + np.testing.assert_array_equal(image_payload_data(result), data[1]) + assert image_payload_metadata(result).source_image_names == ("Processed2",) + assert image_payload_metadata(result).source_path == "/synthetic/ch2.tif" + missing = NamedSourceBinding( + alias="Absent", + selector=SourceSelector(components=(ComponentSelector(AllComponents.CHANNEL, "3"),)), + ) + with pytest.raises(ValueError, match="selects no current planes"): + missing.project_step_input_payload(payload) + + +def test_binding_origin_uses_existing_registered_universe_family(): + assert SourceUniverseRequest.for_binding(NamedSourceBinding(alias="Response")) is StepInputSourceUniverseRequest + assert SourceUniverseRequest.for_binding( + NamedSourceBinding(alias="Raw", origin=SourceBindingOrigin.PIPELINE_START) + ) is PipelineStartSourceUniverseRequest