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-1450.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Fixed
- Saving a loaded job keeps its original run record and preserves unresolved
source configurations for untouched slots. Explicit unbinds survive reload,
and replacement bindings take precedence over retained configurations that
claim the same source ID or content hash.
103 changes: 72 additions & 31 deletions src/orcapod/pipeline/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
import sys
from collections.abc import Iterable, Iterator, Sequence
from copy import deepcopy
from dataclasses import dataclass
from itertools import chain
from typing import TYPE_CHECKING, Any, cast
Expand Down Expand Up @@ -207,6 +208,8 @@ def __init__(
self._auto_compile = auto_compile
# name → bound concrete source (user-facing API: job.sources).
self._sources: dict[str, cp.StreamProtocol] = {}
# Saved configs for untouched slots whose sources could not be rebuilt on load.
self._unresolved_sources: dict[str, dict[str, Any]] = {}
self._rebound_source_keys: set[str] = set()
self._sources_as_captured: dict[str, cp.StreamProtocol | None] = {}
self._has_run: bool = False
Expand All @@ -216,6 +219,8 @@ def __init__(
self._run_id: str | None = None
# The summary of the last run this object completed (ITL-997).
self._last_run: RunSummary | None = None
# A loaded job reads the results of the run this record describes.
self._saved_run: dict[str, Any] | None = None
# True for a job built by load(): it reads stored results and never runs.
self._loaded: bool = False

Expand Down Expand Up @@ -700,6 +705,7 @@ def _apply_source_bindings(
slot._apply_binding(source, form) # pyright: ignore[reportPrivateUsage] # install the validated row form
slot._update_modified_time() # pyright: ignore[reportPrivateUsage] # the job owns the slot's binding
self._rebound_source_keys.add(keys[id(slot)])
self._unresolved_sources.pop(slot.name, None)
if source is None:
self._sources.pop(slot.name, None)
else:
Expand Down Expand Up @@ -1756,7 +1762,10 @@ def save(self, path: "str | Path") -> None:
import tempfile
from pathlib import Path as _Path

from orcapod.pipeline.serialization import PIPELINE_JOB_FORMAT_VERSION
from orcapod.pipeline.serialization import (
PIPELINE_JOB_FORMAT_VERSION,
saved_source_identifiers,
)

# Allow save when either compile() was called or _compiled_pipeline is
# pre-set (e.g. result of run() which has no invocation_lut but does
Expand All @@ -1779,8 +1788,7 @@ def save(self, path: "str | Path") -> None:
finally:
os.unlink(tmp_path)

# Serialize source configs (best-effort — skip non-reconstructable sources)
sources_block: dict[str, Any] = {}
sources_block: dict[str, dict[str, Any]] = {}
for spec_name, source in sorted(self._sources.items()):
if hasattr(source, "to_config"):
try:
Expand All @@ -1797,6 +1805,19 @@ def save(self, path: "str | Path") -> None:
else:
sources_block[spec_name] = {"source_type": "unknown"}

if self._unresolved_sources:
# The serialized live bindings take precedence over retained configs
# with the same identity, even after compile() replaces the node map.
live_identities = {
identity
for config in sources_block.values()
for identity in saved_source_identifiers(config)
}
for name, config in self._unresolved_sources.items():
if live_identities.isdisjoint(saved_source_identifiers(config)):
sources_block[name] = config
sources_block = dict(sorted(sources_block.items()))

# Database config (best-effort). A loaded job's database that could not be
# rebuilt is written back as it was saved (ITL-1391).
database_block = self._unresolved_database
Expand All @@ -1810,9 +1831,33 @@ def save(self, path: "str | Path") -> None:
if self._result_database is not None:
result_database_block = self._result_database.to_config()

output: dict[str, Any] = {
"orcapod_pipeline_job_version": PIPELINE_JOB_FORMAT_VERSION,
"orcapod_version": orcapod.__version__,
"run": self._run_record(),
"pipeline": pipeline_data,
"bindings": {
"sources": sources_block,
"database": database_block,
"result_database": result_database_block,
},
}

with open(path, "w") as f:
_json.dump(output, f, indent=2)

def _run_record(self) -> dict[str, Any]:
"""Return the run metadata to write to a job file."""
# Binding and load-only replay do not write a new run's results. A loaded
# job reports the saved run's status and unbound slots, independent of
# which sources are available in this process.
if self._saved_run is not None:
return self._saved_run

unbound_sources = self.unbound_sources
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if not self._has_run:
status = "pending"
elif self.unbound_sources:
elif unbound_sources:
status = "partial"
else:
status = "complete"
Expand Down Expand Up @@ -1848,29 +1893,16 @@ def save(self, path: "str | Path") -> None:
# takes the job's from here, as a function node does (ITL-1094).
node_job_content_hashes[node.label] = node.content_hash().to_string()

output: dict[str, Any] = {
"orcapod_pipeline_job_version": PIPELINE_JOB_FORMAT_VERSION,
"orcapod_version": orcapod.__version__,
"run": {
"run_id": self._run_id,
"status": status,
"unbound_sources": list(self.unbound_sources),
"node_job_content_hashes": node_job_content_hashes,
# A separate, optional section: deleting it changes nothing but the
# check (ITL-1043).
**({"expected_rows": expected_rows} if expected_rows else {}),
},
"pipeline": pipeline_data,
"bindings": {
"sources": sources_block,
"database": database_block,
"result_database": result_database_block,
},
return {
"run_id": self._run_id,
"status": status,
"unbound_sources": unbound_sources,
"node_job_content_hashes": node_job_content_hashes,
# A separate, optional section: deleting it changes nothing but the
# check (ITL-1043).
**({"expected_rows": expected_rows} if expected_rows else {}),
}

with open(path, "w") as f:
_json.dump(output, f, indent=2)

@classmethod
def load(
cls,
Expand All @@ -1892,10 +1924,12 @@ def load(
The embedded ``Pipeline`` blueprint is always restored. Sources whose data
lives in files (CSV, Delta) are rebuilt from the saved config. In-memory
sources (``DictSource``, ``ListSource``, ``ArrowTableSource``,
``DataFrameSource``) are not saved; loading logs that at INFO, and their
source nodes can be read after ``job.bind(sources=...)``. A source that
``DataFrameSource``) save their configuration without their data. Loading
logs that at INFO. Their source nodes can be read after
``job.bind(sources=...)``. A source that
cannot be rebuilt for another reason (a moved file) is logged as a
warning. Neither affects reading the other nodes.
warning. Neither affects reading the other nodes. A subsequent save
preserves the unresolved source configurations and the original run record.

Args:
path: Path to the JSON file produced by ``save()``.
Expand Down Expand Up @@ -2006,6 +2040,7 @@ def load(
if isinstance(node, SourceNodeBase)
}
sources: dict[str, cp.StreamProtocol] = {}
unresolved_sources: dict[str, dict[str, Any]] = {}
sources_by_config: dict[str, cp.StreamProtocol | None] = {}
for spec_name, src_config in (
data.get("bindings", {}).get("sources", {}).items()
Expand Down Expand Up @@ -2034,14 +2069,17 @@ def load(
# Slots written with the same complete config share one rebuild.
config_key = _json.dumps(src_config, sort_keys=True)
if config_key not in sources_by_config:
# Reconstruction can pass the config to a custom source factory.
# Keep the original intact in case it needs to be saved again.
sources_by_config[config_key] = resolve_source_from_config(
src_config
deepcopy(src_config)
)
source = sources_by_config[config_key]
except Exception as exc:
failure = exc
else:
if source is None:
unresolved_sources[spec_name] = src_config
continue
if (dependency := independent_source_dependency(source)) is not None:
raise binding_dependency_error(dependency, spec_name)
Expand All @@ -2054,10 +2092,11 @@ def load(
failure = exc
else:
sources[spec_name] = source
continue

unresolved_sources[spec_name] = src_config
if isinstance(failure, NotImplementedError):
# In-memory sources (DictSource, ListSource, ArrowTableSource,
# DataFrameSource) are not saved with the job, by design.
# In-memory source data is not saved with the job, by design.
logger.info(
"Source %r (%s) keeps its data in memory and is not saved with the "
"job; the loaded job has no data for it. Stored function-node "
Expand Down Expand Up @@ -2201,12 +2240,14 @@ def load(
from orcapod.pipeline.loaded_side_effects import LoadedSideEffectJobNode

job._sources = dict(sources)
job._unresolved_sources = unresolved_sources

# Extract the live (data-inclusive) content hashes saved at run time.
# These are keyed by node label and used below to override the blueprint
# hash stored in each function and operator node descriptor so that loaded stubs'
# content_hash() matches the _node_content_hash column in the DB.
run_block = data.get("run", {})
job._saved_run = run_block
node_job_content_hashes: dict[str, str] = run_block.get(
"node_job_content_hashes", {}
)
Expand Down
17 changes: 17 additions & 0 deletions src/orcapod/pipeline/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,23 @@ def saved_source_id(config: dict[str, Any]) -> str:
return "unknown"


def saved_source_identifiers(config: dict[str, Any]) -> set[tuple[str, str]]:
"""Read the source ID and content hash available without rebuilding a source."""
inner = config.get("inner_source")
while config.get("source_type") == "cached" and isinstance(inner, dict):
config = cast("dict[str, Any]", inner)
inner = config.get("inner_source")

identifiers: set[tuple[str, str]] = set()
source_id = saved_source_id(config)
if source_id != "unknown":
identifiers.add(("source_id", source_id))
content_hash = config.get("content_hash")
if isinstance(content_hash, str):
identifiers.add(("content_hash", content_hash))
return identifiers


def _source_proxy_from_config(
config: dict[str, Any],
node_descriptor: dict[str, Any] | None = None,
Expand Down
Loading
Loading