Skip to content
Merged
133 changes: 133 additions & 0 deletions docs/validation/prepared-source-filter968/OWNER-CHECKPOINT.rst
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 21 additions & 0 deletions docs/validation/prepared-source-filter968/PR-BODY.md
Original file line number Diff line number Diff line change
@@ -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.
Binary file not shown.
33 changes: 33 additions & 0 deletions docs/validation/prepared-source-filter968/run_source.py
Original file line number Diff line number Diff line change
@@ -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',
]))
10 changes: 9 additions & 1 deletion openhcs/core/orchestrator/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
46 changes: 45 additions & 1 deletion openhcs/core/source_binding_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
29 changes: 27 additions & 2 deletions openhcs/core/source_workspace_projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from openhcs.core.source_bindings import (
SOURCE_BINDING_ALIAS_METADATA_FIELD,
NamedSourceBinding,
SourceBindingsConfig,
SourceProjectionRole,
)
from openhcs.core.source_metadata import (
Expand Down Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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,
)
Expand All @@ -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
Expand All @@ -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."""

Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading