diff --git a/changelog.d/ITL-1450.md b/changelog.d/ITL-1450.md new file mode 100644 index 000000000..4dbaa7568 --- /dev/null +++ b/changelog.d/ITL-1450.md @@ -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. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index d64b113dc..add8a68b3 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -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 @@ -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 @@ -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 @@ -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: @@ -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 @@ -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: @@ -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 @@ -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 if not self._has_run: status = "pending" - elif self.unbound_sources: + elif unbound_sources: status = "partial" else: status = "complete" @@ -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, @@ -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()``. @@ -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() @@ -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) @@ -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 " @@ -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", {} ) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 0f647fe96..3ea71f25c 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -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, diff --git a/tests/test_pipeline/loaded_job/test_loaded_job_readback.py b/tests/test_pipeline/loaded_job/test_loaded_job_readback.py index bbaa52297..228100b44 100644 --- a/tests/test_pipeline/loaded_job/test_loaded_job_readback.py +++ b/tests/test_pipeline/loaded_job/test_loaded_job_readback.py @@ -713,6 +713,198 @@ def test_saving_a_loaded_job_keeps_the_expected_rows( assert node.as_source().as_table().num_rows == 0 +@pytest.mark.parametrize( + ("slots", "rebind"), + [ + pytest.param(("xs",), False, id="in-memory"), + pytest.param(("csv",), False, id="rebuildable"), + pytest.param(("xs", "csv"), False, id="mixed"), + pytest.param(("ys", "xs"), False, id="two-in-memory"), + pytest.param(("ys", "xs"), True, id="rebind-one"), + ], +) +def test_a_loaded_job_saved_again_keeps_the_record_of_a_source_it_could_not_rebuild( + tmp_path: pathlib.Path, slots: tuple[str, ...], rebind: bool +) -> None: + """Source configs and the saved run survive two fresh-process resaves.""" + from orcapod.sources import CSVSource, ListSource + + csv_path = tmp_path / "input.csv" + _ = csv_path.write_text("x\n7\n") + + @function_pod(output_keys="doubled") + def double(x: int | None) -> int: + """Double the input value.""" + return 2 * (x or 0) + + sources = { + "xs": ListSource("x", [5], source_id="xs"), + "ys": ListSource("x", [6], source_id="ys"), + "csv": CSVSource(str(csv_path), tag_only_columns=True, source_id="csv"), + } + + def record() -> None: + """Record one stored result for each input.""" + for slot in slots: + _ = double.pod(sources[slot], label=f"double_{slot}") + + first = pathlib.Path(_save_small_job(tmp_path, record)) + second = tmp_path / "second.json" + third = tmp_path / "third.json" + resave = """ +import sys +from orcapod import PipelineJob +from orcapod.sources import ListSource + +original, target, rebind, *slots = sys.argv[1:] +job = PipelineJob.load(original) +assert set(job.unbound_sources) == set(slots) - {"csv"} +for slot in slots: + assert job.nodes[f"double_{slot}"].as_source().as_table().num_rows == 1 +if rebind == "True": + job.bind(sources={"xs": ListSource("x", [99], source_id="replacement")}) + assert job.unbound_sources == ["ys"] +job.save(target) +""" + for original, target, bind in ((first, second, rebind), (second, third, False)): + _ = subprocess.run( + [ + sys.executable, + "-c", + resave, + str(original), + str(target), + str(bind), + *slots, + ], + check=True, + ) + + first_data = json.loads(first.read_text()) + assert first_data["run"]["status"] == "complete" + assert first_data["run"]["unbound_sources"] == [] + expected_sources = first_data["bindings"]["sources"] + assert list(expected_sources) == sorted(slots) + if rebind: + replacement = ListSource("x", [99], source_id="replacement").to_config() + assert replacement != expected_sources["xs"] + expected_sources["xs"] = replacement + for path in (second, third): + data = json.loads(path.read_text()) + # Compare the order of both slot names and keys inside each config. + assert json.dumps(data["bindings"]["sources"]) == json.dumps(expected_sources) + assert data["run"] == first_data["run"] + + +@pytest.mark.parametrize( + ("change", "after_bind"), + [ + pytest.param("unbind", (), id="unbind"), + pytest.param("bind-with-different-keys", (), id="bind-with-different-keys"), + pytest.param("bind-with-same-hash", (), id="bind-with-same-hash"), + pytest.param("bind-with-different-keys", ("compile",), id="compile"), + pytest.param( + "bind-with-different-keys", ("compile", "load-only"), id="compile-load-only" + ), + pytest.param( + "bind-with-different-keys", ("compile", "compile"), id="compile-twice" + ), + ], +) +def test_resaving_a_loaded_job_respects_binding_changes( + tmp_path: pathlib.Path, change: str, after_bind: tuple[str, ...] +) -> None: + """Reload keeps the explicit binding change after the missing CSV returns.""" + from orcapod.sources import CSVSource + + left_path = tmp_path / "left.csv" + right_path = tmp_path / "right.csv" + replacement = tmp_path / "replacement.csv" + _ = left_path.write_text("x\n7\n") + _ = right_path.write_text("x\n8\n") + _ = replacement.write_text("x\n7\n") + + @function_pod(output_keys="doubled") + def double(x: int | None) -> int: + """Double the input value.""" + return 2 * (x or 0) + + left = CSVSource(str(left_path), source_id="left") + right = CSVSource(str(right_path), source_id="right") + + def record() -> None: + """Record a node for each source slot.""" + _ = double.pod(left, label="double_left") + _ = double.pod(right, label="double_right") + + first = _save_small_job(tmp_path, record) + moved_path = left_path.rename(tmp_path / "moved.csv") + resaved = tmp_path / "resaved.json" + _ = subprocess.run( + [ + sys.executable, + "-c", + """ +import sys +from orcapod import PipelineJob +from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.sources import CSVSource + +original, target, change, replacement, original_hash, *after_bind = sys.argv[1:] +job = PipelineJob.load(original) +assert job.unbound_sources == ["left"] +if change == "unbind": + left = next( + node for node in job.dag.nodes() + if isinstance(node, SourceJobNode) and node.name == "left" + ) + left.bound_source = None +else: + keys = "x" if change == "bind-with-different-keys" else None + source = CSVSource(replacement, source_id="left", record_id_columns=keys) + if keys is None: + assert source.content_hash().to_string() == original_hash + job.bind(sources={"right": source}) +for action in after_bind: + if action == "compile": + job.compile() + elif action == "load-only": + job.run(load_only=True) +job.save(target) +""", + first, + str(resaved), + change, + str(replacement), + left.content_hash().to_string(), + *after_bind, + ], + check=True, + ) + _ = moved_path.rename(left_path) + _ = subprocess.run( + [ + sys.executable, + "-c", + """ +import sys +from orcapod import PipelineJob + +saved, expected_name, *after_bind = sys.argv[1:] +job = PipelineJob.load(saved) +if not after_bind: + assert job.unbound_sources == ["left"] +assert job.sources["right"].source_name == expected_name +""", + str(resaved), + "right" if change == "unbind" else "left", + *after_bind, + ], + check=True, + ) + assert list(json.loads(resaved.read_text())["bindings"]["sources"]) == ["right"] + + def test_loaded_function_node_with_nothing_stored_returns_zero_rows( saved: pathlib.Path, tmp_path: pathlib.Path ) -> None: