diff --git a/benchmark/__init__.py b/benchmark/__init__.py index 02c6cd0685..6c008ef24b 100644 --- a/benchmark/__init__.py +++ b/benchmark/__init__.py @@ -3,111 +3,71 @@ from __future__ import annotations import openhcs as _openhcs_dependency_bootstrap # noqa: F401 - -__all__ = ( - "DatasetSpec", - "AcquiredDataset", - "MetricCollector", - "BenchmarkResult", - "ToolAdapter", - "ToolAdapterError", - "ToolExecutionError", - "ToolNotInstalledError", - "ToolVersionError", - "DatasetAcquisitionError", - "acquire_dataset", - "BBBC021_SINGLE_PLATE", - "DATASET_REGISTRY", - "get_dataset_spec", - "PipelineSpec", - "NUCLEI_SEGMENTATION", - "PIPELINE_REGISTRY", - "get_pipeline_spec", - "TimeMetric", - "MemoryMetric", - "BenchmarkCaseProgress", - "BenchmarkProgressEvent", - "BenchmarkProgressEventKind", - "BenchmarkProgressSnapshot", - "iter_progress_events", - "summarize_progress", - "CellProfilerAdapter", - "OpenHCSAdapter", - "CellProfilerCompatibilityResult", - "run_benchmark", - "run_cellprofiler_compatibility_benchmark", +from python_introspect import lazy_exports + +__all__ = lazy_exports( + globals(), + { + "benchmark.contracts.dataset": ( + "DatasetSpec", + "AcquiredDataset", + ), + "benchmark.contracts.metric": ( + "MetricCollector", + ), + "benchmark.contracts.tool_adapter": ( + "BenchmarkResult", + "ToolAdapter", + "ToolAdapterError", + "ToolExecutionError", + "ToolNotInstalledError", + "ToolVersionError", + ), + "benchmark.datasets.acquire": ( + "DatasetAcquisitionError", + "acquire_dataset", + ), + "benchmark.datasets": ( + "BBBC021_SINGLE_PLATE", + "DATASET_REGISTRY", + ), + "benchmark.datasets.registry": ( + "get_dataset_spec", + ), + "benchmark.contracts.pipeline": ( + "PipelineSpec", + ), + "benchmark.pipelines": ( + "NUCLEI_SEGMENTATION", + ), + "benchmark.pipelines.registry": ( + "PIPELINE_REGISTRY", + "get_pipeline_spec", + ), + "benchmark.metrics.time": ( + "TimeMetric", + ), + "benchmark.metrics.memory": ( + "MemoryMetric", + ), + "benchmark.progress": ( + "BenchmarkCaseProgress", + "BenchmarkProgressEvent", + "BenchmarkProgressEventKind", + "BenchmarkProgressSnapshot", + "iter_progress_events", + "summarize_progress", + ), + "benchmark.adapters.cellprofiler": ( + "CellProfilerAdapter", + ), + "benchmark.adapters.openhcs": ( + "OpenHCSAdapter", + ), + "benchmark.runner": ( + "CellProfilerCompatibilityResult", + "run_benchmark", + "run_cellprofiler_compatibility_benchmark", + ), + }, ) - -_EXPORT_NAMES = frozenset(__all__) -_MISSING_EXPORT = object() - - -def _benchmark_export_modules(): - import benchmark.contracts.dataset as dataset_contracts - - yield dataset_contracts - - import benchmark.contracts.metric as metric_contracts - - yield metric_contracts - - import benchmark.contracts.pipeline as pipeline_contracts - - yield pipeline_contracts - - import benchmark.contracts.tool_adapter as tool_adapter_contracts - - yield tool_adapter_contracts - - import benchmark.datasets as dataset_exports - - yield dataset_exports - - import benchmark.pipelines as pipeline_exports - - yield pipeline_exports - - import benchmark.metrics as metric_exports - - yield metric_exports - - import benchmark.progress as progress_exports - - yield progress_exports - - import benchmark.adapters.openhcs as openhcs_adapter - - yield openhcs_adapter - - import benchmark.adapters.cellprofiler as cellprofiler_adapter - - yield cellprofiler_adapter - - import benchmark.runner as runner_exports - - yield runner_exports - - -def resolve_benchmark_export(name: str): - """Resolve one public benchmark export from its owning module.""" - if name not in _EXPORT_NAMES: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - existing = globals().get(name, _MISSING_EXPORT) - if existing is not _MISSING_EXPORT: - return existing - for module in _benchmark_export_modules(): - namespace = vars(module) - if name in namespace: - value = namespace[name] - globals()[name] = value - return value - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - -def __getattr__(name: str): - """Resolve public benchmark re-exports from their owning modules on demand.""" - return resolve_benchmark_export(name) - - -def __dir__() -> list[str]: - return sorted(set(globals()) | _EXPORT_NAMES) diff --git a/benchmark/adapters/__init__.py b/benchmark/adapters/__init__.py index 5dc925c7ad..2ee06c9821 100644 --- a/benchmark/adapters/__init__.py +++ b/benchmark/adapters/__init__.py @@ -2,42 +2,12 @@ from __future__ import annotations -__all__ = ("CellProfilerAdapter", "OpenHCSAdapter") - -_EXPORT_NAMES = frozenset(__all__) -_MISSING_EXPORT = object() - - -def _adapter_export_modules(): - import benchmark.adapters.openhcs as openhcs_adapter - - yield openhcs_adapter - - import benchmark.adapters.cellprofiler as cellprofiler_adapter - - yield cellprofiler_adapter - - -def resolve_adapter_export(name: str): - """Resolve one public adapter export from its owning module.""" - if name not in _EXPORT_NAMES: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - existing = globals().get(name, _MISSING_EXPORT) - if existing is not _MISSING_EXPORT: - return existing - for module in _adapter_export_modules(): - namespace = vars(module) - if name in namespace: - value = namespace[name] - globals()[name] = value - return value - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - -def __getattr__(name: str): - """Resolve public adapter re-exports from their owning modules on demand.""" - return resolve_adapter_export(name) - - -def __dir__() -> list[str]: - return sorted(set(globals()) | _EXPORT_NAMES) +from python_introspect import lazy_exports + +__all__ = lazy_exports( + globals(), + { + ".cellprofiler": ("CellProfilerAdapter",), + ".openhcs": ("OpenHCSAdapter",), + }, +) diff --git a/benchmark/agent_validation/corpus.py b/benchmark/agent_validation/corpus.py index fe0d896a1d..20fb24c853 100644 --- a/benchmark/agent_validation/corpus.py +++ b/benchmark/agent_validation/corpus.py @@ -31,7 +31,7 @@ from benchmark.agent_validation.perturbations import DiagnosticPerturbationDeclaration from benchmark.agent_validation.scoring import AttemptJournalScorer from openhcs.core.pipeline_document import PipelineDocumentAuthority -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @dataclass(frozen=True, slots=True) diff --git a/benchmark/agent_validation/journal.py b/benchmark/agent_validation/journal.py index cbc3909315..04ab799f68 100644 --- a/benchmark/agent_validation/journal.py +++ b/benchmark/agent_validation/journal.py @@ -7,7 +7,7 @@ from pathlib import Path from benchmark.agent_validation.contracts import AttemptRecord -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @dataclass(frozen=True, slots=True) diff --git a/benchmark/agent_validation/mcp_attempt_recorder.py b/benchmark/agent_validation/mcp_attempt_recorder.py index c8f9533b3d..f736a87158 100644 --- a/benchmark/agent_validation/mcp_attempt_recorder.py +++ b/benchmark/agent_validation/mcp_attempt_recorder.py @@ -17,7 +17,7 @@ from dataclasses import dataclass, fields from pathlib import Path -from python_introspect import dataclass_from_mapping +from python_introspect import JsonObject, dataclass_from_mapping, to_jsonable from benchmark.agent_validation.contracts import ( ArchitectureViolation, @@ -49,7 +49,7 @@ ValidatePipelineCapability, get_agent_capability, ) -from openhcs.agent.dto.common import JsonObject, RenderedSource +from openhcs.agent.dto.common import RenderedSource from openhcs.agent.dto.execution import ArtifactPlanInspection, ExecutionJobRef from openhcs.agent.dto.functions import ( CustomFunctionRegistrationResult, @@ -66,7 +66,6 @@ McpDevToolResult, first_payload_mapping, ) -from openhcs.serialization.json import to_jsonable @dataclass(frozen=True, slots=True) diff --git a/benchmark/annotated_validation.py b/benchmark/annotated_validation.py index 40e2cc1fb5..fd71818c0b 100644 --- a/benchmark/annotated_validation.py +++ b/benchmark/annotated_validation.py @@ -20,7 +20,7 @@ from zipfile import ZipFile from collections.abc import Iterator from metaclass_registry import AutoRegisterMeta -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.core.runtime_measurements import MeasurementRowAxisField from openhcs.processing.backends.cellprofiler.intensity import ( MeasureObjectIntensityModule, diff --git a/benchmark/cellprofiler_benchmark_cli.py b/benchmark/cellprofiler_benchmark_cli.py index d397a42e59..2edd89004d 100644 --- a/benchmark/cellprofiler_benchmark_cli.py +++ b/benchmark/cellprofiler_benchmark_cli.py @@ -108,7 +108,7 @@ def configure( def run(self, args: argparse.Namespace) -> int: from benchmark.contracts.control import BenchmarkRunInspectionRequest from benchmark.control import inspect_benchmark_run, report_benchmark_run - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable inspection = inspect_benchmark_run( BenchmarkRunInspectionRequest( @@ -149,7 +149,7 @@ def run(self, args: argparse.Namespace) -> int: inspect_measured_pipeline_run, report_measured_pipeline_run, ) - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable inspection = inspect_measured_pipeline_run(args.output_dir) if args.report: @@ -226,7 +226,7 @@ def run(self, args: argparse.Namespace) -> int: from openhcs.runtime.zmq_execution_signature import ( ZMQRuntimeObservationExportScope, ) - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable output_dir = args.output_dir.expanduser().resolve() policy = AgentPathPolicy.with_roots( @@ -333,7 +333,7 @@ def configure( def run(self, args: argparse.Namespace) -> int: from benchmark.control import discover_benchmark_cases - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable result = discover_benchmark_cases( args.manifest, @@ -422,7 +422,7 @@ def run(self, args: argparse.Namespace) -> int: well_throughput_start_method_from_manifest, ) from openhcs.core.config import MultiprocessingStartMethod - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable if args.max_memory_mb is not None and ( not math.isfinite(args.max_memory_mb) or args.max_memory_mb <= 0 diff --git a/benchmark/contracts/measured_run_receipt.py b/benchmark/contracts/measured_run_receipt.py index 009409ac08..d16db405c6 100644 --- a/benchmark/contracts/measured_run_receipt.py +++ b/benchmark/contracts/measured_run_receipt.py @@ -9,13 +9,12 @@ from pathlib import Path from typing import Self -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from benchmark.contracts.run_artifacts import write_new_measured_artifact from benchmark.timing import PhaseTimingRecord from openhcs.runtime.environment_provenance import RuntimeEnvironmentSnapshot from openhcs.runtime.zmq_execution_signature import ZMQRuntimeObservationExportScope -from openhcs.serialization.json import to_jsonable MEASURED_PIPELINE_RUN_RECEIPT_SCHEMA_VERSION = "openhcs.benchmark.measured-pipeline.v2" _ARCHIVED_MEASURED_PIPELINE_RUN_RECEIPT_SCHEMA_VERSION = ( diff --git a/benchmark/contracts/run_receipt.py b/benchmark/contracts/run_receipt.py index 94bd8637d0..5a15ce1cf7 100644 --- a/benchmark/contracts/run_receipt.py +++ b/benchmark/contracts/run_receipt.py @@ -14,9 +14,8 @@ from pathlib import Path from typing import Self -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable -from openhcs.serialization.json import to_jsonable COMPARISON_SUITE_RUN_RECEIPT_SCHEMA_VERSION = ( "openhcs.benchmark.comparison-suite-run.v1" diff --git a/benchmark/datasets/__init__.py b/benchmark/datasets/__init__.py index 0b78c5dd86..d282066513 100644 --- a/benchmark/datasets/__init__.py +++ b/benchmark/datasets/__init__.py @@ -1,6 +1,6 @@ """Dataset utilities and registry.""" -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from benchmark.contracts.dataset import ( ArchiveFormat, diff --git a/benchmark/matched_cellprofiler_batch.py b/benchmark/matched_cellprofiler_batch.py index ab0ac57364..c4ddaba76b 100644 --- a/benchmark/matched_cellprofiler_batch.py +++ b/benchmark/matched_cellprofiler_batch.py @@ -121,7 +121,7 @@ ZMQAuxiliaryExecutionParams, ZMQRuntimeObservationExportScope, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def _parser() -> argparse.ArgumentParser: diff --git a/benchmark/metrics/__init__.py b/benchmark/metrics/__init__.py index 891ccebad8..3fd80ce68a 100644 --- a/benchmark/metrics/__init__.py +++ b/benchmark/metrics/__init__.py @@ -1,6 +1,6 @@ """Metric collectors.""" -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from benchmark.metrics.time import TimeMetric from benchmark.metrics.memory import MemoryMetric diff --git a/benchmark/native_measurement_facts.py b/benchmark/native_measurement_facts.py index 1d19eb9d63..61bd518d60 100644 --- a/benchmark/native_measurement_facts.py +++ b/benchmark/native_measurement_facts.py @@ -17,7 +17,7 @@ RuntimeMeasurementSnapshot, runtime_measurement_projection_cache_identity, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def _policy_identity(value): diff --git a/benchmark/pipelines/__init__.py b/benchmark/pipelines/__init__.py index 2148a1ee4d..061b136d0b 100644 --- a/benchmark/pipelines/__init__.py +++ b/benchmark/pipelines/__init__.py @@ -1,6 +1,6 @@ """Pipeline registry.""" -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from benchmark.contracts.pipeline import PipelineSpec from benchmark.pipelines.registry import ( diff --git a/benchmark/prepare_blind_neurite.py b/benchmark/prepare_blind_neurite.py index bce1775467..0155f7f0f9 100644 --- a/benchmark/prepare_blind_neurite.py +++ b/benchmark/prepare_blind_neurite.py @@ -22,7 +22,7 @@ import numpy as np import tifffile -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable class Channel(Enum): diff --git a/benchmark/well_throughput_scaling.py b/benchmark/well_throughput_scaling.py index 897f59f1fc..d3a0a621d5 100644 --- a/benchmark/well_throughput_scaling.py +++ b/benchmark/well_throughput_scaling.py @@ -79,7 +79,7 @@ ZMQAuxiliaryExecutionParams, ZMQRuntimeObservationExportScope, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable WELL_THROUGHPUT_ROWS_CSV = "well_throughput.csv" WELL_THROUGHPUT_EVENTS_CSV = "well_throughput_progress_events.csv" diff --git a/docs/refactor/consolidation-20261009/00-RULES.md b/docs/refactor/consolidation-20261009/00-RULES.md index be11647d4a..a824876298 100644 --- a/docs/refactor/consolidation-20261009/00-RULES.md +++ b/docs/refactor/consolidation-20261009/00-RULES.md @@ -65,5 +65,5 @@ State every claim at its actual strength. Unknowns are decisions with defaults, ## Project specifics - **Python:** 3.11 to 3.14; the repo `.venv` is 3.12. Run heavy commands with `nice -n 19`; the owner runs long jobs on this machine. -- **Exemplars to migrate onto, never fork:** `AutoRegisterMeta` families with key extractors (`microscopes/microscope_base.py:184`); `EnumKeyedStrategyMixin`, `NominalTypeKeyedStrategyMixin`, `MostDerivedContextStrategyMixin` (`metaclass_registry.strategies`, used in 60 files); `AgentCapabilityDeclaration` with transport and profile capability mixins (`agent/capabilities.py:415-560`); `McpDevTypedOutputRenderer` (`mcp/dev_client_rendering.py:280`); `RuntimeSliceProjectableValue` (`core/runtime_plane_projection.py:19`); `ProgressPhaseDeclarationBase` with capability mixins (`core/progress/types.py:153-330`); `NapariControlMessageAction`; `serialization/json.to_jsonable`; `public_api.declared_public_names`; `metaclass_registry.caches.BoundedCache`; pyqt-reactive's `IsomorphicDataclassRowPathPolicy`; CellProfiler module leaves built from policy mixins (`processing/backends/cellprofiler/shape.py:70`). +- **Exemplars to migrate onto, never fork:** `AutoRegisterMeta` families with key extractors (`microscopes/microscope_base.py:184`); `EnumKeyedStrategyMixin`, `NominalTypeKeyedStrategyMixin`, `MostDerivedContextStrategyMixin` (`metaclass_registry.strategies`, used in 60 files); `AgentCapabilityDeclaration` with transport and profile capability mixins (`agent/capabilities.py:415-560`); `McpDevTypedOutputRenderer` (`mcp/dev_client_rendering.py:280`); `RuntimeSliceProjectableValue` (`core/runtime_plane_projection.py:19`); `ProgressPhaseDeclarationBase` with capability mixins (`core/progress/types.py:153-330`); `NapariControlMessageAction`; python-introspect `to_jsonable`, `dataclass_from_mapping`, `declared_public_names` and `lazy_exports`; `metaclass_registry.caches.BoundedCache`; pyqt-reactive's `IsomorphicDataclassRowPathPolicy`; CellProfiler module leaves built from policy mixins (`processing/backends/cellprofiler/shape.py:70`). - **Non-product code:** `benchmark/`, `scripts/`, `paper/`, `docs/`. Excluded from the ratchet. Research and diagnostic tools found inside `openhcs/` move there or are deleted. diff --git a/docs/refactor/consolidation-20261009/L2-codec-public-api.md b/docs/refactor/consolidation-20261009/L2-codec-public-api.md new file mode 100644 index 0000000000..8d6223e1e2 --- /dev/null +++ b/docs/refactor/consolidation-20261009/L2-codec-public-api.md @@ -0,0 +1,45 @@ +# L2: python-introspect owns the dataclass codec and module surfaces + +**Head audited:** `openhcs` `main` at `9a2550401` (#1163); `python-introspect` `main` at `83c1efe` (0.2.1). **Rules:** [00-RULES.md](00-RULES.md). **Step 2.** +**Shared abstractions** ([02-SHARED-ABSTRACTIONS.md](02-SHARED-ABSTRACTIONS.md)). *Builds:* the library half of A2 (one encoder, one decoder). *Uses:* python-introspect `dataclass_from_mapping`. + +## What is wrong + +**Generic codec and module-surface mechanisms live in OpenHCS beside a library that already owns half of them, and the decoder is written three times.** + +- `openhcs/serialization/json.py` (120 lines) holds `to_jsonable` and the `JsonValue`/`JsonObject`/`JsonScalar` aliases. Nothing in it is OpenHCS-specific: dataclass fields, mappings, sequences, enums, paths, callables (via python-introspect's `signature_analysis_target`) and `AutoRegisterMeta` types. 36 production modules and about 80 non-product files import it. +- Its decoder already exists in python-introspect (`dataclass_projection.dataclass_from_mapping`, strict: rejects undeclared fields, validates annotations, decodes nested dataclasses, enums, paths, unions, `JsonValue`). +- OpenHCS writes the decoder twice more: + - `AgentDtoJsonCodec` (`agent/services/ui_bridge_transport.py:83-181`, 99 lines): a looser copy that silently drops undeclared fields, accepts `None` for any annotation and returns the first union member that does not raise. 32 call sites in `ui_bridge_transport.py` and `pyqt_gui/services/ui_bridge_server.py`, plus tests, scripts and `paper/figures`. + - `DebugJsonCodec` (`core/debug.py:394-437`): `dataclass_from_record` passes values through unconverted; `dataclass_record` is `asdict`, a third encoder; `cursor_from_record` patches `step_index` with `int()`. 14 uses, all in `core/debug.py`. +- `openhcs/core/public_api.py` (73 lines): module public-surface derivation, imported by 32 production modules (29 CellProfiler backend modules) and 3 benchmark packages. +- Lazy-export `__getattr__`/`__dir__` written by hand in OpenHCS `__init__`s: `agent/dto/__init__.py` (resolver scanning every DTO module plus a placeholder-swapping module subclass), `benchmark/__init__.py` and `benchmark/adapters/__init__.py` (the same resolver, copied), `pyqt_gui/__init__.py` (one `if` per name), `core/steps/__init__.py`. Three more are dead: `core/__init__.py` (a `CoreExport` enum and loader table nothing reads), `processing/__init__.py` (aliases `openhcs.processing.` for `openhcs.processing.backends.`; no reader), `processing/backends/processors/__init__.py` (re-implements submodule import, which Python already does). +- The same copy lives in arraybridge (`__init__.py:96-109`), PolyStore (`__init__.py:90-103`, `streaming/__init__.py:28-41`), zmqruntime (`__init__.py:277-289`) and pyqt-reactive (`widgets/shared/__init__.py:197-208`). Those repos are out of scope here and are listed for their owners. + +## Target + +- python-introspect 0.2.2 owns `to_jsonable` and the JSON aliases (`python_introspect.jsonable`), the public-surface helpers and a new `lazy_exports(globals(), {owner_module: names}) -> names` (`python_introspect.public_api`). The release is additive and stays inside ObjectState's `python-introspect<0.3` bound. python-introspect depends only on `annotated-types` and `metaclass-registry` (which has no dependencies), so no cycle. +- Every importer imports from `python_introspect` directly. Deleted: `openhcs/serialization/json.py`, `openhcs/core/public_api.py`, `AgentDtoJsonCodec`, `DebugJsonCodec`. +- `dataclass_from_mapping` is the only decoder; `to_jsonable` the only generic encoder. Wire payloads with undeclared fields now fail loudly instead of being dropped. +- Live lazy-export packages call `lazy_exports`; the dead ones lose their `__getattr__` entirely. + +## Guards + +`tests/unit/test_l2_codec_public_api_guards.py`: +- `openhcs/serialization/json.py` and `openhcs/core/public_api.py` do not exist; no tracked Python file imports `openhcs.serialization.json` or `openhcs.core.public_api`. +- No class named `AgentDtoJsonCodec` or `DebugJsonCodec` anywhere under `openhcs/`. +- No module-level `def __getattr__` or `def __dir__` in any `openhcs/**/__init__.py` or `benchmark/**/__init__.py`, except the CellProfiler backend package (a dynamic module type owned by P1) and `processing/custom_functions` (loads user functions from disk; not a lazy export). + +## Tests + +- Library: one round-trip test over every value family (`to_jsonable` then `dataclass_from_mapping`), one registration new-case test, public-name derivation, lazy-export resolution, caching and owner conflicts. +- OpenHCS: the existing UI-bridge, debug and MCP tests exercise the migrated call sites; tests that called the deleted codecs call `dataclass_from_mapping`. + +## New-case experiments + +- A new wire DTO: today it needs nothing for encoding but decodes through whichever of three decoders its call site picked, with different strictness. After: one decoder. +- A new lazy-export package: today a 20-40 line resolver copy. After: one `lazy_exports(...)` call whose mapping is also the `__all__` source. + +## Done when + +The two OpenHCS modules and both codec classes are gone, every importer uses python-introspect, the guards pass, the submodule pointer and pin name python-introspect 0.2.2, and the python-introspect PR is open with its tests green. diff --git a/docs/refactor/receipts/installed-consumers-419-435-450-20261004/readback.py b/docs/refactor/receipts/installed-consumers-419-435-450-20261004/readback.py index 4bb85ca44b..7198b4c6ad 100644 --- a/docs/refactor/receipts/installed-consumers-419-435-450-20261004/readback.py +++ b/docs/refactor/receipts/installed-consumers-419-435-450-20261004/readback.py @@ -28,7 +28,7 @@ def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() import numpy as np, tifffile from scipy.ndimage import distance_transform_edt from openhcs.mcp.dev_client_core import McpDevServerSpec, McpDevStdioSession, McpDevToolResult -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.core.artifacts import ImageArtifactType from openhcs.core.virtual_workspace_metadata import METADATA_CONFIG from benchmark.cellprofiler_reference_exports import CellProfilerReferenceExportArtifact, CellProfilerReferenceArtifactComparison diff --git a/docs/refactor/receipts/public-native-receiving-134-20261004/controller.py b/docs/refactor/receipts/public-native-receiving-134-20261004/controller.py index cc569cce12..61709a072b 100644 --- a/docs/refactor/receipts/public-native-receiving-134-20261004/controller.py +++ b/docs/refactor/receipts/public-native-receiving-134-20261004/controller.py @@ -54,7 +54,7 @@ def environment(): from openhcs.agent.dto.common import AgentResourceRef from openhcs.agent.dto.viewer import ViewerWindowStateRequest,ViewerWindowSnapshotRequest,ViewerWindowCloseRequest,ViewerWindowLayerIsolationRequest,ViewerWindowImageSampleRequest,ViewerWindowRoiSummaryRequest,ViewerWindowPayloadRequest,ViewerWindowViewportRequest from openhcs.mcp.dev_client_core import McpDevServerSpec,McpDevStdioSession,McpDevToolResult -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from zmqruntime.config import TransportMode from zmqruntime.transport import TransportEndpoint from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG diff --git a/docs/source/architecture/serialization_boundaries.rst b/docs/source/architecture/serialization_boundaries.rst index ad300f7f1b..995729ad35 100644 --- a/docs/source/architecture/serialization_boundaries.rst +++ b/docs/source/architecture/serialization_boundaries.rst @@ -16,9 +16,9 @@ before application. JSON transport -------------- -``openhcs.serialization.json.to_jsonable`` is the OpenHCS-owned nominal JSON -projection for agent capabilities and UI-bridge transport. Its singledispatch -implementations cover JSON scalars, collections, paths, enums, callables, +``python_introspect.to_jsonable`` is the nominal JSON projection for agent +capabilities and UI-bridge transport, and ``python_introspect.dataclass_from_mapping`` +is its decoder. The encoder's singledispatch implementations cover JSON scalars, collections, paths, enums, callables, dataclass instances, and registered nominal types. A registered type projects through its declared registry key; a callable projects through a stable import identity. diff --git a/docs/source/development/extension_workflows.rst b/docs/source/development/extension_workflows.rst index 0f7bff4d57..53226a780a 100644 --- a/docs/source/development/extension_workflows.rst +++ b/docs/source/development/extension_workflows.rst @@ -44,7 +44,7 @@ that needs the behavior. * - Python serialization - pycodify * - JSON transport projection - - OpenHCS ``serialization.json.to_jsonable`` + - python-introspect ``to_jsonable`` / ``dataclass_from_mapping`` * - Benchmark command or report entry point - ``BenchmarkCliCommand`` registered declaration family * - Comparison-run provenance or lifecycle diff --git a/external/python-introspect b/external/python-introspect index 83c1efe5ff..496fedb0bd 160000 --- a/external/python-introspect +++ b/external/python-introspect @@ -1 +1 @@ -Subproject commit 83c1efe5ff9933b0fbd8586d2af5c9e7dbbe80ff +Subproject commit 496fedb0bd284361c8b32b74d091582506e0396a diff --git a/openhcs/agent/capabilities.py b/openhcs/agent/capabilities.py index b95997ff6a..73bd5caa95 100644 --- a/openhcs/agent/capabilities.py +++ b/openhcs/agent/capabilities.py @@ -220,7 +220,7 @@ ViewerWindowNativePresentationResult, ) from openhcs.runtime.viewer_controls import ViewerNavigationControlOptions -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable if TYPE_CHECKING: from argparse import ArgumentParser, Namespace diff --git a/openhcs/agent/dto/__init__.py b/openhcs/agent/dto/__init__.py index 617074633d..fa724c95a2 100644 --- a/openhcs/agent/dto/__init__.py +++ b/openhcs/agent/dto/__init__.py @@ -1,350 +1,305 @@ """DTO exports for the headless OpenHCS agent API. -This package intentionally keeps the re-export surface lazy. Importing one -concrete DTO submodule, such as ``openhcs.agent.dto.common``, must not import -the full agent DTO graph. +The re-export surface is lazy: importing one concrete DTO submodule, such as +``openhcs.agent.dto.common``, must not import the full agent DTO graph. """ -from __future__ import annotations +from python_introspect import lazy_exports -import sys -from importlib import import_module -from pkgutil import iter_modules -from types import ModuleType - -__all__ = ( - "SCHEMA_VERSION", - "AgentError", - "AgentResourceRef", - "AgentWarning", - "JsonObject", - "JsonScalar", - "JsonValue", - "RenderedSource", - "McpServerHealthResult", - "WindowSnapshotCaptureScope", - "WindowSnapshotCaptureSpec", - "AuthoringContext", - "AuthoringContextRequest", - "ArchitectureTopic", - "ArchitectureTopicPage", - "ArchitectureTopicSummary", - "InternalApiSymbol", - "ConfigFieldSchema", - "ConfigPatch", - "ConfigRegisteredType", - "ConfigRef", - "ConfigRegistrySchema", - "ConfigSchema", - "ConfigSchemaRequest", - "ConfigSourceRenderRequest", - "ConfigTypeSchema", - "ConfigValidationResult", - "CellProfilerArtifactBindingSummary", - "CellProfilerModuleDeclarationSummary", - "CustomFunctionRegistrationRequest", - "CustomFunctionRegistrationResult", - "FunctionDetailRequest", - "FunctionArtifactSpec", - "FunctionCatalogEntry", - "FunctionCatalogPage", - "FunctionDetail", - "FunctionSearchRequest", - "FunctionParameterSource", - "FunctionParameterSpec", - "FunctionRuntimeContractSummary", - "KnowledgeBaseCatalog", - "KnowledgeBaseDocument", - "KnowledgeBaseDocumentRequest", - "KnowledgeBaseDocumentSourceProjection", - "KnowledgeBaseDocumentSummary", - "KnowledgeBaseSearchHit", - "KnowledgeBaseSearchRequest", - "KnowledgeBaseSearchResult", - "KnowledgeBaseSectionSummary", - "ArtifactInputPlanSummary", - "ArtifactMaterializationPathSummary", - "ArtifactMaterializationPlanSummary", - "ArtifactPlanInspection", - "ArtifactPlanSummary", - "ArtifactStoragePlanSummary", - "CompileSubmissionRequest", - "CompiledStepPlanSummary", - "ExecutionConnectionSpec", - "ExecutionJobRef", - "ExecutionJobStatus", - "ExecutionStatusRequest", - "MainFlowMaterializationPlanSummary", - "OrchestratorSession", - "OrchestratorSessionCreationRequest", - "OrchestratorSessionRequest", - "OrchestratorSessionRef", - "PipelineSourceArtifactPlanInspectionRequest", - "PipelineSourceOrchestratorSessionRequest", - "PipelineExecutionSubmissionRequest", - "RuntimeDebugInspectionRequest", - "RuntimeDebugInspectionResult", - "RuntimeExecutionStatus", - "RuntimeServerExecutionStatusRequest", - "RuntimeServerInfo", - "RuntimeServerInfoRequest", - "RuntimeServerScanRequest", - "RuntimeServerScanResult", - "SourceWorkspaceFileRecord", - "SourceWorkspaceSummary", - "ViewerStreamingPlanSummary", - "CreatePipelineRequest", - "FunctionSpecRef", - "FunctionStepAddRequest", - "FunctionStepSpec", - "PipelineRef", - "PipelineSourceRenderRequest", - "PipelineSpec", - "PipelineValidationRequest", - "PipelineValidationResult", - "PlateFileQueryRecordSummary", - "PlateFileQueryRequest", - "PlateFileQueryResult", - "PlateFileStreamRequest", - "PlateFileStreamResult", - "PlateInspectionBounds", - "PlateInspectionComponentSummary", - "PlateInspectionComponentValue", - "PlateInspectionConfidence", - "PlateInspectionHandlerCandidate", - "PlateInspectionImageFileSummary", - "PlateInspectionImageRecordSummary", - "PlateInspectionIngestionRoute", - "PlateInspectionIssueCode", - "PlateInspectionParseFailure", - "PlateInspectionParseSummary", - "PlateInspectionResultFileRecordSummary", - "PlateInspectionResultFileSummary", - "PlateInspectionStatus", - "PlateInspectionSourceBindingRole", - "PlateInspectionValueSource", - "PlateInspectionWorkflowAdvice", - "PlateInspectionWorkflowScope", - "PlateInspectionWorkspacePreparation", - "PlateImageSampleRequest", - "PlateImageSampleResult", - "PlatePathInspectionRequest", - "PlatePathInspectionResult", - "PlateWorkspacePreparationOperation", - "SelectedPlateFileQueryTarget", - "SelectedPlateFileQueryRequest", - "SelectedPlateFileQueryResult", - "SelectedPlateFileStreamRequest", - "SelectedPlateFileStreamResult", - "SelectedPlateImageInspectionRequest", - "SelectedPlateImageInspectionResult", - "SelectedPlateImageSampleRequest", - "SelectedPlateImageSampleResult", - "SyntheticPlateGenerationRequest", - "SyntheticPlateGenerationResult", - "ViewerWindowDescriptor", - "ViewerWindowLayerPayloads", - "ViewerWindowLayerState", - "ViewerWindowLayerValidationSummary", - "ViewerWindowLayerIsolationRequest", - "ViewerWindowLayerIsolationResult", - "ViewerWindowLayerRetirementRequest", - "ViewerWindowLayerRetirementResult", - "ViewerWindowLayerVisibilityRecord", - "ViewerWindowImageSampleRequest", - "ViewerWindowImageSampleResult", - "ViewerWindowNavigationRequest", - "ViewerWindowNavigationResult", - "ViewerWindowPayloadRecord", - "ViewerWindowPayloadRequest", - "ViewerWindowPayloadResult", - "ViewerWindowProbeResult", - "ViewerWindowRoiSummaryRequest", - "ViewerWindowRoiSummaryResult", - "ViewerWindowSnapshotRequest", - "ViewerWindowSnapshotResult", - "ViewerWindowStateRequest", - "ViewerWindowStateResult", - "ViewerWindowValidationPolicy", - "ViewerWindowValidationRequest", - "ViewerWindowValidationSummaryResult", - "UiActionCatalog", - "UiActionIdentity", - "UiActionInvocationStatus", - "UiActionInvokeRequest", - "UiActionInvokeResult", - "UiActionSummary", - "UiBranchCatalog", - "UiBranchRef", - "UiBranchSwitchRequest", - "UiBridgeConfirmationRequirement", - "UiBridgeConfirmationRequirementCarrier", - "UiBridgeConnectionSpec", - "UiBridgeCatalog", - "UiBridgeDescriptorEnvelope", - "UiBridgeDescriptorFile", - "UiBridgeDescriptorSummary", - "UiBridgeDescriptorWirePayload", - "UiBridgeOperationIdentity", - "UiBridgeOperationRef", - "UiBridgeOperationStatusRequest", - "UiBridgeOperationWaitRequest", - "UiBridgeRequestEnvelope", - "UiBridgeResponseEnvelope", - "UiBridgeStatus", - "UiCodeDocument", - "UiCodeDocumentApplyRequest", - "UiCodeDocumentApplyResult", - "UiCodeDocumentCatalog", - "UiCodeDocumentBaseRevision", - "UiCodeDocumentCurrentRevision", - "UiCodeDocumentId", - "UiCodeDocumentOptionalBaseRevision", - "UiCodeDocumentRequest", - "UiCodeDocumentSelectionMode", - "UiCodeDocumentSummary", - "UiCodeDocumentValidationRequest", - "UiCodeDocumentValidationResult", - "UiMutationReceipt", - "UiMutationRequestToken", - "UiMutationRequestTokenCarrier", - "UiLiveOverviewItem", - "UiLiveOverviewMetric", - "UiLiveOverviewSection", - "UiLiveOverviewSeverity", - "UiLiveOverviewState", - "UiObjectStateFieldListQuery", - "UiObjectStateFieldListOptions", - "UiObjectStateFieldListResult", - "UiObjectStateFieldPathIndex", - "UiObjectStateFieldProjection", - "UiObjectStateFieldProvenance", - "UiObjectStateFieldScopeProjection", - "UiObjectStateFieldHelpQuery", - "UiObjectStateFieldHelpRequest", - "UiObjectStateFieldHelpResult", - "UiObjectStateFieldMutationRequest", - "UiObjectStateFieldMutationResult", - "UiObjectStateFieldSummary", - "UiObjectStateValuePreview", - "UiObjectStateScopeCatalog", - "UiObjectStateScopeIdentity", - "UiObjectStateScopeListRequest", - "UiObjectStateScopeSummary", - "UiObjectStateScopeVisibility", - "UiPlateManagerRowState", - "UiPlateManagerState", - "UiSelectedPlateWorkflowKind", - "UiSelectedPlateWorkflowRequest", - "UiSelectedPlateWorkflowResult", - "UiStateSurfaceDocument", - "UiStateSurfaceEnvelope", - "UiStateSurfaceCatalog", - "UiStateSurfaceId", - "UiStateSurfaceIdentity", - "UiStateSurfaceRequest", - "UiStateSurfaceSummary", - "UiSemanticAddress", - "UiSnapshotCatalog", - "UiSnapshotListRequest", - "UiSnapshotRef", - "UiSnapshotRestoreRequest", - "UiSnapshotRestoreResult", - "UiTimeTravelRuntimeState", - "UiTimeTravelHeadRequest", - "UiWidgetIdentity", - "UiWidgetActionInvokeRequest", - "UiWidgetActionInvokeResult", - "UiWidgetActionIssueCode", - "UiWidgetActionSummary", - "UiWidgetRect", - "UiWidgetTreeNode", - "UiWidgetTreeRequest", - "UiWidgetTreeResult", - "UiWindowCatalog", - "UiWindowCloseRequest", - "UiWindowCloseResult", - "UiWindowFocusRequest", - "UiWindowFocusResult", - "UiWindowIdentity", - "UiWindowManagerScope", - "UiWindowSemanticMarker", - "UiWindowNavigateRequest", - "UiWindowNavigateResult", - "UiWindowOpenPolicy", - "UiWindowOperationRequest", - "UiWindowSnapshotRequest", - "UiWindowSnapshotResult", - "UiWindowSummary", - "MainWindowWidgetIdentity", - "ManagedWindowWidgetIdentity", +__all__ = lazy_exports( + globals(), + { + "openhcs.agent.dto.common": ( + "SCHEMA_VERSION", + "AgentError", + "AgentResourceRef", + "AgentWarning", + "RenderedSource", + ), + "openhcs.agent.dto.mcp": ( + "McpServerHealthResult", + ), + "pyqt_reactive.services.window_snapshot": ( + "WindowSnapshotCaptureScope", + "WindowSnapshotCaptureSpec", + ), + "openhcs.agent.dto.authoring": ( + "AuthoringContext", + "AuthoringContextRequest", + ), + "openhcs.agent.dto.architecture": ( + "ArchitectureTopic", + "ArchitectureTopicPage", + "ArchitectureTopicSummary", + "InternalApiSymbol", + ), + "openhcs.agent.dto.config": ( + "ConfigFieldSchema", + "ConfigPatch", + "ConfigRegisteredType", + "ConfigRef", + "ConfigRegistrySchema", + "ConfigSchema", + "ConfigSchemaRequest", + "ConfigSourceRenderRequest", + "ConfigTypeSchema", + "ConfigValidationResult", + ), + "openhcs.agent.dto.functions": ( + "CellProfilerArtifactBindingSummary", + "CellProfilerModuleDeclarationSummary", + "CustomFunctionRegistrationRequest", + "CustomFunctionRegistrationResult", + "FunctionDetailRequest", + "FunctionArtifactSpec", + "FunctionCatalogEntry", + "FunctionCatalogPage", + "FunctionDetail", + "FunctionSearchRequest", + "FunctionParameterSource", + "FunctionParameterSpec", + "FunctionRuntimeContractSummary", + ), + "openhcs.agent.dto.knowledge": ( + "KnowledgeBaseCatalog", + "KnowledgeBaseDocument", + "KnowledgeBaseDocumentRequest", + "KnowledgeBaseDocumentSourceProjection", + "KnowledgeBaseDocumentSummary", + "KnowledgeBaseSearchHit", + "KnowledgeBaseSearchRequest", + "KnowledgeBaseSearchResult", + "KnowledgeBaseSectionSummary", + ), + "openhcs.agent.dto.execution": ( + "ArtifactInputPlanSummary", + "ArtifactMaterializationPathSummary", + "ArtifactMaterializationPlanSummary", + "ArtifactPlanInspection", + "ArtifactPlanSummary", + "ArtifactStoragePlanSummary", + "CompileSubmissionRequest", + "CompiledStepPlanSummary", + "ExecutionJobRef", + "ExecutionJobStatus", + "ExecutionStatusRequest", + "MainFlowMaterializationPlanSummary", + "OrchestratorSession", + "OrchestratorSessionCreationRequest", + "OrchestratorSessionRequest", + "OrchestratorSessionRef", + "PipelineSourceArtifactPlanInspectionRequest", + "PipelineSourceOrchestratorSessionRequest", + "PipelineExecutionSubmissionRequest", + "RuntimeDebugInspectionRequest", + "RuntimeDebugInspectionResult", + "RuntimeExecutionStatus", + "RuntimeServerExecutionStatusRequest", + "RuntimeServerInfo", + "RuntimeServerInfoRequest", + "RuntimeServerScanRequest", + "RuntimeServerScanResult", + "SourceWorkspaceFileRecord", + "SourceWorkspaceSummary", + "ViewerStreamingPlanSummary", + ), + "openhcs.agent.dto.execution_connection": ( + "ExecutionConnectionSpec", + ), + "openhcs.agent.dto.pipeline": ( + "CreatePipelineRequest", + "FunctionSpecRef", + "FunctionStepAddRequest", + "FunctionStepSpec", + "PipelineRef", + "PipelineSourceRenderRequest", + "PipelineSpec", + "PipelineValidationRequest", + "PipelineValidationResult", + ), + "openhcs.agent.dto.plate": ( + "PlateFileQueryRecordSummary", + "PlateFileQueryRequest", + "PlateFileQueryResult", + "PlateFileStreamRequest", + "PlateFileStreamResult", + "PlateInspectionBounds", + "PlateInspectionComponentSummary", + "PlateInspectionComponentValue", + "PlateInspectionConfidence", + "PlateInspectionHandlerCandidate", + "PlateInspectionImageFileSummary", + "PlateInspectionImageRecordSummary", + "PlateInspectionIngestionRoute", + "PlateInspectionIssueCode", + "PlateInspectionParseFailure", + "PlateInspectionParseSummary", + "PlateInspectionResultFileRecordSummary", + "PlateInspectionResultFileSummary", + "PlateInspectionStatus", + "PlateInspectionSourceBindingRole", + "PlateInspectionValueSource", + "PlateInspectionWorkflowAdvice", + "PlateInspectionWorkflowScope", + "PlateInspectionWorkspacePreparation", + "PlateImageSampleRequest", + "PlateImageSampleResult", + "PlatePathInspectionRequest", + "PlatePathInspectionResult", + "PlateWorkspacePreparationOperation", + "SelectedPlateFileQueryTarget", + "SelectedPlateFileQueryRequest", + "SelectedPlateFileQueryResult", + "SelectedPlateFileStreamRequest", + "SelectedPlateFileStreamResult", + "SelectedPlateImageInspectionRequest", + "SelectedPlateImageInspectionResult", + "SelectedPlateImageSampleRequest", + "SelectedPlateImageSampleResult", + "SyntheticPlateGenerationRequest", + "SyntheticPlateGenerationResult", + ), + "openhcs.agent.dto.viewer": ( + "ViewerWindowDescriptor", + "ViewerWindowLayerPayloads", + "ViewerWindowLayerState", + "ViewerWindowLayerValidationSummary", + "ViewerWindowLayerIsolationRequest", + "ViewerWindowLayerIsolationResult", + "ViewerWindowLayerRetirementRequest", + "ViewerWindowLayerRetirementResult", + "ViewerWindowLayerVisibilityRecord", + "ViewerWindowImageSampleRequest", + "ViewerWindowImageSampleResult", + "ViewerWindowNavigationRequest", + "ViewerWindowNavigationResult", + "ViewerWindowPayloadRecord", + "ViewerWindowPayloadRequest", + "ViewerWindowPayloadResult", + "ViewerWindowProbeResult", + "ViewerWindowRoiSummaryRequest", + "ViewerWindowRoiSummaryResult", + "ViewerWindowSnapshotRequest", + "ViewerWindowSnapshotResult", + "ViewerWindowStateRequest", + "ViewerWindowStateResult", + "ViewerWindowValidationPolicy", + "ViewerWindowValidationRequest", + "ViewerWindowValidationSummaryResult", + ), + "openhcs.agent.dto.ui_bridge": ( + "UiActionCatalog", + "UiActionIdentity", + "UiActionInvocationStatus", + "UiActionInvokeRequest", + "UiActionInvokeResult", + "UiActionSummary", + "UiBranchCatalog", + "UiBranchRef", + "UiBranchSwitchRequest", + "UiBridgeConfirmationRequirement", + "UiBridgeConfirmationRequirementCarrier", + "UiBridgeConnectionSpec", + "UiBridgeCatalog", + "UiBridgeDescriptorEnvelope", + "UiBridgeDescriptorFile", + "UiBridgeDescriptorSummary", + "UiBridgeDescriptorWirePayload", + "UiBridgeOperationIdentity", + "UiBridgeOperationRef", + "UiBridgeOperationStatusRequest", + "UiBridgeOperationWaitRequest", + "UiBridgeRequestEnvelope", + "UiBridgeResponseEnvelope", + "UiBridgeStatus", + "UiCodeDocument", + "UiCodeDocumentApplyRequest", + "UiCodeDocumentApplyResult", + "UiCodeDocumentCatalog", + "UiCodeDocumentBaseRevision", + "UiCodeDocumentCurrentRevision", + "UiCodeDocumentId", + "UiCodeDocumentOptionalBaseRevision", + "UiCodeDocumentRequest", + "UiCodeDocumentSelectionMode", + "UiCodeDocumentSummary", + "UiCodeDocumentValidationRequest", + "UiCodeDocumentValidationResult", + "UiMutationReceipt", + "UiMutationRequestToken", + "UiMutationRequestTokenCarrier", + "UiLiveOverviewItem", + "UiLiveOverviewMetric", + "UiLiveOverviewSection", + "UiLiveOverviewSeverity", + "UiLiveOverviewState", + "UiObjectStateFieldListQuery", + "UiObjectStateFieldListOptions", + "UiObjectStateFieldListResult", + "UiObjectStateFieldPathIndex", + "UiObjectStateFieldProjection", + "UiObjectStateFieldProvenance", + "UiObjectStateFieldScopeProjection", + "UiObjectStateFieldHelpQuery", + "UiObjectStateFieldHelpRequest", + "UiObjectStateFieldHelpResult", + "UiObjectStateFieldMutationRequest", + "UiObjectStateFieldMutationResult", + "UiObjectStateFieldSummary", + "UiObjectStateValuePreview", + "UiObjectStateScopeCatalog", + "UiObjectStateScopeIdentity", + "UiObjectStateScopeListRequest", + "UiObjectStateScopeSummary", + "UiObjectStateScopeVisibility", + "UiPlateManagerRowState", + "UiPlateManagerState", + "UiSelectedPlateWorkflowKind", + "UiSelectedPlateWorkflowRequest", + "UiSelectedPlateWorkflowResult", + "UiStateSurfaceDocument", + "UiStateSurfaceEnvelope", + "UiStateSurfaceCatalog", + "UiStateSurfaceId", + "UiStateSurfaceIdentity", + "UiStateSurfaceRequest", + "UiStateSurfaceSummary", + "UiSemanticAddress", + "UiSnapshotCatalog", + "UiSnapshotListRequest", + "UiSnapshotRef", + "UiSnapshotRestoreRequest", + "UiSnapshotRestoreResult", + "UiTimeTravelRuntimeState", + "UiTimeTravelHeadRequest", + "UiWidgetIdentity", + "UiWidgetActionInvokeRequest", + "UiWidgetActionInvokeResult", + "UiWidgetActionIssueCode", + "UiWidgetActionSummary", + "UiWidgetRect", + "UiWidgetTreeNode", + "UiWidgetTreeRequest", + "UiWidgetTreeResult", + "UiWindowCatalog", + "UiWindowCloseRequest", + "UiWindowCloseResult", + "UiWindowFocusRequest", + "UiWindowFocusResult", + "UiWindowIdentity", + "UiWindowManagerScope", + "UiWindowSemanticMarker", + "UiWindowNavigateRequest", + "UiWindowNavigateResult", + "UiWindowOpenPolicy", + "UiWindowOperationRequest", + "UiWindowSnapshotRequest", + "UiWindowSnapshotResult", + "UiWindowSummary", + ), + "openhcs.agent.ui_bridge_identities": ( + "MainWindowWidgetIdentity", + "ManagedWindowWidgetIdentity", + ), + }, ) - -_EXPORT_NAMES = frozenset(__all__) -_DTO_EXPORT_PLACEHOLDER = object() -_MISSING_EXPORT = object() - - -def _dto_export_module_names() -> tuple[str, ...]: - """Return DTO package modules from the package source authority.""" - return tuple( - f"{__name__}.{module_info.name}" - for module_info in iter_modules(__path__) - if not module_info.ispkg - ) - - -def _external_export_modules() -> tuple[object, ...]: - """Return non-DTO modules intentionally re-exported by this package.""" - from pyqt_reactive.services import window_snapshot - - from openhcs.agent import ui_bridge_identities - - return (window_snapshot, ui_bridge_identities) - - -def resolve_agent_dto_export(name: str): - """Resolve one public DTO export from its owning module.""" - if name not in _EXPORT_NAMES: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - existing = globals().get(name, _MISSING_EXPORT) - if existing is not _MISSING_EXPORT and existing is not _DTO_EXPORT_PLACEHOLDER: - return existing - for module in _external_export_modules(): - module_namespace = vars(module) - if name in module_namespace: - value = module_namespace[name] - globals()[name] = value - return value - for module_name in _dto_export_module_names(): - module_namespace = import_module(module_name).__dict__ - if name in module_namespace: - value = module_namespace[name] - globals()[name] = value - return value - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - -def __getattr__(name: str): - """Resolve public DTO re-exports from their owning modules on demand.""" - return resolve_agent_dto_export(name) - - -def __dir__() -> list[str]: - return sorted(set(globals()) | _EXPORT_NAMES) - - -class _AgentDtoModule(ModuleType): - """Module type that turns export placeholders into resolved DTO objects.""" - - def __getattribute__(self, name: str): - value = super().__getattribute__(name) - if name in _EXPORT_NAMES and value is _DTO_EXPORT_PLACEHOLDER: - return resolve_agent_dto_export(name) - return value - - -for _export_name in __all__: - globals().setdefault(_export_name, _DTO_EXPORT_PLACEHOLDER) - -sys.modules[__name__].__class__ = _AgentDtoModule diff --git a/openhcs/agent/dto/common.py b/openhcs/agent/dto/common.py index e53f338e7a..1cb84a95c4 100644 --- a/openhcs/agent/dto/common.py +++ b/openhcs/agent/dto/common.py @@ -10,15 +10,14 @@ from functools import cache, wraps from typing import Self, cast, get_type_hints -from python_introspect import dataclass_from_mapping - -from openhcs.serialization.json import ( +from python_introspect import ( JsonObject, - JsonScalar as JsonScalar, - JsonValue as JsonValue, + JsonValue, + dataclass_from_mapping, to_jsonable, ) + SCHEMA_VERSION = "openhcs.agent.v1" AGENT_PARAMETER_DESCRIPTION_METADATA_KEY = "agent_parameter_description" AGENT_PARAMETER_PRODUCER_OUTPUT_CONTRACT_METADATA_KEY = ( diff --git a/openhcs/agent/dto/config.py b/openhcs/agent/dto/config.py index bbbda5911e..70de65f39b 100644 --- a/openhcs/agent/dto/config.py +++ b/openhcs/agent/dto/config.py @@ -9,8 +9,8 @@ AgentCliArgumentSpec, AgentCliRequest, AgentResultEnvelope, - JsonObject, ) +from python_introspect import JsonObject @dataclass(frozen=True, slots=True) diff --git a/openhcs/agent/dto/execution.py b/openhcs/agent/dto/execution.py index 9094417395..801bbb20c9 100644 --- a/openhcs/agent/dto/execution.py +++ b/openhcs/agent/dto/execution.py @@ -8,7 +8,7 @@ from functools import wraps from typing import Self -from python_introspect import validate_annotated_dataclass +from python_introspect import JsonObject, JsonValue, validate_annotated_dataclass from zmqruntime.config import ( NonBlankString, PositiveInteger, @@ -34,8 +34,6 @@ AgentError, AgentResultEnvelope, AgentWarning, - JsonObject, - JsonValue, ) from openhcs.agent.dto.execution_connection import ExecutionConnectionSpec from openhcs.agent.ui_bridge_identities import ( diff --git a/openhcs/agent/dto/execution_connection.py b/openhcs/agent/dto/execution_connection.py index 425603f36f..bb29fc2f94 100644 --- a/openhcs/agent/dto/execution_connection.py +++ b/openhcs/agent/dto/execution_connection.py @@ -5,11 +5,15 @@ from dataclasses import asdict, dataclass, replace from typing import TYPE_CHECKING -from python_introspect import project_dataclass, validate_annotated_dataclass +from python_introspect import ( + JsonObject, + project_dataclass, + validate_annotated_dataclass, +) from zmqruntime.config import NonBlankString, SocketPort, TransportMode from zmqruntime.transport import TransportEndpoint -from openhcs.agent.dto.common import AgentDataclassCliRequest, JsonObject +from openhcs.agent.dto.common import AgentDataclassCliRequest from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG, OpenHCSZMQConfig if TYPE_CHECKING: diff --git a/openhcs/agent/dto/knowledge.py b/openhcs/agent/dto/knowledge.py index 176ce5f378..50d65f8578 100644 --- a/openhcs/agent/dto/knowledge.py +++ b/openhcs/agent/dto/knowledge.py @@ -10,8 +10,8 @@ AgentCliArgumentSpec, AgentCliRequest, AgentResultEnvelope, - JsonObject, ) +from python_introspect import JsonObject @dataclass(frozen=True, slots=True) diff --git a/openhcs/agent/dto/pipeline.py b/openhcs/agent/dto/pipeline.py index c9e989db03..ce813cc3d3 100644 --- a/openhcs/agent/dto/pipeline.py +++ b/openhcs/agent/dto/pipeline.py @@ -5,11 +5,8 @@ from collections.abc import Mapping from dataclasses import dataclass, field -from openhcs.agent.dto.common import ( - AgentResultEnvelope, - JsonObject, - JsonValue as JsonValue, -) +from openhcs.agent.dto.common import AgentResultEnvelope +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.config import ConfigPatch from openhcs.agent.dto.functions import FunctionIdentity diff --git a/openhcs/agent/dto/plate.py b/openhcs/agent/dto/plate.py index 906b25e1ce..65ffc9a5ba 100644 --- a/openhcs/agent/dto/plate.py +++ b/openhcs/agent/dto/plate.py @@ -12,9 +12,8 @@ AgentResultEnvelope, AgentResourceRef, AgentWarning, - JsonObject, - JsonValue, ) +from python_introspect import JsonObject, JsonValue, to_jsonable from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.constants.constants import AllComponents from openhcs.core.config import NapariDisplayConfig @@ -28,7 +27,6 @@ SYNTHETIC_PLATE_GENERATION_PROFILE, SyntheticPlateFormat, ) -from openhcs.serialization.json import to_jsonable class PlateInspectionStatus(str, Enum): diff --git a/openhcs/agent/dto/ui_bridge.py b/openhcs/agent/dto/ui_bridge.py index 773f3fb9ef..816347dc27 100644 --- a/openhcs/agent/dto/ui_bridge.py +++ b/openhcs/agent/dto/ui_bridge.py @@ -25,8 +25,11 @@ WindowVisualObservation, ) from python_introspect import ( + JsonObject, + JsonValue, overlay_non_none_dataclass, project_dataclass, + to_jsonable, validate_annotated_dataclass, ) from zmqruntime import EndpointApplication @@ -46,8 +49,6 @@ AgentResultEnvelope, AgentTimedStatusEnvelope, AgentWarning, - JsonObject, - JsonValue, ) from openhcs.agent.dto.execution import ( ExecutionConnectionProjection, @@ -105,7 +106,6 @@ SelectedScopeIdsCarrier, SelectionModeCarrier, ) -from openhcs.serialization.json import to_jsonable UI_BRIDGE_UNKNOWN_OPERATION = "unknown" UI_BRIDGE_UNKNOWN_WIDGET = "unknown" diff --git a/openhcs/agent/dto/viewer.py b/openhcs/agent/dto/viewer.py index bf5b68f0f4..1144b62775 100644 --- a/openhcs/agent/dto/viewer.py +++ b/openhcs/agent/dto/viewer.py @@ -17,7 +17,13 @@ WindowSnapshotFrameCondition, WindowVisualObservation, ) -from python_introspect import dataclass_from_mapping, project_dataclass +from python_introspect import ( + JsonObject, + JsonValue, + dataclass_from_mapping, + project_dataclass, + to_jsonable, +) from pydantic import BeforeValidator, StrictFloat, StrictInt from zmqruntime.timeouts import OperationDeadline from zmqruntime.viewer_protocol import ( @@ -34,8 +40,6 @@ AgentError, AgentResourceRef, AgentResultEnvelope, - JsonObject, - JsonValue, ) from openhcs.agent.dto.execution import ( ExecutionConnectionProjection, @@ -60,7 +64,6 @@ ViewerShapePayloadProjection, ViewerStateControlOptions, ) -from openhcs.serialization.json import to_jsonable from openhcs.runtime.viewer_protocol import ( ViewerPayloadSummary, ViewerPayloadRecord, ViewerPayloadContent, ViewerProjectionRecord, ViewerShapeCoordinateBounds, diff --git a/openhcs/agent/services/config_service.py b/openhcs/agent/services/config_service.py index 52477b1ea1..684235b709 100644 --- a/openhcs/agent/services/config_service.py +++ b/openhcs/agent/services/config_service.py @@ -30,17 +30,13 @@ parameter_description_from_target, ) from python_introspect import ( + JsonValue, coerce_enum_member, declared_enum_type, enum_input_values, ) -from openhcs.agent.dto.common import ( - AgentError, - JsonValue, - RenderedSource, - SCHEMA_VERSION, -) +from openhcs.agent.dto.common import AgentError, RenderedSource, SCHEMA_VERSION from openhcs.agent.dto.config import ( ConfigFieldSchema, ConfigPatch, diff --git a/openhcs/agent/services/execution_session_service.py b/openhcs/agent/services/execution_session_service.py index d4043a1557..afa9f75453 100644 --- a/openhcs/agent/services/execution_session_service.py +++ b/openhcs/agent/services/execution_session_service.py @@ -21,12 +21,8 @@ ResponseType, ) -from openhcs.agent.dto.common import ( - SCHEMA_VERSION, - AgentError, - AgentWarning, - JsonObject, -) +from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, AgentWarning +from python_introspect import JsonObject, to_jsonable from openhcs.agent.dto.execution import ( ArtifactInputPlanSummary, ArtifactMaterializationPathSummary, @@ -84,7 +80,6 @@ ZMQExecutionIdentity, ZMQRuntimeObservationExportScope, ) -from openhcs.serialization.json import to_jsonable MAX_INSPECTION_AXES = 8 MAX_INSPECTION_STEPS = 24 diff --git a/openhcs/agent/services/knowledge_base_service.py b/openhcs/agent/services/knowledge_base_service.py index bb521c7658..7199065ee8 100644 --- a/openhcs/agent/services/knowledge_base_service.py +++ b/openhcs/agent/services/knowledge_base_service.py @@ -20,13 +20,8 @@ python_source_root, ) from openhcs.agent.knowledge_manifest_schema import ComparisonManifestSnapshot -from openhcs.agent.dto.common import ( - AgentError, - AgentWarning, - JsonObject, - JsonValue, - SCHEMA_VERSION, -) +from openhcs.agent.dto.common import AgentError, AgentWarning, SCHEMA_VERSION +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.knowledge import ( KnowledgeBaseCatalog, KnowledgeBaseContentBounds, diff --git a/openhcs/agent/services/object_state_field_help_service.py b/openhcs/agent/services/object_state_field_help_service.py index 3f4db195be..92f427284c 100644 --- a/openhcs/agent/services/object_state_field_help_service.py +++ b/openhcs/agent/services/object_state_field_help_service.py @@ -13,9 +13,9 @@ parameter_help_content, resolved_parameter_description, ) -from python_introspect import UnifiedParameterAnalyzer, enum_input_values +from python_introspect import JsonValue, UnifiedParameterAnalyzer, enum_input_values -from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, AgentWarning, JsonValue +from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, AgentWarning from openhcs.agent.dto.functions import ( FunctionArtifactSpec, FunctionDetail, diff --git a/openhcs/agent/services/object_state_field_projection.py b/openhcs/agent/services/object_state_field_projection.py index e37ba1d3f5..aa253b0744 100644 --- a/openhcs/agent/services/object_state_field_projection.py +++ b/openhcs/agent/services/object_state_field_projection.py @@ -7,9 +7,9 @@ from typing import ClassVar from metaclass_registry import AutoRegisterMeta -from python_introspect import project_dataclass +from python_introspect import JsonValue, project_dataclass -from openhcs.agent.dto.common import JsonValue, SCHEMA_VERSION +from openhcs.agent.dto.common import SCHEMA_VERSION from openhcs.agent.dto.ui_bridge import ( UiObjectStateFieldFilter, UiObjectStateFieldListQuery, diff --git a/openhcs/agent/services/pipeline_authoring_service.py b/openhcs/agent/services/pipeline_authoring_service.py index 652bdb9a53..6b7afa5959 100644 --- a/openhcs/agent/services/pipeline_authoring_service.py +++ b/openhcs/agent/services/pipeline_authoring_service.py @@ -14,10 +14,9 @@ SCHEMA_VERSION, AgentError, AgentWarning, - JsonObject, - JsonValue, RenderedSource, ) +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.config import ConfigPatch from openhcs.agent.dto.pipeline import ( CreatePipelineRequest, diff --git a/openhcs/agent/services/plate_inspection_service.py b/openhcs/agent/services/plate_inspection_service.py index 8a0982f457..7e083f2e29 100644 --- a/openhcs/agent/services/plate_inspection_service.py +++ b/openhcs/agent/services/plate_inspection_service.py @@ -10,12 +10,8 @@ from polystore.base import ImageSamplingRequest from zmqruntime.startup import EndpointStartupPhase, EndpointStartupStatus -from openhcs.agent.dto.common import ( - AgentError, - AgentWarning, - JsonObject, - SCHEMA_VERSION, -) +from openhcs.agent.dto.common import AgentError, AgentWarning, SCHEMA_VERSION +from python_introspect import JsonObject from openhcs.agent.dto.plate import ( PlateFileQueryRecordSummary, PlateFileQueryRequest, diff --git a/openhcs/agent/services/plate_streaming_service.py b/openhcs/agent/services/plate_streaming_service.py index 868a055799..d3a96d777b 100644 --- a/openhcs/agent/services/plate_streaming_service.py +++ b/openhcs/agent/services/plate_streaming_service.py @@ -15,12 +15,8 @@ ) from polystore.streaming.viewer_transport import ViewerStreamProducer -from openhcs.agent.dto.common import ( - SCHEMA_VERSION, - AgentError, - AgentWarning, - JsonObject, -) +from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, AgentWarning +from python_introspect import JsonObject from openhcs.agent.dto.plate import ( PlateFileStreamRequest, PlateFileStreamResult, diff --git a/openhcs/agent/services/runtime_server_service.py b/openhcs/agent/services/runtime_server_service.py index ccacf58fea..ead748d113 100644 --- a/openhcs/agent/services/runtime_server_service.py +++ b/openhcs/agent/services/runtime_server_service.py @@ -5,7 +5,8 @@ from abc import ABC, abstractmethod from dataclasses import replace -from openhcs.agent.dto.common import AgentError, JsonObject, SCHEMA_VERSION +from openhcs.agent.dto.common import AgentError, SCHEMA_VERSION +from python_introspect import JsonObject from openhcs.agent.dto.execution import ( RuntimeDebugArtifactExportRequest, RuntimeDebugArtifactExportResult, diff --git a/openhcs/agent/services/selected_plate_service.py b/openhcs/agent/services/selected_plate_service.py index 66cffa25d4..102f377931 100644 --- a/openhcs/agent/services/selected_plate_service.py +++ b/openhcs/agent/services/selected_plate_service.py @@ -5,7 +5,8 @@ from collections.abc import Mapping from dataclasses import dataclass -from openhcs.agent.dto.common import AgentError, AgentWarning, JsonValue, SCHEMA_VERSION +from openhcs.agent.dto.common import AgentError, AgentWarning, SCHEMA_VERSION +from python_introspect import JsonValue from openhcs.agent.dto.plate import ( PlateInspectionDefaults, PlatePathInspectionRequest, diff --git a/openhcs/agent/services/ui_bridge_service.py b/openhcs/agent/services/ui_bridge_service.py index cb1009c78f..a62615792e 100644 --- a/openhcs/agent/services/ui_bridge_service.py +++ b/openhcs/agent/services/ui_bridge_service.py @@ -18,6 +18,7 @@ from metaclass_registry import AutoRegisterMeta from python_introspect import ( EnvironmentVariable, + JsonObject, dataclass_from_mapping, overlay_dataclass_from_environment, project_dataclass, @@ -29,7 +30,7 @@ TransportMode, ) -from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, JsonObject +from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError from openhcs.agent.dto.ui_bridge import ( UI_BRIDGE_UNKNOWN_WIDGET, UNKNOWN_UI_BRIDGE_OPERATION_ROUTE, @@ -269,12 +270,7 @@ def invoke_with_payload( return cls.gateway_method.invoke(gateway, connection) @classmethod - def decode_request_payload( - cls, - payload: JsonObject, - decoder: Callable[[type[UiBridgeRequestT], JsonObject], UiBridgeRequestT], - ) -> None: - del decoder + def decode_request_payload(cls, payload: JsonObject) -> None: if payload: raise ValueError( f"UI bridge operation {cls.name!r} does not accept a payload." @@ -310,12 +306,8 @@ def invoke_with_payload( return cls.gateway_method.invoke(gateway, connection, payload) @classmethod - def decode_request_payload( - cls, - payload: JsonObject, - decoder: Callable[[type[UiBridgeRequestT], JsonObject], UiBridgeRequestT], - ) -> UiBridgeRequestT: - return decoder(cls.request_type, payload) + def decode_request_payload(cls, payload: JsonObject) -> UiBridgeRequestT: + return dataclass_from_mapping(cls.request_type, payload) @classmethod def validate_request_payload(cls, payload: UiBridgeRequestT) -> None: diff --git a/openhcs/agent/services/ui_bridge_transport.py b/openhcs/agent/services/ui_bridge_transport.py index fa4855afed..3e842a4781 100644 --- a/openhcs/agent/services/ui_bridge_transport.py +++ b/openhcs/agent/services/ui_bridge_transport.py @@ -3,16 +3,12 @@ from __future__ import annotations import uuid -from collections.abc import Mapping, Sequence -from dataclasses import MISSING, fields, is_dataclass -from enum import Enum -from types import NoneType, UnionType -from typing import TypeVar, get_args, get_origin, get_type_hints +from collections.abc import Mapping -from typing_extensions import TypeForm +from python_introspect import JsonObject, dataclass_from_mapping, to_jsonable import openhcs.agent.services.ui_bridge_service as ui_bridge_service -from openhcs.agent.dto.common import SCHEMA_VERSION, JsonObject, JsonValue +from openhcs.agent.dto.common import SCHEMA_VERSION from openhcs.agent.dto.ui_bridge import ( UiActionCatalog, UiActionInvokeRequest, @@ -73,113 +69,11 @@ ) from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG -from openhcs.serialization.json import to_jsonable -DtoT = TypeVar("DtoT") UI_BRIDGE_CONTROL_TIMEOUT_MAX_MS = DEFAULT_UI_BRIDGE_TIMEOUT_MS UI_BRIDGE_CONTROL_TIMEOUT_MIN_MS = 1 -class AgentDtoJsonCodec: - """Typed JSON hydration for OpenHCS agent dataclasses.""" - - @classmethod - def dataclass_from_json( - cls, - target_type: type[DtoT], - payload: JsonObject, - ) -> DtoT: - if not is_dataclass(target_type): - raise TypeError(f"Target is not a dataclass: {target_type!r}") - if not isinstance(payload, Mapping): - raise TypeError( - f"Expected JSON object for {target_type.__name__}, " - f"got {type(payload).__name__}" - ) - type_hints = get_type_hints(target_type) - kwargs = {} - for field in fields(target_type): - if field.name in payload: - if field.name in type_hints: - annotation = type_hints[field.name] - else: - annotation = field.type - kwargs[field.name] = cls.coerce( - annotation, - payload[field.name], - ) - continue - if field.default is not MISSING or field.default_factory is not MISSING: - continue - raise KeyError( - f"Missing required field {field.name!r} for {target_type.__name__}" - ) - return target_type(**kwargs) - - @classmethod - def coerce(cls, annotation: TypeForm, value: JsonValue): - if value is None: - return None - - origin = get_origin(annotation) - args = get_args(annotation) - - if origin in (UnionType,): - return cls._coerce_union(args, value) - if origin is None and isinstance(annotation, UnionType): - return cls._coerce_union(args, value) - if str(origin) == "typing.Union": - return cls._coerce_union(args, value) - if origin is tuple: - return cls._coerce_tuple(args, value) - if origin in (list, Sequence): - element_type = args[0] if args else JsonValue - return [cls.coerce(element_type, item) for item in cls._sequence(value)] - if origin in (dict, Mapping): - if not isinstance(value, Mapping): - raise TypeError(f"Expected JSON object, got {type(value).__name__}") - return dict(value) - if is_dataclass(annotation): - return cls.dataclass_from_json(annotation, value) - if isinstance(annotation, type) and issubclass(annotation, Enum): - return annotation(value) - return value - - @classmethod - def _coerce_union(cls, args: tuple[TypeForm, ...], value: JsonValue): - errors: list[Exception] = [] - for candidate in args: - if candidate is NoneType: - continue - try: - return cls.coerce(candidate, value) - except Exception as exc: - errors.append(exc) - if errors: - raise errors[-1] - return value - - @classmethod - def _coerce_tuple(cls, args: tuple[TypeForm, ...], value: JsonValue): - sequence = cls._sequence(value) - if not args: - return tuple(sequence) - if len(args) == 2 and args[1] is Ellipsis: - return tuple(cls.coerce(args[0], item) for item in sequence) - return tuple( - cls.coerce(item_type, item) - for item_type, item in zip(args, sequence, strict=False) - ) - - @staticmethod - def _sequence(value: JsonValue) -> Sequence[JsonValue]: - if isinstance(value, (str, bytes, bytearray)) or not isinstance( - value, Sequence - ): - raise TypeError(f"Expected JSON array, got {type(value).__name__}") - return value - - class UiBridgeControlClient: """Small JSON/ZMQ client for the UI bridge control socket.""" @@ -203,7 +97,7 @@ def request( payload=self._payload_object(payload), ) response_payload = self._send(connection, to_jsonable(request)) - response = AgentDtoJsonCodec.dataclass_from_json( + response = dataclass_from_mapping( UiBridgeResponseEnvelope, response_payload, ) @@ -315,7 +209,7 @@ def _request( def status(self, connection: UiBridgeConnectionSpec) -> UiBridgeStatus: payload = self._request(connection, ui_bridge_service.UiBridgeStatusOperation) - return AgentDtoJsonCodec.dataclass_from_json(UiBridgeStatus, payload) + return dataclass_from_mapping(UiBridgeStatus, payload) def list_documents( self, @@ -324,7 +218,7 @@ def list_documents( payload = self._request( connection, ui_bridge_service.UiBridgeListDocumentsOperation ) - return AgentDtoJsonCodec.dataclass_from_json(UiCodeDocumentCatalog, payload) + return dataclass_from_mapping(UiCodeDocumentCatalog, payload) def list_state_surfaces( self, @@ -333,7 +227,7 @@ def list_state_surfaces( payload = self._request( connection, ui_bridge_service.UiBridgeListStateSurfacesOperation ) - return AgentDtoJsonCodec.dataclass_from_json(UiStateSurfaceCatalog, payload) + return dataclass_from_mapping(UiStateSurfaceCatalog, payload) def list_actions( self, @@ -342,7 +236,7 @@ def list_actions( payload = self._request( connection, ui_bridge_service.UiBridgeListActionsOperation ) - return AgentDtoJsonCodec.dataclass_from_json(UiActionCatalog, payload) + return dataclass_from_mapping(UiActionCatalog, payload) def list_windows( self, @@ -351,7 +245,7 @@ def list_windows( payload = self._request( connection, ui_bridge_service.UiBridgeListWindowsOperation ) - return AgentDtoJsonCodec.dataclass_from_json(UiWindowCatalog, payload) + return dataclass_from_mapping(UiWindowCatalog, payload) def list_object_state_scopes( self, @@ -363,7 +257,7 @@ def list_object_state_scopes( ui_bridge_service.UiBridgeListObjectStateScopesOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiObjectStateScopeCatalog, payload) + return dataclass_from_mapping(UiObjectStateScopeCatalog, payload) def describe_object_state_field( self, @@ -375,7 +269,7 @@ def describe_object_state_field( ui_bridge_service.UiBridgeDescribeObjectStateFieldOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json( + return dataclass_from_mapping( UiObjectStateFieldHelpResult, payload, ) @@ -390,7 +284,7 @@ def mutate_object_state_field( ui_bridge_service.UiBridgeMutateObjectStateFieldOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json( + return dataclass_from_mapping( UiObjectStateFieldMutationResult, payload, ) @@ -403,7 +297,7 @@ def get_document( payload = self._request( connection, ui_bridge_service.UiBridgeGetDocumentOperation, request ) - return AgentDtoJsonCodec.dataclass_from_json(UiCodeDocument, payload) + return dataclass_from_mapping(UiCodeDocument, payload) def get_state_surface( self, @@ -415,7 +309,7 @@ def get_state_surface( ui_bridge_service.UiBridgeGetStateSurfaceOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiStateSurfaceDocument, payload) + return dataclass_from_mapping(UiStateSurfaceDocument, payload) def invoke_action( self, @@ -427,7 +321,7 @@ def invoke_action( ui_bridge_service.UiBridgeInvokeActionOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiActionInvokeResult, payload) + return dataclass_from_mapping(UiActionInvokeResult, payload) def selected_plate_workflow( self, @@ -439,7 +333,7 @@ def selected_plate_workflow( ui_bridge_service.UiBridgeSelectedPlateWorkflowOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json( + return dataclass_from_mapping( UiSelectedPlateWorkflowResult, payload, ) @@ -454,7 +348,7 @@ def focus_window( ui_bridge_service.UiBridgeFocusWindowOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiWindowFocusResult, payload) + return dataclass_from_mapping(UiWindowFocusResult, payload) def navigate_window( self, @@ -466,7 +360,7 @@ def navigate_window( ui_bridge_service.UiBridgeNavigateWindowOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiWindowNavigateResult, payload) + return dataclass_from_mapping(UiWindowNavigateResult, payload) def close_window( self, @@ -478,7 +372,7 @@ def close_window( ui_bridge_service.UiBridgeCloseWindowOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiWindowCloseResult, payload) + return dataclass_from_mapping(UiWindowCloseResult, payload) def snapshot_window( self, @@ -490,7 +384,7 @@ def snapshot_window( ui_bridge_service.UiBridgeSnapshotWindowOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiWindowSnapshotResult, payload) + return dataclass_from_mapping(UiWindowSnapshotResult, payload) def widget_tree( self, @@ -502,7 +396,7 @@ def widget_tree( ui_bridge_service.UiBridgeWidgetTreeOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiWidgetTreeResult, payload) + return dataclass_from_mapping(UiWidgetTreeResult, payload) def invoke_widget_action( self, @@ -514,7 +408,7 @@ def invoke_widget_action( ui_bridge_service.UiBridgeInvokeWidgetActionOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json( + return dataclass_from_mapping( UiWidgetActionInvokeResult, payload, ) @@ -529,7 +423,7 @@ def validate_document( ui_bridge_service.UiBridgeValidateDocumentOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json( + return dataclass_from_mapping( UiCodeDocumentValidationResult, payload, ) @@ -544,7 +438,7 @@ def apply_document( ui_bridge_service.UiBridgeApplyDocumentOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiCodeDocumentApplyResult, payload) + return dataclass_from_mapping(UiCodeDocumentApplyResult, payload) def list_snapshots( self, @@ -556,7 +450,7 @@ def list_snapshots( ui_bridge_service.UiBridgeListSnapshotsOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiSnapshotCatalog, payload) + return dataclass_from_mapping(UiSnapshotCatalog, payload) def restore_snapshot( self, @@ -568,7 +462,7 @@ def restore_snapshot( ui_bridge_service.UiBridgeRestoreSnapshotOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiSnapshotRestoreResult, payload) + return dataclass_from_mapping(UiSnapshotRestoreResult, payload) def time_travel_head( self, @@ -580,13 +474,13 @@ def time_travel_head( ui_bridge_service.UiBridgeTimeTravelHeadOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiSnapshotRestoreResult, payload) + return dataclass_from_mapping(UiSnapshotRestoreResult, payload) def list_branches(self, connection: UiBridgeConnectionSpec) -> UiBranchCatalog: payload = self._request( connection, ui_bridge_service.UiBridgeListBranchesOperation ) - return AgentDtoJsonCodec.dataclass_from_json(UiBranchCatalog, payload) + return dataclass_from_mapping(UiBranchCatalog, payload) def switch_branch( self, @@ -598,7 +492,7 @@ def switch_branch( ui_bridge_service.UiBridgeSwitchBranchOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiSnapshotRestoreResult, payload) + return dataclass_from_mapping(UiSnapshotRestoreResult, payload) def get_operation_status( self, @@ -610,4 +504,4 @@ def get_operation_status( ui_bridge_service.UiBridgeGetOperationStatusOperation, request, ) - return AgentDtoJsonCodec.dataclass_from_json(UiBridgeOperationRef, payload) + return dataclass_from_mapping(UiBridgeOperationRef, payload) diff --git a/openhcs/agent/services/viewer_endpoint_discovery.py b/openhcs/agent/services/viewer_endpoint_discovery.py index 34bd2463b6..538d268e15 100644 --- a/openhcs/agent/services/viewer_endpoint_discovery.py +++ b/openhcs/agent/services/viewer_endpoint_discovery.py @@ -215,7 +215,7 @@ class ViewerEndpointDiscoveryService: def sweep(self) -> "ViewerEndpointDiscoveryResult": from openhcs.agent.dto.viewer import ViewerEndpointDiscoveryResult - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable endpoints = tuple(record.as_dict() for record in discover_viewer_endpoints()) return ViewerEndpointDiscoveryResult( diff --git a/openhcs/agent/services/viewer_window_service.py b/openhcs/agent/services/viewer_window_service.py index f92d8556ce..fdd33d70ba 100644 --- a/openhcs/agent/services/viewer_window_service.py +++ b/openhcs/agent/services/viewer_window_service.py @@ -12,7 +12,12 @@ import zmq from metaclass_registry import AutoRegisterMeta -from python_introspect import dataclass_from_mapping, project_dataclass +from python_introspect import ( + JsonObject, + JsonValue, + dataclass_from_mapping, + project_dataclass, +) from python_introspect.validation import validate_annotation_value from polystore.streaming.identity import StreamProducerIdentity from pyqt_reactive.services.window_snapshot import ( @@ -36,8 +41,6 @@ AgentError, AgentResourceRef, AgentWarning, - JsonObject, - JsonValue, ) from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.viewer import ( diff --git a/openhcs/core/__init__.py b/openhcs/core/__init__.py index 13bd04d02f..e0f2c7e530 100644 --- a/openhcs/core/__init__.py +++ b/openhcs/core/__init__.py @@ -1,45 +1 @@ """Core module for openhcs.""" - -from enum import Enum - - -class CoreExport(Enum): - PROCESSING_CONTEXT = "ProcessingContext" - STEP = "Step" - - -def _load_processing_context(): - from openhcs.core.context.processing_context import ProcessingContext - - return ProcessingContext - - -def _load_step(): - from openhcs.core.steps.abstract import AbstractStep - - return AbstractStep - - -_LAZY_EXPORTS = { - CoreExport.PROCESSING_CONTEXT: _load_processing_context, - CoreExport.STEP: _load_step, -} - - -def __getattr__(name): - """Lazy public re-exports without import-time pipeline/runtime side effects.""" - - try: - export = CoreExport(name) - except ValueError as exc: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from exc - try: - return _LAZY_EXPORTS[export]() - except KeyError as exc: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from exc - - -__all__ = [ - "ProcessingContext", - "Step", -] diff --git a/openhcs/core/artifacts.py b/openhcs/core/artifacts.py index 435113f553..ce2bfd0b27 100644 --- a/openhcs/core/artifacts.py +++ b/openhcs/core/artifacts.py @@ -1715,7 +1715,7 @@ def compose_runtime_values( def materialization_payload(cls, value: "RuntimeValue") -> object: from openhcs.core.runtime_slice_alignment import RuntimeSliceAlignedValueSet from openhcs.core.runtime_spatial_grid import SpatialGrid - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable grids = ( tuple( diff --git a/openhcs/core/debug.py b/openhcs/core/debug.py index 3853cdfbb7..8b455394c7 100644 --- a/openhcs/core/debug.py +++ b/openhcs/core/debug.py @@ -9,7 +9,7 @@ import traceback import threading from abc import ABC, abstractmethod -from dataclasses import asdict, dataclass, field, fields, is_dataclass, replace +from dataclasses import dataclass, field, replace from enum import Enum from pathlib import Path from types import MappingProxyType @@ -17,6 +17,7 @@ from uuid import uuid4 from metaclass_registry import AutoRegisterMeta +from python_introspect import dataclass_from_mapping, to_jsonable import numpy as np from openhcs.core.artifacts import ( @@ -276,7 +277,7 @@ def to_dict(self) -> dict[str, Any]: "cursor": ( None if self.cursor is None - else DebugJsonCodec.cursor_to_record(self.cursor) + else to_jsonable(self.cursor) ), } @@ -287,7 +288,7 @@ def from_dict(cls, payload: Mapping[str, Any]) -> "DebugPausedWorkerStatus": debug_session_id=str(payload["debug_session_id"]), state=DebugPausedWorkerState(str(payload["state"])), cursor=( - None if cursor is None else DebugJsonCodec.cursor_from_record(cursor) + None if cursor is None else dataclass_from_mapping(DebugCursor, cursor) ), ) @@ -391,52 +392,6 @@ def matches_invocation_key_parts( ) -class DebugJsonCodec: - """JSON-record codec derived from debug dataclass field authority.""" - - @staticmethod - def cursor_to_record(cursor: DebugCursor) -> dict[str, Any]: - return DebugJsonCodec.dataclass_record(cursor) - - @staticmethod - def cursor_from_record(record: Mapping[str, Any]) -> DebugCursor: - cursor_record = dict(record) - cursor_record["step_index"] = int(cursor_record["step_index"]) - return DebugJsonCodec.dataclass_from_record(DebugCursor, cursor_record) - - @staticmethod - def dataclass_record(value: object) -> dict[str, Any]: - if not is_dataclass(value): - raise TypeError( - "DebugJsonCodec.dataclass_record requires a dataclass instance, " - f"got {type(value).__name__}." - ) - return asdict(value) - - @staticmethod - def dataclass_from_record(dataclass_type: type, record: Mapping[str, Any]): - if not is_dataclass(dataclass_type): - raise TypeError( - "DebugJsonCodec.dataclass_from_record requires a dataclass type, " - f"got {dataclass_type!r}." - ) - missing_fields = tuple( - field_info.name - for field_info in fields(dataclass_type) - if field_info.name not in record - ) - if missing_fields: - raise KeyError( - f"Debug record missing dataclass fields: {', '.join(missing_fields)}" - ) - return dataclass_type( - **{ - field_info.name: record[field_info.name] - for field_info in fields(dataclass_type) - } - ) - - @dataclass(frozen=True, slots=True) class DebugArtifactRef: """Reference to a debug artifact or preview payload.""" @@ -507,7 +462,7 @@ def to_json_dict(self) -> dict[str, Any]: return { "kind": self.kind.value, "name": self.name, - "cursor": DebugJsonCodec.cursor_to_record(self.cursor), + "cursor": to_jsonable(self.cursor), "storage_ref": self.storage_ref, "storage_backend": self.storage_backend, "preview_ref": self.preview_ref, @@ -523,7 +478,7 @@ def from_json_dict(cls, data: Mapping[str, Any]) -> "DebugArtifactRef": return cls( kind=ArtifactType.coerce(data["kind"]), name=str(data["name"]), - cursor=DebugJsonCodec.cursor_from_record(data["cursor"]), + cursor=dataclass_from_mapping(DebugCursor, data["cursor"]), storage_ref=str(data["storage_ref"]), storage_backend=data.get("storage_backend"), preview_ref=data.get("preview_ref"), @@ -862,7 +817,7 @@ def from_kwargs( ) def to_json_dict(self) -> dict[str, str]: - return DebugJsonCodec.dataclass_record(self) + return to_jsonable(self) @classmethod def from_json_dict(cls, data: Mapping[str, Any]) -> "DebugInvocationParameter": @@ -903,7 +858,7 @@ class DebugSnapshot(DebugBoundaryState): def to_json_dict(self) -> dict[str, Any]: return { "snapshot_id": self.snapshot_id, - "cursor": DebugJsonCodec.cursor_to_record(self.cursor), + "cursor": to_jsonable(self.cursor), "step_name": self.step_name, "callable_name": self.callable_name, "axis_id": self.axis_id, @@ -928,7 +883,7 @@ def to_json_dict(self) -> dict[str, Any]: def from_json_dict(cls, data: Mapping[str, Any]) -> "DebugSnapshot": return cls( snapshot_id=str(data["snapshot_id"]), - cursor=DebugJsonCodec.cursor_from_record(data["cursor"]), + cursor=dataclass_from_mapping(DebugCursor, data["cursor"]), step_name=str(data["step_name"]), callable_name=data.get("callable_name"), axis_id=data.get("axis_id"), @@ -1843,7 +1798,7 @@ def to_progress_context(self) -> dict[str, Any]: return { "debug_session_id": self.debug_session_id, "snapshot_id": self.snapshot_id, - "cursor": DebugJsonCodec.cursor_to_record(self.cursor), + "cursor": to_jsonable(self.cursor), "event_type": self.event_type.value, "snapshot_store_ref": self.snapshot_store_ref, "snapshot_store_backend": self.snapshot_store_backend, @@ -1857,7 +1812,7 @@ def from_progress_context( return cls( debug_session_id=str(context["debug_session_id"]), snapshot_id=context.get("snapshot_id"), - cursor=DebugJsonCodec.cursor_from_record(context["cursor"]), + cursor=dataclass_from_mapping(DebugCursor, context["cursor"]), event_type=DebugEventType(context["event_type"]), snapshot_store_ref=context.get("snapshot_store_ref"), snapshot_store_backend=context.get("snapshot_store_backend"), diff --git a/openhcs/core/measurement_lookup_dialect.py b/openhcs/core/measurement_lookup_dialect.py index d14872dd61..f792076485 100644 --- a/openhcs/core/measurement_lookup_dialect.py +++ b/openhcs/core/measurement_lookup_dialect.py @@ -10,7 +10,7 @@ from types import MappingProxyType from typing import Iterator -from openhcs.core.public_api import declared_public_names +from python_introspect import declared_public_names from metaclass_registry.caches import ProcessLocalBoundedCache from openhcs.core.runtime_identifier import normalize_runtime_identifier diff --git a/openhcs/core/public_api.py b/openhcs/core/public_api.py deleted file mode 100644 index 0f362ab6fa..0000000000 --- a/openhcs/core/public_api.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Helpers for deriving module public API surfaces.""" - -from __future__ import annotations - -from collections.abc import Iterable, Mapping -from inspect import isclass, isfunction -from types import ModuleType -from typing import Any - - -def declared_public_names( - module_globals: Mapping[str, object], - *, - constant_prefixes: Iterable[str] = (), - excluded_names: Iterable[str] = (), - extra_names: Iterable[str] = (), -) -> tuple[str, ...]: - """Return public names declared by the module represented by globals().""" - module_name = module_globals["__name__"] - prefixes = tuple(constant_prefixes) - excluded = set(excluded_names) - declared_names = tuple( - name - for name, value in module_globals.items() - if name not in excluded - if is_declared_public_name( - module_name, - name, - value, - constant_prefixes=prefixes, - ) - ) - return declared_names + tuple(name for name in extra_names if name not in excluded) - - -def exported_public_names( - module_globals: Mapping[str, object], - *, - excluded_names: Iterable[str] = (), -) -> tuple[str, ...]: - """Return public re-export names declared by explicit module imports.""" - excluded = set(excluded_names) - return tuple( - name - for name, value in module_globals.items() - if not name.startswith("_") - if name not in excluded - if not isinstance(value, ModuleType) - ) - - -def public_names_from_objects( - *objects: Any, extra_names: Iterable[str] = () -) -> tuple[str, ...]: - """Return public names from exported object identities plus explicit aliases.""" - return tuple( - item if isinstance(item, str) else item.__name__ for item in objects - ) + tuple(extra_names) - - -def is_declared_public_name( - module_name: str, - name: str, - value: object, - *, - constant_prefixes: tuple[str, ...] = (), -) -> bool: - """Return whether a global is a public module declaration.""" - if name.startswith("_"): - return False - if name.isupper(): - return any(name.startswith(prefix) for prefix in constant_prefixes) - return (isclass(value) or isfunction(value)) and value.__module__ == module_name diff --git a/openhcs/core/roi_source_metadata.py b/openhcs/core/roi_source_metadata.py index adfb3275d4..51fef9ba48 100644 --- a/openhcs/core/roi_source_metadata.py +++ b/openhcs/core/roi_source_metadata.py @@ -13,7 +13,7 @@ from openhcs.core.runtime_image_values import ImagePayloadMetadata from openhcs.core.runtime_slice_projection import RuntimeProjectionPlaneMetadata from openhcs.core.source_image_provenance import SourceComponentMetadata -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @dataclass(frozen=True, slots=True) diff --git a/openhcs/core/runtime_image_values.py b/openhcs/core/runtime_image_values.py index 2e7466ed4b..4bb5e53343 100644 --- a/openhcs/core/runtime_image_values.py +++ b/openhcs/core/runtime_image_values.py @@ -14,13 +14,12 @@ import numpy as np from arraybridge import ArrayGeometry, MemoryType, detect_memory_type -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from zmqruntime.viewer_protocol import ( ViewerWireField, ViewerWireMapping, ViewerWirePayload, ) -from openhcs.serialization.json import to_jsonable from collections.abc import Mapping from openhcs.constants.constants import AllComponents diff --git a/openhcs/core/runtime_stores.py b/openhcs/core/runtime_stores.py index e44a272a2d..1a84a47b5e 100644 --- a/openhcs/core/runtime_stores.py +++ b/openhcs/core/runtime_stores.py @@ -10,7 +10,7 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Any, TypeVar, cast -from python_introspect import RuntimeParameterDeclarationABC +from python_introspect import RuntimeParameterDeclarationABC, to_jsonable from openhcs.constants.constants import AllComponents, Backend from openhcs.core.artifacts import ( @@ -47,7 +47,6 @@ semantic_source_metadata_value, ) from openhcs.core.source_bindings import CompiledSourceBindingPlan -from openhcs.serialization.json import to_jsonable if TYPE_CHECKING: from openhcs.processing.materialization.core import Output diff --git a/openhcs/core/source_bindings.py b/openhcs/core/source_bindings.py index cd08216f46..6b65435782 100644 --- a/openhcs/core/source_bindings.py +++ b/openhcs/core/source_bindings.py @@ -2072,7 +2072,7 @@ def discovery_path_matches(self, root: Path, path: Path) -> bool: def declaration_identity(self) -> str: """Return a stable identity for this complete source declaration.""" - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable declaration = to_jsonable(self) if not isinstance(declaration, Mapping): diff --git a/openhcs/core/source_image_provenance.py b/openhcs/core/source_image_provenance.py index 389a97ad42..45dd7a4ee9 100644 --- a/openhcs/core/source_image_provenance.py +++ b/openhcs/core/source_image_provenance.py @@ -14,7 +14,7 @@ from metaclass_registry import AutoRegisterMeta from python_introspect.validation import validate_annotation_value -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.constants.constants import AllComponents from openhcs.core.source_metadata import ( diff --git a/openhcs/core/source_projection.py b/openhcs/core/source_projection.py index 1349e94927..2deefe36ea 100644 --- a/openhcs/core/source_projection.py +++ b/openhcs/core/source_projection.py @@ -42,7 +42,7 @@ source_metadata_dict, source_metadata_scalar, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable class SourceDatasetConflictError(ValueError): diff --git a/openhcs/core/source_spatial_domain.py b/openhcs/core/source_spatial_domain.py index d0c5d1ae2c..c579949cae 100644 --- a/openhcs/core/source_spatial_domain.py +++ b/openhcs/core/source_spatial_domain.py @@ -18,7 +18,7 @@ ) from metaclass_registry.strategies import NominalTypeKeyedStrategyMixin -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable SourceSpatialAliasValueT = TypeVar("SourceSpatialAliasValueT") diff --git a/openhcs/core/steps/__init__.py b/openhcs/core/steps/__init__.py index 6356e5202e..e5239e00f9 100644 --- a/openhcs/core/steps/__init__.py +++ b/openhcs/core/steps/__init__.py @@ -2,36 +2,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from python_introspect import lazy_exports from openhcs.core.steps.abstract import AbstractStep -if TYPE_CHECKING: - from openhcs.core.steps.function_step import FunctionStep -# Specialized step implementations -# from openhcs.core.steps.specialized import (CompositeStep, FocusStep, -# NormStep, ZFlatStep) - -# Define public exports -__all__ = [ - # New API - Core interfaces +__all__ = ( "AbstractStep", - # New API - Canonical step types - "FunctionStep", - # Specialized step implementations - # 'ZFlatStep', - # 'FocusStep', - # 'CompositeStep', - # 'NormStep', -] - - -def __getattr__(name: str) -> object: - if name == "FunctionStep": - from openhcs.core.steps.function_step import FunctionStep - - return FunctionStep - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + *lazy_exports(globals(), {"openhcs.core.steps.function_step": ("FunctionStep",)}), +) # PERFORMANCE OPTIMIZATION: Pre-warm step editor cache at import time diff --git a/openhcs/interop/cellprofiler/__init__.py b/openhcs/interop/cellprofiler/__init__.py index 6941b77ac1..f99d020cba 100644 --- a/openhcs/interop/cellprofiler/__init__.py +++ b/openhcs/interop/cellprofiler/__init__.py @@ -5,7 +5,7 @@ canonical owner of `.cppipe` import or CellProfiler measurement semantics. """ -from openhcs.core.public_api import exported_public_names +from python_introspect import exported_public_names from openhcs.interop.cellprofiler.measurement_dialect import ( CELLPROFILER_MEASUREMENT_DIALECT, CELLPROFILER_MEASUREMENT_LOOKUP_DIALECT, diff --git a/openhcs/interop/cellprofiler/measurement_lookup.py b/openhcs/interop/cellprofiler/measurement_lookup.py index 120db857d4..28ab02d4b3 100644 --- a/openhcs/interop/cellprofiler/measurement_lookup.py +++ b/openhcs/interop/cellprofiler/measurement_lookup.py @@ -10,7 +10,7 @@ from metaclass_registry import AutoRegisterMeta from openhcs.core.runtime_relationships import ChildCountFeatureDeclaration -from openhcs.core.public_api import declared_public_names +from python_introspect import declared_public_names from openhcs.core.measurement_feature_queries import measurement_values_for_feature diff --git a/openhcs/mcp/dev_client.py b/openhcs/mcp/dev_client.py index 31b099cf48..ac95337138 100644 --- a/openhcs/mcp/dev_client.py +++ b/openhcs/mcp/dev_client.py @@ -14,8 +14,7 @@ from dataclasses import dataclass from typing import TextIO -from openhcs.serialization.json import to_jsonable as to_jsonable -from openhcs.agent.dto.common import JsonObject +from python_introspect import JsonObject, to_jsonable from openhcs.agent.capabilities import ( FullLocalCapabilitySurfaceProfile, LocalCapabilitySurfaceProfile, @@ -76,7 +75,6 @@ "main", "parse_json_object", "state_surface_tool_arguments", - "to_jsonable", "workflow_poll_has_reached_terminal_state", "workflow_poll_summary_result", "workflow_poll_terminal_status", diff --git a/openhcs/mcp/dev_client_commanding.py b/openhcs/mcp/dev_client_commanding.py index 2bfacbf37a..b52c2727b6 100644 --- a/openhcs/mcp/dev_client_commanding.py +++ b/openhcs/mcp/dev_client_commanding.py @@ -21,12 +21,8 @@ get_capability_registry, require_agent_type_contract, ) -from openhcs.agent.dto.common import ( - AgentCliArgumentSpec, - AgentCliRequest, - JsonObject, - JsonValue, -) +from openhcs.agent.dto.common import AgentCliArgumentSpec, AgentCliRequest +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.execution import ( RuntimeServerConnectionToolRequest, ) @@ -220,7 +216,7 @@ def render_response( def render_result(self, response, args: argparse.Namespace) -> str: """Render a framed production result without requiring a JSON round trip.""" - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable return self.render_response(to_jsonable(response), args) @@ -250,7 +246,7 @@ class TypedCompositeCommandSpec(McpDevCommandSpec): def render_result(self, response, args: argparse.Namespace) -> str: if self.requests_json_output(args): - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable return super().render_response(to_jsonable(response), args) return self.render_response(response, args) diff --git a/openhcs/mcp/dev_client_commands/knowledge_pipeline.py b/openhcs/mcp/dev_client_commands/knowledge_pipeline.py index 080a87f218..03cbd91b7c 100644 --- a/openhcs/mcp/dev_client_commands/knowledge_pipeline.py +++ b/openhcs/mcp/dev_client_commands/knowledge_pipeline.py @@ -13,7 +13,7 @@ ) from openhcs.agent.capabilities import agent_capabilities from openhcs.agent.dto.authoring import AuthoringContextRequest -from openhcs.agent.dto.common import JsonObject, JsonValue +from python_introspect import JsonObject, JsonValue, to_jsonable from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.functions import ( CustomFunctionRegistrationRequest, @@ -53,7 +53,6 @@ CatalogRenderOptions, ) from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG -from openhcs.serialization.json import to_jsonable class KnowledgeCommandSpec(SingleToolCommandSpec): diff --git a/openhcs/mcp/dev_client_commands/plate.py b/openhcs/mcp/dev_client_commands/plate.py index 198bd911da..e3798533f1 100644 --- a/openhcs/mcp/dev_client_commands/plate.py +++ b/openhcs/mcp/dev_client_commands/plate.py @@ -5,7 +5,7 @@ import argparse from openhcs.agent.capabilities import agent_capabilities -from openhcs.agent.dto.common import JsonValue +from python_introspect import JsonValue from openhcs.agent.dto.plate import ( PlateFileQueryRequest, PlateFileStreamRequest, diff --git a/openhcs/mcp/dev_client_commands/ui.py b/openhcs/mcp/dev_client_commands/ui.py index b6a5596046..a30cd3e4ba 100644 --- a/openhcs/mcp/dev_client_commands/ui.py +++ b/openhcs/mcp/dev_client_commands/ui.py @@ -8,7 +8,7 @@ from collections.abc import Mapping from typing import cast -from python_introspect import dataclass_from_mapping +from python_introspect import JsonObject, JsonValue, dataclass_from_mapping from pyqt_reactive.services.window_snapshot import ( WindowSnapshotCaptureScope, @@ -16,7 +16,6 @@ ) from openhcs.agent.capabilities import agent_capabilities -from openhcs.agent.dto.common import JsonObject, JsonValue from openhcs.agent.dto.ui_bridge import ( UiActionInvokeRequest, UiCodeDocumentApplyRequest, diff --git a/openhcs/mcp/dev_client_commands/viewer.py b/openhcs/mcp/dev_client_commands/viewer.py index bee6d1c3de..992f06a5c9 100644 --- a/openhcs/mcp/dev_client_commands/viewer.py +++ b/openhcs/mcp/dev_client_commands/viewer.py @@ -8,7 +8,7 @@ from pyqt_reactive.services.window_snapshot import WindowSnapshotCaptureScope from openhcs.agent.capabilities import agent_capabilities -from openhcs.agent.dto.common import JsonValue +from python_introspect import JsonValue from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.viewer import ( VIEWER_WINDOW_CONTROL_TIMEOUT_MS_DEFAULT, diff --git a/openhcs/mcp/dev_client_core.py b/openhcs/mcp/dev_client_core.py index d52ee2d8e0..89a59c0439 100644 --- a/openhcs/mcp/dev_client_core.py +++ b/openhcs/mcp/dev_client_core.py @@ -21,10 +21,13 @@ from metaclass_registry import AutoRegisterMeta from python_introspect import ( + JsonObject, + JsonValue, dataclass_from_mapping, is_enum_type, optional_member_type, signature_analysis_target, + to_jsonable, ) from zmqruntime.config import TransportMode @@ -35,13 +38,7 @@ LocalCapabilitySurfaceProfile, get_agent_capability, ) -from openhcs.agent.dto.common import ( - AgentCliRequest, - AgentError, - AgentResultEnvelope, - JsonObject, - JsonValue, -) +from openhcs.agent.dto.common import AgentCliRequest, AgentError, AgentResultEnvelope from openhcs.agent.dto.execution import PipelineExecutionSubmissionRequest from openhcs.agent.dto.mcp import McpBoundaryFailure, McpToolErrorResult from openhcs.agent.dto.ui_bridge import ( @@ -74,7 +71,6 @@ ) from openhcs.agent.ui_bridge_environment import UIConfigCacheEnvironment from openhcs.runtime.import_authority import OpenHCSRuntimeImportAuthority -from openhcs.serialization.json import to_jsonable from openhcs.utils.environment import OpenHCSProcessEnvironment if TYPE_CHECKING: diff --git a/openhcs/mcp/dev_client_renderers/knowledge.py b/openhcs/mcp/dev_client_renderers/knowledge.py index 172353c1d3..eb4d2eb526 100644 --- a/openhcs/mcp/dev_client_renderers/knowledge.py +++ b/openhcs/mcp/dev_client_renderers/knowledge.py @@ -12,7 +12,7 @@ InternalApiSymbol, ) from openhcs.agent.dto.authoring import AuthoringContext -from openhcs.agent.dto.common import JsonObject, JsonValue +from python_introspect import JsonObject, JsonValue, to_jsonable from openhcs.agent.dto.functions import ( CustomFunctionRegistrationResult, FunctionCatalogPage, @@ -32,7 +32,6 @@ McpDevOutputRenderOptions, McpDevPayloadProjection, ) -from openhcs.serialization.json import to_jsonable from openhcs.mcp.dev_client_renderers.object_state import ObjectStateScopeRenderer from openhcs.mcp.dev_client_renderers.viewer import ( RuntimeServerRenderer, diff --git a/openhcs/mcp/dev_client_renderers/object_state.py b/openhcs/mcp/dev_client_renderers/object_state.py index 6104ae3f75..f226536f2c 100644 --- a/openhcs/mcp/dev_client_renderers/object_state.py +++ b/openhcs/mcp/dev_client_renderers/object_state.py @@ -5,7 +5,7 @@ import json from collections.abc import Mapping -from openhcs.agent.dto.common import JsonObject, JsonValue +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.ui_bridge import ( UiObjectStateFieldFilter, UiObjectStateFieldHelpResult, diff --git a/openhcs/mcp/dev_client_renderers/plate.py b/openhcs/mcp/dev_client_renderers/plate.py index 1ac3944386..19db27c7f3 100644 --- a/openhcs/mcp/dev_client_renderers/plate.py +++ b/openhcs/mcp/dev_client_renderers/plate.py @@ -9,7 +9,7 @@ from typing import ClassVar from openhcs.agent.capabilities import agent_capabilities -from openhcs.agent.dto.common import JsonObject, JsonValue +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.plate import ( PlateFileQueryResult, PlateFileStreamResult, diff --git a/openhcs/mcp/dev_client_renderers/ui_bridge.py b/openhcs/mcp/dev_client_renderers/ui_bridge.py index f994e8646c..13c1f466f5 100644 --- a/openhcs/mcp/dev_client_renderers/ui_bridge.py +++ b/openhcs/mcp/dev_client_renderers/ui_bridge.py @@ -11,7 +11,7 @@ from metaclass_registry import AutoRegisterMeta from openhcs.agent.capabilities import agent_capabilities -from openhcs.agent.dto.common import JsonObject, JsonValue +from python_introspect import JsonObject, JsonValue from openhcs.agent.dto.ui_bridge import ( UiActionCatalog, UiActionInvokeResult, diff --git a/openhcs/mcp/dev_client_renderers/viewer.py b/openhcs/mcp/dev_client_renderers/viewer.py index 78bf2f4e1f..1906a85d26 100644 --- a/openhcs/mcp/dev_client_renderers/viewer.py +++ b/openhcs/mcp/dev_client_renderers/viewer.py @@ -3,11 +3,10 @@ from __future__ import annotations import json -from openhcs.serialization.json import to_jsonable +from python_introspect import JsonObject, JsonValue, to_jsonable from collections.abc import Mapping from pathlib import Path -from openhcs.agent.dto.common import JsonObject, JsonValue from openhcs.agent.dto.execution import ( RuntimeDebugInspectionResult, RuntimeExecutionStatus, diff --git a/openhcs/mcp/dev_client_rendering.py b/openhcs/mcp/dev_client_rendering.py index a4c35b0479..6fbb5e3df2 100644 --- a/openhcs/mcp/dev_client_rendering.py +++ b/openhcs/mcp/dev_client_rendering.py @@ -10,14 +10,14 @@ from typing import ClassVar, TypeAlias, TypeVar from metaclass_registry import AutoRegisterMeta -from python_introspect import dataclass_from_mapping +from python_introspect import JsonObject, JsonValue, dataclass_from_mapping from openhcs.agent.capabilities import ( AgentCapabilityDeclaration, CapabilityWorkflowGroup, get_agent_capability, ) -from openhcs.agent.dto.common import AgentError, JsonObject, JsonValue +from openhcs.agent.dto.common import AgentError DEFAULT_CODE_DOCUMENT_MAX_CHARS = 2_000 PresentationValue = TypeVar("PresentationValue") @@ -222,7 +222,7 @@ def render_bindings(cls) -> tuple["McpDevOutputRendererBinding", ...]: @classmethod def render_result(cls, response, options: McpDevOutputRenderOptions) -> str: - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable return cls.render_with_options(to_jsonable(response), options) @@ -250,7 +250,7 @@ class McpDevOutputRendererBinding: def render_result(self, response, options: McpDevOutputRenderOptions) -> str: if self.render_function is not None: - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable return self.render_function(to_jsonable(response)) return self.renderer_type.render_result(response, options) diff --git a/openhcs/mcp/server.py b/openhcs/mcp/server.py index a8fa594b10..e2239fc8a3 100644 --- a/openhcs/mcp/server.py +++ b/openhcs/mcp/server.py @@ -35,7 +35,7 @@ from pydantic import Field as PydanticField from pydantic import WithJsonSchema from pyqt_reactive.services.window_snapshot import WindowSnapshotCaptureScope -from python_introspect import dataclass_from_mapping +from python_introspect import JsonValue, dataclass_from_mapping, to_jsonable from zmqruntime.config import TransportMode from zmqruntime.startup import EndpointStartupStatus @@ -57,7 +57,6 @@ AGENT_PARAMETER_PRODUCER_OUTPUT_CONTRACT_METADATA_KEY, SCHEMA_VERSION, AgentError, - JsonValue, ) from openhcs.agent.dto.execution import ( ExecutionConnectionSpec, @@ -89,7 +88,6 @@ McpProcessLifecycle, McpProcessRecoveryStatus, ) -from openhcs.serialization.json import to_jsonable MCP_SERVER_INSTRUCTIONS = CapabilityTransport.LOCAL_STDIO.server_instructions() diff --git a/openhcs/processing/backends/cellprofiler/alignment.py b/openhcs/processing/backends/cellprofiler/alignment.py index b69437e219..7c1becdd96 100644 --- a/openhcs/processing/backends/cellprofiler/alignment.py +++ b/openhcs/processing/backends/cellprofiler/alignment.py @@ -27,7 +27,7 @@ from openhcs.core.pipeline.function_contracts import ( required_variable_components, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_tabular_values import ( FieldSpec, diff --git a/openhcs/processing/backends/cellprofiler/classification.py b/openhcs/processing/backends/cellprofiler/classification.py index 173dea6be1..d83d2ecd40 100644 --- a/openhcs/processing/backends/cellprofiler/classification.py +++ b/openhcs/processing/backends/cellprofiler/classification.py @@ -1291,7 +1291,7 @@ def artifact_output_relations( special_inputs, ) from openhcs.core.runtime_batch_contracts import SliceIndexRuntimeParameter -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_measurements import ObjectLabelMeasurementValues from openhcs.core.runtime_object_labels import ( ObjectLabelValue, diff --git a/openhcs/processing/backends/cellprofiler/colocalization.py b/openhcs/processing/backends/cellprofiler/colocalization.py index b2c4f35b91..49639292ae 100644 --- a/openhcs/processing/backends/cellprofiler/colocalization.py +++ b/openhcs/processing/backends/cellprofiler/colocalization.py @@ -48,7 +48,7 @@ runtime_bound_parameters, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_batch_contracts import ( RuntimeBatchInvocationRequest, measurement_image_batch_executor, diff --git a/openhcs/processing/backends/cellprofiler/edge.py b/openhcs/processing/backends/cellprofiler/edge.py index 4ba25b984b..54f959a1e6 100644 --- a/openhcs/processing/backends/cellprofiler/edge.py +++ b/openhcs/processing/backends/cellprofiler/edge.py @@ -52,7 +52,7 @@ class EnhanceEdgesModule(CellProfilerModule): running_variance_numba, ) from openhcs.core.memory.decorators import numpy as numpy_decorator -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( image_payload_data, diff --git a/openhcs/processing/backends/cellprofiler/flagging.py b/openhcs/processing/backends/cellprofiler/flagging.py index d35aafb21e..ae213a6683 100644 --- a/openhcs/processing/backends/cellprofiler/flagging.py +++ b/openhcs/processing/backends/cellprofiler/flagging.py @@ -22,7 +22,7 @@ from openhcs.core.pipeline.function_contracts import ( runtime_bound_parameters, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_measurements import MeasurementTable from openhcs.core.runtime_measurements import MeasurementRowAxisField from openhcs.core.runtime_tabular_values import ColumnarRows, FieldSpec diff --git a/openhcs/processing/backends/cellprofiler/grid.py b/openhcs/processing/backends/cellprofiler/grid.py index 3504eef493..03f9c4ce5d 100644 --- a/openhcs/processing/backends/cellprofiler/grid.py +++ b/openhcs/processing/backends/cellprofiler/grid.py @@ -32,7 +32,7 @@ DataclassMeasurementColumnarRows, ) from openhcs.core.pipeline.function_contracts import special_inputs -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_object_labels import ( ObjectLabelPayload, diff --git a/openhcs/processing/backends/cellprofiler/illumination.py b/openhcs/processing/backends/cellprofiler/illumination.py index 81096bad23..2fd02ed70b 100644 --- a/openhcs/processing/backends/cellprofiler/illumination.py +++ b/openhcs/processing/backends/cellprofiler/illumination.py @@ -30,7 +30,7 @@ from openhcs.core.callable_contract import processing_prepare from openhcs.core.memory.decorators import numpy from openhcs.core.pipeline.function_contracts import special_inputs -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( diff --git a/openhcs/processing/backends/cellprofiler/intensity.py b/openhcs/processing/backends/cellprofiler/intensity.py index 5d4380438c..ec635c0221 100644 --- a/openhcs/processing/backends/cellprofiler/intensity.py +++ b/openhcs/processing/backends/cellprofiler/intensity.py @@ -283,7 +283,7 @@ def active_artifact_bindings( measurement_image_batch_executor, pure_2d_batch_executor, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_object_label_domains import ( ConsecutiveObjectLabelIdProjection, ObjectLabelDomain, diff --git a/openhcs/processing/backends/cellprofiler/intensity_distribution.py b/openhcs/processing/backends/cellprofiler/intensity_distribution.py index 0a75976bc7..32d36a1959 100644 --- a/openhcs/processing/backends/cellprofiler/intensity_distribution.py +++ b/openhcs/processing/backends/cellprofiler/intensity_distribution.py @@ -43,7 +43,7 @@ runtime_bound_parameters, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_identifier import normalize_runtime_identifier from openhcs.core.equivalence.policy import ( RuntimeMeasurementQualifierSuffixMatchStrategy, diff --git a/openhcs/processing/backends/cellprofiler/maxima.py b/openhcs/processing/backends/cellprofiler/maxima.py index d56fcd7454..7d7f215443 100644 --- a/openhcs/processing/backends/cellprofiler/maxima.py +++ b/openhcs/processing/backends/cellprofiler/maxima.py @@ -23,7 +23,7 @@ from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_measurements import MeasurementRowAxisField from openhcs.core.memory.decorators import numpy -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.interop.cellprofiler.module_artifact_declarations import ( MeasurementArtifactOutputModule, ) diff --git a/openhcs/processing/backends/cellprofiler/measurement_math.py b/openhcs/processing/backends/cellprofiler/measurement_math.py index f3f10e292f..c27d87ac26 100644 --- a/openhcs/processing/backends/cellprofiler/measurement_math.py +++ b/openhcs/processing/backends/cellprofiler/measurement_math.py @@ -32,7 +32,7 @@ from openhcs.core.pipeline.function_contracts import ( runtime_bound_parameters, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import ( EnumKeyedStrategyMixin, enum_member_with_payload, diff --git a/openhcs/processing/backends/cellprofiler/median_filter.py b/openhcs/processing/backends/cellprofiler/median_filter.py index 4d08c36a70..17b9a84b90 100644 --- a/openhcs/processing/backends/cellprofiler/median_filter.py +++ b/openhcs/processing/backends/cellprofiler/median_filter.py @@ -14,7 +14,7 @@ from openhcs.core.artifacts import ImageArtifactType from openhcs.core.callable_contract import runtime_image_execution_mode from openhcs.core.memory.decorators import numpy -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_batch_contracts import ( RuntimePure2DSliceBatchRequest, pure_2d_batch_executor, diff --git a/openhcs/processing/backends/cellprofiler/morphology.py b/openhcs/processing/backends/cellprofiler/morphology.py index 45bbef5c72..c9714fdc24 100644 --- a/openhcs/processing/backends/cellprofiler/morphology.py +++ b/openhcs/processing/backends/cellprofiler/morphology.py @@ -681,7 +681,7 @@ def artifact_output_relations( object_label_input_execution_mode, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.processing.backends.cellprofiler.morphology_connected_components_numba import ( equal_value_components_numba, diff --git a/openhcs/processing/backends/cellprofiler/object_filtering.py b/openhcs/processing/backends/cellprofiler/object_filtering.py index f6f89c9bbd..6475549cfe 100644 --- a/openhcs/processing/backends/cellprofiler/object_filtering.py +++ b/openhcs/processing/backends/cellprofiler/object_filtering.py @@ -21,7 +21,7 @@ import numpy as np from metaclass_registry import AutoRegisterMeta from numba import njit -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.memory.decorators import numpy from openhcs.core.callable_contract import KeywordRuntimeParameter from openhcs.core.pipeline.function_contracts import ( diff --git a/openhcs/processing/backends/cellprofiler/object_images.py b/openhcs/processing/backends/cellprofiler/object_images.py index 5e5e00c3eb..a8abfa54c1 100644 --- a/openhcs/processing/backends/cellprofiler/object_images.py +++ b/openhcs/processing/backends/cellprofiler/object_images.py @@ -23,7 +23,7 @@ object_label_input_execution_mode, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.processing_preparation import PersistentNumbaKernelPreparation from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_image_values import ( diff --git a/openhcs/processing/backends/cellprofiler/object_overlap.py b/openhcs/processing/backends/cellprofiler/object_overlap.py index f7204c73ab..d399187ecd 100644 --- a/openhcs/processing/backends/cellprofiler/object_overlap.py +++ b/openhcs/processing/backends/cellprofiler/object_overlap.py @@ -20,7 +20,7 @@ object_label_input_execution_mode, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_tabular_values import ( FieldSpec, ) diff --git a/openhcs/processing/backends/cellprofiler/outlines.py b/openhcs/processing/backends/cellprofiler/outlines.py index 3d848ee7f4..817a501d6b 100644 --- a/openhcs/processing/backends/cellprofiler/outlines.py +++ b/openhcs/processing/backends/cellprofiler/outlines.py @@ -42,7 +42,7 @@ object_label_input_execution_mode, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_object_labels import ( ObjectLabelValue, ObjectLabelStorageStrategy, diff --git a/openhcs/processing/backends/cellprofiler/primary_objects.py b/openhcs/processing/backends/cellprofiler/primary_objects.py index 925acae8e4..7e0184f8b9 100644 --- a/openhcs/processing/backends/cellprofiler/primary_objects.py +++ b/openhcs/processing/backends/cellprofiler/primary_objects.py @@ -10,7 +10,7 @@ from typing import TYPE_CHECKING from enum import Enum from openhcs.core.memory import numpy -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, diff --git a/openhcs/processing/backends/cellprofiler/projection.py b/openhcs/processing/backends/cellprofiler/projection.py index 7ce4114419..7136d7b709 100644 --- a/openhcs/processing/backends/cellprofiler/projection.py +++ b/openhcs/processing/backends/cellprofiler/projection.py @@ -19,7 +19,7 @@ from openhcs.core.measurement_row_materialization import ( DataclassMeasurementColumnarRows, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.interop.cellprofiler.setting_names import SettingNameFamily from openhcs.interop.cellprofiler.settings_binder import ( SettingToKeywordBinding, diff --git a/openhcs/processing/backends/cellprofiler/relationships.py b/openhcs/processing/backends/cellprofiler/relationships.py index 6cd9b20e9a..36daf6bb55 100644 --- a/openhcs/processing/backends/cellprofiler/relationships.py +++ b/openhcs/processing/backends/cellprofiler/relationships.py @@ -755,7 +755,7 @@ def feature_name(cls, identity: object) -> str: ) from openhcs.core.runtime_measurements import MeasurementTable from openhcs.core.pipeline.function_contracts import special_inputs -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_output_matching import ( RuntimeOutputBundle, ) diff --git a/openhcs/processing/backends/cellprofiler/secondary.py b/openhcs/processing/backends/cellprofiler/secondary.py index c1af66ca3a..38086973c3 100644 --- a/openhcs/processing/backends/cellprofiler/secondary.py +++ b/openhcs/processing/backends/cellprofiler/secondary.py @@ -12,7 +12,7 @@ import numpy as np from metaclass_registry import AutoRegisterMeta from numba import njit -from python_introspect import set_signature_analysis_target +from python_introspect import public_names_from_objects, set_signature_analysis_target from openhcs.constants.constants import MemoryType from openhcs.core.artifacts import ( @@ -33,7 +33,6 @@ from openhcs.core.pipeline.function_contracts import ( special_inputs, ) -from openhcs.core.public_api import public_names_from_objects from metaclass_registry.strategies import ( EnumKeyedStrategyMixin, RegisteredLeafClassSpec, diff --git a/openhcs/processing/backends/cellprofiler/skeleton.py b/openhcs/processing/backends/cellprofiler/skeleton.py index ba8c710ced..25f3a686a2 100644 --- a/openhcs/processing/backends/cellprofiler/skeleton.py +++ b/openhcs/processing/backends/cellprofiler/skeleton.py @@ -30,7 +30,7 @@ RuntimeMeasurementFeature, ) from openhcs.core.pipeline.function_contracts import special_inputs -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_object_labels import ( ObjectLabelValue, object_label_dense_array, diff --git a/openhcs/processing/backends/cellprofiler/smoothing.py b/openhcs/processing/backends/cellprofiler/smoothing.py index 6911307b83..5759522bbb 100644 --- a/openhcs/processing/backends/cellprofiler/smoothing.py +++ b/openhcs/processing/backends/cellprofiler/smoothing.py @@ -75,7 +75,7 @@ class SmoothModule(CellProfilerModule): RuntimePure2DSliceBatchRequest, pure_2d_batch_executor, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_image_values import ( image_payload_mask, diff --git a/openhcs/processing/backends/cellprofiler/texture.py b/openhcs/processing/backends/cellprofiler/texture.py index cdc31351b2..81b82da728 100644 --- a/openhcs/processing/backends/cellprofiler/texture.py +++ b/openhcs/processing/backends/cellprofiler/texture.py @@ -19,7 +19,7 @@ MeasurementProjectedColumnarRows, ) from openhcs.core.pipeline.function_contracts import special_inputs -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.core.runtime_identifier import normalize_runtime_identifier from openhcs.core.runtime_object_labels import ( ObjectLabelPayload, diff --git a/openhcs/processing/backends/cellprofiler/thresholding.py b/openhcs/processing/backends/cellprofiler/thresholding.py index 2ad54d963e..ff8dfdc60a 100644 --- a/openhcs/processing/backends/cellprofiler/thresholding.py +++ b/openhcs/processing/backends/cellprofiler/thresholding.py @@ -43,7 +43,7 @@ ) from openhcs.core.memory.decorators import numpy from openhcs.core.pipeline.function_contracts import runtime_bound_parameters -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( diff --git a/openhcs/processing/backends/cellprofiler/tracking.py b/openhcs/processing/backends/cellprofiler/tracking.py index 619f8515d3..4502ec6308 100644 --- a/openhcs/processing/backends/cellprofiler/tracking.py +++ b/openhcs/processing/backends/cellprofiler/tracking.py @@ -41,7 +41,7 @@ required_variable_components, special_inputs, ) -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_image_values import ( RuntimeArrayData, diff --git a/openhcs/processing/backends/cellprofiler/watershed.py b/openhcs/processing/backends/cellprofiler/watershed.py index 4fcc85e58c..cfcb2b3f97 100644 --- a/openhcs/processing/backends/cellprofiler/watershed.py +++ b/openhcs/processing/backends/cellprofiler/watershed.py @@ -5,7 +5,7 @@ from enum import Enum from typing import Callable, ClassVar, TYPE_CHECKING from metaclass_registry import AutoRegisterMeta -from python_introspect import set_signature_analysis_target +from python_introspect import public_names_from_objects, set_signature_analysis_target from openhcs.core.artifacts import ( ArtifactSpecCollection, ImageArtifactType, @@ -395,7 +395,6 @@ def postprocess_bound_settings( from openhcs.core.callable_contract import runtime_image_execution_mode from openhcs.core.memory.decorators import numpy from openhcs.core.pipeline.function_contracts import special_inputs -from openhcs.core.public_api import public_names_from_objects from openhcs.core.image_shapes import trailing_spatial_factors from openhcs.core.runtime_profile import RuntimeProfileLogger from openhcs.core.runtime_object_label_domains import ( diff --git a/openhcs/processing/backends/cellprofiler/zernike.py b/openhcs/processing/backends/cellprofiler/zernike.py index 5423426746..8d90902a93 100644 --- a/openhcs/processing/backends/cellprofiler/zernike.py +++ b/openhcs/processing/backends/cellprofiler/zernike.py @@ -46,7 +46,7 @@ project_image_mask_to_data_domain, ) from openhcs.core.runtime_identifier import normalize_runtime_identifier -from openhcs.core.public_api import public_names_from_objects +from python_introspect import public_names_from_objects from openhcs.interop.cellprofiler.module_measurement_features import ( IntensityFeature, ShapeDescriptorFeature, diff --git a/openhcs/processing/backends/lib_registry/openhcs_registry.py b/openhcs/processing/backends/lib_registry/openhcs_registry.py index e1c14afeb8..5091a6fc31 100644 --- a/openhcs/processing/backends/lib_registry/openhcs_registry.py +++ b/openhcs/processing/backends/lib_registry/openhcs_registry.py @@ -29,7 +29,7 @@ FunctionStepExecutionScope, ) from openhcs.core.function_contract_metadata import FunctionContractAttribute -from openhcs.core.public_api import is_declared_public_name +from python_introspect import is_declared_public_name from openhcs.processing.backends.lib_registry.unified_registry import ( FunctionMetadata, LibraryRegistryBase, diff --git a/openhcs/processing/backends/processors/__init__.py b/openhcs/processing/backends/processors/__init__.py index 7fe1bd42a7..4bcd5110fb 100644 --- a/openhcs/processing/backends/processors/__init__.py +++ b/openhcs/processing/backends/processors/__init__.py @@ -7,24 +7,3 @@ Each processor module provides the same set of functions but optimized for its specific backend. """ - -from __future__ import annotations - -import importlib - -__all__ = [ - "numpy_processor", - "cupy_processor", - "torch_processor", - "tensorflow_processor", - "jax_processor", - "pyclesperanto_processor", -] - - -def __getattr__(name: str): - if name not in __all__: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - module = importlib.import_module(f"{__name__}.{name}") - globals()[name] = module - return module diff --git a/openhcs/pyqt_gui/__init__.py b/openhcs/pyqt_gui/__init__.py index 82ea9a85f2..f40f505574 100644 --- a/openhcs/pyqt_gui/__init__.py +++ b/openhcs/pyqt_gui/__init__.py @@ -2,7 +2,6 @@ import logging import sys -from typing import TYPE_CHECKING, Any # CRITICAL: Check for SILENT mode BEFORE any OpenHCS imports # This must be at MODULE LEVEL to run before main.py is imported @@ -14,23 +13,12 @@ root_logger = logging.getLogger() root_logger.setLevel(logging.CRITICAL + 1) -if TYPE_CHECKING: - from openhcs.pyqt_gui.app import OpenHCSPyQtApp - from openhcs.pyqt_gui.main import OpenHCSMainWindow +from python_introspect import lazy_exports # noqa: E402 -__all__ = ["OpenHCSMainWindow", "OpenHCSPyQtApp"] - - -def __getattr__(name: str) -> Any: - """Resolve public GUI classes without importing the full UI at package load.""" - if name == "OpenHCSMainWindow": - from openhcs.pyqt_gui.main import OpenHCSMainWindow - - globals()[name] = OpenHCSMainWindow - return OpenHCSMainWindow - if name == "OpenHCSPyQtApp": - from openhcs.pyqt_gui.app import OpenHCSPyQtApp - - globals()[name] = OpenHCSPyQtApp - return OpenHCSPyQtApp - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") +__all__ = lazy_exports( + globals(), + { + "openhcs.pyqt_gui.main": ("OpenHCSMainWindow",), + "openhcs.pyqt_gui.app": ("OpenHCSPyQtApp",), + }, +) diff --git a/openhcs/pyqt_gui/services/desktop_update.py b/openhcs/pyqt_gui/services/desktop_update.py index 1e03a55acd..de49fc8533 100644 --- a/openhcs/pyqt_gui/services/desktop_update.py +++ b/openhcs/pyqt_gui/services/desktop_update.py @@ -28,7 +28,7 @@ from pyqt_reactive.services.window_navigation import ( RegisteredWindowNavigationRequest, ) -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from openhcs import __version__ as OPENHCS_VERSION from openhcs.desktop_deployment import ( @@ -42,7 +42,6 @@ from openhcs.pyqt_gui.services.desktop_update_worker import DesktopUpdatePlan from openhcs.pyqt_gui.services.history_migration import DesktopHistoryUpgrade from openhcs.pyqt_gui.services.ui_window_ids import OpenHCSUiWindowId -from openhcs.serialization.json import to_jsonable from openhcs.ui.shared.plate_manager_code_document import ( PlateManagerCodeDocumentAuthority, ) diff --git a/openhcs/pyqt_gui/services/ui_agent_bridge.py b/openhcs/pyqt_gui/services/ui_agent_bridge.py index 872cff2a47..91fe1477a4 100644 --- a/openhcs/pyqt_gui/services/ui_agent_bridge.py +++ b/openhcs/pyqt_gui/services/ui_agent_bridge.py @@ -27,8 +27,7 @@ AgentWarning, AgentResultEnvelope, ) -from openhcs.serialization.json import to_jsonable -from python_introspect import project_dataclass +from python_introspect import project_dataclass, to_jsonable from openhcs.agent.services.function_catalog_service import FunctionCatalogServiceABC from openhcs.core.function_reference import FunctionReference from openhcs.agent.dto.ui_bridge import ( diff --git a/openhcs/pyqt_gui/services/ui_bridge_live_overview.py b/openhcs/pyqt_gui/services/ui_bridge_live_overview.py index 171969e65e..4c20e10081 100644 --- a/openhcs/pyqt_gui/services/ui_bridge_live_overview.py +++ b/openhcs/pyqt_gui/services/ui_bridge_live_overview.py @@ -19,7 +19,7 @@ UiStateSurfaceRequest, UiStateSurfaceSummary, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.agent.ui_bridge_identities import ( UiLiveOverviewStateSurfaceIdentityDeclaration, ) diff --git a/openhcs/pyqt_gui/services/ui_bridge_object_state.py b/openhcs/pyqt_gui/services/ui_bridge_object_state.py index da3958dcc2..254ab9a2db 100644 --- a/openhcs/pyqt_gui/services/ui_bridge_object_state.py +++ b/openhcs/pyqt_gui/services/ui_bridge_object_state.py @@ -25,12 +25,14 @@ resolved_parameter_description, ) from python_introspect import ( + JsonValue, UnifiedParameterAnalyzer, enum_input_values, project_dataclass, + to_jsonable, ) -from openhcs.agent.dto.common import AgentError, JsonValue, SCHEMA_VERSION +from openhcs.agent.dto.common import AgentError, SCHEMA_VERSION from openhcs.agent.dto.ui_bridge import ( UiCodeDocument, UiCodeDocumentApplyRequest, @@ -56,7 +58,6 @@ UiObjectStateValuePreview, UiSemanticAddress, ) -from openhcs.serialization.json import to_jsonable from openhcs.agent.services.object_state_field_projection import ( ObjectStateFieldFilterDeclaration, ) diff --git a/openhcs/pyqt_gui/services/ui_bridge_pipeline_editor.py b/openhcs/pyqt_gui/services/ui_bridge_pipeline_editor.py index 0b36957d9b..d8aba4af4f 100644 --- a/openhcs/pyqt_gui/services/ui_bridge_pipeline_editor.py +++ b/openhcs/pyqt_gui/services/ui_bridge_pipeline_editor.py @@ -40,7 +40,7 @@ PipelineEditorWidgetIdentity, PlateManagerStateSurfaceIdentityDeclaration, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from objectstate.object_state import ObjectStateRegistry from openhcs.core.function_reference import FunctionReferenceTransportAuthority from openhcs.core.progress.debug_projection import DebugRuntimeFrame diff --git a/openhcs/pyqt_gui/services/ui_bridge_plate_manager.py b/openhcs/pyqt_gui/services/ui_bridge_plate_manager.py index bd0f0e3dfe..c61cebed37 100644 --- a/openhcs/pyqt_gui/services/ui_bridge_plate_manager.py +++ b/openhcs/pyqt_gui/services/ui_bridge_plate_manager.py @@ -41,7 +41,7 @@ PlateManagerStateSurfaceIdentityDeclaration, PlateManagerWidgetIdentity, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from objectstate.object_state import ObjectStateRegistry from openhcs.core.selection import SelectedAllSelectionMode from openhcs.pyqt_gui.widgets.shared.services.plate_manager_workflows import ( diff --git a/openhcs/pyqt_gui/services/ui_bridge_server.py b/openhcs/pyqt_gui/services/ui_bridge_server.py index a84711d751..a20b3f3fbb 100644 --- a/openhcs/pyqt_gui/services/ui_bridge_server.py +++ b/openhcs/pyqt_gui/services/ui_bridge_server.py @@ -13,7 +13,12 @@ from typing import ClassVar from metaclass_registry import AutoRegisterMeta -from python_introspect import project_dataclass +from python_introspect import ( + JsonObject, + dataclass_from_mapping, + project_dataclass, + to_jsonable, +) from zmqruntime.messages import ( ControlErrorResponse, ControlMessageType, @@ -28,7 +33,7 @@ resolve_transport_mode, ) -from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, JsonObject +from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.ui_bridge import ( UiActionCatalog, @@ -66,9 +71,6 @@ UiBridgeOperationContract, UiBridgeOperationContractABC, ) -from openhcs.agent.services.ui_bridge_transport import ( - AgentDtoJsonCodec, -) from openhcs.pyqt_gui.config import AgentUiBridgeConfig from openhcs.pyqt_gui.services.ui_agent_bridge import ( InProcessUiBridgeGateway, @@ -76,7 +78,6 @@ ) from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG, OpenHCSZMQConfig -from openhcs.serialization.json import to_jsonable DEFAULT_UI_BRIDGE_START_TIMEOUT_SECONDS = 5.0 UI_BRIDGE_BROWSER_SERVER_NAME = "OpenHCSUiBridgeServer" @@ -353,7 +354,7 @@ def bridge_connection(self) -> UiBridgeConnectionSpec: def dispatch(self, payload: JsonObject) -> JsonObject: try: - request = AgentDtoJsonCodec.dataclass_from_json( + request = dataclass_from_mapping( UiBridgeRequestEnvelope, payload, ) @@ -396,17 +397,14 @@ def _validate_auth( @staticmethod def request_payload(target_type, request: UiBridgeRequestEnvelope): - return AgentDtoJsonCodec.dataclass_from_json(target_type, request.payload) + return dataclass_from_mapping(target_type, request.payload) def contract_payload( self, contract: UiBridgeOperationContract, request: UiBridgeRequestEnvelope, ): - return contract.decode_request_payload( - request.payload, - AgentDtoJsonCodec.dataclass_from_json, - ) + return contract.decode_request_payload(request.payload) @staticmethod def _result_payload(result) -> JsonObject: diff --git a/openhcs/runtime/napari_viewer_server.py b/openhcs/runtime/napari_viewer_server.py index e3c4d9c0b0..c97a05ea34 100644 --- a/openhcs/runtime/napari_viewer_server.py +++ b/openhcs/runtime/napari_viewer_server.py @@ -159,7 +159,7 @@ from openhcs.runtime.viewer_measurements import ( NativeImageMeasurement, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.runtime.viewer_protocol import ( NapariLayerKind, NapariViewerServerRequest, diff --git a/openhcs/runtime/viewer_protocol.py b/openhcs/runtime/viewer_protocol.py index 1769723064..cf248a918d 100644 --- a/openhcs/runtime/viewer_protocol.py +++ b/openhcs/runtime/viewer_protocol.py @@ -19,7 +19,13 @@ from annotated_types import Gt, Le from metaclass_registry import AutoRegisterMeta -from python_introspect import dataclass_from_mapping +from python_introspect import ( + JsonObject, + JsonScalar, + JsonValue, + dataclass_from_mapping, + to_jsonable, +) from python_introspect.validation import validate_annotated_dataclass from pydantic import StrictInt from polystore.backend_registry import register_cleanup_callback @@ -96,7 +102,6 @@ ViewerStateControlOptions, ) from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION -from openhcs.serialization.json import JsonObject, JsonScalar, JsonValue, to_jsonable if TYPE_CHECKING: from openhcs.runtime.napari_streaming_handlers import NapariNativeWindowPresentation diff --git a/openhcs/runtime/viewer_snapshot.py b/openhcs/runtime/viewer_snapshot.py index 78a084cb12..f14a8b82f2 100644 --- a/openhcs/runtime/viewer_snapshot.py +++ b/openhcs/runtime/viewer_snapshot.py @@ -14,7 +14,7 @@ from openhcs.agent.dto.common import AgentResourceRef from openhcs.agent.dto.viewer import ViewerWindowDescriptor -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @dataclass(frozen=True, kw_only=True) diff --git a/openhcs/runtime/zmq_server_hooks.py b/openhcs/runtime/zmq_server_hooks.py index 6d116318d6..fffc87aff0 100644 --- a/openhcs/runtime/zmq_server_hooks.py +++ b/openhcs/runtime/zmq_server_hooks.py @@ -19,7 +19,7 @@ CompiledPlateExecutionExtras, ) from openhcs.runtime.zmq_execution_signature import ZMQAuxiliaryParamField -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable logger = logging.getLogger(__name__) diff --git a/openhcs/serialization/json.py b/openhcs/serialization/json.py deleted file mode 100644 index 845a2c2832..0000000000 --- a/openhcs/serialization/json.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Generic JSON-native projection for OpenHCS transport values.""" - -from __future__ import annotations - -import inspect -from collections.abc import Callable, Mapping -from dataclasses import fields, is_dataclass -from enum import Enum -from functools import singledispatch -from pathlib import Path -from typing import ForwardRef, TypeAlias - -from metaclass_registry import AutoRegisterMeta -from python_introspect import signature_analysis_target - -JsonScalar: TypeAlias = str | int | float | bool | None -# Recursive aliases retain this declaration's namespace when imported by DTOs. -# Bare strings are evaluated in each consuming dataclass module by get_type_hints. -_JSON_VALUE_REFERENCE = ForwardRef("JsonValue", module=__name__) -JsonValue: TypeAlias = ( - JsonScalar - | Mapping[str, _JSON_VALUE_REFERENCE] - | tuple[_JSON_VALUE_REFERENCE, ...] - | list[_JSON_VALUE_REFERENCE] -) -JsonObject: TypeAlias = Mapping[str, JsonValue] - - -def _jsonable_dataclass(value) -> JsonValue: - """Project fields without ``asdict`` deep-copying immutable containers.""" - - return { - field.name: to_jsonable(getattr(value, field.name)) for field in fields(value) - } - - -@singledispatch -def to_jsonable(value) -> JsonValue: - """Project dataclasses and registered OpenHCS values into JSON-native data.""" - - if is_dataclass(value) and not isinstance(value, type): - return _jsonable_dataclass(value) - raise TypeError( - "Value is not JSON-serializable through OpenHCS transport: " - f"{type(value).__name__}" - ) - - -@to_jsonable.register(Mapping) -def _jsonable_mapping(value: Mapping) -> JsonValue: - return {str(to_jsonable(key)): to_jsonable(item) for key, item in value.items()} - - -@to_jsonable.register(tuple) -@to_jsonable.register(list) -@to_jsonable.register(set) -@to_jsonable.register(frozenset) -def _jsonable_sequence(value) -> JsonValue: - return [to_jsonable(item) for item in value] - - -@to_jsonable.register(Callable) -def _jsonable_callable(value: Callable[..., object]) -> JsonValue: - if is_dataclass(value) and not isinstance(value, type): - return _jsonable_dataclass(value) - target = signature_analysis_target(value) - module = inspect.getmodule(target) - module_name = type(target).__module__ if module is None else module.__name__ - if ( - inspect.isfunction(target) - or inspect.ismethod(target) - or inspect.isclass(target) - ): - qualname = target.__qualname__ - else: - qualname = type(target).__qualname__ - return { - "kind": "callable", - "name": qualname.rsplit(".", 1)[-1], - "module": module_name, - "qualname": qualname, - "import_path": f"{module_name}.{qualname}", - } - - -@to_jsonable.register(AutoRegisterMeta) -def _jsonable_registered_type(value: AutoRegisterMeta) -> JsonValue: - key_attribute = value.__registry_key__ - declaring_owner = next( - (owner for owner in value.__mro__ if key_attribute in vars(owner)), - None, - ) - if declaring_owner is None: - raise TypeError( - f"Registered type {value.__qualname__} has no declared " - f"{key_attribute!r} key." - ) - key = vars(declaring_owner)[key_attribute] - if key is None: - raise TypeError(f"Registered type {value.__qualname__} has no registry key.") - return to_jsonable(key) - - -@to_jsonable.register(Enum) -def _jsonable_enum(value: Enum) -> JsonValue: - return to_jsonable(value.value) - - -@to_jsonable.register(Path) -def _jsonable_path(value: Path) -> JsonValue: - return str(value) - - -@to_jsonable.register(type(None)) -@to_jsonable.register(str) -@to_jsonable.register(int) -@to_jsonable.register(float) -@to_jsonable.register(bool) -def _jsonable_scalar(value) -> JsonValue: - return value diff --git a/paper/figures/validate_slas_roundtrip.py b/paper/figures/validate_slas_roundtrip.py index 9d1077175d..b5de758631 100644 --- a/paper/figures/validate_slas_roundtrip.py +++ b/paper/figures/validate_slas_roundtrip.py @@ -14,7 +14,7 @@ from openhcs.mcp.dev_client import McpDevClient from openhcs.agent.dto.ui_bridge import UiWindowCatalog -from openhcs.agent.services.ui_bridge_transport import AgentDtoJsonCodec +from python_introspect import dataclass_from_mapping from pyqt_reactive.services.function_list_editor_actions import FunctionListEditorAction @@ -182,7 +182,7 @@ def capture(label, window_id): action_kind="button", ) for _ in range(30): - windows = AgentDtoJsonCodec.dataclass_from_json( + windows = dataclass_from_mapping( UiWindowCatalog, call("openhcs_ui_list_windows") ) code_windows = [ diff --git a/pyproject.toml b/pyproject.toml index a3ca03163e..1fcddf5fdd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -102,7 +102,7 @@ dependencies = [ "zmqruntime>=0.4.1,<0.5", "pycodify>=0.1.3,<0.2", "objectstate>=1.3.1,<2", - "python-introspect>=0.2.1,<0.3", + "python-introspect>=0.2.2,<0.3", "metaclass-registry>=0.3.0,<0.4", "arraybridge>=0.3.8,<0.4", "polystore>=0.3.3,<0.4", diff --git a/scripts/capture_media_gallery.py b/scripts/capture_media_gallery.py index 3ec6921dd7..0d39f9534a 100755 --- a/scripts/capture_media_gallery.py +++ b/scripts/capture_media_gallery.py @@ -35,7 +35,7 @@ from pyqt_reactive.services.tab_identity import TabLabelDeclarationMixin from pyqt_reactive.services.widget_tree_projection import WidgetActionKind from pyqt_reactive.services.window_snapshot import WindowSnapshotCaptureScope -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.ui_bridge import ( @@ -64,7 +64,6 @@ from openhcs.agent.services.ui_bridge_service import UiBridgeService from openhcs.agent.services.viewer_window_service import ViewerWindowService from openhcs.mcp.control_timeout import McpUiBridgeTimeoutPolicy, McpViewerTimeoutPolicy -from openhcs.serialization.json import to_jsonable from scripts.gallery_catalog import ( SOURCE_CAPTURE_EVIDENCE_RECORD_NAME, FunctionSelectorCaptureTarget, diff --git a/scripts/gallery_catalog.py b/scripts/gallery_catalog.py index 498ecbaadf..910f9f38d3 100644 --- a/scripts/gallery_catalog.py +++ b/scripts/gallery_catalog.py @@ -23,7 +23,7 @@ ) from pyqt_reactive.services.function_navigation import FUNCTION_FIELD_ROOT from pyqt_reactive.services.system_monitor_actions import SystemMonitorAction -from python_introspect import dataclass_from_mapping +from python_introspect import JsonValue, dataclass_from_mapping, to_jsonable from openhcs.agent.dto.execution_connection import ExecutionConnectionSpec from openhcs.agent.ui_bridge_actions import PlateManagerAction @@ -38,7 +38,6 @@ ) from openhcs.core.streaming_config_declarations import ViewerType from openhcs.pyqt_gui.ui_tab_identities import DualEditorTab, PlateViewerTab -from openhcs.serialization.json import JsonValue, to_jsonable if TYPE_CHECKING: from openhcs.pyqt_gui.services.step_scope_identity import StepEditorScope diff --git a/scripts/mcp_thesis_demo_live.py b/scripts/mcp_thesis_demo_live.py index 1d1ff75910..911544980a 100755 --- a/scripts/mcp_thesis_demo_live.py +++ b/scripts/mcp_thesis_demo_live.py @@ -65,7 +65,7 @@ UiCodeDocumentSummary, UiWindowSummary, ) -from openhcs.agent.services.ui_bridge_transport import AgentDtoJsonCodec +from python_introspect import dataclass_from_mapping from openhcs.agent.ui_bridge_identities import ( ManagedWindowWidgetIdentity, PipelineEditorStateSurfaceIdentityDeclaration, @@ -968,7 +968,7 @@ def managed_window_action_target( if not isinstance(actions, list): raise RehearsalFailure("Managed-window action catalog is unavailable.") summaries = ( - AgentDtoJsonCodec.dataclass_from_json(UiActionSummary, row) for row in actions + dataclass_from_mapping(UiActionSummary, row) for row in actions ) matches = [ row @@ -1100,7 +1100,7 @@ def exact_config_document_source( if not isinstance(documents, list): raise RehearsalFailure("Code-document catalog is unavailable.") summaries = ( - AgentDtoJsonCodec.dataclass_from_json(UiCodeDocumentSummary, row) + dataclass_from_mapping(UiCodeDocumentSummary, row) for row in documents ) matches = [ @@ -1843,7 +1843,7 @@ def inspect_and_apply_code_document( timeout=30, ) documents = ( - AgentDtoJsonCodec.dataclass_from_json(UiCodeDocumentSummary, row) + dataclass_from_mapping(UiCodeDocumentSummary, row) for row in first_payload(docs)["documents"] ) if not any( @@ -2747,7 +2747,7 @@ def visible_window_ids(ctx: RunContext, *, label: str) -> frozenset[str]: def window_ids_from_catalog(windows: list[Any]) -> frozenset[str]: return frozenset( - AgentDtoJsonCodec.dataclass_from_json(UiWindowSummary, window).window_id + dataclass_from_mapping(UiWindowSummary, window).window_id for window in windows ) @@ -2769,7 +2769,7 @@ def plate_action_summary( if not isinstance(actions, list): raise RehearsalFailure("PlateManager action catalog is unavailable.") summaries = ( - AgentDtoJsonCodec.dataclass_from_json(UiActionSummary, row) for row in actions + dataclass_from_mapping(UiActionSummary, row) for row in actions ) matches = [ row diff --git a/scripts/smoke_installed_gui.py b/scripts/smoke_installed_gui.py index 63bcf564bc..9908044ef9 100644 --- a/scripts/smoke_installed_gui.py +++ b/scripts/smoke_installed_gui.py @@ -455,10 +455,10 @@ def _typed_tool_payload( ) -> AgentDtoT: """Hydrate one MCP result through the declared agent DTO contract.""" - from openhcs.agent.services.ui_bridge_transport import AgentDtoJsonCodec + from python_introspect import dataclass_from_mapping payload = _tool_payload(execution, tool_name=tool_name) - return AgentDtoJsonCodec.dataclass_from_json(payload_type, dict(payload)) + return dataclass_from_mapping(payload_type, dict(payload)) def _declared_catalog_items( diff --git a/tests/diagnostics/check_custom_registration_live.py b/tests/diagnostics/check_custom_registration_live.py index a09cb6e587..22f5931eed 100644 --- a/tests/diagnostics/check_custom_registration_live.py +++ b/tests/diagnostics/check_custom_registration_live.py @@ -235,7 +235,7 @@ def run(args) -> None: from openhcs.processing.custom_functions.manager import CustomFunctionManager from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG from openhcs.runtime.zmq_execution_client import ZMQExecutionClient - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable imports = {"openhcs": openhcs.__file__, "polystore": polystore.__file__} assert Path(openhcs.__file__).resolve() == SOURCE / "openhcs/__init__.py" diff --git a/tests/diagnostics/check_owned_bootstrap_live.py b/tests/diagnostics/check_owned_bootstrap_live.py index 0ad003a693..55b214d313 100644 --- a/tests/diagnostics/check_owned_bootstrap_live.py +++ b/tests/diagnostics/check_owned_bootstrap_live.py @@ -139,7 +139,7 @@ def save(): from openhcs.pyqt_gui.config import UIConfig, save_ui_config_sync from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG from openhcs.runtime.zmq_execution_client import ZMQExecutionClient - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable modules = (openhcs, polystore, zmqruntime, metaclass_registry, importlib.import_module('openhcs.core._tabular_native'), diff --git a/tests/diagnostics/check_viewer_feature_measurement_live.py b/tests/diagnostics/check_viewer_feature_measurement_live.py index 9fa35d7fe3..72476cf80f 100644 --- a/tests/diagnostics/check_viewer_feature_measurement_live.py +++ b/tests/diagnostics/check_viewer_feature_measurement_live.py @@ -200,7 +200,7 @@ def save() -> None: from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG from openhcs.core.streaming_config_declarations import ViewerType from zmqruntime.config import TransportMode - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable from openhcs.agent.runtime_platform import AgentRuntimePlatformAuthority from polystore.imagej_distribution import ( FijiArchiveDistribution, diff --git a/tests/diagnostics/owned_bootstrap_readback.py b/tests/diagnostics/owned_bootstrap_readback.py index a90c30258c..1c71506b64 100644 --- a/tests/diagnostics/owned_bootstrap_readback.py +++ b/tests/diagnostics/owned_bootstrap_readback.py @@ -22,7 +22,7 @@ VirtualWorkspaceSourceProjectionEntries, ) from openhcs.runtime.zmq_execution_observation import ZMQRuntimeExecutionObservationExport -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from polystore.roi import load_rois_from_zip diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index 991dfd9a0f..b8eb1f7c1f 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -161,7 +161,7 @@ def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_bi CellProfilerThresholdMethod, ) from openhcs.processing.materialization.core import MaterializationInput - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable def binding(module, plan_type, artifact_type): (declared,) = module.declared_artifact_bindings( diff --git a/tests/unit/agent/test_agent_serialization.py b/tests/unit/agent/test_agent_serialization.py index 4ace90a25b..c2f9de9ca3 100644 --- a/tests/unit/agent/test_agent_serialization.py +++ b/tests/unit/agent/test_agent_serialization.py @@ -3,7 +3,7 @@ from types import MappingProxyType from typing import Mapping -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable class ThresholdMode(Enum): diff --git a/tests/unit/agent/test_agent_services.py b/tests/unit/agent/test_agent_services.py index 1ab1e51508..f5918b9137 100644 --- a/tests/unit/agent/test_agent_services.py +++ b/tests/unit/agent/test_agent_services.py @@ -140,7 +140,7 @@ ZMQExecutionIdentity, ZMQRuntimeObservationExportScope, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def sample_processing_function(image, sigma: float = 1.0): diff --git a/tests/unit/agent/test_architecture_projection_service.py b/tests/unit/agent/test_architecture_projection_service.py index 7d87ddc9ce..52cddd9358 100644 --- a/tests/unit/agent/test_architecture_projection_service.py +++ b/tests/unit/agent/test_architecture_projection_service.py @@ -1,4 +1,4 @@ -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.agent.services.architecture_projection_service import ( ArchitectureProjectionService, ) diff --git a/tests/unit/agent/test_authoring_roundtrip_boundaries.py b/tests/unit/agent/test_authoring_roundtrip_boundaries.py index 006daf206b..86a01ca462 100644 --- a/tests/unit/agent/test_authoring_roundtrip_boundaries.py +++ b/tests/unit/agent/test_authoring_roundtrip_boundaries.py @@ -9,7 +9,7 @@ import pytest from pycodify import FormatContext, to_source -from python_introspect import dataclass_from_mapping +from python_introspect import JsonObject, dataclass_from_mapping, to_jsonable from skimage.exposure import adjust_gamma import openhcs.serialization.pycodify_formatters # noqa: F401 @@ -36,7 +36,6 @@ FunctionMetadata, ProcessingContract, ) -from openhcs.serialization.json import JsonObject, to_jsonable @dataclass(frozen=True) diff --git a/tests/unit/agent/test_config_schema_authority.py b/tests/unit/agent/test_config_schema_authority.py index d249a61144..0899d814bb 100644 --- a/tests/unit/agent/test_config_schema_authority.py +++ b/tests/unit/agent/test_config_schema_authority.py @@ -19,7 +19,7 @@ ) from openhcs.core.source_bindings import NamedSourceBinding from openhcs.core.steps.abstract import AbstractStep -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def _field_by_path(schema, path: str): diff --git a/tests/unit/agent/test_custom_registration_admission.py b/tests/unit/agent/test_custom_registration_admission.py index fa8f85fb93..08fcad8bd4 100644 --- a/tests/unit/agent/test_custom_registration_admission.py +++ b/tests/unit/agent/test_custom_registration_admission.py @@ -742,7 +742,7 @@ async def invoke(): "openhcs_start_function_catalog_preparation", {"port": 15993, "transport_mode": "tcp"}, ) - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable args = to_jsonable(handle) status = await built.call_tool( diff --git a/tests/unit/agent/test_function_declaration_help.py b/tests/unit/agent/test_function_declaration_help.py index ab4e096fd3..6a4576d7d2 100644 --- a/tests/unit/agent/test_function_declaration_help.py +++ b/tests/unit/agent/test_function_declaration_help.py @@ -22,7 +22,7 @@ count_neuronal_cell_bodies_metaxpress, neurite_outgrowth_metaxpress, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @dataclass(frozen=True) diff --git a/tests/unit/agent/test_knowledge_base_service.py b/tests/unit/agent/test_knowledge_base_service.py index a25994f60c..6820b26a2e 100644 --- a/tests/unit/agent/test_knowledge_base_service.py +++ b/tests/unit/agent/test_knowledge_base_service.py @@ -18,7 +18,7 @@ KnowledgeBaseService, ) from openhcs.mcp.context import OpenHCSAgentContext -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def test_knowledge_base_catalog_lists_source_backed_documents(): diff --git a/tests/unit/agent/test_mcp_affine_inspection_progress.py b/tests/unit/agent/test_mcp_affine_inspection_progress.py index ae7d61582b..98c9b2a828 100644 --- a/tests/unit/agent/test_mcp_affine_inspection_progress.py +++ b/tests/unit/agent/test_mcp_affine_inspection_progress.py @@ -26,7 +26,7 @@ UiThreadDispatchError, UiThreadDispatcherClosedError, UiThreadDispatchTimeoutError, ) from openhcs.mcp.server import build_server -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @pytest.mark.parametrize("declaration", ( diff --git a/tests/unit/agent/test_mcp_dev_client_declared_decoder.py b/tests/unit/agent/test_mcp_dev_client_declared_decoder.py index 329374b7bd..52dcada244 100644 --- a/tests/unit/agent/test_mcp_dev_client_declared_decoder.py +++ b/tests/unit/agent/test_mcp_dev_client_declared_decoder.py @@ -16,7 +16,7 @@ workflow_result_payload, ) from openhcs.mcp.dev_client_rendering import McpDevOutputRenderer -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def test_valid_tool_boundary_failure_is_not_a_malformed_runtime_state(): diff --git a/tests/unit/agent/test_mcp_dev_client_generated_inputs.py b/tests/unit/agent/test_mcp_dev_client_generated_inputs.py index 4b771fe259..e97691d575 100644 --- a/tests/unit/agent/test_mcp_dev_client_generated_inputs.py +++ b/tests/unit/agent/test_mcp_dev_client_generated_inputs.py @@ -4,7 +4,7 @@ import json import pytest -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from zmqruntime.config import TransportMode from zmqruntime.messages import ProcessIdentity @@ -17,7 +17,6 @@ from openhcs.agent.dto.functions import FunctionCatalogPreparationHandle from openhcs.mcp.dev_client import _build_parser, _calls_from_args from openhcs.mcp.dev_client_core import McpDevCliUsageError -from openhcs.serialization.json import to_jsonable @pytest.fixture(scope="module") diff --git a/tests/unit/agent/test_mcp_dev_client_pipeline_results.py b/tests/unit/agent/test_mcp_dev_client_pipeline_results.py index d102080a0d..d357514973 100644 --- a/tests/unit/agent/test_mcp_dev_client_pipeline_results.py +++ b/tests/unit/agent/test_mcp_dev_client_pipeline_results.py @@ -55,7 +55,7 @@ McpDevTypedOutputRenderer, ) from openhcs.mcp.dev_client_renderers.pipeline import PipelineArtifactPlanRenderer -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable class ControlledWireSession: @@ -693,7 +693,7 @@ async def controlled_entry(args): def test_generic_call_cli_uses_nominal_typed_contract_without_json_roundtrip( monkeypatch, capsys ): - import openhcs.serialization.json as serialization + import python_introspect.jsonable as serialization response = batch( agent_capabilities.inspect_pipeline_source_artifact_plan, plan_fixture() diff --git a/tests/unit/agent/test_mcp_dev_client_runtime_debug_renderer.py b/tests/unit/agent/test_mcp_dev_client_runtime_debug_renderer.py index 7d88fb30c1..6e6653117a 100644 --- a/tests/unit/agent/test_mcp_dev_client_runtime_debug_renderer.py +++ b/tests/unit/agent/test_mcp_dev_client_runtime_debug_renderer.py @@ -17,7 +17,7 @@ CatalogRenderOptions, McpDevOutputRenderer, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable DEBUG_SESSION_ID = "debug-session-renderer" diff --git a/tests/unit/agent/test_mcp_dev_client_sampling_results.py b/tests/unit/agent/test_mcp_dev_client_sampling_results.py index 45d324ba16..9c24d73719 100644 --- a/tests/unit/agent/test_mcp_dev_client_sampling_results.py +++ b/tests/unit/agent/test_mcp_dev_client_sampling_results.py @@ -25,7 +25,7 @@ from openhcs.mcp.dev_client_renderers.plate import PlateImageSampleRenderer, SelectedPlateSampleRenderer from openhcs.mcp.dev_client_renderers.viewer import ViewerImageSampleRenderer from openhcs.runtime.viewer_protocol import ViewerArrayValueSummary -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @pytest.fixture(autouse=True) @@ -109,7 +109,7 @@ def test_generated_commands_retain_decoded_sampling_facts(monkeypatch, selected_ def forbidden(value): raise AssertionError("Typed sampling must not flatten an owned result to JSON") monkeypatch.setattr(dev_client, "to_jsonable", forbidden) - monkeypatch.setattr("openhcs.serialization.json.to_jsonable", forbidden) + monkeypatch.setattr("python_introspect.jsonable.to_jsonable", forbidden) argv = ("call", capability.name, "--arguments", "{}") if generic_call else ( ("selected-plate-sample",) if selected_case else ("sample-plate-image", "source-plate", "image.tif") ) diff --git a/tests/unit/agent/test_mcp_dev_client_ui_action_results.py b/tests/unit/agent/test_mcp_dev_client_ui_action_results.py index 1c6066c40a..8d262f4a12 100644 --- a/tests/unit/agent/test_mcp_dev_client_ui_action_results.py +++ b/tests/unit/agent/test_mcp_dev_client_ui_action_results.py @@ -36,7 +36,7 @@ McpDevOutputRenderer, McpDevOutputRenderOptions, ) from openhcs.mcp.dev_client_renderers.ui_bridge import UiActionInvokeRenderer -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def action_fixture(): @@ -113,7 +113,7 @@ async def controlled_session(args): ControlledWireSession(), args, ) - import openhcs.serialization.json as serialization + import python_introspect.jsonable as serialization monkeypatch.setattr(dev_client, "_run_async", controlled_session) if not json_output: def forbidden_serialization(value): @@ -191,7 +191,7 @@ async def controlled_wire(args): def forbidden_serialization(value): raise AssertionError("Compact presentation must retain the decoded result") - import openhcs.serialization.json as serialization + import python_introspect.jsonable as serialization monkeypatch.setattr(dev_client, "_run_async", controlled_wire) monkeypatch.setattr(serialization, "to_jsonable", forbidden_serialization) assert dev_client.main([ diff --git a/tests/unit/agent/test_mcp_distribution_runtime.py b/tests/unit/agent/test_mcp_distribution_runtime.py index b89d4bb5e1..bf6a3f38c9 100644 --- a/tests/unit/agent/test_mcp_distribution_runtime.py +++ b/tests/unit/agent/test_mcp_distribution_runtime.py @@ -19,7 +19,7 @@ UiBridgeDescriptorReader, ) from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def _write_descriptor(path: Path) -> None: diff --git a/tests/unit/agent/test_mcp_server.py b/tests/unit/agent/test_mcp_server.py index c75758d75a..758df3b7a9 100644 --- a/tests/unit/agent/test_mcp_server.py +++ b/tests/unit/agent/test_mcp_server.py @@ -14,6 +14,7 @@ import pytest from pyqt_reactive.services.window_snapshot import WindowSnapshotCaptureScope +from python_introspect import to_jsonable from zmqruntime.client import EndpointShutdownResult from zmqruntime.config import TransportMode @@ -278,7 +279,8 @@ def test_agent_dto_package_exports_mcp_debugging_contracts(): ) for exported_name in exported_names: - assert exported_name in vars(dto) + assert exported_name in dto.__all__ + assert getattr(dto, exported_name).__name__ == exported_name def test_mcp_server_builds_when_optional_dependency_is_installed(): @@ -657,7 +659,7 @@ def test_mcp_dev_client_prefers_structured_content_and_preserves_tool_metadata() import openhcs.mcp.dev_client as dev_client from openhcs.mcp.dev_client_core import mcp_tool_metadata_from_wire - result = server.to_jsonable( + result = to_jsonable( server.McpToolErrorResult( schema_version=SCHEMA_VERSION, ok=False, @@ -1074,9 +1076,9 @@ def test_mcp_widget_tree_projection_preserves_required_empty_action_fields(): } assert action["label"] == "Compile" assert action["geometry"] == {"x": 8, "y": 160, "width": 72, "height": 24} - from openhcs.agent.services.ui_bridge_transport import AgentDtoJsonCodec + from python_introspect import dataclass_from_mapping - decoded = AgentDtoJsonCodec.dataclass_from_json(UiWidgetTreeResult, payload) + decoded = dataclass_from_mapping(UiWidgetTreeResult, payload) assert decoded == result @@ -1249,18 +1251,18 @@ def test_mcp_widget_tree_projection_preserves_semantic_action_values(): def test_mcp_ui_catalog_invocations_preserve_declared_identity( capability, method, catalog ): - from openhcs.agent.services.ui_bridge_transport import AgentDtoJsonCodec + from python_introspect import dataclass_from_mapping context = SimpleNamespace( ui_bridge_service=SimpleNamespace(**{method: lambda connection: catalog}) ) - payload = server.to_jsonable( + payload = to_jsonable( capability.invocation.execute(context, DEFAULT_UI_BRIDGE_CONNECTION_SPEC) ) - assert payload == server.to_jsonable(catalog) + assert payload == to_jsonable(catalog) assert ( - AgentDtoJsonCodec.dataclass_from_json(capability.output_contract, payload) + dataclass_from_mapping(capability.output_contract, payload) == catalog ) @@ -4803,7 +4805,6 @@ def test_mcp_dev_client_authoring_context_renders_bounded_content(): def _dev_client_server_fixture(): from openhcs.mcp.dev_client_core import McpDevServerIdentity, McpDevServerSpec - from openhcs.serialization.json import to_jsonable return to_jsonable(McpDevServerIdentity.from_spec(McpDevServerSpec(sys.executable))) @@ -5396,7 +5397,7 @@ async def fake_call_tool(session, call, timeout_seconds): assert timeouts[1] >= 22 rendered = dev_client.McpDevCommandSpec.for_name("execute-source").render_response( - dev_client.to_jsonable(response), + to_jsonable(response), args, ) @@ -11203,7 +11204,7 @@ def test_mcp_dev_client_workflow_poll_terminal_state_policy(): def _state_surface_dev_wire(dev_client): """Declare the complete wire envelope; each poll test supplies its body.""" - return dev_client.to_jsonable(UiStateSurfaceDocument( + return to_jsonable(UiStateSurfaceDocument( schema_version=SCHEMA_VERSION, summary=UiStateSurfaceSummary( SCHEMA_VERSION, UiStateSurfaceIdentity(surface_id="plate_manager.state"), @@ -11468,7 +11469,7 @@ async def fake_call_tool(session, call, timeout_seconds): summary = response.results[-1] assert summary.tool == "mcp_dev_selected_workflow_poll" assert summary.mcp_error is False - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "completed", "poll_requested": True, "poll_completed": True, @@ -11555,7 +11556,7 @@ async def fake_call_tool(session, call, timeout_seconds): if receipt_status is not None: expected_call_names.append("openhcs_ui_wait_for_operation_receipt") assert [call.name for call in calls] == expected_call_names - assert dev_client.to_jsonable(response.results[-1].payloads[0]) == { + assert to_jsonable(response.results[-1].payloads[0]) == { "poll_status": expected_poll_status, "poll_requested": True, "poll_completed": False, @@ -11881,7 +11882,7 @@ async def fake_call_tool(session, call, timeout_seconds): ) summary = response.results[-1] assert summary.mcp_error is False - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "completed", "poll_requested": True, "poll_completed": True, @@ -11987,7 +11988,7 @@ async def fake_call_tool(session, call, timeout_seconds): ) summary = response.results[-1] assert summary.mcp_error is False - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "completed", "poll_requested": True, "poll_completed": True, @@ -12080,7 +12081,7 @@ async def fake_call_tool(session, call, timeout_seconds): assert response.results[-2].has_errors() summary = response.results[-1] assert summary.mcp_error is True - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "timeout", "poll_requested": True, "poll_completed": False, @@ -12169,7 +12170,7 @@ async def fake_call_tool(session, call, timeout_seconds): summary = response.results[-1] assert summary.tool == "mcp_dev_selected_workflow_poll" assert summary.mcp_error is True - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "failed", "poll_requested": True, "poll_completed": False, @@ -12262,7 +12263,7 @@ async def fake_call_tool(session, call, timeout_seconds): summary = response.results[-1] assert summary.tool == "mcp_dev_selected_workflow_poll" assert summary.mcp_error is True - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "failed", "poll_requested": True, "poll_completed": False, @@ -12317,7 +12318,7 @@ def test_mcp_dev_client_selected_workflow_poll_renders_compact_summary(): schema_version="test", summary=surface_summary, payload_schema="openhcs.ui.plate_manager_state.v1", - payload=dev_client.to_jsonable(native_state), + payload=to_jsonable(native_state), ) response = dev_client.McpDevToolBatchResponse.from_results( dev_client.McpDevServerSpec(sys.executable), @@ -12325,7 +12326,7 @@ def test_mcp_dev_client_selected_workflow_poll_renders_compact_summary(): _accepted_workflow_dev_result(dev_client, workflow="run_plate"), dev_client.McpDevToolResult( tool="openhcs_ui_get_state_surface", mcp_error=False, - payloads=(dev_client.to_jsonable(state),), + payloads=(to_jsonable(state),), ), dev_client.workflow_poll_summary_result( workflow="run_plate", status=dev_client.WorkflowPollSummaryStatus.COMPLETED, @@ -12379,7 +12380,7 @@ def test_mcp_dev_client_selected_workflow_poll_summarizes_rejection( baseline_document = UiStateSurfaceDocument( schema_version="test", summary=surface_summary, payload_schema="openhcs.ui.plate_manager_state.v1", - payload=dev_client.to_jsonable(baseline), current_revision_token="rev-1", + payload=to_jsonable(baseline), current_revision_token="rev-1", ) calls: list[dev_client.McpDevToolCall] = [] @@ -12390,7 +12391,7 @@ async def fake_call_tool(session, call, timeout_seconds): return dev_client.McpDevToolResult( tool=call.name, mcp_error=False, - payloads=(dev_client.to_jsonable(baseline_document),), + payloads=(to_jsonable(baseline_document),), ) return _rejected_workflow_dev_result( dev_client, @@ -12424,7 +12425,7 @@ async def fake_call_tool(session, call, timeout_seconds): summary = response.results[-1] assert summary.tool == "mcp_dev_selected_workflow_poll" assert summary.mcp_error is True - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "skipped", "poll_requested": True, "poll_completed": False, @@ -12460,7 +12461,7 @@ def test_mcp_dev_client_workflow_poll_timeout_summary_is_error(): assert summary.tool == "mcp_dev_selected_workflow_poll" assert summary.mcp_error is True - assert dev_client.to_jsonable(summary.payloads[0]) == { + assert to_jsonable(summary.payloads[0]) == { "poll_status": "timeout", "poll_requested": True, "poll_completed": False, @@ -15033,7 +15034,7 @@ async def call_health_through_dev_client(): ) payload = asyncio.run(call_health_through_dev_client()) - payload = dev_client.to_jsonable(payload) + payload = to_jsonable(payload) result = payload["results"][0] health_payload = result["payloads"][0] @@ -15189,7 +15190,7 @@ async def call_missing_server_module(): ) payload = asyncio.run(call_missing_server_module()) - payload = dev_client.to_jsonable(payload) + payload = to_jsonable(payload) error = payload["errors"][0] assert payload["server"]["module"] == "openhcs.mcp_missing" @@ -15210,7 +15211,7 @@ def test_mcp_dev_client_transport_failure_projects_leaf_causes(): server_stderr_tail="captured server log", ) - error = dev_client.to_jsonable(failure) + error = to_jsonable(failure) assert error["exception_type"] == "ExceptionGroup" assert error["causes"] == [ diff --git a/tests/unit/agent/test_official30_knowledge_examples.py b/tests/unit/agent/test_official30_knowledge_examples.py index 9e8b9e0c06..30de2dcc86 100644 --- a/tests/unit/agent/test_official30_knowledge_examples.py +++ b/tests/unit/agent/test_official30_knowledge_examples.py @@ -33,7 +33,7 @@ from openhcs.core.steps.function_step import FunctionStep from openhcs.mcp.context import OpenHCSAgentContext from openhcs.mcp.dev_client_renderers.knowledge import KnowledgeDocumentRenderer -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable OFFICIAL30_DOCUMENT_ID = "openhcs_official30_benchmark_recipes" diff --git a/tests/unit/agent/test_owned_runtime_bootstrap.py b/tests/unit/agent/test_owned_runtime_bootstrap.py index aaca528aab..6faed35b1a 100644 --- a/tests/unit/agent/test_owned_runtime_bootstrap.py +++ b/tests/unit/agent/test_owned_runtime_bootstrap.py @@ -2,8 +2,7 @@ from unittest.mock import Mock import pytest -from python_introspect import dataclass_from_mapping -from openhcs.serialization.json import to_jsonable +from python_introspect import dataclass_from_mapping, to_jsonable from zmqruntime.config import TransportMode from zmqruntime.messages import ProcessIdentity, PongResponse, ServerRole from zmqruntime.startup import EndpointStartupPhase, EndpointStartupStatus diff --git a/tests/unit/agent/test_runtime_debug_inspection.py b/tests/unit/agent/test_runtime_debug_inspection.py index 1399ceefdb..448a6cb211 100644 --- a/tests/unit/agent/test_runtime_debug_inspection.py +++ b/tests/unit/agent/test_runtime_debug_inspection.py @@ -26,7 +26,7 @@ DebugViewTable, DebugViewTableProjection, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable DEBUG_SESSION_ID = "debug-session-1" diff --git a/tests/unit/agent/test_s1_native_viewer_records.py b/tests/unit/agent/test_s1_native_viewer_records.py index 5bb57a4bf8..d84497040e 100644 --- a/tests/unit/agent/test_s1_native_viewer_records.py +++ b/tests/unit/agent/test_s1_native_viewer_records.py @@ -38,7 +38,7 @@ ViewerArrayValueSummary, ViewerPayloadSummary, ViewerProjectionRecord, ViewerPayloadControlOptions, ViewerPayloadProjectionOptions, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def item(data, *, kind=StreamingDataType.IMAGE): diff --git a/tests/unit/agent/test_s1_typed_viewer_rendering.py b/tests/unit/agent/test_s1_typed_viewer_rendering.py index 6b90c6f5d9..4d067c1bde 100644 --- a/tests/unit/agent/test_s1_typed_viewer_rendering.py +++ b/tests/unit/agent/test_s1_typed_viewer_rendering.py @@ -39,7 +39,7 @@ from openhcs.mcp.dev_client_renderers.viewer import ViewerProbeRenderer, ViewerStateRenderer from openhcs.mcp.dev_client_rendering import McpDevOutputRenderer from openhcs.mcp.dev_client_rendering import McpDevTypedOutputRenderer -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def response(capability, value): diff --git a/tests/unit/agent/test_ui_bridge_service.py b/tests/unit/agent/test_ui_bridge_service.py index ebf0436e0a..07a81f7b32 100644 --- a/tests/unit/agent/test_ui_bridge_service.py +++ b/tests/unit/agent/test_ui_bridge_service.py @@ -105,7 +105,7 @@ from openhcs.agent.services.ui_bridge_transport import UiBridgeControlClient from openhcs.runtime.viewer_protocol import ViewerLaunchContextMode from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable DOCUMENT_ID = UiCodeDocumentId.PLATE_MANAGER_ORCHESTRATOR.value STATE_SURFACE_ID = UiStateSurfaceId.PLATE_MANAGER.value diff --git a/tests/unit/agent/test_viewer_render_snapshot.py b/tests/unit/agent/test_viewer_render_snapshot.py index 2cb88489a7..3824883407 100644 --- a/tests/unit/agent/test_viewer_render_snapshot.py +++ b/tests/unit/agent/test_viewer_render_snapshot.py @@ -14,7 +14,7 @@ WindowSnapshotRenderOwner, WindowVisualObservation, ) -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from openhcs.agent.capabilities import ViewerSnapshotWindowCapability from openhcs.agent.dto.common import AgentError @@ -28,7 +28,6 @@ from openhcs.agent.services.viewer_window_service import ViewerWindowService from openhcs.core.streaming_config_declarations import ViewerType from openhcs.runtime.viewer_snapshot import ViewerWindowSnapshotService -from openhcs.serialization.json import to_jsonable def _request(tmp_path): diff --git a/tests/unit/benchmark/test_agent_validation_attempt_recorder.py b/tests/unit/benchmark/test_agent_validation_attempt_recorder.py index 64fd76585a..611349d576 100644 --- a/tests/unit/benchmark/test_agent_validation_attempt_recorder.py +++ b/tests/unit/benchmark/test_agent_validation_attempt_recorder.py @@ -36,7 +36,7 @@ from openhcs.core.pipeline_document import PipelineDocumentAuthority from openhcs.core.steps.function_step import FunctionStep from openhcs.mcp.dev_client import McpDevCommandExecution -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable class _FakeMcpClient: diff --git a/tests/unit/pyqt_gui/test_ui_agent_bridge.py b/tests/unit/pyqt_gui/test_ui_agent_bridge.py index 624079980d..6f881fdef5 100644 --- a/tests/unit/pyqt_gui/test_ui_agent_bridge.py +++ b/tests/unit/pyqt_gui/test_ui_agent_bridge.py @@ -221,7 +221,7 @@ from openhcs.pyqt_gui.windows.live_measurements_window import LiveMeasurementTableModel from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.ui.shared.plate_manager_code_document import ( PlateManagerCodeDocumentAuthority, ) diff --git a/tests/unit/pyqt_gui/test_ui_window_flash_snapshot.py b/tests/unit/pyqt_gui/test_ui_window_flash_snapshot.py index b63ade45a7..27a51ec95f 100644 --- a/tests/unit/pyqt_gui/test_ui_window_flash_snapshot.py +++ b/tests/unit/pyqt_gui/test_ui_window_flash_snapshot.py @@ -8,10 +8,9 @@ from openhcs.agent.dto.ui_bridge import UiWindowSnapshotRequest, UiWindowSnapshotResult from openhcs.agent.services.ui_bridge_service import UiBridgeOperationContractABC -from openhcs.agent.services.ui_bridge_transport import AgentDtoJsonCodec +from python_introspect import dataclass_from_mapping, to_jsonable from openhcs.pyqt_gui.services.ui_agent_bridge import UiAgentBridgeService from openhcs.pyqt_gui.services.ui_bridge_windows import QtTopLevelWindowProjection -from openhcs.serialization.json import to_jsonable from pyqt_reactive.services.window_snapshot import WindowSnapshotFrameCondition @@ -98,7 +97,7 @@ def test_async_snapshot_uses_existing_operation_and_registered_response_contract operation = bridge.get_operation_status(accepted.operation_id) assert operation.status == "completed" contract = UiBridgeOperationContractABC.for_name(operation.identity.operation_name) - result = AgentDtoJsonCodec.dataclass_from_json( + result = dataclass_from_mapping( contract.response_type, operation.result_payload ) assert isinstance(result, UiWindowSnapshotResult) @@ -106,11 +105,11 @@ def test_async_snapshot_uses_existing_operation_and_registered_response_contract assert result.frame_condition is request.frame_condition assert result.observation.frame.has_maximum_alpha assert result.resource.path.endswith(".png") - wire_operation = AgentDtoJsonCodec.dataclass_from_json( + wire_operation = dataclass_from_mapping( type(operation), to_jsonable(operation) ) assert wire_operation == operation - wire_result = AgentDtoJsonCodec.dataclass_from_json( + wire_result = dataclass_from_mapping( contract.response_type, wire_operation.result_payload, ) @@ -174,7 +173,7 @@ def test_noop_reset_quiet_operation_preserves_actual_interval_receipt( ) operation = bridge.get_operation_status(accepted.operation_id) contract = UiBridgeOperationContractABC.for_name(operation.identity.operation_name) - result = AgentDtoJsonCodec.dataclass_from_json( + result = dataclass_from_mapping( contract.response_type, operation.result_payload ) assert result.captured @@ -216,7 +215,7 @@ def test_failed_observation_frame_and_existing_trace_decode_through_registered_o operation = bridge.get_operation_status(accepted.operation_id) assert operation.status == "failed" contract = UiBridgeOperationContractABC.for_name(operation.identity.operation_name) - result = AgentDtoJsonCodec.dataclass_from_json( + result = dataclass_from_mapping( contract.response_type, operation.result_payload ) assert not result.captured and result.resource is None @@ -226,7 +225,7 @@ def test_failed_observation_frame_and_existing_trace_decode_through_registered_o isinstance(record, FlashTraceRecord) for record in result.observation.trace ) assert ( - AgentDtoJsonCodec.dataclass_from_json(type(result), to_jsonable(result)) + dataclass_from_mapping(type(result), to_jsonable(result)) == result ) @@ -307,7 +306,7 @@ def _route_index(self): contract = UiBridgeOperationContractABC.for_name( operation.identity.operation_name ) - result = AgentDtoJsonCodec.dataclass_from_json( + result = dataclass_from_mapping( contract.response_type, operation.result_payload ) assert isinstance(result, UiWindowNavigateResult) diff --git a/tests/unit/test_annotated_validation.py b/tests/unit/test_annotated_validation.py index 549da7213f..5d3ccb4564 100644 --- a/tests/unit/test_annotated_validation.py +++ b/tests/unit/test_annotated_validation.py @@ -37,7 +37,7 @@ summarize_cell_partition, Treatment, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def test_official039_decoder_separates_reused_colors_and_touching_intensities(tmp_path): diff --git a/tests/unit/test_capture_media_gallery.py b/tests/unit/test_capture_media_gallery.py index c4afbb1cda..ae289fdbb6 100644 --- a/tests/unit/test_capture_media_gallery.py +++ b/tests/unit/test_capture_media_gallery.py @@ -11,14 +11,13 @@ from pyqt_reactive.animation import WindowFlashOverlay from pyqt_reactive.animation.flash_overlay_opengl import WindowFlashOverlayGL from pyqt_reactive.services.window_snapshot import WindowSnapshotCaptureScope -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from openhcs.agent.dto.common import SCHEMA_VERSION, AgentResourceRef from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.ui_bridge import UiWindowSnapshotResult from openhcs.agent.dto.viewer import ViewerWindowDescriptor, ViewerWindowSnapshotResult from openhcs.core.streaming_config_declarations import ViewerType -from openhcs.serialization.json import to_jsonable from scripts.capture_media_gallery import ( CaptureManifest, CaptureRecord, diff --git a/tests/unit/test_derived_role_publication_435.py b/tests/unit/test_derived_role_publication_435.py index 98592c2da4..e85a47f10c 100644 --- a/tests/unit/test_derived_role_publication_435.py +++ b/tests/unit/test_derived_role_publication_435.py @@ -40,7 +40,7 @@ from openhcs.core.steps.function_output_identity import FunctionOutputIdentity from openhcs.core.runtime_plane_projection import RuntimePlaneAxis, RuntimePlaneAxisValueProjection -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.processing.materialization import ( ImageFileOptions, MaterializationSpec, MaterializedFilenameIdentity, ) diff --git a/tests/unit/test_function_catalog_zmq.py b/tests/unit/test_function_catalog_zmq.py index 40766ff775..24ab4baef2 100644 --- a/tests/unit/test_function_catalog_zmq.py +++ b/tests/unit/test_function_catalog_zmq.py @@ -139,7 +139,7 @@ def test_real_mcp_context_composes_typed_preparation_and_catalog_authority( from openhcs.mcp.context import OpenHCSAgentContext, create_agent_context from openhcs.mcp.server import build_server from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable connection = ExecutionConnectionSpec(port=22319) endpoint = replace(OPENHCS_ZMQ_CONFIG, default_port=connection.port) diff --git a/tests/unit/test_image_stream_request_projection.py b/tests/unit/test_image_stream_request_projection.py index b925a31484..3906d59839 100644 --- a/tests/unit/test_image_stream_request_projection.py +++ b/tests/unit/test_image_stream_request_projection.py @@ -28,7 +28,7 @@ ImageStreamingRequest, ViewerStreamingSource, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def image_with_declaration(axis, count=1, *, color=False, masked=False): diff --git a/tests/unit/test_l2_codec_public_api_guards.py b/tests/unit/test_l2_codec_public_api_guards.py new file mode 100644 index 0000000000..c657274a6d --- /dev/null +++ b/tests/unit/test_l2_codec_public_api_guards.py @@ -0,0 +1,77 @@ +"""Surface L2 guards: python-introspect is the one codec and module-surface helper.""" + +from __future__ import annotations + +import ast +import subprocess +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +MOVED_MODULES = ("openhcs.serialization.json", "openhcs.core.public_api") +DELETED_CODECS = {"AgentDtoJsonCodec", "DebugJsonCodec"} +# A dynamic module type (P1) and a loader of user functions from disk, neither a lazy export. +NON_EXPORT_MODULE_HOOKS = { + "openhcs/processing/backends/cellprofiler/__init__.py", + "openhcs/processing/custom_functions/__init__.py", +} + + +def tracked_python_files() -> list[Path]: + listed = subprocess.run( + ["git", "ls-files", "*.py"], cwd=REPO, capture_output=True, text=True, check=True + ).stdout.split() + return [REPO / name for name in listed if not name.startswith("external/")] + + +def parsed(path: Path) -> ast.Module | None: + try: + return ast.parse(path.read_text(encoding="utf-8")) + except (SyntaxError, UnicodeDecodeError): + return None + + +def imported_modules(tree: ast.Module) -> set[str]: + modules: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module and not node.level: + modules.add(node.module) + elif isinstance(node, ast.Import): + modules.update(alias.name for alias in node.names) + return modules + + +def test_moved_modules_are_gone_and_unimported(): + for module in MOVED_MODULES: + assert not (REPO / (module.replace(".", "/") + ".py")).exists(), module + offenders = [] + for path in tracked_python_files(): + tree = parsed(path) + if tree is not None and imported_modules(tree) & set(MOVED_MODULES): + offenders.append(str(path.relative_to(REPO))) + assert offenders == [] + + +def test_no_local_dataclass_codecs(): + offenders = [ + f"{path.relative_to(REPO)}:{node.name}" + for path in (REPO / "openhcs").rglob("*.py") + if (tree := parsed(path)) is not None + for node in ast.walk(tree) + if isinstance(node, ast.ClassDef) and node.name in DELETED_CODECS + ] + assert offenders == [] + + +def test_package_lazy_exports_use_python_introspect(): + offenders = [] + for root in ("openhcs", "benchmark"): + for path in (REPO / root).rglob("__init__.py"): + relative = str(path.relative_to(REPO)) + if relative in NON_EXPORT_MODULE_HOOKS or (tree := parsed(path)) is None: + continue + offenders.extend( + f"{relative}:{node.name}" + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name in {"__getattr__", "__dir__"} + ) + assert offenders == [] diff --git a/tests/unit/test_materialization_source_extension.py b/tests/unit/test_materialization_source_extension.py index 7130b502d2..533b6dbfbf 100644 --- a/tests/unit/test_materialization_source_extension.py +++ b/tests/unit/test_materialization_source_extension.py @@ -33,7 +33,7 @@ ParserBackedSourceStemAuthority, materialization_outputs, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable COMPONENTS = { "well": "image.ome.tif", diff --git a/tests/unit/test_mcp_dev_client_persistent_session.py b/tests/unit/test_mcp_dev_client_persistent_session.py index 382f0b8267..794fa2a72d 100644 --- a/tests/unit/test_mcp_dev_client_persistent_session.py +++ b/tests/unit/test_mcp_dev_client_persistent_session.py @@ -126,7 +126,7 @@ def test_persistent_client_initializes_once_for_distinct_command_specs( ) -> None: from openhcs.mcp.dev_client_commands import ui from openhcs.mcp.server import McpCapabilityBinder - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable health_payload = to_jsonable(McpCapabilityBinder.server_health()) @@ -330,7 +330,7 @@ def test_persistent_client_timeout_is_transport_inactivity_not_total_duration( monkeypatch, ) -> None: from openhcs.mcp.server import McpCapabilityBinder - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable health_payload = to_jsonable(McpCapabilityBinder.server_health()) diff --git a/tests/unit/test_persisted_image_metadata.py b/tests/unit/test_persisted_image_metadata.py index 393ce4abfc..b902fdb003 100644 --- a/tests/unit/test_persisted_image_metadata.py +++ b/tests/unit/test_persisted_image_metadata.py @@ -42,7 +42,7 @@ VirtualWorkspaceSourceProjectionEntries, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def metadata_fixture(): diff --git a/tests/unit/test_persisted_semantic_metadata.py b/tests/unit/test_persisted_semantic_metadata.py index 8b965cecd9..673ddb0d78 100644 --- a/tests/unit/test_persisted_semantic_metadata.py +++ b/tests/unit/test_persisted_semantic_metadata.py @@ -35,7 +35,7 @@ ) from openhcs.core.virtual_workspace_metadata import VirtualWorkspaceSourceProjectionEntries from openhcs.microscopes.source_schema import SourceSchemaFilenameParser -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable VIRTUAL_PATH = "A01_s001_w1_z001_t001.tif" diff --git a/tests/unit/test_runtime_values.py b/tests/unit/test_runtime_values.py index fb8f40d49b..8b88addc3d 100644 --- a/tests/unit/test_runtime_values.py +++ b/tests/unit/test_runtime_values.py @@ -6,7 +6,7 @@ import numpy as np import pytest -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( diff --git a/tests/unit/test_source_image_provenance.py b/tests/unit/test_source_image_provenance.py index 78c9868a16..03b2716f36 100644 --- a/tests/unit/test_source_image_provenance.py +++ b/tests/unit/test_source_image_provenance.py @@ -403,7 +403,7 @@ def test_removed_runtime_axis_retains_distinct_current_named_sources() -> None: def test_factored_provenance_preserves_current_facts_and_independent_wire_occurrences(): - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable shared = SourceImageIdentity("birth.tif", {"source_metadata": {"site": "001"}}) birth = shared.identity diff --git a/tests/unit/test_source_metadata_owner.py b/tests/unit/test_source_metadata_owner.py index fa323dcb57..67b40fea25 100644 --- a/tests/unit/test_source_metadata_owner.py +++ b/tests/unit/test_source_metadata_owner.py @@ -53,7 +53,7 @@ from openhcs.core.virtual_workspace_metadata import ( VirtualWorkspaceSourceMetadataEntries, ) -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable @pytest.mark.parametrize("owner", (ResolvedSourceMetadataRecord, DurableSourceMetadata)) diff --git a/tests/unit/test_viewer_feature_measurement.py b/tests/unit/test_viewer_feature_measurement.py index 0af191c811..76b58d8ce2 100644 --- a/tests/unit/test_viewer_feature_measurement.py +++ b/tests/unit/test_viewer_feature_measurement.py @@ -14,7 +14,7 @@ StreamProducerIdentity, ) from polystore.streaming_constants import StreamingDataType -from python_introspect import dataclass_from_mapping +from python_introspect import dataclass_from_mapping, to_jsonable from zmqruntime.viewer_protocol import ViewerComponentMode from openhcs.agent.capabilities import ( @@ -55,7 +55,6 @@ ) from openhcs.runtime.viewer_measurements import NativeImageMeasurement from openhcs.runtime.viewer_protocol import OpenHCSViewerControlMessageType -from openhcs.serialization.json import to_jsonable def native_route(): diff --git a/tests/unit/test_viewer_receipt_replay.py b/tests/unit/test_viewer_receipt_replay.py index ce2aefbf7c..2dd21c6b22 100644 --- a/tests/unit/test_viewer_receipt_replay.py +++ b/tests/unit/test_viewer_receipt_replay.py @@ -40,7 +40,7 @@ from openhcs.core.viewer_streaming_service import ViewerStreamingSource from openhcs.core.plate_file_inventory import PlateFileKind from openhcs.core.plate_image_inventory import PlateFileRecord -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable from openhcs.runtime.viewer_protocol import ViewerPayloadSummary diff --git a/tests/unit/test_viewer_retirement_contract.py b/tests/unit/test_viewer_retirement_contract.py index e27a8aa7bf..61ef40165c 100644 --- a/tests/unit/test_viewer_retirement_contract.py +++ b/tests/unit/test_viewer_retirement_contract.py @@ -23,7 +23,7 @@ from openhcs.mcp.server import McpCapabilityBinder, build_server from openhcs.mcp.dev_client_commands.viewer import RetireViewerCommandSpec from openhcs.runtime.viewer_protocol import ViewerLayerRetirementReceipt -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable def producers(): diff --git a/validation/public_two_vector_388.py b/validation/public_two_vector_388.py index 386aad30a7..784f818a1f 100644 --- a/validation/public_two_vector_388.py +++ b/validation/public_two_vector_388.py @@ -135,14 +135,14 @@ def __init__(self, client, receipt_dir): self.sequence = 0 def save(self, filename, value): - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable with (self.root / filename).open("x") as stream: stream.write(json.dumps(to_jsonable(value), indent=2) + "\n") def call(self, name, arguments): from openhcs.agent.capabilities import get_agent_capability from openhcs.mcp.dev_client_core import McpDevToolBatchResponse - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable capability = get_agent_capability(name) self.sequence += 1 stem = f"{self.sequence:03d}-{name}" @@ -183,7 +183,7 @@ def readiness_observer(self, bootstrap_handle, phase, validate_handle): terminal inference; real terminal/unknown-owner/transport errors stop. """ import psutil - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable started = time.monotonic() last_progress = None last_report = float("-inf") @@ -236,7 +236,7 @@ def run(args): from openhcs.agent.dto.execution import RuntimeBootstrapCloseRequest, RuntimeBootstrapHandle from openhcs.mcp.dev_client import McpDevClient from openhcs.processing.custom_functions.manager import CustomFunctionManager - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable from python_introspect import dataclass_from_mapping from zmqruntime.messages import ExecutionStatus diff --git a/validation/registration-observation-567/test_closed_cli_roundtrip.py b/validation/registration-observation-567/test_closed_cli_roundtrip.py index 3b5532695b..798f5bbea4 100644 --- a/validation/registration-observation-567/test_closed_cli_roundtrip.py +++ b/validation/registration-observation-567/test_closed_cli_roundtrip.py @@ -14,7 +14,7 @@ from openhcs.agent.dto.functions import CustomFunctionRegistrationObservation from openhcs.mcp import dev_client from openhcs.mcp.dev_client_core import McpDevPayloadFailure, McpDevToolBatchResponse -from openhcs.serialization.json import to_jsonable +from python_introspect import to_jsonable ROOT = Path('/home/ts/wt/openhcs-issue-batch-20260929/engineering567/public94-attempt01') diff --git a/validation/s1-sampling-owner-trace.py b/validation/s1-sampling-owner-trace.py index b27dc43f99..514639e2f4 100644 --- a/validation/s1-sampling-owner-trace.py +++ b/validation/s1-sampling-owner-trace.py @@ -16,7 +16,6 @@ repo / "openhcs/mcp", repo / "openhcs/core/plate_image_inventory.py", repo / "openhcs/runtime/viewer_protocol.py", - repo / "openhcs/serialization/json.py", backing / "python_introspect", paired / "metaclass_registry", paired / "pyqt_reactive", diff --git a/validation/test_public_two_vector_driver_388.py b/validation/test_public_two_vector_driver_388.py index 8c0111de9d..6c468d9cb7 100644 --- a/validation/test_public_two_vector_driver_388.py +++ b/validation/test_public_two_vector_driver_388.py @@ -138,7 +138,7 @@ def test_original_decoder_recovers_real_public_pipeline_response(driver): from openhcs.agent.dto.common import SCHEMA_VERSION from openhcs.agent.dto.pipeline import PipelineRef from openhcs.mcp.dev_client_core import McpDevToolBatchResponse, McpDevToolResult, McpDevServerIdentity - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable batch = McpDevToolBatchResponse(server=McpDevServerIdentity(command="source-proof-no-spawn", module="openhcs.mcp.server"), results=(McpDevToolResult( tool="openhcs_create_pipeline", mcp_error=False, payloads=(to_jsonable(PipelineRef("pipeline-proof", "openhcs://pipelines/pipeline-proof")),)),)) @@ -160,7 +160,7 @@ def test_same_handle_warm_and_cold_readiness_has_no_elapsed_terminal_cutoff(driv ) from zmqruntime.messages import ProcessIdentity from zmqruntime.startup import EndpointStartupPhase, EndpointStartupStatus - from openhcs.serialization.json import to_jsonable + from python_introspect import to_jsonable identity = ProcessIdentity.current() # This source test process, NOT native. handle = FunctionCatalogPreparationHandle(ExecutionConnectionSpec(port=5993), identity)