Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions changelog.d/ITL-1974.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 3 additions & 2 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
17 changes: 16 additions & 1 deletion src/orcapod/pipeline/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -2453,6 +2454,7 @@ def _load_saved_job(
*,
result_database: ArrowDatabaseProtocol | None = None,
read_only: bool,
repository_database: ArrowDatabaseProtocol | None = None,
) -> PipelineJob | SourceOnlyPipelineJob: ...

@classmethod
Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions src/orcapod/pipeline/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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}.")
Expand Down
39 changes: 39 additions & 0 deletions src/orcapod/pipeline/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.

Expand Down
123 changes: 122 additions & 1 deletion tests/test_pipeline/test_pipeline_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Loading