diff --git a/docs/validation/prepared-source-filter968/OWNER-CHECKPOINT.rst b/docs/validation/prepared-source-filter968/OWNER-CHECKPOINT.rst new file mode 100644 index 0000000000..4baa640b15 --- /dev/null +++ b/docs/validation/prepared-source-filter968/OWNER-CHECKPOINT.rst @@ -0,0 +1,133 @@ +Prepared workspace source-filter admission: contribution to #968 +================================================================ + +Dewey owns integration and installed acceptance. The initial sections below are +historical investigation, superseded by the implemented checkpoint at the end. +Singer contributes the source +correction in this branch. Base is main2945688c4; no scientific request is +replayed and no active package, plate metadata or author client is modified. + +Determining source relationship +------------------------------ + +MicroscopeSourceSelectionRole.PREPARED_WORKSPACE preserves the prepared handler +when create_microscope_handler receives new source bindings. This preservation +is legitimate: replacing the handler with raw-file ingestion can discard the +persisted source reference/provenance contract. OpenHCSMicroscopeHandler then +initializes the persisted main directory without consuming source declarations. +Orchestrator.source_workspace_projection obtains the entire persisted projection +from VirtualWorkspaceSourceProjectionAuthority, also without those declarations. +SourceBindingWorkspaceProjector.source_candidates and +projection_set_for_candidates already own declared path-filter admission. +The fix must bring retained candidates through that existing admission owner; +it must not introduce another filename matcher or rewrite acquisition metadata. + +Retained original execution87ce42df-e3a5-4662-a5ee-0b9104cc6804 selected nine sites +despite the declared filename clause in REPAIR01-site7.py. The original inputs, +settings, outputs and terminal receipt remain immutable. Issue968 carries their +exact paths. This is a source-universe mismatch, not scientific accuracy proof. + +Ownership coordination and implementation boundary +------------------------------------------------- + +Requested exact shared-file/hunk release from Dewey before production edits. +PR973ea48dd982 changes runtime input consumption, not workspace candidate admission. +PR96460973129a changes compiled retention/runtime queries. PR966723d22cd changes +completed publication and DOES touch source_workspace_projection.py; that hunk +requires direct integration coordination. Neither PR is treated as the filter fix. +No shared production file has been edited in this checkpoint. + +NRA/refactor-audit and the catalog README were reread. Relevant ownership leads +are BOUND-2 (bypassing the existing admission owner), IMPL-12 (avoid a copied +filter procedure), and AGENT-2 (migrate the retained route, not only fresh input). +The existing refactor-audit Repository/Package loader parsed all702 production +modules at2945688c4 with zero parse omissions. An AST declaration/name/attribute +query enumerated the projector/filter/factory/projection family across handler, +orchestrator, compilation session/compiler, runtime context/function runtime, +execution-session/inspection services, inventory, viewer source and CP export. +The query also identified unrelated measurement_feature_queries.source_candidates +names; these are not workspace admission consumers. Relevant dependency/MRO +semantic closure remains pending, not silently omitted or claimed as global proof. + +The factory passes source_bindings_config to MicroscopeHandler.create, whose +base implementation discards it; the prepared handler inherits that method. +VirtualWorkspaceSourceProjectionAuthority.from_context and from_plate_metadata +also receive no source declarations. This confirms the bypass family rather +than a failure of SourceBindingsConfig.source_path_filters_match itself. + +Acceptance and remaining work +----------------------------- + +After the coherent owner correction: selected, unfiltered and no-match retained +workspace controls, two-channel exact source references/provenance, and a new +declaration admitted without generic consumer edits. Then ordinary installed +inspect/compile/execute in an engineering destination with the selected domain +and exact outputs. These are pending, not passed. No timeout or scope guard is +weakened. No new environment, worktree or scientific run is needed. + +Checkout custody +---------------- + +Reused the finished UI checkout through its original persistent path. Dalton's +cold relocation remains intact. Eight foreign gitlinks, historical validation +deletions/symlink targets and untracked originals remain unchanged. Only this +new receipt is staged; no reset, cleanup, bulk add or foreign edit. + +Implemented and source-qualified checkpoint (2026-10-06) +------------------------------------------------------- + +Dewey released candidate admission, prepared create/initialize, orchestrator, +from_plate_metadata and subsequent from_context declaration plumbing. The five +production files are source_binding_workspace.py, source_workspace_projection.py, +microscope_base.py, microscopes/openhcs.py and orchestrator/orchestrator.py. +SourceBindingWorkspaceProjector admits retained references using the original +SourceBindingsConfig matcher and SourceMetadataFields.source_filter_paths. +Empty/absent filter-path identities retain the existing backend/path fallback; +no new absence policy or reserved-field decoder is introduced. + +MicroscopeHandler.source_admission_config is the nominal handler hook; the +prepared handler retains its original resolved declaration and supplies it. +The existing authority consumes it on both plate and runtime-context paths. +Orchestrator selects the admitted component domain, then applies its original +common component filter. No second filtering procedure, registry, matcher or +acquisition metadata rewrite remains. The prepared handler protection remains. + +Mainc882d5edc67bffe7ec7f2eb3a2eeb7fe64e9415a is integrated in the two-parent +merge bdf5c6a3c410e1a49260d1bb72cfc103d9a4a876. The #966 runtime authority +and completed-output overlay are preserved: raw source admission occurs before +completed outputs are overlaid, not as a filter on produced filenames. +Normal porcelain merge refused the pre-existing validation symlink/deletions +before mutation (stash failed). Git merge-tree/read-tree/commit-tree integrated +the actual merge with both parents; the validation tree diff was empty. No +stash, reset, history restoration or foreign gitlink edit was performed. + +The original AST census parsed 702 production modules with zero omissions. +Relevant declarations/consumers were read through source metadata, projector, +handler factory/MRO, orchestrator and runtime authority. BOUND-2 and IMPL-12 +review corrections remove the reserved-field decode copy and duplicate filter +procedure. This is family source evidence, not global NRA/dynamic proof. + +qualification05: 65 PASS, terminal0, pytest10.00s/wall11.57s, peak350384KiB, +swaps0. Both source-binding workspace and completed-output lifecycle files run +through the original source bootstrap with byte-matched native extensions and +read-only target25 dependencies. No package installation/native/UI launch. +The controls exercise actual prepared handler, ProcessingContext and +PipelineOrchestrator: selected site7/two channels, unfiltered18 references, +independent site3 declaration, site99 no-match, original provenance object +identity, unchanged serialized metadata, component-filter intersection and +completed-output overlay outside the raw filename clause. + +Original qualification01 collection failure (stale PolyStore API) and +qualification02 fixture identity failures remain byte-exact. The fixture now +declares its filename metadata explicitly; no matching assertions were waived. +qualification03/04 passed the focused controls; qualification05 is the integrated +batch. qualification-logs.tar.gz contains all original stdout/stderr, including +the failures. Loose pytest scratch remains uncommitted and is not a new authority. + +Remaining acceptance belongs to Dewey: ordinary whole-candidate installed +inspect/compile/execute for selected, unfiltered and no-match prepared input. +Use the existing test fixture's nine-site/two-channel explicit metadata rules; +assert selected site7 yields two source references and exact two-channel +provenance, unfiltered yields18, no-match refuses before execution. Verify the +compiled/executed domain and exact persisted outputs through public routes, +then close the original engineering handles. No scientific request is replayed. diff --git a/docs/validation/prepared-source-filter968/PR-BODY.md b/docs/validation/prepared-source-filter968/PR-BODY.md new file mode 100644 index 0000000000..b7e7482f51 --- /dev/null +++ b/docs/validation/prepared-source-filter968/PR-BODY.md @@ -0,0 +1,21 @@ +## Implemented source checkpoint — addresses #968 + +Dewey owns integration and ordinary installed receiving; Singer contributes the released source family. Main c882d5ed is incorporated with #964/#966. No scientific request, UNKNOWN operation, installed package or foreign checkout was changed. + +Prepared handlers now retain the original SourceBindingsConfig declaration. The existing SourceBindingWorkspaceProjector admits retained sources through the existing matcher and SourceMetadataFields.source_filter_paths; the plate and runtime authorities consume the nominal handler hook. Orchestrator selects the admitted domain and reuses its common component filter. No copied reserved-field decode, matcher or second component-filter procedure. The runtime completed-output overlay remains after raw-source admission. + +Five production files: core/source_binding_workspace.py, core/source_workspace_projection.py, microscopes/microscope_base.py, microscopes/openhcs.py, core/orchestrator/orchestrator.py. + +## Qualification + +65 source controls PASS through real prepared handler, ProcessingContext and PipelineOrchestrator: selected/unfiltered/no-match, two-channel provenance identity, independent site3 declaration without consumer edits, component-filter intersection and completed-output overlay. Wall11.57s/peak350384KiB/swaps0. Original collection/fixture failures are preserved, not rewritten. + +Owner/AST/merge custody receipt: `docs/validation/prepared-source-filter968/OWNER-CHECKPOINT.rst`. Relevant 702-module census has zero parse omissions; scoped family evidence is not a global dynamic proof. Applicable BOUND-2/IMPL-12 corrections are implemented. + +Byte-exact logs: `docs/validation/prepared-source-filter968/qualification-logs.tar.gz`, SHA256 `60ce8a7834e48472e05dcfa8b47acad5401ff0d4ef5c4c5d7a57db17f6cccaa0`. + +## Remaining + +Dewey's ordinary whole-candidate installed public inspect/compile/execute acceptance: selected two-channel site7, unfiltered nine-site domain, and no-match pre-execution rejection with exact provenance/output checks. Source passing is not installed acceptance. No timeout/guard weakening, new environment or scientific replay. + +Eight foreign gitlink changes and the historical validation symlink/deletions are preserved and excluded. Normal merge failed before mutation on the historical symlink; Git's merge-tree backend produced the real two-parent integration with an empty historical validation tree diff. diff --git a/docs/validation/prepared-source-filter968/qualification-logs.tar.gz b/docs/validation/prepared-source-filter968/qualification-logs.tar.gz new file mode 100644 index 0000000000..e5a942d7d5 Binary files /dev/null and b/docs/validation/prepared-source-filter968/qualification-logs.tar.gz differ diff --git a/docs/validation/prepared-source-filter968/run_source.py b/docs/validation/prepared-source-filter968/run_source.py new file mode 100644 index 0000000000..7d6f29f554 --- /dev/null +++ b/docs/validation/prepared-source-filter968/run_source.py @@ -0,0 +1,33 @@ +"""Original source controls, qualified read-only dependencies and native owners.""" +from pathlib import Path +import runpy +import sys +from importlib.metadata import distribution + +root = Path(__file__).resolve().parents[3] +target = Path('/home/ts/wt/openhcs-issue-batch-20260929/engineering-pre-first-routing-20261004/receiving25/target') +sys.path.insert(0, str(target)) +installed = distribution('openhcs') +for item in installed.files: + if str(item).endswith('.cpp'): + assert (root / item).read_bytes() == installed.locate_file(item).read_bytes(), item +runpy.run_path(str(root / 'docs/validation/mcp-affine-inspection-436-20261002/source_fixture.py'))['load_readonly_native_extensions']() +sys.path.insert(0, str(root)) +import openhcs +assert Path(openhcs.__file__).resolve().parent == root / 'openhcs' +# OpenHCS's normal bootstrap activated the retained foreign externals. Prefer +# the existing qualified dependency target for subsequent dependency imports; +# OpenHCS submodule resolution stays on its already loaded source package. +sys.path.insert(0, str(target)) +import polystore.config +print('OpenHCS source:', openhcs.__file__, flush=True) +print('PolyStore:', polystore.config.__file__, flush=True) +assert Path(polystore.config.__file__).is_relative_to(target) +assert polystore.config.TiffPhotometric +import pytest +raise SystemExit(pytest.main([ + '--noconftest', '-o', 'addopts=', '-p', 'no:cacheprovider', + '--basetemp=' + str(Path(sys.argv[1]).resolve() / 'pytest'), + 'tests/unit/test_source_binding_workspace.py', + 'tests/unit/test_completed_output_publication_lifecycle.py', +])) diff --git a/openhcs/core/orchestrator/orchestrator.py b/openhcs/core/orchestrator/orchestrator.py index 495d3262dc..79752d3746 100644 --- a/openhcs/core/orchestrator/orchestrator.py +++ b/openhcs/core/orchestrator/orchestrator.py @@ -698,6 +698,9 @@ def source_workspace_projection(self): plate_path=plate_path, metadata_handler=self.microscope_handler.metadata_handler, filemanager=self.filemanager, + source_bindings=source_bindings_defaults_to_base( + self.get_effective_config().source_bindings_config + ), ).projection_if_available() if projection is not None: return projection @@ -830,12 +833,17 @@ def get_component_keys( # Convert to AllComponents for cache lookup (includes multiprocessing axis) component = convert_enum_by_value(component, AllComponents) or component + source_bindings = source_bindings_defaults_to_base( + self.get_effective_config().source_bindings_config + ) # Use component directly - let natural errors occur for wrong types component_name = component.value # Try metadata cache first (preferred source) cached_metadata = self._metadata_cache_service.get_cached_metadata(component) - if cached_metadata: + if source_bindings.source_filter_declarations: + all_components = list(self.source_workspace_projection().component_values(component)) + elif cached_metadata: all_components = list(cached_metadata.keys()) logger.debug( f"Using metadata cache for {component_name}: {len(all_components)} components" diff --git a/openhcs/core/source_binding_workspace.py b/openhcs/core/source_binding_workspace.py index 3567219876..d29dd287db 100644 --- a/openhcs/core/source_binding_workspace.py +++ b/openhcs/core/source_binding_workspace.py @@ -8,7 +8,7 @@ from itertools import product from pathlib import Path from types import MappingProxyType -from typing import ClassVar, cast +from typing import TYPE_CHECKING, ClassVar, cast from metaclass_registry import AutoRegisterMeta from polystore.virtual_workspace import SourcePixelRef @@ -68,6 +68,9 @@ ) from openhcs.core.vfs_protocol import FileManagerLike +if TYPE_CHECKING: + from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection + @dataclass(frozen=True, slots=True) class _SourceSet: @@ -627,6 +630,47 @@ def __post_init__(self) -> None: f"SourceBindingsConfig, got {type(self.source_bindings).__name__}." ) + def admit_prepared_projection( + self, projection: "VirtualWorkspaceSourceProjection" + ) -> "VirtualWorkspaceSourceProjection": + """Admit retained sources without rebuilding their paths or provenance.""" + from openhcs.core.source_workspace_projection import ( + VirtualWorkspacePathLookup, + VirtualWorkspaceSourceProjection, + ) + + if not self.source_bindings.source_filter_declarations: + return projection + selected_paths: set[str] = set() + selected_metadata_paths: set[str] = set() + for path, ref in projection.source_refs_by_virtual_path.items(): + metadata = projection.source_metadata_for( + VirtualWorkspacePathLookup.from_paths(path, path) + ) + filter_paths = ( + () if metadata is None else SourceMetadataFields.source_filter_paths(metadata) + ) or (ref.backend_address, path) + if self.source_bindings.source_path_filters_match(filter_paths): + selected_paths.add(path) + selected_metadata_paths.update((path, ref.backend_address)) + if not selected_paths: + raise ValueError("Declared source filters matched no prepared workspace sources.") + return VirtualWorkspaceSourceProjection( + source_refs_by_virtual_path=MappingProxyType({ + path: ref for path, ref in projection.source_refs_by_virtual_path.items() + if path in selected_paths + }), + source_metadata_by_path=MappingProxyType({ + path: metadata for path, metadata in projection.source_metadata_by_path.items() + if path in selected_metadata_paths + }), + source_projections_by_virtual_path=MappingProxyType({ + path: source for path, source in projection.source_projections_by_virtual_path.items() + if path in selected_paths + }), + workspace_root=projection.workspace_root, + ) + def projection_set( self, plate_path: Path, diff --git a/openhcs/core/source_workspace_projection.py b/openhcs/core/source_workspace_projection.py index 7b392d9458..9ab3c527d3 100644 --- a/openhcs/core/source_workspace_projection.py +++ b/openhcs/core/source_workspace_projection.py @@ -22,6 +22,7 @@ from openhcs.core.source_bindings import ( SOURCE_BINDING_ALIAS_METADATA_FIELD, NamedSourceBinding, + SourceBindingsConfig, SourceProjectionRole, ) from openhcs.core.source_metadata import ( @@ -522,6 +523,18 @@ def relative_virtual_paths(self) -> tuple[str, ...]: return relative_virtual_paths return tuple(self.source_refs_by_virtual_path) + def component_values(self, component) -> tuple[str, ...]: + """Derive the execution component domain from admitted source metadata.""" + return tuple(dict.fromkeys( + value + for path in self.relative_virtual_paths() + for value in source_component_metadata_values( + self.source_metadata_for(VirtualWorkspacePathLookup.from_paths( + path, self._loadable_virtual_path(path) + )) or {}, component, + ) + )) + def filtered_by_axis( self, *, @@ -764,6 +777,7 @@ class VirtualWorkspaceSourceProjectionAuthority: metadata_handler: "MetadataHandler" filemanager: "FileManager" cache: VirtualWorkspaceSourceProjectionCache | None = None + source_bindings: SourceBindingsConfig | None = None _workspace_metadata_handler: "OpenHCSMetadataHandler | None" = field( default=None, init=False, compare=False, repr=False, ) @@ -781,6 +795,7 @@ def from_context( filemanager=context.filemanager, cache=DEFAULT_SOURCE_PROJECTION_CACHE if cache is None else cache, context=context, + source_bindings=context.microscope_handler.source_admission_config(), ) @classmethod @@ -791,6 +806,7 @@ def from_plate_metadata( metadata_handler: "MetadataHandler", filemanager: "FileManager", cache: VirtualWorkspaceSourceProjectionCache | None = None, + source_bindings: SourceBindingsConfig | None = None, ) -> "VirtualWorkspaceSourceProjectionAuthority": """Build projection authority from the plate-level metadata owners.""" @@ -799,6 +815,7 @@ def from_plate_metadata( metadata_handler=metadata_handler, filemanager=filemanager, cache=DEFAULT_SOURCE_PROJECTION_CACHE if cache is None else cache, + source_bindings=source_bindings, ) def is_bound_to_context(self, context: "ProcessingContext") -> bool: @@ -845,11 +862,19 @@ def projection_if_available(self) -> VirtualWorkspaceSourceProjection | None: if not OpenHCSMetadataSubdirectories(metadata).has_workspace_mapping(): continue if self.cache is None: - return VirtualWorkspaceSourceProjection.from_openhcs_metadata( + projection = VirtualWorkspaceSourceProjection.from_openhcs_metadata( self.plate_path, metadata, ) - return self.cache.projection_for(self.plate_path, metadata) + else: + projection = self.cache.projection_for(self.plate_path, metadata) + if self.source_bindings is not None: + from openhcs.core.source_binding_workspace import SourceBindingWorkspaceProjector + + projection = SourceBindingWorkspaceProjector( + self.source_bindings + ).admit_prepared_projection(projection) + return projection return None def projection_or_empty(self) -> VirtualWorkspaceSourceProjection: diff --git a/openhcs/microscopes/microscope_base.py b/openhcs/microscopes/microscope_base.py index 500d4ea1d8..6b2ed605b2 100644 --- a/openhcs/microscopes/microscope_base.py +++ b/openhcs/microscopes/microscope_base.py @@ -242,6 +242,10 @@ def projects_declared_source_bindings(cls) -> bool: return False + def source_admission_config(self) -> Optional["SourceBindingsConfig"]: + """Return declarations still required to admit a retained source universe.""" + return None + @classmethod def source_selection_role(cls) -> MicroscopeSourceSelectionRole: """Declare this handler as the owner of a format-specific source layout.""" diff --git a/openhcs/microscopes/openhcs.py b/openhcs/microscopes/openhcs.py index 367e05bc5b..04deddf86f 100644 --- a/openhcs/microscopes/openhcs.py +++ b/openhcs/microscopes/openhcs.py @@ -1337,6 +1337,28 @@ class OpenHCSMicroscopeHandler(MicroscopeHandler): _microscope_type = Microscope.OPENHCS.value _metadata_handler_class = None # Set explicitly after class definition + @classmethod + def create( + cls, *, filemanager: FileManager, pattern_format: Optional[str] = None, + source_bindings_config=None, + ) -> "OpenHCSMicroscopeHandler": + """Keep prepared source ownership while consuming declared admission.""" + from openhcs.core.source_bindings import source_bindings_defaults_to_base + + handler = super().create( + filemanager=filemanager, pattern_format=pattern_format, + source_bindings_config=source_bindings_config, + ) + handler._source_bindings_config = ( + None if source_bindings_config is None + else source_bindings_defaults_to_base(source_bindings_config) + ) + return handler + + def source_admission_config(self): + """Expose the original prepared-workspace declaration to runtime readers.""" + return self._source_bindings_config + @classmethod def source_selection_role(cls) -> MicroscopeSourceSelectionRole: """Declare OpenHCS data as an already prepared workspace format.""" @@ -1368,6 +1390,7 @@ def __init__(self, filemanager: FileManager, pattern_format: Optional[str] = Non None # Will be set by factory or post_workspace ) self.pattern_format = pattern_format # Store for parser instantiation + self._source_bindings_config = None # Initialize super with a None parser. The actual parser is loaded dynamically. # The `parser` property will handle on-demand loading. @@ -1592,6 +1615,17 @@ def initialize_workspace(self, plate_path: Path, filemanager: FileManager) -> Pa # Set plate_folder to the metadata-owning root, even if the caller passed # a child such as images/ or images_results/. self.plate_folder = plate_root + if self._source_bindings_config is not None: + from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjectionAuthority + + projection = VirtualWorkspaceSourceProjectionAuthority.from_plate_metadata( + plate_path=plate_root, + metadata_handler=self.metadata_handler, + filemanager=filemanager, + source_bindings=self._source_bindings_config, + ).projection_if_available() + if projection is None and self._source_bindings_config.source_filter_declarations: + raise ValueError("Prepared source filtering requires a typed workspace projection.") logger.debug("OpenHCSHandler: plate_folder set to %s", self.plate_folder) # Determine the main subdirectory from metadata - fail-loud on errors diff --git a/tests/unit/test_completed_output_publication_lifecycle.py b/tests/unit/test_completed_output_publication_lifecycle.py index 61a6601e83..53b1d9348b 100644 --- a/tests/unit/test_completed_output_publication_lifecycle.py +++ b/tests/unit/test_completed_output_publication_lifecycle.py @@ -59,6 +59,7 @@ def _context(plate_root: Path, count: int) -> ProcessingContext: context.microscope_handler = SimpleNamespace( parser=SourceSchemaFilenameParser(), metadata_handler=SimpleNamespace(source_workspace_metadata_document=lambda _p: None), + source_admission_config=lambda: None, ) context.freeze() return context diff --git a/tests/unit/test_source_binding_workspace.py b/tests/unit/test_source_binding_workspace.py index 94c7c0c6c5..10ebe119af 100644 --- a/tests/unit/test_source_binding_workspace.py +++ b/tests/unit/test_source_binding_workspace.py @@ -49,6 +49,8 @@ ) from openhcs.core.source_workspace_projection import ( VirtualWorkspaceSourceProjectionCache, + VirtualWorkspaceSourceProjectionAuthority, + VirtualWorkspacePathLookup, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.microscopes.source_bindings_handler import SourceBindingsHandler @@ -69,6 +71,94 @@ def _filemanager() -> FileManager: return FileManager(dict(storage_registry)) +@pytest.mark.parametrize("selection,expected_sites", ((None, tuple(range(1, 10))), (7, (7,)), (3, (3,)))) +def test_prepared_workspace_admits_declared_source_universe_without_rewriting_provenance( + tmp_path, selection, expected_sites, +): + source = tmp_path / "source" + source.mkdir() + files = tuple(source / f"A01_s{site:03}_w{channel}.tif" + for site in range(1, 10) for channel in (1, 2)) + for path in files: + _write_tiff_stack(path, (11,)) + filemanager = _filemanager() + workspace = tmp_path / "prepared" + materialization = SourceBindingWorkspaceProjector( + SourceBindingsConfig(metadata_rules=(MetadataExtractionRule( + source=MetadataSource.FILE_NAME, + pattern=r"(?PA\d+)_s(?P\d+)_w(?P\d+)", + ),)), + parser=SourceSchemaFilenameParser(), + ).materialize(source, workspace, filemanager=filemanager, + source_backend=Backend.DISK, workspace_backend=Backend.DISK, + source_files=files) + (workspace / FIELDS.DEFAULT_SUBDIRECTORY).mkdir(exist_ok=True) + original_bytes = materialization.metadata_path.read_bytes() + config = SourceBindingsConfig(source_filters=() if selection is None else ( + SourceFilterClause(subject=SourceFilterSubject.FILE, + match_type=SourceFilterMatchType.CONTAINS, + value=f"_s{selection:03}_"), + )) + handler = create_microscope_handler("auto", workspace, filemanager, + source_bindings_config=config) + from openhcs.microscopes.openhcs import OpenHCSMicroscopeHandler + assert isinstance(handler, OpenHCSMicroscopeHandler) + handler.initialize_workspace(workspace, filemanager) + cache = VirtualWorkspaceSourceProjectionCache() + full = VirtualWorkspaceSourceProjectionAuthority.from_plate_metadata( + plate_path=workspace, metadata_handler=handler.metadata_handler, + filemanager=filemanager, cache=cache, + ).projection_or_empty() + selected = VirtualWorkspaceSourceProjectionAuthority.from_plate_metadata( + plate_path=workspace, metadata_handler=handler.metadata_handler, + filemanager=filemanager, cache=cache, source_bindings=config, + ).projection_or_empty() + assert set(selected.component_values(AllComponents.SITE)) == set(map(str, expected_sites)) + assert set(selected.component_values(AllComponents.CHANNEL)) == {"1", "2"} + assert len(selected.pipeline_start_files()) == len(expected_sites) * 2 + for path in selected.pipeline_start_files(): + lookup = VirtualWorkspacePathLookup.from_paths(path, path) + assert selected.source_ref_for(lookup) is full.source_ref_for(lookup) + assert selected.require_source_projection_for(lookup) is full.require_source_projection_for(lookup) + assert selected.source_metadata_for(lookup) == full.source_metadata_for(lookup) + assert len(full.pipeline_start_files()) == 18 + from openhcs.core.context.processing_context import ProcessingContext + context = ProcessingContext(filemanager=filemanager, axis_id="A01") + context.plate_path = workspace + context.microscope_handler = handler + runtime_projection = VirtualWorkspaceSourceProjectionAuthority.from_context( + context, + ).projection_or_empty() + assert runtime_projection.pipeline_start_files() == selected.pipeline_start_files() + from openhcs.core.config import PipelineConfig, LazySourceBindingsConfig + from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator + orchestrator = PipelineOrchestrator( + workspace, pipeline_config=PipelineConfig( + source_bindings_config=LazySourceBindingsConfig(source_filters=config.source_filters), + ), + ).initialize() + assert orchestrator.source_workspace_files() == selected.pipeline_start_files() + assert set(orchestrator.get_component_keys(AllComponents.SITE)) == set(map(str, expected_sites)) + assert orchestrator.get_component_keys(AllComponents.SITE, [str(expected_sites[0])]) == [str(expected_sites[0])] + assert orchestrator.get_component_keys(AllComponents.SITE, ["99"]) == [] + from tests.unit.test_completed_output_publication_lifecycle import _facts + context.record_completed_step_outputs(_facts(workspace)) + with_output = VirtualWorkspaceSourceProjectionAuthority.from_context(context).projection_or_empty() + assert set(with_output.pipeline_start_files()) == { + *selected.pipeline_start_files(), str(workspace / "images/saved.tif"), + } + assert materialization.metadata_path.read_bytes() == original_bytes + with pytest.raises(ValueError, match="matched no prepared workspace sources"): + VirtualWorkspaceSourceProjectionAuthority.from_plate_metadata( + plate_path=workspace, metadata_handler=handler.metadata_handler, + filemanager=filemanager, source_bindings=SourceBindingsConfig(source_filters=( + SourceFilterClause(subject=SourceFilterSubject.FILE, + match_type=SourceFilterMatchType.CONTAINS, + value="_s099_"), + )), + ).projection_if_available() + + @pytest.mark.parametrize( "spacing,expected_scalar,physical", (