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
5 changes: 5 additions & 0 deletions changelog.d/ITL-1967.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Fixed
- Loading a saved or published job opens existing local Delta roots for its
`database` and `result_database` bindings without creating missing directories.
In a source-only load, pass `result_database=` to read function results from a
saved separate result database.
14 changes: 10 additions & 4 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ independent slot for each job.
Pass `read_only=True` to `PipelineJob.load()` to inspect stored results without the
original function code or source data. This provisional option warns when first used
in a process. The view refuses `run()` and `run_async()`, including load-only runs.
Opening the view and reading from it make no writes to any database table.
Opening the view and reading from it make no writes to any database table. If the
job was saved with a separate result database, pass it as `result_database=` to
read those function results. Without that argument the function results are
unavailable.

```python
from pathlib import Path
Expand Down Expand Up @@ -787,15 +790,18 @@ own storage. For SpiralDB, a viewer opens the repository with

Load only publications from publishers you would trust to give you a saved job
file. As with `PipelineJob.load`, loading a publication reconstructs its saved
database bindings under the reader's authority. For example, opening a saved
local Delta binding can create its missing directory (ITL-1967).
database bindings under the reader's authority. When reopening the job's
`database` or `result_database` binding from a saved local Delta configuration,
the root directory must already exist. If the directory is missing, loading logs a
warning and leaves that binding unresolved.

A loaded job can run in `load_only=True` mode, and nodes with stored results
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.
the reasons other nodes are unavailable. Pass `result_database=` to read
function results from a saved separate result database.

## How it connects to other concepts

Expand Down
25 changes: 17 additions & 8 deletions src/orcapod/databases/delta_lake_databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -2096,12 +2096,15 @@ def __init__(
# _local_root is the absolute filesystem root (for list_sources, mkdir, etc.)
# NOTE: do NOT access self._local_root on cloud instances.
self._local_root = Path(self._root_uri)
if create_base_path:
self._local_root.mkdir(parents=True, exist_ok=True)
elif not self._local_root.exists():
raise ValueError(
f"Base path {self._local_root} does not exist and create_base_path=False"
)
# Scoped views share their root and never create it.
if _root is None:
if create_base_path:
self._local_root.mkdir(parents=True, exist_ok=True)
elif not self._local_root.is_dir():
raise ValueError(
f"Base path {self._local_root} is not an existing directory "
"and create_base_path=False"
)
# For cloud paths: create_base_path is silently ignored (no directory needed).

# Shared state — when constructed via at(), these dicts are shared with the
Expand Down Expand Up @@ -4193,12 +4196,18 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]:
return config

@classmethod
def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase":
def from_config(
cls, config: dict[str, Any], *, create_base_path: bool = True
) -> "DeltaTableDatabase":
"""Reconstruct a DeltaTableDatabase from a config dict.

Supports both the current format (``"root_uri"`` for the storage root,
``"base_path"`` as a list for the scoping prefix) and the legacy format
produced before ENG-341 (``"base_path"`` as a URI string, no prefix).

Args:
config: A saved Delta database configuration.
create_base_path: Create the local storage root if it is missing.
"""
if "root_uri" in config:
# Current format (post-ENG-341)
Expand All @@ -4217,7 +4226,7 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase":
storage_options={
name: value for name, value in options.items() if value is not None
},
create_base_path=True,
create_base_path=create_base_path,
batch_size=config.get("batch_size", 1000),
max_hierarchy_depth=config.get("max_hierarchy_depth", 10),
allow_schema_evolution=config.get("allow_schema_evolution", True),
Expand Down
39 changes: 21 additions & 18 deletions src/orcapod/pipeline/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -2372,6 +2372,8 @@ def load(
cannot be rebuilt for another reason (a moved file) is logged as a
warning. Neither affects reading the other nodes. A subsequent save
preserves the unresolved source configurations and the original run record.
Saved local Delta database bindings require existing root directories.
A missing root leaves the binding unresolved and logs a warning.

Args:
path: Path to the JSON file produced by ``save()``.
Expand All @@ -2384,15 +2386,16 @@ def load(
database (ITL-1408), required when the file names a connector
database. When provided, it is used whatever the file
says, except that when the saved and the given databases are both
SpiralDB, their modes (writable or plain) must match. Otherwise the one the file names is rebuilt from its saved
configuration, as the job's database is; a file that names none
keeps the results in the job's database (``<name>/_result``). When
the file names one that cannot be rebuilt, the function nodes get no
database (a warning says what to pass) rather than the job's own
``_result`` location, which holds none of their results.
SpiralDB, their modes (writable or plain) must match. By default,
the separate database is rebuilt from its saved configuration.
A file that names none keeps the results in the job's database
(``<name>/_result``). If the named database cannot be rebuilt, a
warning is logged and the function results are unavailable.
read_only: Open the provisional stored source view without restoring
original source bindings or operator implementations. Opening the
view and reading its sources make no writes to database tables.
original source bindings or operator implementations. A saved
separate result database requires an explicit ``result_database``
to expose its function results. Opening the view and reading its
sources make no writes to database tables.

Returns:
A ``PipelineJob`` by default, or a ``SourceOnlyPipelineJob`` when
Expand Down Expand Up @@ -2474,6 +2477,7 @@ def _load_saved_job(
check_source_config_binding,
require_current_format,
require_tag_only_columns,
resolve_database_from_config,
resolve_source_from_config,
saved_connector_kind,
saved_database_kind,
Expand Down Expand Up @@ -2684,11 +2688,9 @@ def _load_saved_job(
store_config = bindings.get("database")
if store_config:
try:
from orcapod.pipeline.serialization import (
resolve_database_from_config,
effective_database = resolve_database_from_config(
store_config, create_base_path=False
)

effective_database = resolve_database_from_config(store_config)
except Exception as exc:
unresolved_database = store_config
# The exception's type, never its text (ITL-1391).
Expand All @@ -2711,7 +2713,12 @@ def _load_saved_job(
unresolved_result_database: dict[str, Any] | None = None
if effective_result_database is None:
result_config = data.get("bindings", {}).get("result_database")
if result_config and result_config.get("type") == "in_memory":
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.
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
# one would be empty, so it is not available, as a connector is not.
unresolved_result_database = result_config
Expand All @@ -2724,12 +2731,8 @@ def _load_saved_job(
)
elif result_config:
try:
from orcapod.pipeline.serialization import (
resolve_database_from_config,
)

effective_result_database = resolve_database_from_config(
result_config
result_config, create_base_path=False
)
except Exception as exc:
unresolved_result_database = result_config
Expand Down
4 changes: 3 additions & 1 deletion src/orcapod/pipeline/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,9 @@ def load(
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.
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.
database: Optional override for the job's database binding.
result_database: Optional override for the job's result database binding.

Expand Down
12 changes: 10 additions & 2 deletions src/orcapod/pipeline/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,10 @@ def _ensure_registries() -> None:


def resolve_database_from_config(
config: dict[str, Any], db_registry: dict | None = None
config: dict[str, Any],
db_registry: dict[str, Any] | None = None,
*,
create_base_path: bool = True,
) -> Any:
"""Reconstruct a database instance from a config dict.

Expand All @@ -470,6 +473,7 @@ def resolve_database_from_config(
db_registry: Optional plain dict mapping ``"db_<key>"`` → config dict
(the output of ``DatabaseRegistry.to_dict()``). Required when
``config["type"] == "scoped"``; ignored otherwise.
create_base_path: Create a missing local Delta storage root.

Returns:
A new database instance constructed from the config.
Expand All @@ -489,7 +493,9 @@ def resolve_database_from_config(
f"Registry key {ref!r} not found; available keys: {sorted(db_registry.keys())}"
)
root_config = db_registry[ref]
root_db = resolve_database_from_config(root_config)
root_db = resolve_database_from_config(
root_config, create_base_path=create_base_path
)
return root_db.at(*config["path"])
if db_type not in DATABASE_REGISTRY:
raise ValueError(
Expand All @@ -501,6 +507,8 @@ def resolve_database_from_config(
"original run is not available — nodes will have UNAVAILABLE status."
)
cls = DATABASE_REGISTRY[db_type]
if db_type == "delta_table" and not create_base_path:
return cls.from_config(config, create_base_path=False)
return cls.from_config(config)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,8 @@ def test_a_failed_delta_rebuild_logs_the_slot_kind_and_exception_type_only(
path.write_text(json.dumps(changed))
caplog.clear()

def refuse(config: dict[str, Any]) -> Any:
def refuse(config: dict[str, Any], *, create_base_path: bool) -> Any:
assert not create_base_path
raise OSError(f"cannot open {config}")

with ExitStack() as stack:
Expand Down
17 changes: 0 additions & 17 deletions tests/test_pipeline/loaded_job/test_source_only.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,23 +307,6 @@ def test_read_only_in_fresh_process_without_code_or_source(
)


@pytest.mark.xfail(
strict=True,
raises=AssertionError,
reason="ITL-1967: loading creates a missing Delta root",
)
def test_delta_missing_root_stays_missing(tmp_path: Path) -> None:
root = tmp_path / "cache"
job = PipelineJob(name=("example", "report"), database=DeltaTableDatabase(root))
with job:
_source().select_data_columns(("x", "y"), label="selection")
saved = tmp_path / "job.json"
job.save(saved)
root.rmdir()
PipelineJob.load(saved, read_only=True)
assert not root.exists()


@pytest.mark.parametrize(
"tag_order,order",
[
Expand Down
107 changes: 107 additions & 0 deletions tests/test_pipeline/test_pipeline_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
SQLiteConnector,
)
from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL
from orcapod.pipeline.serialization import LoadStatus
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
from orcapod.sources import DictSource
from tests.test_databases import fake_spiral_sdk
Expand Down Expand Up @@ -219,6 +220,112 @@ def test_load_source_only_matches_file_loader_for_latest_and_pinned_versions(
assert actual.equals(expected.sort_by("trial"), check_metadata=True)


def test_read_only_rejects_non_object_result_database(tmp_path: Path) -> None:
database = InMemoryArrowDatabase()
job = _run_job(
"daily", database, 10, result_database=InMemoryArrowDatabase(), run=False
)
saved = tmp_path / "job.json"
job.save(saved)
document = json.loads(saved.read_text())
document["bindings"]["result_database"] = ["malformed"]
saved.write_text(json.dumps(document))

with pytest.raises(ValueError, match=r"bindings\.result_database"):
PipelineJob.load(saved, database, read_only=True)

assert isinstance(
PipelineJob.load(saved, database, result_database=database, read_only=True),
SourceOnlyPipelineJob,
)


@pytest.mark.parametrize("loader", ["file", "repository"])
@pytest.mark.parametrize("binding", ["database", "result_database"])
@pytest.mark.parametrize("read_only", [False, True])
def test_load_saved_delta_binding(
tmp_path: Path,
loader: str,
binding: str,
read_only: bool,
caplog: pytest.LogCaptureFixture,
) -> None:
root = tmp_path / "results"
delta = DeltaTableDatabase(root)
separate = binding == "result_database"
database = InMemoryArrowDatabase() if separate else delta
job = _run_job(
"daily",
database,
10,
reverse_layout=separate,
result_database=delta if separate else None,
)
saved = tmp_path / "job.json"
job.save(saved)
repository = PipelineRepository(InMemoryArrowDatabase())
publication = repository.publish(job)

def load(
*,
database_override: ArrowDatabaseProtocol | None = None,
result_database: ArrowDatabaseProtocol | None = None,
) -> PipelineJob | SourceOnlyPipelineJob:
given = database if separate else database_override
if loader == "file":
return PipelineJob.load(
saved, given, result_database=result_database, read_only=read_only
)
return repository.load(
publication.name,
ver=publication.version,
database=given,
result_database=result_database,
read_only=read_only,
)

if read_only and separate:
with patch.object(
DeltaTableDatabase, "from_config", wraps=DeltaTableDatabase.from_config
) as rebuild:
loaded = load()
rebuild.assert_not_called()
else:
loaded = load()
if read_only:
assert isinstance(loaded, SourceOnlyPipelineJob)
if separate:
assert "total" in loaded.unavailable
loaded = load(result_database=delta)
assert isinstance(loaded, SourceOnlyPipelineJob)
assert loaded.nodes["total"].as_table().sort_by("trial")[
"total"
].to_pylist() == [11, 12]
else:
assert isinstance(loaded, PipelineJob)
assert _totals(loaded) == [11, 12]

root.rename(tmp_path / "moved")
caplog.clear()
loaded = load()
assert not root.exists()
if read_only:
assert isinstance(loaded, SourceOnlyPipelineJob)
assert "total" in loaded.unavailable
if separate:
assert "bindings.result_database" not in caplog.text
else:
assert isinstance(loaded, PipelineJob)
assert f"bindings.{binding}" in caplog.text
assert "ValueError" in caplog.text
assert loaded.nodes["total"].load_status is LoadStatus.UNAVAILABLE

if not separate:
# An explicit database can still be scoped after its directory is moved.
load(database_override=delta)
assert not root.exists()


def test_publish_under_multiple_names_preserves_job_name_and_saved_text(
open_repository_database: Callable[[], ArrowDatabaseProtocol], tmp_path: Path
) -> None:
Expand Down
Loading