diff --git a/changelog.d/ITL-1467.md b/changelog.d/ITL-1467.md new file mode 100644 index 000000000..491a21184 --- /dev/null +++ b/changelog.d/ITL-1467.md @@ -0,0 +1,11 @@ +### Added + +- `RunSummary.skipped_unbound_sources` maps each skipped node to the unbound source slots that blocked it. + +### Fixed + +- Load-only run summaries report nodes skipped for unbound sources, including when no node ran. +- Loading a saved job leaves missing Delta stores, source caches, and SQLite input database files absent. A local Delta store requires directories for the saved root and any saved scope. +- Saving a loaded job retains the recorded locations of stores that could not be opened. +- Load-only runs read existing source cache rows without writing to the cache or changing the source state used by a full run. +- SQLite sources save the original filesystem path text, including for path-like objects. Restored sources preserve literal filenames, including `file:` prefixes and `..` after a symlink. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 8aebfb95f..039f04179 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -671,7 +671,11 @@ but it does compute the results that are missing. `job.run(load_only=True)` fill with what is already stored for this run's inputs and never computes: sources are read, operators run on the rows that reach them, each function node takes the stored results of its inputs and skips the inputs that have none, no side effect is delivered and nothing is -written to the database. The summary counts what each node loaded and skipped: +written to the database. A cached source checks its store on each run and reads only the +rows already there. If it has no stored rows, it warns and supplies an empty input. +These cache snapshots, including those read through a derived source, leave the source's +full-run rows and modification time intact. +The summary counts what each node loaded and skipped: ```python more_mice = mice + [{"subject_id": "mouse_04", "weight": 30.0, "height": 0.12}] @@ -699,6 +703,10 @@ incomplete: a group formed after it may lack members, and the result stored for group by an earlier run may then be loaded for it. `run_async(load_only=True)` does the same on the asynchronous orchestrator. +A run skips unbound source slots and every node that depends on them. The summary lists those +nodes and the slots blocking each one in `summary.skipped_unbound_sources`. Bind the missing +sources with `job.bind(sources=...)` to include those nodes on the next run. + A load-only run reads only job nodes, sources and streams that neither compute nor deliver. A pod's stream built outside the job (a function pod's, which computes when it is read, or a side-effect pod's, which delivers) is refused with a `ValueError` before anything is read, @@ -1023,6 +1031,19 @@ file saved by an earlier release (format `0.1.0` to `0.3.0`) is refused, with a saying so. Rebuild the pipeline from code and save it again; taking older files to the current format is the work of a separate migration tool, not of `load`. +For a saved local Delta database, `load()` requires directories for its saved root +and any saved scope. A directory can hold zero Delta tables. If either path is +missing or is a file, loading warns and +leaves the database unbound. Use +`PipelineJob.load(path, database=...)` to give the job a moved store, or +`PipelineJob.load(path, result_database=...)` for a moved separate result store. +If a cached source's Delta cache cannot be opened, its source slot stays unbound. +For a remote Delta database, the connection is deferred until the store is accessed. +Saving the loaded job retains unavailable store and source cache locations. + +See [Saving and loading](pipeline-job.md#saving-and-loading) for how loading handles +SQLite source paths and write-ahead log files. + For example: ```python @@ -1057,7 +1078,7 @@ loaded job cannot compute: function pods are not saved with it, so `loaded.run() `loaded.run(load_only=True)` fills its nodes from the database instead, as for any job (see *Loading without computing* above): the sources are read (an in-memory source must be bound first, since its data is not saved), the rebuilt operators run, and each function node takes -the results stored for those inputs. Nodes below a source that is not available stay empty. +the results stored for those inputs. The run summary lists the nodes skipped for unbound sources. `node.run(load_only=True)` does the same for one node and what it depends on. ```python diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 41a19df1b..6a34dae08 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -359,9 +359,10 @@ tag_schema=Schema({...}), data_schema=Schema({...}))`) means one Arrow type per zones, declare the slot with Arrow schemas (`tag_schema=pa.schema([...])`). Binding a source never changes a node's schema or where its results are stored. -A job made without sources has **unbound** slots. It can still be run: nodes that depend on -an unbound source are skipped, and `job.unbound_sources` lists what is missing. Bind later -with `job.bind(...)`: +A job made without sources has **unbound** slots. It can still run the parts of the +pipeline with bound inputs. `job.unbound_sources` lists the missing slots, and +`summary.skipped_unbound_sources` maps each skipped node to the slots blocking it. +Bind a source later with `job.bind(...)`: ```python job_c = PipelineJob.from_pipeline(pipeline, database=database) @@ -478,11 +479,40 @@ the **Nodes** table below the picture for each node's columns and status. ## Saving and loading `job.save(path)` writes the job to a JSON file: the graph, the database's location (and the -result database's, when one was given) and how each source was configured. `PipelineJob.load(path)` reads it back, for example in a later -Python session. An `InMemoryArrowDatabase` has no location to record, so here the database -is passed again; `PipelineJob.load(path, database=...)` is also how you point a loaded job -at a database that has moved, and `PipelineJob.load(path, result_database=...)` at a result -database. The file records each node's own Arrow types, so saving types +result database's, when one was given) and how each source was configured. +`PipelineJob.load(path)` reads it back, for example in a later Python session. Pass the +original `InMemoryArrowDatabase` again to read its rows in the same process. For a +local Delta store, loading requires existing directories for the saved root and +any saved scope under it. +If the path is missing or is a file, loading warns and leaves the database unbound. +This also applies to a source's Delta cache, in which case the source slot stays +unbound. Open a moved store by passing `database=...` or `result_database=...` to +`PipelineJob.load()`. Bind a cached source with `job.bind(sources=...)` after giving +it the cache's new location. An existing directory opens even if it holds no Delta +tables. A remote Delta store's location is checked when it is accessed. + +Saving a loaded job keeps the recorded locations of databases and source caches +that could not be opened, so a later load can find them when they return. + +Loading a job creates no files or directories, with one exception. If an existing +SQLite database uses write-ahead logging (WAL), you may see `-wal` and `-shm` +files appear next to it. SQLite can create these working files as part of opening +the database in read-only mode. This is expected and harmless. Orcapod writes +nothing to the database. A missing SQLite database file stays absent and its +source slot stays unbound. + +SQLite saves the supplied path text and uses it in the default source ID. A +relative path stays relative in the saved job, so loading the job in a different +working directory reads relative to that directory. Each live or restored source +pins its absolute filename when built and keeps using it after a working-directory +change. SQLite treats a `file:` prefix as part of the filename and follows symlinks +as it opens the file, including when a symlink is followed by `..`. + +The `create_base_path` option on `DeltaTableDatabase.from_config()` is +**provisional**. Passing `False` requires the saved local root and scope directories +to exist. Job loading uses this setting. + +The file records each node's own Arrow types, so saving types every node from its inputs' types, as previewing an empty job does, and costs what that preview costs: a pipeline whose joins keep many system-tag columns saves as slowly as it previews. @@ -504,9 +534,9 @@ not their code, so a loaded job cannot compute: `as_source()` read what the database holds for the node: here the three rows of cohort A and the one of cohort B, because both cohorts were read through a source named `"mice"`. - `loaded.run()` raises `RuntimeError`. To compute, run the code that defines the pipeline. -- `loaded.run(load_only=True)` fills the nodes with the stored results for the sources' - current rows, computing nothing. An in-memory source such as `DictSource` is not saved - with the job, so bind it first: +- `loaded.run(load_only=True)` fills the nodes with stored results for the bound + sources' current rows. It computes nothing. The data in a `DictSource` is kept in + memory, so the summary names the skipped nodes and their blocking slot until you bind it. ```python try: @@ -515,6 +545,11 @@ except RuntimeError: print("a loaded job cannot compute") # a loaded job cannot compute +print(loaded.run(load_only=True)) +# Load-only run of job 'bmi': no nodes ran. +# 'bmi': skipped (unbound sources: 'mice') +# 'mice': skipped (unbound sources: 'mice') + loaded.bind(sources={"mice": mice(cohort_a)}) summary = loaded.run(load_only=True) print(loaded.nodes["bmi"].as_table().num_rows, summary.nodes["bmi"].not_stored) diff --git a/docs/dev/plans/ITL-1467.md b/docs/dev/plans/ITL-1467.md new file mode 100644 index 000000000..758b9cff1 --- /dev/null +++ b/docs/dev/plans/ITL-1467.md @@ -0,0 +1,75 @@ +# ITL-1467 — Report nodes skipped for unbound sources and open existing stores + +## Reproduced on origin/main + +Run `uv run python docs/dev/scripts/itl_1467/reproduce.py` on `5eb327ad`. A job +over a saved `DictSource` slot loads with the slot unbound. With either the +original in-memory database or a Delta database supplied, the downstream +function has zero rows and the summary says “nothing to do; every node holds a +current run.” Moving a relative Delta store and loading without an override +recreates the empty root in the current working directory. The stored view +returns zero rows and warns when read. + +## Run summary + +`PipelineJob._prepare_run` excludes unbound slots and their descendants before +`plan_run` applies the held-node state rule. The summary sees only the remaining +graph. An empty `plan.to_run` therefore cannot establish that every node was +held. + +Carry the exclusion reasons through the job's shared run preparation and +completion paths. Propagate the unbound slot names through the saved graph and +include only restored job nodes in the result. Add +`RunSummary.skipped_unbound_sources: Mapping[str, tuple[str, ...]]`, keyed by +skipped node label with sorted, unique blocking slot names. Include unbound +slots themselves. Keep `RunSummary.nodes` and `NodeRunSummary.held` as the +function and side-effect row counts for the resolvable graph. +`ran_nothing` still means that no node was run. + +When there are exclusions and no node ran, use this headline: + +> Load-only run of job 'small': no nodes ran. + +When a partial load-only run ran nodes and had no stored-result misses, use +`every available input had a stored result.` in place of +`every input had a stored result.` The stored-result miss headline stays the +same. Under the headline, in text and notebook HTML, list the excluded nodes +by label using this wording (both the node label and each slot name are +represented as Python strings): + +```text + 'joined': skipped (unbound sources: 'memory') + 'memory': skipped (unbound sources: 'memory') + 'total': skipped (unbound sources: 'memory') +``` + +Use the same skip lines for partial full runs of freshly compiled jobs. The +held headline still applies when there are no exclusions. + +## Reopen the existing database + +`DeltaTableDatabase.from_config` always requests local root creation, including +when the read-only job loader calls it. Give Delta config resolution a way to +require an existing local root. Use it for both the saved job and separate +result databases, so a missing root takes the existing load-time warning and +override/bind path. Continue honoring explicit overrides, relative path +resolution, and remote Delta behavior. Retain creation defaults for callers +that reconstruct a store for writing. Apply the same rule when rebuilding a +saved source's Delta cache. The root and any saved scope must be directories. +A missing directory or regular file leaves the binding unavailable, and saving +the job preserves the configuration. An existing directory can open with zero +Delta tables. Open existing SQLite source files read-only; SQLite can still +make its own working files while reading an existing WAL database. Restore the +embedded blueprint directly from the decoded job instead of using a temporary +file. There is no saved-format, stored-path, or identity change. + +## Verification + +Write public regression tests before library edits. Exercise memory and Delta, +sync and async, using a rebuilt CSV and a skipped in-memory source with two tag +and two data columns, a function and an operator. Check the summary fields and +text, including the no-execution and partial-execution cases and an unchanged +rerun. Check directory absence in a temporary working directory after loading +a moved Delta store, the warning and the explicit override. Update the +published load and load-only documentation and add the issue changelog +fragment. Run targeted tests and the golden check without updating goldens. diff --git a/docs/dev/scripts/itl_1467/reproduce.py b/docs/dev/scripts/itl_1467/reproduce.py new file mode 100644 index 000000000..b14d9042a --- /dev/null +++ b/docs/dev/scripts/itl_1467/reproduce.py @@ -0,0 +1,56 @@ +"""Reproduce both ITL-1467 symptoms on origin/main at 5eb327ad.""" + +from contextlib import chdir +from pathlib import Path +from tempfile import TemporaryDirectory + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes import FunctionJobNode +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.sources import DictSource + + +@function_pod(output_keys="total") +def total(x: int, y: int) -> int: + """Add the two data values.""" + return x + y + + +def make_job(database: InMemoryArrowDatabase | DeltaTableDatabase) -> None: + """Run and save a job over a source whose data is not saved.""" + source = DictSource( + [{"id": 1, "group": "a", "x": 2, "y": 3}], + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="memory", + ) + job = PipelineJob(name="small", database=database) + with job: + _ = total.pod(source, label="total") + _ = job.run() + job.save("job.json") + + +def main() -> None: + """Show the load-only summary and the creation of a missing Delta root.""" + with TemporaryDirectory() as directory, chdir(directory): + for database in (InMemoryArrowDatabase(), DeltaTableDatabase("store")): + make_job(database) + loaded = PipelineJob.load("job.json", database=database) + print(type(database).__name__, loaded.unbound_sources) + print(loaded.run(load_only=True)) + node = loaded.nodes["total"] + assert isinstance(node, FunctionJobNode) + print("function rows:", node.as_table().num_rows) + + _ = Path("store").rename("moved") + print("store exists before load:", Path("store").exists()) + loaded = PipelineJob.load("job.json") + print("store exists after load:", Path("store").exists()) + node = loaded.nodes["total"] + assert isinstance(node, FunctionJobNode) + print("stored rows:", node.as_source().as_table().num_rows) + + +if __name__ == "__main__": + main() diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 22282a2f7..e5a33c4a2 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -294,7 +294,8 @@ and what the pipeline imports must be there. - The job was read with `PipelineJob.load()`. A loaded job's nodes read empty until `loaded.run(load_only=True)`. - A source of the job is not bound. `job.unbound_sources` lists such sources; the nodes - below them do not run. + below them do not run. The run summary's `skipped_unbound_sources` field names the + skipped nodes and which slots to bind. **Fix.** Call `job.run()`, then read `job.nodes[label]`. To see everything the database holds for a node, whatever run it came from, use `job.nodes[label].as_source()`. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9a0353053..80879910f 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -376,6 +376,7 @@ def run_job_node( sources the check could not check; returns its ``RunSummary`` or ``None``. caller: The frame of the ``run()`` caller. """ + from orcapod.core.sources.cached_source import stored_source_caches from orcapod.pipeline.node_run import ( check_sources, depends_on_job_nodes, @@ -385,27 +386,28 @@ def run_job_node( from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures - # A source read under two restrictions, or a caching operator over a restricted - # source, is refused before any source is checked and before anything is - # computed or written (ITL-1218). - refuse_restriction_conflicts([node]) - # Every source feeding the run first takes in any new data (ITL-1102). - unchecked = check_sources([node]) - if node.holds_current_run(load_only=load_only): - return - if depends_on_job_nodes(node): - summary = run_with_dependencies( - node, load_only=load_only, unchecked_sources=unchecked - ) - else: - if load_only: - refuse_unloadable_inputs(node) - summary = run_alone(unchecked) - if summary is None: - return - node._last_run = summary - if not summary.ok: - warn_row_failures(summary, caller) + with stored_source_caches(load_only): + # A source read under two restrictions, or a caching operator over a restricted + # source, is refused before any source is checked and before anything is + # computed or written (ITL-1218). + refuse_restriction_conflicts([node]) + # Every source feeding the run first takes in any new data (ITL-1102). + unchecked = check_sources([node]) + if node.holds_current_run(load_only=load_only): + return + if depends_on_job_nodes(node): + summary = run_with_dependencies( + node, load_only=load_only, unchecked_sources=unchecked + ) + else: + if load_only: + refuse_unloadable_inputs(node) + summary = run_alone(unchecked) + if summary is None: + return + node._last_run = summary + if not summary.ok: + warn_row_failures(summary, caller) class FunctionNodeBase(StreamBase): diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..e47124745 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -97,6 +97,7 @@ logger = logging.getLogger(__name__) if TYPE_CHECKING: + from types import FrameType from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -1882,6 +1883,18 @@ def run(self, *, load_only: bool = False) -> StreamView: ValueError: If this node or one it depends on caches (``LOG`` or ``REPLAY``) over a restricted source (ITL-1218); nothing has run. """ + from orcapod.core.sources.cached_source import stored_source_caches + + with stored_source_caches(load_only): + return self._run_in_source_context( + load_only=load_only, + caller=sys._getframe(1), # pyright: ignore[reportPrivateUsage] # warning belongs at the caller's line + ) + + def _run_in_source_context( + self, *, load_only: bool, caller: FrameType + ) -> StreamView: + """Run with the source cache policy chosen by ``run()``.""" from orcapod.pipeline.node_run import ( check_sources, depends_on_job_nodes, @@ -1907,7 +1920,7 @@ def run(self, *, load_only: bool = False) -> StreamView: ) self._last_run = summary if not summary.ok: - warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + warn_row_failures(summary, caller) return self._run_view(computed=False) if self._loaded: raise self._cannot_compute_error() diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..eeff1c66f 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1647,24 +1647,25 @@ def run(self, *, load_only: bool = False) -> StreamView: As every job node's ``run()``, it first checks the bound source for new data (``check_sources``, ITL-1102): a check that raises warns (``SourceCheckFailedWarning``) and the source's held rows are read. A source is - read, never computed, so ``load_only`` changes nothing, except that a load-only - run refuses a bound stream that computes or delivers when read (ITL-1121); a job - node's ``run()`` takes it (ITL-1095). + read, never computed. A load-only run reads stored source cache rows + and refuses a bound stream that computes or delivers when read (ITL-1121). Args: - load_only: Accepted for every job node; a source reads its rows either way. + load_only: Read source caches without ingesting live rows. Raises: UnboundSourceError: When no concrete source is bound. ValueError: If ``load_only`` and the bound stream computes or delivers when read (``node_run.refuse_unloadable_inputs``). """ + from orcapod.core.sources.cached_source import stored_source_caches from orcapod.pipeline.node_run import check_sources, refuse_unloadable_inputs - _ = check_sources([self]) - if load_only: - refuse_unloadable_inputs(self) - return super().run() + with stored_source_caches(load_only): + _ = check_sources([self]) + if load_only: + refuse_unloadable_inputs(self) + return super().run() @property def bound_source(self) -> StreamProtocol | None: diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..88b637ddb 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -2,7 +2,9 @@ import logging -from datetime import datetime +from contextlib import contextmanager +from contextvars import ContextVar +from datetime import datetime, timezone from collections.abc import Iterator from typing import Any, ClassVar, TYPE_CHECKING @@ -52,6 +54,23 @@ logger = logging.getLogger(__name__) +stored_source_streams: ContextVar[dict[int, ArrowTableStream] | None] = ContextVar( + "stored_source_streams", default=None +) + + +@contextmanager +def stored_source_caches(load_only: bool) -> Iterator[None]: + """Share snapshots of source caches for the duration of a load-only run.""" + if not load_only or stored_source_streams.get() is not None: + yield + return + token = stored_source_streams.set({}) + try: + yield + finally: + stored_source_streams.reset(token) + class CachedSource(RootSource): """DB-backed wrapper around a source that caches every data. @@ -151,6 +170,8 @@ def __init__( # built; ``None`` before a build. A cache shared with another source can hold # rows this source has not presented yet (ITL-1102). self._presented_hashes: set[bytes] | None = None + self._load_only_hashes: set[bytes] | None = None + self._load_only_modified_time: datetime | None = None # ------------------------------------------------------------------------- # Serialization @@ -206,6 +227,8 @@ def from_config( ``SourceProxy`` preserving the original source's identity. The CachedSource can still serve data from its cache database. + A saved local Delta cache must already have a root directory. + Args: config: Dict as produced by ``to_config``. db_registry: Optional registry. When ``cache_database`` is a @@ -215,6 +238,10 @@ def from_config( Returns: A new CachedSource constructed from the config. + + Raises: + ValueError: If a registry reference cannot be resolved without a + registry, or if a local Delta cache has no root directory. """ from orcapod.pipeline.serialization import ( resolve_database_from_config, @@ -228,9 +255,10 @@ def from_config( f"cache_database is a registry key {cache_db_ref!r} but no " "db_registry was provided." ) - cache_db = resolve_database_from_config(db_registry.resolve(cache_db_ref)) + cache_config = db_registry.resolve(cache_db_ref) else: - cache_db = resolve_database_from_config(cache_db_ref) + cache_config = cache_db_ref + cache_db = resolve_database_from_config(cache_config, create_base_path=False) # All sources accept db_registry — always forward it so nested # CachedSources can resolve their own cache database references. @@ -459,6 +487,11 @@ def check_for_new_data(self) -> bool: CachedSourceIdMismatchError: If the cache holds rows of another source id; raised before the wrapped source is checked (ITL-1425). """ + snapshots = stored_source_streams.get() + if snapshots is not None: + previous = self._load_only_hashes + _ = self._stored_stream(snapshots) + return previous != self._load_only_hashes if not isinstance(self._source, RootSource): return False # The cache first: a cache of another source id is refused before the @@ -585,7 +618,7 @@ def _require_source_ids(self, records: pa.Table) -> None: "cache database), or the reader's version pinned to the one that " "wrote it." ) - if stored_ids: + if stored_ids and stored_source_streams.get() is None: self._source_ids_checked = True def _build_merged_stream(self) -> ArrowTableStream: @@ -605,18 +638,52 @@ def _build_merged_stream(self) -> ArrowTableStream: ) stored = self._read_cached_records_with_hashes() + self._presented_hashes = self._record_hashes(stored) + self._note_stored_hashes(self._presented_hashes) + return self._stream_from_records(stored) + + def _record_hashes(self, stored: pa.Table | None) -> set[bytes]: + """Return the row identities held in a cache snapshot.""" if stored is None: - self._presented_hashes = set() - all_records = self._empty_table() - else: - self._presented_hashes = { - h - for h in stored.column(self.HASH_COLUMN_NAME).to_pylist() - if h is not None - } - all_records = stored.drop( - [self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL] + return set() + return { + value + for value in stored.column(self.HASH_COLUMN_NAME).to_pylist() + if value is not None + } + + def _stored_stream( + self, snapshots: dict[int, ArrowTableStream] + ) -> ArrowTableStream: + """Snapshot stored cache rows for this run without ingesting live data.""" + if id(self) in snapshots: + return snapshots[id(self)] + self._cache_database.refresh_table(self.cache_path) + records = self._read_cached_records_with_hashes() + hashes = self._record_hashes(records) + stream = self._stream_from_records(records) + if not hashes: + logger.warning( + "Cached source %r has no stored rows for this load-only run.", + self.source_id, ) + self._note_stored_hashes(hashes) + snapshots[id(self)] = stream + return stream + + def _note_stored_hashes(self, hashes: set[bytes]) -> None: + """Track changes to the stored view, including rows written by a full read.""" + if hashes != self._load_only_hashes: + self._load_only_hashes = hashes + self._load_only_modified_time = datetime.now(timezone.utc) + + def _stream_from_records(self, stored: pa.Table | None) -> ArrowTableStream: + """Present stored cache rows using the wrapped source's schema.""" + all_records = ( + self._empty_table() + if stored is None + else stored.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]) + ) tag_keys = self._source.keys()[0] # Cached rows are this source's: give them its data context, not the default. @@ -671,6 +738,14 @@ def _empty_table(self) -> pa.Table: arrow_schema = type_converter.python_schema_to_arrow_schema(merged) return pa.Table.from_pylist([], schema=arrow_schema) + @property + @override + def last_modified(self) -> datetime | None: + """Report the timestamp for the view the current run can read.""" + if stored_source_streams.get() is not None: + return self._load_only_modified_time + return super().last_modified + @property def is_stale(self) -> bool: """True if the wrapped source has been modified since the last build. @@ -684,22 +759,24 @@ def is_stale(self) -> bool: src_time = self._source.last_modified return src_time is None or src_time > own_time - def _ensure_stream(self) -> None: - """Build the merged stream on first access, or rebuild if source is stale.""" + def _current_stream(self) -> ArrowTableStream: + """Read the run's snapshot or build the merged stream when stale.""" + snapshots = stored_source_streams.get() + if snapshots is not None: + return self._stored_stream(snapshots) if self._cached_stream is not None and self.is_stale: self._cached_stream = None if self._cached_stream is None: self._cached_stream = self._build_merged_stream() self._update_modified_time() + return self._cached_stream def clear_cache(self) -> None: """Discard in-memory cached stream (forces rebuild on next access).""" self._cached_stream = None def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - self._ensure_stream() - assert self._cached_stream is not None - return self._cached_stream.iter_data() + return self._current_stream().iter_data() def as_table( self, @@ -707,9 +784,7 @@ def as_table( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> "pa.Table": - self._ensure_stream() - assert self._cached_stream is not None - return self._cached_stream.as_table(columns=columns, all_info=all_info) + return self._current_stream().as_table(columns=columns, all_info=all_info) def _typed_zero_row_table(self) -> "pa.Table | None": """The wrapped source's zero-row table: the cache stores that source's rows. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..9014b9790 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -15,6 +15,7 @@ from typing_extensions import override from orcapod.core.sources.base import RootSource +from orcapod.core.sources.cached_source import CachedSource, stored_source_streams from orcapod.core.sources.provisional import warn_provisional_source from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import hash_source_name @@ -291,6 +292,9 @@ def __init__( source_id = hash_source_name(origin.content_hash()) super().__init__(source_id=source_id, **kwargs) self._origin = origin + self._uses_source_cache = isinstance(origin, CachedSource) or ( + isinstance(origin, DerivedSource) and origin._uses_source_cache + ) self._record_id_columns = key_columns self._key_columns = key_columns or () self._cached_table: pa.Table | None = None @@ -618,6 +622,14 @@ def _get_stream(self) -> ArrowTableStream: # Every read of rows notes the provisional use, also of rows kept from an # earlier read (ITL-1331), as a provisional operator's stream does. self._note_provisional_identity_use() + snapshots = stored_source_streams.get() + if self._uses_source_cache and snapshots is not None: + if id(self) not in snapshots: + records = self._origin_records() + snapshots[id(self)] = self._stream_over( + records if records is not None else self._empty_origin_table() + ) + return snapshots[id(self)] if self._tags_as_data is not None: if self._cached_stream is not None: return self._cached_stream @@ -668,7 +680,9 @@ def check_for_new_data(self) -> bool: none and its origin changed. """ if isinstance(self._origin, RootSource): - _ = self._origin.check_for_new_data() + changed = self._origin.check_for_new_data() + if self._uses_source_cache and stored_source_streams.get() is not None: + return changed seen = self._origin.last_modified if seen == self._origin_seen: return False @@ -699,6 +713,14 @@ def check_for_new_data(self) -> bool: self._update_modified_time() return True + @property + @override + def last_modified(self) -> datetime | None: + """Use the cache snapshot's time only while reading its load-only view.""" + if self._uses_source_cache and stored_source_streams.get() is not None: + return self._origin.last_modified + return super().last_modified + def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the origin.""" return schema_requires_io(self._origin, config) diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..e941c54e2 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -26,6 +26,7 @@ import os from collections.abc import Collection, Iterator from contextlib import contextmanager +from pathlib import PurePath from typing import Any, ClassVar, TYPE_CHECKING from orcapod.core.data_tags import TagOnlyColumns @@ -44,15 +45,21 @@ from orcapod.config import OrcapodConfig -def _access_path(db_path: str | os.PathLike[str]) -> str | os.PathLike[str]: +def _access_path(db_path: str) -> str: """The path a later read opens: a file path made absolute, a special name as given. - ``":memory:"`` and ``file:`` URIs are not file system paths. + SQLite's empty and in-memory database names are kept as given. """ - text = os.fspath(db_path) - if text == ":memory:" or text.startswith("file:"): + if db_path in {"", ":memory:"} or PurePath(db_path).is_absolute(): return db_path - return os.path.abspath(text) + # Pin the directory without normalizing the filename. The filesystem must + # still follow a symlink before processing a following '..'. + pinned = os.path.join(os.getcwd(), db_path) + if PurePath(pinned).is_absolute(): + return pinned + # A relative Windows filename on another drive uses that drive's current + # directory. Resolve only the bare drive before appending the original name. + return os.path.join(os.path.abspath(PurePath(db_path).drive), db_path) class SQLiteTableSource(DBTableSource): @@ -75,8 +82,9 @@ class SQLiteTableSource(DBTableSource): connection is released immediately to avoid holding file locks. Args: - db_path: Path to the SQLite database file, or ``":memory:"`` for an - in-process in-memory database. + db_path: String or path-like object for the SQLite database file, or + ``":memory:"`` for an in-process in-memory database. The original path + text supplies the default source name and is saved in the configuration. table_name: Name of the table to expose as a source. tag_columns: Columns to use as tag columns. A bare string is accepted as a single column name. If ``None`` (default), @@ -108,7 +116,7 @@ class SQLiteTableSource(DBTableSource): def __init__( self, - db_path: str | os.PathLike, + db_path: str | os.PathLike[str], table_name: str, tag_columns: str | Collection[str] | None = None, system_tag_columns: Collection[str] = (), @@ -119,12 +127,13 @@ def __init__( config: "OrcapodConfig | None" = None, *, tag_only_columns: TagOnlyColumns = (), + _read_only: bool = False, ) -> None: - self._db_path = db_path - # A check (ITL-1102) reopens the database found now, whatever the working - # directory is then; an in-memory database or a URI is kept as given. - self._access_path: str | os.PathLike[str] = _access_path(db_path) - connector = SQLiteConnector(db_path) + self._db_path = os.fspath(db_path) + # Keep the original name for configuration and identity, and pin where reads go. + self._access_path = _access_path(self._db_path) + self._read_only = _read_only + connector = SQLiteConnector(self._access_path, _read_only=_read_only) try: # A missing table is reported as missing, not as a table without a key. @@ -201,7 +210,7 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str # The path is read up to the last ``:main.``, so only the table name must not # hold a ``:``; the path is kept as passed, colons included (``C:\\data``). table = joined_location(":", f"main.{table_name}") - return f"{os.fspath(self._db_path)}:{table}" + return f"{self._db_path}:{table}" @contextmanager @override @@ -210,7 +219,7 @@ def _open_connector(self) -> Iterator[SQLiteConnector]: The connector the source was built with was closed once the table was read. """ - connector = SQLiteConnector(self._access_path) + connector = SQLiteConnector(self._access_path, _read_only=self._read_only) try: yield connector finally: @@ -220,7 +229,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize source configuration to a JSON-compatible dict.""" base = super().to_config() base.pop("connector", None) - return {**base, "source_type": self.SOURCE_KIND, "db_path": str(self._db_path)} + return {**base, "source_type": self.SOURCE_KIND, "db_path": self._db_path} @classmethod def from_config( @@ -234,9 +243,12 @@ def from_config( Returns: A new ``SQLiteTableSource`` instance. - Note: - ``:memory:`` sources cannot be reconstructed — the new in-memory - database will be empty and ``ValueError`` will be raised. + The database file must already exist. SQLite opens it read-only and may + create its own WAL working files while reading an existing WAL database. + + Raises: + ValueError: If the saved source was in memory. + sqlite3.OperationalError: If the database file cannot be opened. """ return cls._from_saved_name( config, @@ -250,5 +262,6 @@ def from_config( source_id=name, label=config.get("label"), data_context=config.get("data_context"), + _read_only=True, ), ) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..7819c9904 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1760,6 +1760,7 @@ def __init__( self._path_prefix = _path_prefix self._root = _root self._scoped_path = _scoped_path + self._create_base_path = create_base_path self.batch_size = batch_size self.max_hierarchy_depth = max_hierarchy_depth self.allow_schema_evolution = allow_schema_evolution @@ -1770,9 +1771,10 @@ def __init__( 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(): + elif not self._local_root.is_dir(): raise ValueError( - f"Base path {self._local_root} does not exist and create_base_path=False" + 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). @@ -3407,12 +3409,20 @@ def to_config(self, db_registry: Any = None) -> 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: The saved database configuration. + create_base_path: PROVISIONAL. Create a missing local root when true. When false, + require existing directories for the root and the saved scope. + Remote stores are opened lazily. """ if "root_uri" in config: # Current format (post-ENG-341) @@ -3425,15 +3435,26 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": # Legacy format (pre-ENG-341): "base_path" was the root URI string root_uri = config["base_path"] _path_prefix = () - return cls( + database = cls( base_path=root_uri, storage_options=config.get("storage_options"), - 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), _path_prefix=_path_prefix, ) + if not create_base_path: + database._require_existing_scope() + return database + + def _require_existing_scope(self) -> None: + """Validate a saved local scope without creating it.""" + if self._is_cloud or not self._path_prefix: + return + scope = Path(self._get_table_uri(())) + if not scope.is_dir(): + raise ValueError(f"Delta store scope {scope} is not an existing directory") @property def keeps_field_metadata(self) -> bool: @@ -4281,6 +4302,7 @@ def at(self, *path_components: str) -> "DeltaTableDatabase": return DeltaTableDatabase( base_path=self._root_uri, storage_options=self._storage_options, + create_base_path=self._create_base_path, batch_size=self.batch_size, max_hierarchy_depth=self.max_hierarchy_depth, allow_schema_evolution=self.allow_schema_evolution, diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index e3bb8e10f..9b578189b 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -19,6 +19,7 @@ import sqlite3 import threading from collections.abc import Iterator +from pathlib import Path from typing import Any import pyarrow as pa @@ -238,10 +239,26 @@ class SQLiteConnector: in-process in-memory database. Defaults to ":memory:". """ - def __init__(self, db_path: str | os.PathLike = ":memory:") -> None: + def __init__( + self, + db_path: str | os.PathLike[str] = ":memory:", + *, + _read_only: bool = False, + ) -> None: self._db_path = db_path + location = str(db_path) + if _read_only: + if location in {"", ":memory:"}: + raise ValueError( + "A saved SQLite source requires an existing database file" + ) + # The source has pinned the absolute filename without normalising it. + location = f"{Path(location).as_uri()}?mode=ro" self._conn: sqlite3.Connection | None = sqlite3.connect( - str(db_path), check_same_thread=False, isolation_level=None + location, + uri=_read_only, + check_same_thread=False, + isolation_level=None, ) self._conn.row_factory = sqlite3.Row self._lock = threading.RLock() diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index baec82ecf..57e0ba8b0 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -324,6 +324,15 @@ def load(cls, path: str | Path) -> "Pipeline": writes (an earlier format is refused, never migrated). """ import json as _json + + path = Path(path) + with open(path) as f: + data = _json.load(f) + return cls._from_saved_data(data, path) + + @classmethod + def _from_saved_data(cls, data: dict[str, Any], path: Path) -> "Pipeline": + """Build a blueprint already decoded from a pipeline or job file.""" from orcapod.pipeline.serialization import ( FALL_THROUGH_TAGS_KEY, OPERATOR_INPUTS_KEY, @@ -339,10 +348,6 @@ def load(cls, path: str | Path) -> "Pipeline": from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass from orcapod.types import Schema - path = Path(path) - with open(path) as f: - data = _json.load(f) - try: require_current_format( data.get("orcapod_pipeline_version", ""), PIPELINE_FORMAT_VERSION diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 2f80d1fa0..d5035e8c7 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -15,6 +15,7 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.core.sources.cached_source import stored_source_caches from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.streams.base import StreamBase from orcapod.side_effects import SideEffectJobNode, SideEffectNode @@ -50,6 +51,7 @@ from orcapod.utils.database_errors import database_write_path, flush_best_effort if TYPE_CHECKING: + from collections.abc import Mapping from pathlib import Path from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator @@ -92,6 +94,7 @@ class _PreparedRun: plan: What the run runs and holds (``plan_run``, ITL-1095). unchecked_sources: The sources the start-of-run check could not check (``check_sources``, ITL-1102). + skipped_unbound_sources: Excluded node labels and the source slots blocking them. """ exec_dag: OrcaDAG[Any] @@ -101,6 +104,7 @@ class _PreparedRun: result_db: "ArrowDatabaseProtocol" plan: "RunPlan" unchecked_sources: tuple[str, ...] + skipped_unbound_sources: Mapping[str, set[str]] def _with_counter( @@ -176,6 +180,7 @@ def __init__( ) -> None: super().__init__(name=name, tracker_manager=tracker_manager) self._database = database + self._unresolved_database: dict[str, Any] | None = None self._result_database: "ArrowDatabaseProtocol | None" = result_database # For a loaded job whose file names a separate result database that is not # available (it could not be rebuilt, or it was in memory) and none was given: @@ -187,6 +192,7 @@ def __init__( self._auto_compile = auto_compile # name → bound concrete source (user-facing API: job.sources). self._sources: dict[str, cp.StreamProtocol] = {} + self._unresolved_sources: dict[str, dict[str, Any]] = {} # hash → bound concrete source, keyed by the same hash as # _persistent_node_map. Used by bind() for O(1) lookup by content # hash; avoids name collisions when multiple concrete sources share @@ -535,6 +541,8 @@ def bind( # the job as it was, its database included (ITL-1112). self._database = new_database self._result_database = new_result_database + if database is not None: + self._unresolved_database = None if result_database_given: self._unresolved_result_database = None @@ -548,6 +556,8 @@ def bind( schema_hash = job_node.as_node().content_hash().to_string() self._sources_by_hash[schema_hash] = sources[job_node.name] self._sources.update(sources) + for source_name in sources: + self._unresolved_sources.pop(source_name, None) # Every node predicts its schema again (ITL-1111). Since ITL-1112 a bind # should never change a prediction: ``validate`` refuses a source of other # column names or types, and the slot gives the declared schema, so this @@ -980,9 +990,8 @@ def run( """Execute the resolvable subgraph of this job in place. Nodes whose upstream includes an unbound source (and all their - dependents) are excluded from execution. Partial execution is a - first-class outcome — ``unbound_sources`` reports which source - slots were excluded. + dependents) are excluded from execution. The summary's + ``skipped_unbound_sources`` names those nodes and the slots that block them. After a successful run, ``job.nodes`` returns the execution-ready nodes with populated database caches. @@ -1074,43 +1083,46 @@ def run( """ from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator - prepared = self._prepare_run(commit_every_rows, load_only=load_only) - # The state rule (ITL-1095): a node that holds a current run is not run again. - plan = prepared.plan - counter = RunCountingObserver() - effective_orchestrator = orchestrator or SyncPipelineOrchestrator() - is_sync = isinstance(effective_orchestrator, SyncPipelineOrchestrator) - with self._executing(prepared, plan, commit_every_rows, load_only=load_only): - if is_sync: - # Held nodes give their output streams on the sync path (ITL-1347). - _ = effective_orchestrator.run( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, - load_only=load_only, - held=plan.held, - ) - else: - # The async path sends the rows the plan took (until stage 5). - _ = effective_orchestrator.run( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, - load_only=load_only, - held_rows=plan.held_rows, - ) - summary = self._finish_run( - prepared, - counter, - plan, - load_only=load_only, - unchecked_sources=prepared.unchecked_sources, - asynchronous=not is_sync, - ) + with stored_source_caches(load_only): + prepared = self._prepare_run(commit_every_rows, load_only=load_only) + # The state rule (ITL-1095): a node that holds a current run is not run again. + plan = prepared.plan + counter = RunCountingObserver() + effective_orchestrator = orchestrator or SyncPipelineOrchestrator() + is_sync = isinstance(effective_orchestrator, SyncPipelineOrchestrator) + with self._executing( + prepared, plan, commit_every_rows, load_only=load_only + ): + if is_sync: + # Held nodes give their output streams on the sync path (ITL-1347). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held=plan.held, + ) + else: + # The async path sends the rows the plan took (until stage 5). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held_rows=plan.held_rows, + ) + summary = self._finish_run( + prepared, + counter, + plan, + load_only=load_only, + unchecked_sources=prepared.unchecked_sources, + asynchronous=not is_sync, + ) if not summary.ok: warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown return summary @@ -1161,28 +1173,31 @@ async def run_async( f"{type(orchestrator).__name__}. Use job.run(orchestrator=...) to run " "it." ) - prepared = self._prepare_run(commit_every_rows, load_only=load_only) - # The state rule (ITL-1095): a node that holds a current run is not run again. - plan = prepared.plan - counter = RunCountingObserver() - with self._executing(prepared, plan, commit_every_rows, load_only=load_only): - _ = await orchestrator.run_async( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, + with stored_source_caches(load_only): + prepared = self._prepare_run(commit_every_rows, load_only=load_only) + # The state rule (ITL-1095): a node that holds a current run is not run again. + plan = prepared.plan + counter = RunCountingObserver() + with self._executing( + prepared, plan, commit_every_rows, load_only=load_only + ): + _ = await orchestrator.run_async( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held_rows=plan.held_rows, + ) + summary = self._finish_run( + prepared, + counter, + plan, load_only=load_only, - held_rows=plan.held_rows, + unchecked_sources=prepared.unchecked_sources, + asynchronous=True, ) - summary = self._finish_run( - prepared, - counter, - plan, - load_only=load_only, - unchecked_sources=prepared.unchecked_sources, - asynchronous=True, - ) if not summary.ok: warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown return summary @@ -1304,28 +1319,31 @@ def _prepare_run( if node_hash not in hash_dag: hash_dag.add_node(node_hash) - # Walk topologically; exclude unbound sources and all their dependents. - excluded_hashes: set[str] = set() + # Keep the causes of exclusion through every saved node, even one the + # loader did not restore, so the nodes below it also report their blockers. + blocked_by: dict[str, set[str]] = {} + skipped_unbound_sources: dict[str, set[str]] = {} for node_hash in hash_dag.topological_sort(): - if node_hash not in self._persistent_node_map: - # A node a loaded job did not restore (a kind PipelineJob.load does - # not know): below an unbound source it is left out too, so the nodes - # below it are as well. - if any(p in excluded_hashes for p in hash_dag.predecessors(node_hash)): - excluded_hashes.add(node_hash) - continue - node = self._persistent_node_map[node_hash] + node = self._persistent_node_map.get(node_hash) + slots = { + slot + for parent_hash in hash_dag.predecessors(node_hash) + for slot in blocked_by.get(parent_hash, ()) + } if isinstance(node, SourceJobNode) and node.bound_source is None: - excluded_hashes.add(node_hash) - elif any(p in excluded_hashes for p in hash_dag.predecessors(node_hash)): - excluded_hashes.add(node_hash) + slots.add(node.name) + if not slots: + continue + blocked_by[node_hash] = slots + if node is not None: + skipped_unbound_sources[node.label] = slots # A loaded job whose graph lost a node (the file records a node of a kind # PipelineJob.load does not restore) cannot feed the nodes below it: every # saved input of a node must be a restored node. if self._loaded: for node_hash, node in self._persistent_node_map.items(): - if node_hash in excluded_hashes: + if node_hash in blocked_by: continue # below an unbound source: not part of this run if not isinstance(node, (FunctionJobNode, OperatorJobNode)): continue @@ -1348,12 +1366,12 @@ def _prepare_run( # --- Build execution OrcaDAG from existing node objects (no cloning) --- exec_dag: OrcaDAG = OrcaDAG() for node_hash, node in self._persistent_node_map.items(): - if node_hash not in excluded_hashes: + if node_hash not in blocked_by: exec_dag.add_node(node) for u_hash, v_hash in self._graph_edges: if ( - u_hash not in excluded_hashes - and v_hash not in excluded_hashes + u_hash not in blocked_by + and v_hash not in blocked_by and u_hash in self._persistent_node_map and v_hash in self._persistent_node_map ): @@ -1425,6 +1443,7 @@ def _prepare_run( result_db=result_db, plan=plan, unchecked_sources=unchecked, + skipped_unbound_sources=skipped_unbound_sources, ) @contextlib.contextmanager @@ -1562,6 +1581,7 @@ def _finish_run( ran_nothing=not plan.to_run, restricted_sources=restrictions_in_force(prepared.exec_dag.nodes()), asynchronous=asynchronous, + skipped_unbound_sources=prepared.skipped_unbound_sources, ) return self._last_run @@ -1584,6 +1604,7 @@ def save(self, path: "str | Path") -> None: Saves topology (via the embedded Pipeline) plus bindings metadata and run state. The format covers both "template" (pre-run) and "completed" (post-run) states — distinguished by ``run.status``. + Recorded configurations for unavailable bindings are saved until replaced. Args: path: File path to write JSON output to. @@ -1621,9 +1642,9 @@ 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] = {} - for spec_name, source in sorted(self._sources.items()): + # Unavailable sources keep their saved config until replaced by a binding. + sources_block: dict[str, Any] = dict(self._unresolved_sources) + for spec_name, source in self._sources.items(): if hasattr(source, "to_config"): try: # ``hasattr`` checked it: every source declares it. @@ -1640,7 +1661,7 @@ def save(self, path: "str | Path") -> None: sources_block[spec_name] = {"source_type": "unknown"} # Database config (best-effort) - database_block = None + database_block = self._unresolved_database if self._database is not None and hasattr(self._database, "to_config"): database_block = self._database.to_config() # A separate result database (ITL-1408), saved by the same rule; ``None`` when @@ -1703,7 +1724,7 @@ def save(self, path: "str | Path") -> None: }, "pipeline": pipeline_data, "bindings": { - "sources": sources_block, + "sources": dict(sorted(sources_block.items())), "database": database_block, "result_database": result_database_block, }, @@ -1738,6 +1759,12 @@ def load( cannot be rebuilt for another reason (a moved file) is logged as a warning. Neither affects reading the other nodes. + A saved local Delta store must already have directories for its root and + any saved scope. If either path is missing or is a file, loading warns + and leaves the corresponding database or cached source unbound. Remote + Delta stores are opened on access. SQLite inputs open existing files + read-only. SQLite may create its own WAL working files while reading. + Args: path: Path to the JSON file produced by ``save()``. database: Optional database override. When provided, takes precedence @@ -1764,8 +1791,6 @@ def load( such a file then loads. """ import json as _json - import os - import tempfile from pathlib import Path as _Path from orcapod.core.nodes.source_node import SourceNodeBase @@ -1792,20 +1817,7 @@ def load( exc.add_note(f"Loading the job file {path}") raise - # Reconstruct pipeline from embedded blueprint data - with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as tmp: - tmp_path = tmp.name - _json.dump(data["pipeline"], tmp) - try: - pipeline = Pipeline.load(tmp_path) - except ValueError as exc: - # The embedded pipeline was read from a temporary file: name the job file. - message = str(exc) - if tmp_path in message: - exc.args = (message.replace(tmp_path, str(path)),) - raise - finally: - os.unlink(tmp_path) + pipeline = Pipeline._from_saved_data(data["pipeline"], path) # pyright: ignore[reportPrivateUsage] # the job embeds a pipeline blueprint # Reconstruct sources (best-effort) slots = { @@ -1814,9 +1826,9 @@ def load( if isinstance(node, SourceNodeBase) } sources: dict[str, cp.StreamProtocol] = {} - for spec_name, src_config in ( - data.get("bindings", {}).get("sources", {}).items() - ): + bindings = data.get("bindings", {}) + saved_sources: dict[str, dict[str, Any]] = bindings.get("sources", {}) + for spec_name, src_config in saved_sources.items(): source_type = src_config.get("source_type") # Every source states its plain tags (ITL-1019): a refusal is the file's # error, not a source that could not be rebuilt. @@ -1878,8 +1890,8 @@ def load( # Reconstruct database effective_database = database + unresolved_database: dict[str, Any] | None = None if effective_database is None: - bindings = data.get("bindings", {}) if bindings.get("store") and "database" not in bindings: # A file saved before ITL-1082 renamed the key. It is not read under # the old name: the job would load without its database, silently. @@ -1897,8 +1909,11 @@ def load( resolve_database_from_config, ) - effective_database = resolve_database_from_config(store_config) + effective_database = resolve_database_from_config( + store_config, create_base_path=False + ) except Exception as exc: + unresolved_database = store_config logger.warning( "Could not reconstruct the database from its saved config: %s. " "Node results cannot be read until a database is given: " @@ -1915,7 +1930,7 @@ def load( effective_result_database = result_database unresolved_result_database: dict[str, Any] | None = None if effective_result_database is None: - result_config = data.get("bindings", {}).get("result_database") + result_config = bindings.get("result_database") if 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. @@ -1934,7 +1949,7 @@ def load( ) effective_result_database = resolve_database_from_config( - result_config + result_config, create_base_path=False ) except Exception as exc: unresolved_result_database = result_config @@ -1953,6 +1968,12 @@ def load( result_database=effective_result_database, ) job._unresolved_result_database = unresolved_result_database + job._unresolved_database = unresolved_database + job._unresolved_sources = { + name: config + for name, config in saved_sources.items() + if name not in sources + } job._loaded = True job._compiled_pipeline = pipeline # Mark compiled so save() / compiled_pipeline can be accessed. diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 638334871..2867918b4 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -19,7 +19,7 @@ from orcapod.pipeline.restrictions import restriction_text if TYPE_CHECKING: - from collections.abc import Mapping, Sequence + from collections.abc import Collection, Mapping, Sequence from types import FrameType from orcapod.protocols.core_protocols import DataProtocol, TagProtocol @@ -90,6 +90,9 @@ class RunSummary: for new data at the start of the run (ITL-1102): each raised in ``check_for_new_data``, was reported by a ``SourceCheckFailedWarning``, and fed the run with the data it already held. + skipped_unbound_sources: The labels of omitted job nodes (including unbound + source nodes), mapped to the sorted slot names that blocked each one. + The labels are sorted and each slot appears once per node. conditions: The ``Condition`` each source of the run read under, by slot name (the name ``bind`` takes; a source read directly by a node's ``run()`` by its label), for the slots whose source has one (ITL-1218). @@ -101,9 +104,8 @@ class RunSummary: slots whose source has one. restricted_source_ids: The source id of every restricted source (a slot in ``conditions``, ``limits`` or both), by slot name. - ran_nothing: Whether the run ran no node: every node held a current run - (ITL-1095). Decided by the run's plan, which counts every kind of node, so a - run that ran only a side-effect or operator node is not "nothing to do". + ran_nothing: Whether the plan executed any nodes, including operators and + side effects. True when it executed zero nodes. """ def __init__( @@ -117,6 +119,7 @@ def __init__( ran_nothing: bool = False, restricted_sources: Mapping[str, RestrictedSource] | None = None, asynchronous: bool = False, + skipped_unbound_sources: Mapping[str, Collection[str]] | None = None, ) -> None: """Build the summary. @@ -126,18 +129,23 @@ def __init__( load_only: Whether the run loaded stored results only. target: The label of the node whose ``run()`` this was, if any. unchecked_sources: The sources that could not be checked for new data. - ran_nothing: Whether the run ran no node (every node held a current run). + ran_nothing: Whether the run ran no node. restricted_sources: Slot name to the source id, the condition (empty for none) and the limit of each restricted source of the run (``restrictions.restrictions_in_force``). Displayed by slot name or direct source label. asynchronous: Whether the async orchestrator executed the run. + skipped_unbound_sources: Omitted node labels and their unbound slot names. """ self.job_name: str = job_name self.nodes: Mapping[str, NodeRunSummary] = {node.label: node for node in nodes} self.load_only: bool = load_only self.target: str | None = target self.unchecked_sources: tuple[str, ...] = tuple(unchecked_sources) + self.skipped_unbound_sources: Mapping[str, tuple[str, ...]] = { + label: tuple(sorted(set(slots))) + for label, slots in sorted((skipped_unbound_sources or {}).items()) + } self.ran_nothing: bool = ran_nothing self._attribution_note: str = ( _ASYNC_ATTRIBUTION_NOTE @@ -217,13 +225,16 @@ def _headline(self) -> str: # only a side-effect or operator node did something (ITL-1121). if self.ran_nothing: run = "Load-only run" if self.load_only else "Run" + if self.skipped_unbound_sources: + return f"{run} of {subject}: no nodes ran." return f"{run} of {subject}: nothing to do; every node holds a current run." if self.load_only: skipped = sum(node.not_stored for node in self.nodes.values()) + available = "available " if self.skipped_unbound_sources else "" outcome = ( f"{_rows(skipped)} without a stored result skipped." if skipped - else "every input had a stored result." + else f"every {available}input had a stored result." ) return f"Load-only run of {subject}: {outcome}" if self.failed_rows: @@ -250,27 +261,26 @@ def _restrictions_line(self) -> str | None: for slot, source_id in self.restricted_source_ids.items() ) - def _source_lines_html(self) -> str: - """The unchecked and restricted source lines as HTML paragraphs, or ``""``.""" - restricted = self._restrictions_line() - return self._unchecked_html() + ( - "" if restricted is None else f"

{html.escape(restricted)}

" + def _source_lines(self) -> list[str]: + """Describe skipped nodes, source check failures and source restrictions.""" + lines = [ + f"{label!r}: skipped (unbound sources: {', '.join(map(repr, slots))})" + for label, slots in self.skipped_unbound_sources.items() + ] + lines.extend( + line + for line in (self._unchecked_line(), self._restrictions_line()) + if line is not None ) + return lines - def _unchecked_html(self) -> str: - """The unchecked-sources line as an HTML paragraph, or ``""``.""" - unchecked = self._unchecked_line() - return "" if unchecked is None else f"

{html.escape(unchecked)}

" + def _source_lines_html(self) -> str: + """Render the source lines as HTML paragraphs.""" + return "".join(f"

{html.escape(line)}

" for line in self._source_lines()) def __repr__(self) -> str: """The summary as text: one line per node, and the first error of a failing one.""" - lines = [self._headline()] - unchecked = self._unchecked_line() - if unchecked is not None: - lines.append(f" {unchecked}") - restricted = self._restrictions_line() - if restricted is not None: - lines.append(f" {restricted}") + lines = [self._headline(), *(f" {line}" for line in self._source_lines())] if self._attribution_note: lines.append(f" {self._attribution_note}") for node in self.nodes.values(): diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index abbebf83d..eb14f0286 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -407,7 +407,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, dict[str, Any]] | None = None, + *, + create_base_path: bool = True, ) -> Any: """Reconstruct a database instance from a config dict. @@ -418,6 +421,8 @@ def resolve_database_from_config( db_registry: Optional plain dict mapping ``"db_"`` → config dict (the output of ``DatabaseRegistry.to_dict()``). Required when ``config["type"] == "scoped"``; ignored otherwise. + create_base_path: Whether a Delta database may create a missing local root. + If false, a local Delta root and saved scope must be directories. Returns: A new database instance constructed from the config. @@ -437,8 +442,16 @@ 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) - return root_db.at(*config["path"]) + root_db = resolve_database_from_config( + root_config, create_base_path=create_base_path + ) + scoped_db = root_db.at(*config["path"]) + if not create_base_path: + from orcapod.databases.delta_lake_databases import DeltaTableDatabase + + if isinstance(scoped_db, DeltaTableDatabase): + scoped_db._require_existing_scope() # pyright: ignore[reportPrivateUsage] # validate the saved registry scope + return scoped_db if db_type not in DATABASE_REGISTRY: raise ValueError( f"Unknown database type: {db_type!r}. " @@ -450,6 +463,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) diff --git a/tests/test_pipeline/loaded_job/test_load_exclusions_and_stores.py b/tests/test_pipeline/loaded_job/test_load_exclusions_and_stores.py new file mode 100644 index 000000000..6e74d240d --- /dev/null +++ b/tests/test_pipeline/loaded_job/test_load_exclusions_and_stores.py @@ -0,0 +1,954 @@ +"""Report skipped nodes and reopen saved stores without creating directories.""" + +import json +import ntpath +import os +import sqlite3 +import sys +import tempfile +from collections.abc import Sequence +from contextlib import closing +from inspect import signature +from pathlib import Path, PureWindowsPath +from types import SimpleNamespace + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes import FunctionJobNode, OperatorJobNode +from orcapod.core.operators import Join, SelectDataColumns +from orcapod.core.sources import sqlite_table_source +from orcapod.databases import ( + DeltaTableDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) +from orcapod.errors import OrcapodDatabaseContentWarning +from orcapod.pipeline.run_summary import RunSummary +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.side_effects import SideEffectPod +from orcapod.sources import CSVSource, DerivedSource, DictSource, SQLiteTableSource + +SOURCE_ORDERS = pytest.mark.parametrize( + "memory_first", [False, True], ids=["file-first", "memory-first"] +) + + +@function_pod(output_keys="total") +def total(x: int | None, y: int | None) -> int: + """Add the two data values.""" + return (x or 0) + (y or 0) + + +def deliver(ctx: object, x: int | None, y: int | None) -> None: + """Represent an external delivery without doing any I/O.""" + del ctx, x, y + + +def save_job( + database: ArrowDatabaseProtocol, + *, + result_database: ArrowDatabaseProtocol | None = None, + cache_database: ArrowDatabaseProtocol | None = None, + memory_first: bool = False, + file_source: StreamProtocol | None = None, + extra_nodes: bool = False, +) -> Path: + """Save a job whose file-backed source can be restored independently.""" + _ = Path("rows.csv").write_text("id,group,x,y\n1,a,5,6\n2,b,7,8\n3,c,9,10\n") + csv = CSVSource( + "rows.csv", + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="file", + ) + memory = DictSource( + [ + {"id": 1, "group": "a", "x": 2, "y": 3}, + {"id": 2, "group": "b", "x": 4, "y": 5}, + {"id": 3, "group": "c", "x": 6, "y": 7}, + ], + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="memory", + ) + file = file_source if file_source is not None else csv + if cache_database is not None: + file = csv.cached(cache_database=cache_database) + recorded = PipelineJob(name="small") + with recorded: + calculated = total.pod(memory, label="memory_total") + _ = Join()(calculated, file, label="joined") + _ = total.pod(file, label="file_total") + if extra_nodes: + _ = SelectDataColumns("x")(file, label="selected") + _ = SideEffectPod(deliver)(file, label="delivered") + sources: dict[str, StreamProtocol] = {"file": file, "memory": memory} + if memory_first: + sources = dict(reversed(sources.items())) + job = PipelineJob.from_pipeline( + recorded.pipeline, + database=database, + result_database=result_database, + sources=sources, + ) + assert list(job.sources) == list(sources) + _ = job.run() + path = Path("job.json") + job.save(path) + # Save orders source configs by name. Exercise the loader with either JSON order. + if memory_first: + saved = json.loads(path.read_text()) + bindings = saved["bindings"] + bindings["sources"] = {name: bindings["sources"][name] for name in sources} + _ = path.write_text(json.dumps(saved)) + return path + + +async def load_only(job: PipelineJob, *, asynchronous: bool) -> RunSummary: + """Exercise both public job run forms.""" + if asynchronous: + return await job.run_async(load_only=True) + return job.run(load_only=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("durable", [False, True], ids=["memory", "delta"]) +@SOURCE_ORDERS +async def test_runs_report_excluded_nodes_and_their_unbound_slots( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + asynchronous: bool, + durable: bool, + memory_first: bool, +) -> None: + """A skipped branch and a held branch report different outcomes.""" + monkeypatch.chdir(tmp_path) + store = DeltaTableDatabase("store") if durable else InMemoryArrowDatabase() + path = save_job(store, memory_first=memory_first) + loaded = PipelineJob.load(path, database=None if durable else store) + + summary = await load_only(loaded, asynchronous=asynchronous) + expected_skips = { + "joined": ("memory",), + "memory": ("memory",), + "memory_total": ("memory",), + } + assert loaded.unbound_sources == ["memory"] + file_total = loaded.nodes["file_total"] + memory_total = loaded.nodes["memory_total"] + joined = loaded.nodes["joined"] + assert isinstance(file_total, FunctionJobNode) + assert isinstance(memory_total, FunctionJobNode) + assert isinstance(joined, OperatorJobNode) + assert file_total.as_table().num_rows == 3 + assert memory_total.as_table().num_rows == 0 + assert joined.as_table().num_rows == 0 + assert loaded.last_run is summary + assert summary.ran_nothing is False + assert summary.skipped_unbound_sources == expected_skips + assert list(summary.skipped_unbound_sources) == sorted(expected_skips) + assert set(summary.nodes) == {"file_total"} + assert summary.nodes["file_total"].reused == 3 + assert summary.nodes["file_total"].held == 0 + assert str(summary) == ( + "Load-only run of job 'small': every available input had a stored result.\n" + " 'joined': skipped (unbound sources: 'memory')\n" + " 'memory': skipped (unbound sources: 'memory')\n" + " 'memory_total': skipped (unbound sources: 'memory')\n" + " file_total: 3 rows: 3 loaded" + ) + assert ( + "'joined': skipped (unbound sources: 'memory')" + in summary._repr_html_() # pyright: ignore[reportPrivateUsage] # notebook display protocol + ) + + held = await load_only(loaded, asynchronous=asynchronous) + assert held.ran_nothing is True + assert held.skipped_unbound_sources == expected_skips + assert held.nodes["file_total"].held == 3 + assert held.nodes["file_total"].reused == 0 + assert str(held) == ( + "Load-only run of job 'small': no nodes ran.\n" + " 'joined': skipped (unbound sources: 'memory')\n" + " 'memory': skipped (unbound sources: 'memory')\n" + " 'memory_total': skipped (unbound sources: 'memory')\n" + " file_total: 3 rows: held from the previous run" + ) + + _ = Path("rows.csv").rename("moved.csv") + blocked = PipelineJob.load(path, database=None if durable else store) + skipped = await load_only(blocked, asynchronous=asynchronous) + assert skipped.ran_nothing is True + assert not skipped.nodes + assert skipped.skipped_unbound_sources == { + "file": ("file",), + "file_total": ("file",), + "joined": ("file", "memory"), + "memory": ("memory",), + "memory_total": ("memory",), + } + assert str(skipped) == ( + "Load-only run of job 'small': no nodes ran.\n" + " 'file': skipped (unbound sources: 'file')\n" + " 'file_total': skipped (unbound sources: 'file')\n" + " 'joined': skipped (unbound sources: 'file', 'memory')\n" + " 'memory': skipped (unbound sources: 'memory')\n" + " 'memory_total': skipped (unbound sources: 'memory')" + ) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("binding", ["database", "result_database"]) +@pytest.mark.parametrize("replacement", ["absent", "shared-cache", "file"]) +@SOURCE_ORDERS +def test_loading_a_moved_delta_store_refuses_an_unusable_root( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + binding: str, + replacement: str, + memory_first: bool, +) -> None: + """A present store reads its rows, and a missing root needs an override.""" + monkeypatch.chdir(tmp_path) + store = DeltaTableDatabase("store") + results = DeltaTableDatabase("results") if binding == "result_database" else None + shared_cache = (results or store) if replacement == "shared-cache" else None + path = save_job( + store, + result_database=results, + cache_database=shared_cache, + memory_first=memory_first, + ) + + present = PipelineJob.load(path) + present_node = present.nodes["file_total"] + assert isinstance(present_node, FunctionJobNode) + assert present_node.as_source().as_table().num_rows == 3 + assert present.unbound_sources == ["memory"] + assert not caplog.records + + original = Path("results" if results is not None else "store") + moved = original.rename("moved") + if replacement == "file": + _ = original.write_text("regular file") + missing = PipelineJob.load(path) + if replacement == "file": + assert original.read_text() == "regular file" + else: + assert not original.exists() + assert "Could not reconstruct" in caplog.text + assert f"{binding}=..." in caplog.text + if shared_cache is not None: + assert set(missing.unbound_sources) == {"file", "memory"} + assert "Could not reconstruct source 'file' (cached)" in caplog.text + if results is None: + assert missing.database is None + restored = PipelineJob.load(path, database=DeltaTableDatabase(moved)) + else: + assert missing.result_database is None + restored = PipelineJob.load(path, result_database=DeltaTableDatabase(moved)) + restored_node = restored.nodes["file_total"] + assert isinstance(restored_node, FunctionJobNode) + assert restored_node.as_source().as_table().num_rows == 3 + assert original.exists() == (replacement == "file") + + +@SOURCE_ORDERS +def test_loading_a_missing_source_cache_does_not_create_its_directory( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + memory_first: bool, +) -> None: + """Losing a source's own cache leaves its slot unbound and the job store open.""" + monkeypatch.chdir(tmp_path) + cache = DeltaTableDatabase("cache") + path = save_job( + DeltaTableDatabase("store"), cache_database=cache, memory_first=memory_first + ) + _ = Path("cache").rename("moved") + + loaded = PipelineJob.load(path) + assert not Path("cache").exists() + assert isinstance(loaded.database, DeltaTableDatabase) + assert set(loaded.unbound_sources) == {"file", "memory"} + assert "Could not reconstruct source 'file' (cached)" in caplog.text + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_loading_a_delta_root_without_tables_opens_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """A store root can exist before any Delta table has been written to it.""" + monkeypatch.chdir(tmp_path) + path = save_job(DeltaTableDatabase("store")) + root = Path("store") + _ = root.rename("moved") + root.mkdir() + + loaded = PipelineJob.load(path) + assert isinstance(loaded.database, DeltaTableDatabase) + assert not caplog.records + node = loaded.nodes["file_total"] + assert isinstance(node, FunctionJobNode) + with pytest.warns(OrcapodDatabaseContentWarning): + assert node.as_source().as_table().num_rows == 0 + assert list(root.iterdir()) == [] + + +@pytest.mark.parametrize("store_type", [InMemoryArrowDatabase, NoOpArrowDatabase]) +def test_loading_a_non_filesystem_store_leaves_the_working_directory_alone( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + store_type: type[InMemoryArrowDatabase] | type[NoOpArrowDatabase], +) -> None: + """The other built-in job stores have no filesystem root.""" + monkeypatch.chdir(tmp_path) + path = save_job(store_type()) + before = set(tmp_path.iterdir()) + loaded = PipelineJob.load(path) + assert isinstance(loaded.database, store_type) + assert set(tmp_path.iterdir()) == before + + +@pytest.mark.parametrize("binding", ["database", "result_database", "cache"]) +@pytest.mark.parametrize("absolute", [False, True], ids=["relative", "absolute"]) +@SOURCE_ORDERS +def test_loading_a_scoped_delta_store_requires_a_directory_at_the_scope( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + binding: str, + absolute: bool, + memory_first: bool, +) -> None: + """The stored prefix must name a directory even when the root is present.""" + monkeypatch.chdir(tmp_path) + root = tmp_path / "root" if absolute else Path("root") + scoped = DeltaTableDatabase(root).at("scope") + path = save_job( + scoped if binding == "database" else DeltaTableDatabase("store"), + result_database=scoped if binding == "result_database" else None, + cache_database=scoped if binding == "cache" else None, + memory_first=memory_first, + ) + _ = (root / "scope").rename(root / "moved") + _ = (root / "scope").write_text("regular file") + + loaded = PipelineJob.load(path) + if binding == "cache": + assert "file" in loaded.unbound_sources + elif binding == "database": + assert loaded.database is None + else: + assert loaded.result_database is None + assert "not an existing directory" in caplog.text + assert (root / "scope").read_text() == "regular file" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("binding", ["database", "result_database", "cache", "all"]) +@SOURCE_ORDERS +async def test_resaving_a_job_preserves_the_location_of_an_unavailable_delta_store( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + binding: str, + asynchronous: bool, + memory_first: bool, +) -> None: + """A resaved job can use each saved binding when its store returns.""" + monkeypatch.chdir(tmp_path) + unavailable = ( + {"database", "result_database", "cache"} if binding == "all" else {binding} + ) + targets = {name: DeltaTableDatabase(name) for name in sorted(unavailable)} + path = save_job( + targets["database"] if "database" in targets else DeltaTableDatabase("store"), + result_database=targets.get("result_database"), + cache_database=targets.get("cache"), + memory_first=memory_first, + ) + moved = {name: Path(name).rename(f"{name}-moved") for name in targets} + loaded = PipelineJob.load(path) + copy_path = Path("copy.json") + loaded.save(copy_path) + + saved_bindings = json.loads(path.read_text())["bindings"] + copied_bindings = json.loads(copy_path.read_text())["bindings"] + if "cache" in targets: + assert copied_bindings["sources"]["file"] == saved_bindings["sources"]["file"] + for name in ("database", "result_database"): + if name in targets: + assert copied_bindings[name] == saved_bindings[name] + for name, moved_path in moved.items(): + assert not Path(name).exists() + _ = moved_path.rename(name) + restored = PipelineJob.load(copy_path) + summary = await load_only(restored, asynchronous=asynchronous) + assert summary.nodes["file_total"].reused == 3 + assert restored.unbound_sources == ["memory"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("absolute", [False, True], ids=["relative", "absolute"]) +@pytest.mark.parametrize("journal_mode", ["delete", "wal"]) +@SOURCE_ORDERS +async def test_loading_a_sqlite_source_reads_existing_rows_without_creating_a_database( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + asynchronous: bool, + absolute: bool, + journal_mode: str, + memory_first: bool, +) -> None: + """Read an existing SQLite input in either journal mode; never recreate it.""" + monkeypatch.chdir(tmp_path) + original = Path("input #.sqlite") + with closing(sqlite3.connect(original)) as connection: + assert connection.execute(f"PRAGMA journal_mode={journal_mode}").fetchone() == ( + journal_mode, + ) + _ = connection.execute( + 'CREATE TABLE samples (id INTEGER PRIMARY KEY, "group" TEXT NOT NULL, ' + "x INTEGER NOT NULL, y INTEGER NOT NULL)" + ) + _ = connection.executemany( + "INSERT INTO samples VALUES (?, ?, ?, ?)", + [(1, "a", 4, 5), (2, "b", 6, 7), (3, "c", 8, 9)], + ) + connection.commit() + source = SQLiteTableSource( + original.absolute() if absolute else original, + "samples", + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="file", + ) + path = save_job( + DeltaTableDatabase("store"), memory_first=memory_first, file_source=source + ) + present = PipelineJob.load(path) + summary = await load_only(present, asynchronous=asynchronous) + assert summary.nodes["file_total"].reused == 3 + + _ = original.rename("moved.sqlite") + missing = PipelineJob.load(path) + assert not original.exists() + assert set(missing.unbound_sources) == {"file", "memory"} + summary = await load_only(missing, asynchronous=asynchronous) + assert summary.skipped_unbound_sources["file_total"] == ("file",) + + +def test_loading_a_job_does_not_create_a_temporary_blueprint( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A job's embedded blueprint can be read directly from the saved file.""" + monkeypatch.chdir(tmp_path) + path = save_job(DeltaTableDatabase("store")) + + def refuse_tempfile(*_args: object, **_kwargs: object) -> None: + raise AssertionError("load tried to create a temporary file") + + monkeypatch.setattr(tempfile, "NamedTemporaryFile", refuse_tempfile) + assert PipelineJob.load(path).unbound_sources == ["memory"] + + +def write_sqlite_input(path: Path, value: int) -> None: + """Create three rows with a value that identifies this database.""" + with closing(sqlite3.connect(path)) as connection: + _ = connection.execute( + 'CREATE TABLE samples (id INTEGER PRIMARY KEY, "group" TEXT NOT NULL, ' + '"x" INTEGER NOT NULL, y INTEGER NOT NULL)' + ) + _ = connection.executemany( + "INSERT INTO samples VALUES (?, ?, ?, ?)", + [(1, "a", value, 5), (2, "b", value, 7), (3, "c", value, 9)], + ) + connection.commit() + + +def test_loading_relative_sqlite_from_another_directory_only_creates_wal_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Load a saved relative SQLite binding from three different directories.""" + + def contents(directory: Path) -> dict[Path, bytes | None]: + return { + path.relative_to(directory): path.read_bytes() if path.is_file() else None + for path in directory.rglob("*") + } + + filename = "input.sqlite" + original = tmp_path / "original" + original.mkdir() + write_sqlite_input(original / filename, 1) + monkeypatch.chdir(original) + source = SQLiteTableSource( + filename, "samples", source_id="file", tag_only_columns=True + ) + job = PipelineJob("sqlite_paths", database=DeltaTableDatabase(original / "store")) + with job: + _ = total.pod(source) + saved = original / "job.json" + job.save(saved) + saved_binding = json.loads(saved.read_bytes())["bindings"]["sources"]["file"] + assert saved_binding["db_path"] == filename + + missing_dir = tmp_path / "missing" + missing_dir.mkdir() + (missing_dir / "nested").mkdir() + _ = (missing_dir / "nested" / "existing.txt").write_bytes(b"keep these bytes") + before = contents(missing_dir) + monkeypatch.chdir(missing_dir) + missing = PipelineJob.load(saved) + assert contents(missing_dir) == before + assert missing.unbound_sources == ["file"] + resaved = original / "resaved.json" + missing.save(resaved) + assert ( + json.loads(resaved.read_bytes())["bindings"]["sources"]["file"] == saved_binding + ) + + for journal_mode, value in (("delete", 2), ("wal", 3)): + directory = tmp_path / journal_mode + directory.mkdir() + database = directory / filename + write_sqlite_input(database, value) + with closing(sqlite3.connect(database)) as connection: + assert connection.execute( + f"PRAGMA journal_mode={journal_mode}" + ).fetchone() == (journal_mode,) + before = contents(directory) + assert set(before) == {Path(filename)} + monkeypatch.chdir(directory) + restored = PipelineJob.load(saved).sources["file"] + assert isinstance(restored, SQLiteTableSource) + after = contents(directory) + created = after.keys() - before.keys() + assert created == ( + {Path(f"{filename}-wal"), Path(f"{filename}-shm")} + if journal_mode == "wal" + else set() + ) + assert all(after[path] is not None for path in created) + assert after[Path(filename)] == before[Path(filename)] + + monkeypatch.chdir(original) + assert restored.check_for_new_data() is False + assert restored.as_table().column("x").to_pylist() == [value] * 3 + + +class SQLitePath: + """A path-like object whose display name is not its filesystem name.""" + + def __init__(self, path: str) -> None: + self.path = path + self.calls = 0 + + def __fspath__(self) -> str: + self.calls += 1 + return self.path + + +@pytest.mark.parametrize( + "kind", + [ + "relative", + "absolute", + "pathlib", + "pathlike", + "dot-dot", + pytest.param( + "file-prefix", + marks=pytest.mark.skipif( + sys.platform == "win32", reason="colon in filename" + ), + ), + ], +) +def test_sqlite_job_round_trip_keeps_path_text_and_default_id( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + """Save the original spelling and keep both live and restored reads pinned.""" + original = tmp_path / "original" + elsewhere = tmp_path / "elsewhere" + for directory, value in ((original, 2), (elsewhere, 99)): + (directory / "child").mkdir(parents=True) + name = "file:input.sqlite" if kind == "file-prefix" else "input.sqlite" + write_sqlite_input(directory / name, value) + + pathlike = SQLitePath("input.sqlite") + paths: dict[str, str | os.PathLike[str]] = { + "relative": "./input.sqlite", + "absolute": str(original / "input.sqlite"), + "pathlib": Path("input.sqlite"), + "pathlike": pathlike, + "dot-dot": "child/../input.sqlite", + "file-prefix": "file:input.sqlite", + } + expected_path = pathlike.path if kind == "pathlike" else str(paths[kind]) + # This is the default ID format on main, including the unmodified filename. + expected_id = f"sqlite_table_v1:{expected_path}:main.samples" + monkeypatch.chdir(original) + source = SQLiteTableSource(paths[kind], "samples", tag_only_columns=True) + job = PipelineJob("sqlite_paths", database=DeltaTableDatabase(original / "store")) + with job: + _ = total.pod(source) + assert source.source_id == expected_id + assert source.to_config()["db_path"] == expected_path + + saved = original / "job.json" + job.save(saved) + loaded = PipelineJob.load(saved) + restored = next(iter(loaded.sources.values())) + assert isinstance(restored, SQLiteTableSource) + assert restored.source_id == expected_id + resaved = original / "resaved.json" + loaded.save(resaved) + assert resaved.read_bytes() == saved.read_bytes() + + monkeypatch.chdir(elsewhere) + for current in (source, restored): + assert current.check_for_new_data() is False + assert current.as_table().column("x").to_pylist() == [2] * 3 + assert pathlike.calls == (1 if kind == "pathlike" else 0) + # An absolute filename in a previously saved job is still read from its old location. + if kind == "absolute": + loaded_elsewhere = PipelineJob.load(saved) + assert ( + next(iter(loaded_elsewhere.sources.values())) + .as_table() + .column("x") + .to_pylist() + == [2] * 3 + ) + + +@pytest.mark.skipif(sys.platform == "win32", reason="colon in filename") +def test_sqlite_source_load_preserves_filename_interpretation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The file: prefix is part of the filename.""" + monkeypatch.chdir(tmp_path) + write_sqlite_input(tmp_path / "file:input.sqlite", 2) + write_sqlite_input(tmp_path / "input.sqlite", 99) + source = SQLiteTableSource( + "file:input.sqlite", + "samples", + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="file", + ) + expected = [2] * 3 + assert source.as_table().column("x").to_pylist() == expected + path = save_job(DeltaTableDatabase("store"), file_source=source) + loaded = PipelineJob.load(path) + assert loaded.nodes["file"].as_table().column("x").to_pylist() == expected + Path("input.sqlite").unlink() + loaded = PipelineJob.load(path) + assert loaded.nodes["file"].as_table().column("x").to_pylist() == expected + + +def test_relative_sqlite_source_pins_its_file_at_construction_and_load( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Refresh resolves the same file after chdir, for live and restored sources.""" + first = tmp_path / "first" + second = tmp_path / "second" + first.mkdir() + second.mkdir() + write_sqlite_input(first / "input.sqlite", 2) + write_sqlite_input(second / "input.sqlite", 99) + monkeypatch.chdir(first) + source = SQLiteTableSource("input.sqlite", "samples", tag_only_columns=True) + assert source.source_id == "sqlite_table_v1:input.sqlite:main.samples" + named = SQLiteTableSource( + "input.sqlite", + "samples", + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="file", + ) + path = first / save_job(DeltaTableDatabase(first / "store"), file_source=named) + monkeypatch.chdir(second) + assert source.check_for_new_data() is False + assert source.as_table().column("x").to_pylist() == [2] * 3 + loaded = PipelineJob.load(path) + restored = loaded.sources["file"] + assert isinstance(restored, SQLiteTableSource) + assert restored.as_table().column("x").to_pylist() == [99] * 3 + monkeypatch.chdir(first) + assert restored.check_for_new_data() is False + assert restored.as_table().column("x").to_pylist() == [99] * 3 + assert "uri" not in signature(SQLiteTableSource).parameters + + +@pytest.mark.skipif( + sys.platform == "win32", reason="directory symlinks need privileges" +) +def test_sqlite_source_keeps_dot_dot_after_a_symlink( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """SQLite follows the symlink before stepping back to the parent.""" + monkeypatch.chdir(tmp_path) + physical = tmp_path / "physical" + child = physical / "child" + child.mkdir(parents=True) + (tmp_path / "alias").symlink_to(child, target_is_directory=True) + write_sqlite_input(physical / "data.db", 2) + write_sqlite_input(tmp_path / "data.db", 99) + source = SQLiteTableSource( + "alias/../data.db", + "samples", + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="file", + ) + path = save_job(DeltaTableDatabase("store"), file_source=source) + loaded = PipelineJob.load(path) + assert source.as_table().column("x").to_pylist() == [2] * 3 + assert loaded.nodes["file"].as_table().column("x").to_pylist() == [2] * 3 + + +def test_sqlite_source_pins_rooted_windows_filename_to_the_working_drive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A Windows path with a root and no drive needs the working drive.""" + monkeypatch.setattr( + sqlite_table_source, + "os", + SimpleNamespace(path=ntpath, fspath=os.fspath, getcwd=lambda: r"C:\work"), + ) + monkeypatch.setattr(sqlite_table_source, "PurePath", PureWindowsPath) + path = sqlite_table_source._access_path(r"\input.sqlite") # pyright: ignore[reportPrivateUsage] # exercise Windows path semantics on any test host + assert PureWindowsPath(path).as_uri() == "file:///C:/input.sqlite" + + +def test_sqlite_source_pins_a_relative_filename_on_another_windows_drive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Resolve the drive's current directory while preserving the filename.""" + + def drive_directory(drive: str) -> str: + assert drive == "C:" + return r"C:\source" + + monkeypatch.setattr( + sqlite_table_source, + "os", + SimpleNamespace( + path=SimpleNamespace(join=ntpath.join, abspath=drive_directory), + fspath=os.fspath, + getcwd=lambda: r"D:\work", + ), + ) + monkeypatch.setattr(sqlite_table_source, "PurePath", PureWindowsPath) + path = sqlite_table_source._access_path(r"C:alias\..\input.sqlite") # pyright: ignore[reportPrivateUsage] # exercise Windows path semantics on any test host + assert path == r"C:\source\alias\..\input.sqlite" + assert PureWindowsPath(path).as_uri() == "file:///C:/source/alias/../input.sqlite" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +async def test_load_only_invalidates_full_operator_after_cache_returns_to_empty( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """The same empty snapshot after a full run must invalidate its held rows.""" + monkeypatch.chdir(tmp_path) + _ = Path("rows.csv").write_text("id,x\n1,10\n") + source = CSVSource("rows.csv", tag_columns=["id"], tag_only_columns=True) + root = Path("cache") + cached = source.cached(cache_database=DeltaTableDatabase(root)) + job = PipelineJob(name="small", database=InMemoryArrowDatabase()) + with job: + _ = SelectDataColumns("x")(cached, label="selected") + node = job.nodes["selected"] + assert isinstance(node, OperatorJobNode) + + _ = await load_only(job, asynchronous=asynchronous) + assert node.as_table().num_rows == 0 + if asynchronous: + _ = await job.run_async() + else: + _ = job.run() + assert node.as_table().column("x").to_pylist() == [10] + + _ = root.rename("moved") + summary = await load_only(job, asynchronous=asynchronous) + assert summary.ran_nothing is False + assert node.as_table().num_rows == 0 + repeated = await load_only(job, asynchronous=asynchronous) + assert repeated.ran_nothing is True + assert not root.exists() + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +async def test_load_only_empty_derived_source_does_not_replace_full_run_rows( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """A load-only view of an absent cache is independent of full-run state.""" + monkeypatch.chdir(tmp_path) + _ = Path("rows.csv").write_text("id,group,x,y\n1,a,7,3\n") + csv = CSVSource( + "rows.csv", + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="file", + ) + root = Path("cache") + cached = csv.cached(cache_database=DeltaTableDatabase(root)) + derived = DerivedSource( + cached, tags_as_data={"group": "group_copy"}, source_id="derived" + ) + job = PipelineJob(name="small", database=DeltaTableDatabase("store")) + with job: + _ = total.pod(derived, label="total") + + async def run(*, stored: bool = False) -> Sequence[object]: + if asynchronous: + _ = await job.run_async(load_only=stored) + else: + _ = job.run(load_only=stored) + node = job.nodes["total"] + assert isinstance(node, FunctionJobNode) + return node.as_table().column("total").to_pylist() + + first = await run() + full_times = (cached.last_modified, derived.last_modified) + moved = root.rename("moved") + temporary_view = await run(stored=True) + assert not root.exists() + after_load_only = (cached.last_modified, derived.last_modified) + _ = moved.rename(root) + recovered = await run() + held = await run() + assert [first, temporary_view, recovered, held] == [[10], [], [10], [10]] + assert after_load_only == full_times + + +@pytest.mark.parametrize("binding", ["database", "result_database", "cache"]) +def test_loading_a_delta_scope_uses_the_same_path_mapping_as_writes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, binding: str +) -> None: + """Simulate Windows's colon mapping while accessing a real store.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setattr( + DeltaTableDatabase, + "_sanitize_path_component", + staticmethod(lambda component: component.replace(":", "!")), + ) + scoped = DeltaTableDatabase("root").at("experiment:one") + path = save_job( + scoped if binding == "database" else DeltaTableDatabase("store"), + result_database=scoped if binding == "result_database" else None, + cache_database=scoped if binding == "cache" else None, + ) + assert (Path("root") / "experiment!one").is_dir() + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == ["memory"] + summary = loaded.run(load_only=True) + assert summary.nodes["file_total"].reused == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +async def test_load_only_rechecks_a_source_cache_that_reappears( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """A missing cache on the first run cannot hide restored rows on the second.""" + monkeypatch.chdir(tmp_path) + root = Path("cache") + path = save_job( + DeltaTableDatabase("store"), cache_database=DeltaTableDatabase(root) + ) + loaded = PipelineJob.load(path) + moved = root.rename("moved") + empty = await load_only(loaded, asynchronous=asynchronous) + assert empty.nodes["file_total"].rows == 0 + assert not root.exists() + + _ = moved.rename(root) + restored = await load_only(loaded, asynchronous=asynchronous) + assert restored.ran_nothing is False + assert restored.nodes["file_total"].reused == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "cache_state", ["moved", "moved-after-load", "empty", "present"] +) +async def test_load_only_uses_only_stored_cache_rows( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + cache_state: str, + asynchronous: bool, +) -> None: + """Load-only never ingests live rows, even when the cache could accept them.""" + monkeypatch.chdir(tmp_path) + root = Path("cache") + path = save_job( + DeltaTableDatabase("store"), + cache_database=DeltaTableDatabase(root), + extra_nodes=True, + ) + if cache_state in {"moved", "empty"}: + _ = root.rename("moved") + if cache_state == "empty": + root.mkdir() + with Path("rows.csv").open("a") as csv: + _ = csv.write("4,d,11,12\n") + before = {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} + loaded = PipelineJob.load(path) + if cache_state == "moved-after-load": + _ = root.rename("moved") + before = {} + summary = await load_only(loaded, asynchronous=asynchronous) + + assert {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} == before + assert root.exists() == (cache_state in {"empty", "present"}) + assert loaded.nodes["file_total"].as_table().num_rows == ( + 3 if cache_state == "present" else 0 + ) + for label in ("selected", "delivered"): + assert loaded.nodes[label].as_table().num_rows == ( + 3 if cache_state == "present" else 0 + ) + if cache_state == "moved": + assert summary.skipped_unbound_sources["file_total"] == ("file",) + assert "Could not reconstruct source 'file'" in caplog.text + else: + assert summary.nodes["file_total"].not_stored == 0 + if cache_state != "present": + assert "has no stored rows" in caplog.text + + +@pytest.mark.parametrize("label", ["file", "file_total", "selected", "delivered"]) +def test_node_load_only_uses_only_stored_source_cache_rows( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + label: str, +) -> None: + """A direct node run has the same source-cache guarantee as a job run.""" + monkeypatch.chdir(tmp_path) + root = Path("cache") + path = save_job( + DeltaTableDatabase("store"), + cache_database=DeltaTableDatabase(root), + extra_nodes=True, + ) + _ = root.rename("moved") + root.mkdir() + loaded = PipelineJob.load(path) + + _ = loaded.nodes[label].run(load_only=True) + assert list(root.iterdir()) == []