From a43072feff8df645bb29d5c365255ede74a6a1d6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 08:07:14 -0800 Subject: [PATCH 1/2] feat(pipeline): reuse matching repository database bindings --- changelog.d/ITL-1974.md | 5 + src/orcapod/pipeline/job.py | 15 +++ src/orcapod/pipeline/repository.py | 5 + src/orcapod/pipeline/serialization.py | 30 ++++++ .../test_pipeline/test_pipeline_repository.py | 91 +++++++++++++++++++ 5 files changed, 146 insertions(+) create mode 100644 changelog.d/ITL-1974.md diff --git a/changelog.d/ITL-1974.md b/changelog.d/ITL-1974.md new file mode 100644 index 000000000..2b7ad5b7f --- /dev/null +++ b/changelog.d/ITL-1974.md @@ -0,0 +1,5 @@ +### Changed + +- `PipelineRepository.load` reuses the repository database for saved keyed + SpiralDB and absolute-path SQLite bindings that identify the same database + and table scope, including separate result bindings and read-only loads. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 9c40edacb..91bb744f2 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2439,6 +2439,7 @@ def _load_saved_job( *, result_database: ArrowDatabaseProtocol | None = None, read_only: Literal[False] = False, + repository_database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob: ... @classmethod @@ -2450,6 +2451,7 @@ def _load_saved_job( *, result_database: ArrowDatabaseProtocol | None = None, read_only: bool, + repository_database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob | SourceOnlyPipelineJob: ... @classmethod @@ -2460,6 +2462,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 @@ -2474,6 +2477,7 @@ def _load_saved_job( check_source_config_binding, require_current_format, require_tag_only_columns, + reuse_repository_database, resolve_source_from_config, saved_connector_kind, saved_database_kind, @@ -2509,6 +2513,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. diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 1d23aca86..299e1dd69 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -407,6 +407,10 @@ def load( ) -> PipelineJob | SourceOnlyPipelineJob: """Load a published job with the same rules as `PipelineJob.load`. + An omitted connector binding can reuse the repository database when + its saved configuration identifies the same connector 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. @@ -443,6 +447,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 0bd3edb5b..e8d3459cc 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -580,6 +580,36 @@ 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 connector identifies its scope.""" + from pathlib import PurePath + + 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 + from orcapod.databases.sqlite_connector import SQLiteConnector + + kind = saved_connector_kind(config) + 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 kind == "sqlite" and type(connector) is SQLiteConnector: + path = config["connector"].get("db_path") + if not isinstance(path, str) or not PurePath(path).is_absolute(): + return None + elif kind != "spiraldb_keyed" or type(connector) is not SpiralDBKeyedConnector: + # A PostgreSQL DSN alone can leave the effective database or schema + # unspecified, and other connectors have no known saved identity. + return None + + # These config formats contain no credentials. Exact config equality also + # covers the database view's base path and table path layout. + return repository if config == database.to_config() else 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 277319e92..d75ec403a 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -219,6 +219,97 @@ 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("read_only", [False, True]) +def test_load_reuses_file_backed_sqlite_connector( + tmp_path: Path, read_only: bool +) -> None: + path = tmp_path / "repository.sqlite" + with SQLiteConnector(path) as writer, SQLiteConnector(path) as reader: + database = ConnectorArrowDatabase(writer) + job = PipelineJob(name="daily", database=database) + job.compile() + _ = PipelineRepository(database).publish(job) + reader_database = ConnectorArrowDatabase(reader) + loaded = PipelineRepository(reader_database).load("daily", read_only=read_only) + assert loaded.name == ("daily",) + if isinstance(loaded, SourceOnlyPipelineJob): + assert read_only + else: + assert loaded.database is reader_database + + def test_publish_under_multiple_names_preserves_job_name_and_saved_text( open_repository_database: Callable[[], ArrowDatabaseProtocol], tmp_path: Path ) -> None: From 498611df0a0f169dd3abf6b94c275370a484e21e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 08:16:15 -0800 Subject: [PATCH 2/2] fix(pipeline): match keyed SpiralDB repository identities --- changelog.d/ITL-1974.md | 10 ++- src/orcapod/pipeline/repository.py | 4 +- src/orcapod/pipeline/serialization.py | 39 +++++++----- .../test_pipeline/test_pipeline_repository.py | 63 ++++++++++++++----- 4 files changed, 81 insertions(+), 35 deletions(-) diff --git a/changelog.d/ITL-1974.md b/changelog.d/ITL-1974.md index 2b7ad5b7f..2041e88b3 100644 --- a/changelog.d/ITL-1974.md +++ b/changelog.d/ITL-1974.md @@ -1,5 +1,11 @@ ### Changed - `PipelineRepository.load` reuses the repository database for saved keyed - SpiralDB and absolute-path SQLite bindings that identify the same database - and table scope, including separate result bindings and read-only loads. + 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/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 299e1dd69..f4feb150a 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -407,8 +407,8 @@ def load( ) -> PipelineJob | SourceOnlyPipelineJob: """Load a published job with the same rules as `PipelineJob.load`. - An omitted connector binding can reuse the repository database when - its saved configuration identifies the same connector and table scope. + 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: diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index e8d3459cc..dea833181 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -583,31 +583,40 @@ def saved_connector_kind(config: Any) -> str | None: def reuse_repository_database( config: Any, repository: ArrowDatabaseProtocol ) -> ArrowDatabaseProtocol | None: - """Return the repository database if the saved connector identifies its scope.""" - from pathlib import PurePath - + """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 - from orcapod.databases.sqlite_connector import SQLiteConnector - kind = saved_connector_kind(config) + 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 kind == "sqlite" and type(connector) is SQLiteConnector: - path = config["connector"].get("db_path") - if not isinstance(path, str) or not PurePath(path).is_absolute(): - return None - elif kind != "spiraldb_keyed" or type(connector) is not SpiralDBKeyedConnector: - # A PostgreSQL DSN alone can leave the effective database or schema - # unspecified, and other connectors have no known saved identity. + 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") + ) - # These config formats contain no credentials. Exact config equality also - # covers the database view's base path and table path layout. - return repository if config == database.to_config() else None + 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: diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index d75ec403a..4015a1919 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -32,6 +32,7 @@ SQLiteConnector, ) from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL +from orcapod.pipeline.serialization import reuse_repository_database from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import DictSource from tests.test_databases import fake_spiral_sdk @@ -291,23 +292,53 @@ def test_load_reuses_only_matching_connector_bindings( PipelineJob.load(saved, read_only=read_only) -@pytest.mark.parametrize("read_only", [False, True]) -def test_load_reuses_file_backed_sqlite_connector( - tmp_path: Path, read_only: bool +@pytest.mark.parametrize("difference", ["depth", "empty_overrides"]) +def test_same_spiral_scope_loads_with_equivalent_settings( + tmp_path: Path, difference: str ) -> None: - path = tmp_path / "repository.sqlite" - with SQLiteConnector(path) as writer, SQLiteConnector(path) as reader: - database = ConnectorArrowDatabase(writer) - job = PipelineJob(name="daily", database=database) - job.compile() - _ = PipelineRepository(database).publish(job) - reader_database = ConnectorArrowDatabase(reader) - loaded = PipelineRepository(reader_database).load("daily", read_only=read_only) - assert loaded.name == ("daily",) - if isinstance(loaded, SourceOnlyPipelineJob): - assert read_only - else: - assert loaded.database is reader_database + 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_publish_under_multiple_names_preserves_job_name_and_saved_text(