diff --git a/changelog.d/ITL-1974.md b/changelog.d/ITL-1974.md new file mode 100644 index 000000000..2041e88b3 --- /dev/null +++ b/changelog.d/ITL-1974.md @@ -0,0 +1,11 @@ +### Changed + +- `PipelineRepository.load` reuses the repository database for saved keyed + SpiralDB bindings that identify the same database and table scope, including + separate result bindings and read-only loads. + +### Known limitations + +- Saved keyed SpiralDB bindings record explicit endpoint overrides. When both + bindings omit an override, the endpoint check matches even if the environment + points the saved job and repository at different deployments. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 4524bdf41..51da440ec 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -800,8 +800,9 @@ expose them through their stored views without importing the original function modules. Pass `read_only=True` with either the latest or a pinned version to get a provisional `SourceOnlyPipelineJob` with stored sources, saved labels, and -the reasons other nodes are unavailable. Pass `result_database=` to read -function results from a saved separate result database. +the reasons other nodes are unavailable. To read function results from a saved +separate result database, pass `result_database=` or load from a keyed SpiralDB +repository whose database matches the saved result binding. ## How it connects to other concepts diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index acd7aaa9f..4e35f2e34 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2442,6 +2442,7 @@ def _load_saved_job( *, result_database: ArrowDatabaseProtocol | None = None, read_only: Literal[False] = False, + repository_database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob: ... @classmethod @@ -2453,6 +2454,7 @@ def _load_saved_job( *, result_database: ArrowDatabaseProtocol | None = None, read_only: bool, + repository_database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob | SourceOnlyPipelineJob: ... @classmethod @@ -2463,6 +2465,7 @@ def _load_saved_job( *, result_database: ArrowDatabaseProtocol | None = None, read_only: bool = False, + repository_database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob | SourceOnlyPipelineJob: """Reconstruct a job or its stored source view from saved text.""" import json as _json @@ -2478,6 +2481,7 @@ def _load_saved_job( require_current_format, require_tag_only_columns, resolve_database_from_config, + reuse_repository_database, resolve_source_from_config, saved_connector_kind, saved_database_kind, @@ -2513,6 +2517,17 @@ def _load_saved_job( ] if unreadable: raise ValueError(f"{path}: " + "; ".join(unreadable) + ".") + if repository_database is not None: + bindings = data.get("bindings", {}) + if database is None: + database = reuse_repository_database( + bindings.get("database"), repository_database + ) + if result_database is None: + result_database = reuse_repository_database( + bindings.get("result_database"), repository_database + ) + # A connector is supplied by the user, never rebuilt from the file (ITL-1391): # refused before anything is rebuilt. Nothing of the saved configuration is # shown. @@ -2716,7 +2731,7 @@ def _load_saved_job( if result_config is not None and not isinstance(result_config, dict): raise ValueError(f"{path}: bindings.result_database must be an object.") if result_config and read_only: - # The function nodes need an explicit handle to their separate store. + # The function nodes need a live handle to their separate store. unresolved_result_database = result_config elif result_config and result_config.get("type") == "in_memory": # An in-memory database holds nothing once its process ended: a new diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 2184b479a..4ecc4fbc1 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -407,12 +407,17 @@ def load( ) -> PipelineJob | SourceOnlyPipelineJob: """Load a published job with the same rules as `PipelineJob.load`. + An omitted keyed SpiralDB binding can reuse the repository database when + its saved identity identifies the same database and table scope. + This applies independently to the job and separate result databases. + Args: name: Pipeline name as a string or tuple of name components. ver: Publication to load. Defaults to the latest version. - read_only: Open the provisional stored source view of the job. A - saved separate result database requires an explicit - ``result_database`` to expose its function results. + read_only: Open the provisional stored source view of the job. + Function results in a saved separate database require a live + handle, either an explicit ``result_database`` or a matching + keyed SpiralDB repository database. database: Optional override for the job's database binding. result_database: Optional override for the job's result database binding. @@ -445,6 +450,7 @@ def load( database=database, result_database=result_database, read_only=read_only, + repository_database=self._database, ) except ValueError as exc: exc.add_note(f"Loading pipeline {name!r} at version {ver}.") diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 6c796e9eb..f9d1ec617 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -588,6 +588,45 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" +def reuse_repository_database( + config: Any, repository: ArrowDatabaseProtocol +) -> ArrowDatabaseProtocol | None: + """Return the repository database if the saved keyed SpiralDB scope matches.""" + from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.extension_aware_database import unwrap_database_views + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector + + if saved_connector_kind(config) != "spiraldb_keyed": + return None + database = unwrap_database_views(repository) + if not isinstance(database, ConnectorArrowDatabase): + return None + connector = database._connector # pyright: ignore[reportPrivateUsage] # inspect the live connector without a read + if type(connector) is not SpiralDBKeyedConnector: + return None + + saved = cast("dict[str, Any]", config["connector"]) + saved_overrides: object = saved.get("overrides") + if saved_overrides is not None and not isinstance(saved_overrides, dict): + return None + saved_endpoint = ( + None if saved_overrides is None else saved_overrides.get("server.url") + ) + + live_config = database.to_config() + live = cast("dict[str, Any]", live_config["connector"]) + live_endpoint = (live["overrides"] or {}).get("server.url") + if ( + saved.get("project_id") == live["project_id"] + and saved.get("dataset") == live["dataset"] + and config.get("base_path") == live_config["base_path"] + and saved.get("writable", False) is live.get("writable", False) + and saved_endpoint == live_endpoint + ): + return repository + return None + + def spiraldb_saved_config_refusal(config: Any) -> str | None: """Why a saved SpiralDB connector configuration is not read, or ``None``. diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 758560751..9ab6cb739 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -32,7 +32,7 @@ SQLiteConnector, ) from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL -from orcapod.pipeline.serialization import LoadStatus +from orcapod.pipeline.serialization import LoadStatus, reuse_repository_database from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import DictSource from tests.test_databases import fake_spiral_sdk @@ -220,6 +220,127 @@ def test_load_source_only_matches_file_loader_for_latest_and_pinned_versions( assert actual.equals(expected.sort_by("trial"), check_metadata=True) +@pytest.mark.parametrize("read_only", [False, True]) +@pytest.mark.parametrize( + ("binding", "missing"), + [ + ("same_dataset", None), + ("same_result_dataset", None), + ("other_dataset", "database"), + ("other_result_dataset", "result_database"), + ("other_table_root", "database"), + ("missing_dataset", "database"), + ], +) +def test_load_reuses_only_matching_connector_bindings( + tmp_path: Path, read_only: bool, binding: str, missing: str | None +) -> None: + with ( + fake_spiral_sdk.install(tmp_path), + SpiralDBKeyedConnector("p", "pipelines", writable=True) as writer, + SpiralDBKeyedConnector("p", "pipelines", writable=True) as reader, + SpiralDBKeyedConnector("p", "other", writable=True) as other, + ): + common_database = ConnectorArrowDatabase(writer) + other_database = ConnectorArrowDatabase(other) + database = { + "other_dataset": other_database, + "other_table_root": common_database.at("other"), + }.get(binding, common_database) + result_database = { + "same_result_dataset": common_database, + "other_result_dataset": other_database, + }.get(binding) + job = _run_job("daily", database, 10, result_database=result_database) + publisher = PipelineRepository(common_database) + if binding == "missing_dataset": + config = common_database.to_config() + del config["connector"]["dataset"] + with patch.object(common_database, "to_config", return_value=config): + _ = publisher.publish(job) + else: + _ = publisher.publish(job) + + repository = PipelineRepository(ConnectorArrowDatabase(reader)) + if missing: + with pytest.raises( + ValueError, match="a database connector is not rebuilt from a saved job" + ) as error: + repository.load("daily", read_only=read_only) + assert f"pass {missing}=" in str(error.value) + if missing == "result_database": + assert "pass database=" not in str(error.value) + + loaded = repository.load( + "daily", + read_only=read_only, + database=database if missing == "database" else None, + result_database=result_database if missing == "result_database" else None, + ) + if isinstance(loaded, SourceOnlyPipelineJob): + assert read_only + table = loaded.nodes["total"].as_table().sort_by("trial") + assert table["total"].to_pylist() == [11, 12] + else: + assert not read_only + assert _totals(loaded) == [11, 12] + + if binding == "same_dataset": + saved = tmp_path / "job.json" + job.save(saved) + with pytest.raises(ValueError, match="pass database="): + PipelineJob.load(saved, read_only=read_only) + + +@pytest.mark.parametrize("difference", ["depth", "empty_overrides"]) +def test_same_spiral_scope_loads_with_equivalent_settings( + tmp_path: Path, difference: str +) -> None: + with ( + fake_spiral_sdk.install(tmp_path), + SpiralDBKeyedConnector("p", "d", writable=True) as writer, + SpiralDBKeyedConnector( + "p", + "d", + overrides={} if difference == "empty_overrides" else None, + writable=True, + ) as reader, + ): + write_db = ConnectorArrowDatabase(writer) + _ = PipelineRepository(write_db).publish(_run_job("daily", write_db, 10)) + read_db = ConnectorArrowDatabase( + reader, + max_hierarchy_depth=20 if difference == "depth" else 10, + ) + assert _totals(PipelineRepository(read_db).load("daily")) == [11, 12] + + +def test_spiral_identity_changes_are_refused(tmp_path: Path) -> None: + with ( + fake_spiral_sdk.install(tmp_path), + SpiralDBKeyedConnector("p", "d", writable=True) as reference, + SpiralDBKeyedConnector("q", "d", writable=True) as other_project, + SpiralDBKeyedConnector("p", "e", writable=True) as other_dataset, + SpiralDBKeyedConnector("p", "d", writable=False) as other_layout, + SpiralDBKeyedConnector( + "p", + "d", + overrides={"server.url": "https://different.invalid"}, + writable=True, + ) as other_endpoint, + ): + database = ConnectorArrowDatabase(reference) + saved = database.to_config() + for different in ( + ConnectorArrowDatabase(other_project), + ConnectorArrowDatabase(other_dataset), + ConnectorArrowDatabase(other_layout), + ConnectorArrowDatabase(other_endpoint), + database.at("different"), + ): + assert reuse_repository_database(saved, different) is None + + def test_read_only_rejects_non_object_result_database(tmp_path: Path) -> None: database = InMemoryArrowDatabase() job = _run_job(