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/changelog.d/ITL-1489.md b/changelog.d/ITL-1489.md new file mode 100644 index 000000000..f85df68fa --- /dev/null +++ b/changelog.d/ITL-1489.md @@ -0,0 +1,18 @@ +### Changed + +- CSV sources now derive their default ID from `os.fspath(path)` when it differs from + `str(path)`, so pass the previous `str(path)` value as `source_id` to keep using the old + ID and cache. + +### Fixed + +- CSV, Delta and SQLite sources accept text path-like objects such as `pathlib.Path`. + Jobs using these sources save the supplied path text as JSON strings. Delta sources + pin local paths for reads and pass URI addresses through to deltalake. + +### Known limitations + +- A saved job loads relative source paths from its current working directory. If a + relative path now points to a different dataset, reading the restored cached source + mixes both datasets in the original cache (ITL-1546). Use absolute source paths + when building a job you expect to load from a different working directory. 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..c1e5774f0 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -181,6 +181,12 @@ A `CachedSource` is not a node of the job: its cache is kept in the cache databa the path it was created with, whatever job reads it, so two jobs given one `CachedSource` (or one cache database and path) share its cache. +When a saved `CachedSource` wraps a relative file path, the path is relative to the +working directory when the job is loaded. The restored source still uses the original +cache. If the path points to a different dataset there, reading the restored source +mixes rows from both datasets in that cache (ITL-1546). Use absolute source paths when +building a job you expect to load from a different working directory. + Every run reads a function node's stored tables (its result table and its pipeline records) as they are when the node starts: results that another job, or another handle on the same database (a second `DeltaTableDatabase` over the same directory, another @@ -359,9 +365,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 +485,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 +540,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 +551,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/concepts/sources.md b/docs/concepts/sources.md index 4f6b04177..27dd5c484 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -30,8 +30,23 @@ hashing) and produces the final immutable stream. | `DictSource` | `list[dict]` | Each dict becomes one (Tag, Data) pair | | `ListSource` | `list[Any]` | Each element stored under the data column given by `name`; the tag defaults to `element_index` | | `DataFrameSource` | Pandas or Polars `DataFrame` | Converts via Arrow | -| `CSVSource` | File path (string) | Reads CSV into Arrow | -| `DeltaTableSource` | Directory path | Reads Delta Lake table | +| `CSVSource` | CSV file path | Reads CSV into Arrow | +| `DeltaTableSource` | Table directory path | Reads Delta Lake table | + +`CSVSource`, `DeltaTableSource`, and `SQLiteTableSource` accept `str` or +`os.PathLike[str]`, including `pathlib.Path`. At construction, they call `os.fspath` once +and use its result for the default source ID, the saved job configuration, and opening the +source. For example, a CSV path object whose `__fspath__` returns `data/entries.csv` and +whose `__str__` returns `display.csv` gets the default ID `csv_v1:data/entries.csv`. For +local files or tables, the source anchors a relative path to the working directory at +construction. The reader handles symlinks and `..` in that path, and later reads keep +the same working-directory anchor. A saved relative path is relative to the working +directory when the job is loaded. Use absolute source paths when building a job you +expect to load from a different working directory. If a relative path points to a +different dataset after loading, reading the restored `CachedSource` mixes rows from +both datasets in the existing source cache (ITL-1546). + +Delta URIs such as `s3://bucket/table` are saved and passed to deltalake as given. `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over diff --git a/docs/dev/design_issues/PLT-4864-TUT1.md b/docs/dev/design_issues/PLT-4864-TUT1.md index 8a3c429a6..b2210b143 100644 --- a/docs/dev/design_issues/PLT-4864-TUT1.md +++ b/docs/dev/design_issues/PLT-4864-TUT1.md @@ -3,7 +3,7 @@ ### TUT1 — Newcomer-facing defects found while writing the tutorial **Status:** open **Severity:** medium -**Issue:** PLT-4864 (related: ITL-821, ITL-817) +**Issue:** PLT-4864 (related: ITL-821, ITL-817, ITL-1489) Writing `docs/tutorial/` against the library exercised paths the existing docs did not. The tutorial and `docs/troubleshooting.md` describe each of these as it behaves today; none is @@ -13,6 +13,8 @@ items found then to be fixed were removed. 1. **`CSVSource` rejects a `pathlib.Path`.** `CSVSource(Path("f.csv"), tag_columns=["a"])` raises `TypeError: 'PosixPath' object is not iterable`; the `file_path` parameter is typed `str` and the path is used as the default `source_id`. `CSVSource(str(path), ...)` works. + **Fix (ITL-1489):** `CSVSource` accepts `pathlib.Path` directly and stores its + filesystem text, so job saving works with both given and default source names. 2. **`list(job.nodes)` order depends on `PYTHONHASHSEED`** for source nodes: a job over two sources `units` and `sessions` lists `['units', 'sessions', 'Join', 'fn']` under some seeds and `['sessions', 'units', 'Join', 'fn']` under others. Cosmetic, but it makes 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/plans/ITL-1489.md b/docs/dev/plans/ITL-1489.md new file mode 100644 index 000000000..6fb7199ab --- /dev/null +++ b/docs/dev/plans/ITL-1489.md @@ -0,0 +1,16 @@ +# ITL-1489 — Save jobs built from path-like sources + +1. Reproduce the CSV job save error on `main` and cover text conversion and source identity + for CSV, Delta and SQLite. +2. Convert the input once at construction with `os.fspath`. Use the path text as passed + for saved paths and default source names. Pin local access paths at construction by + joining the working directory without resolving symlinks or `..`. Give Delta URIs + directly to deltalake. Stack on PR #581 for SQLite read-only restoration and preserving + unavailable source bindings when re-saving jobs. +3. Verify the source tests, lint, format, type checking and golden hashes. Update docs + examples if the pending tutorial PR has merged. + +The developer confirmed on November 27, 2026, that the filesystem path determines +the default source ID. A CSV path object with `str(path) == "display.csv"` and +`os.fspath(path) == "data/entries.csv"` now defaults to `csv_v1:data/entries.csv`, +which names the file the source actually opens. 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..ea60f3564 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -83,11 +83,10 @@ column. See [Arrow types of a source](concepts/sources.md#arrow-types-of-a-sourc ### `TypeError: 'PosixPath' object is not iterable` from `CSVSource` -**Cause.** `CSVSource` was given a `pathlib.Path` and no `source_id`. The file path is -typed as a string; without a `source_id` it is used to build the default one, which fails -for a `Path`. This is a known defect. - -**Fix.** `CSVSource(str(path), ...)`. +Current Orcapod accepts `str` or `os.PathLike[str]`, including `pathlib.Path`, in +`CSVSource`, `DeltaTableSource`, and `SQLiteTableSource`. Saved jobs store the paths as +JSON strings. If you see this error on an older version, upgrade Orcapod or pass +`str(path)` to `CSVSource`. ### `ValueError: Parameter 'x' has no type annotation and is not specified in input_types.` @@ -294,7 +293,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/base.py b/src/orcapod/core/sources/base.py index 07221924c..d7655d0db 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,7 +1,9 @@ from __future__ import annotations +import os import warnings from collections.abc import Callable +from pathlib import PurePath from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from orcapod import contexts @@ -35,6 +37,42 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +def source_path_text(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str: + """Return the supplied path text, rejecting byte paths before opening a source.""" + text = os.fspath(path) + if isinstance(text, bytes): + raise TypeError("Source paths must be str or os.PathLike[str], not bytes") + return text + + +def source_paths( + path: str | os.PathLike[str], + *, + passthrough: Callable[[str], bool] | None = None, +) -> tuple[str, str]: + """Return the supplied text and the path pinned for reads at construction. + + Args: + path: The supplied file path or address. + passthrough: Identifies addresses or special names passed directly to the reader. + + Returns: + The original text for names and configs, and the pinned access path. + """ + text = source_path_text(path) + if passthrough is not None and passthrough(text): + return text, text + local_path = PurePath(text) + if local_path.is_absolute(): + return text, text + # Keep every component so the reader can follow a symlink before a following '..'. + pinned = os.path.join(os.getcwd(), text) + if PurePath(pinned).is_absolute(): + return text, pinned + # On Windows, a drive-relative path can use another drive's working directory. + return text, os.path.join(os.path.abspath(local_path.drive), text) + + def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: """Return the ``tag_only_columns`` of a saved source config (ITL-1019). 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/csv_source.py b/src/orcapod/core/sources/csv_source.py index f39681d9e..68ec9a6a0 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -10,7 +10,11 @@ import pyarrow as pa from typing_extensions import override -from orcapod.core.sources.base import RootSource, saved_tag_only_columns +from orcapod.core.sources.base import ( + RootSource, + saved_tag_only_columns, + source_paths, +) from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import keep_nullable_columns, same_rows @@ -273,6 +277,9 @@ class CSVSource(RootSource): Data-tags (ITL-1023): every declared tag column is a data-tag by default, also a data column of the same name. ``tag_only_columns`` (keyword-only) names the tags kept plain (tag only, not data, as in v0.3); ``True`` keeps all of them plain. + + A path-like ``file_path`` is stored as its filesystem text, which also supplies + the default source name. """ SOURCE_KIND: ClassVar[str] = "csv" @@ -284,7 +291,7 @@ class CSVSource(RootSource): def __init__( self, - file_path: str, + file_path: str | os.PathLike[str], tag_columns: str | Collection[str] = (), system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, @@ -294,16 +301,13 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **kwargs: Any, ) -> None: + self._file_path, self._access_path = source_paths(file_path) super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). - self._source_name = location_source_name(str(file_path)) + self._source_name = location_source_name(self._file_path) - self._file_path = file_path - # Every later read (a check, ITL-1102) opens the file found now, whatever the - # working directory is then. - self._access_path = os.path.abspath(file_path) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._system_tag_columns: Collection[str] = system_tag_columns diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..c6840696d 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -1,15 +1,19 @@ from __future__ import annotations import os +import re from collections.abc import Collection -from pathlib import Path from typing import Any, ClassVar, TYPE_CHECKING import pyarrow as pa from typing_extensions import override -from orcapod.core.sources.base import RootSource, saved_tag_only_columns +from orcapod.core.sources.base import ( + RootSource, + saved_tag_only_columns, + source_paths, +) from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import same_rows @@ -19,7 +23,6 @@ SourceStreamResult, ) from orcapod.databases.storage_utils import delta_to_pyarrow_dataset -from orcapod.types import PathLike from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import _normalize_column_list @@ -29,6 +32,14 @@ deltalake = LazyModule("deltalake") +def _is_delta_uri(path: str) -> bool: + """Identify a URI address, excluding Windows drive paths.""" + return ( + re.match(r"[a-zA-Z][a-zA-Z0-9+.-]*://", path) is not None + and not os.path.splitdrive(path)[0] + ) + + class DeltaTableSource(RootSource): """A source backed by a Delta Lake table. @@ -57,7 +68,7 @@ class DeltaTableSource(RootSource): def __init__( self, - delta_table_path: PathLike, + delta_table_path: str | os.PathLike[str], tag_columns: str | Collection[str] = (), system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, @@ -66,21 +77,21 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **kwargs: Any, ) -> None: - resolved = Path(delta_table_path).resolve() + self._delta_table_path, access_path = source_paths( + delta_table_path, passthrough=_is_delta_uri + ) super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # The table folder's path or URI as passed: a relative path stays relative. # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). - self._source_name = location_source_name(os.fspath(delta_table_path)) - - self._delta_table_path = resolved + self._source_name = location_source_name(self._delta_table_path) try: - self._delta_table = deltalake.DeltaTable(str(self._delta_table_path)) + self._delta_table = deltalake.DeltaTable(access_path) except deltalake.exceptions.TableNotFoundError: - raise ValueError(f"Delta table not found at {self._delta_table_path}") + raise ValueError(f"Delta table not found at {access_path}") self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._system_tag_columns: Collection[str] = system_tag_columns @@ -149,7 +160,7 @@ def check_for_new_data(self) -> bool: table = self._read_table() if not table.schema.equals(self._table.schema, check_metadata=True): raise ValueError( - f"Delta table {str(self._delta_table_path)!r} changed its columns at " + f"Delta table {self._delta_table_path!r} changed its columns at " f"version {version}: the source was built with {self._table.schema}, " f"the table now has {table.schema}. Build a new DeltaTableSource to " "read it" @@ -169,7 +180,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize this source's configuration to a JSON-compatible dict.""" return { "source_type": self.SOURCE_KIND, - "delta_table_path": str(self._delta_table_path), + "delta_table_path": self._delta_table_path, "tag_columns": list(self._tag_columns), **self._tag_only_config(), "system_tag_columns": list(self._system_tag_columns), 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..1c0406751 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -34,7 +34,7 @@ from orcapod.core.sources.db_table_source import DBTableSource from orcapod.core.sources.source_ids import joined_location from orcapod.core.sources.stream_builder import normalize_record_id_columns -from orcapod.core.sources.base import saved_tag_only_columns +from orcapod.core.sources.base import saved_tag_only_columns, source_paths from orcapod.databases.sqlite_connector import SQLiteConnector from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.utils.schema_utils import _normalize_column_list @@ -44,17 +44,6 @@ from orcapod.config import OrcapodConfig -def _access_path(db_path: str | os.PathLike[str]) -> str | os.PathLike[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. - """ - text = os.fspath(db_path) - if text == ":memory:" or text.startswith("file:"): - return db_path - return os.path.abspath(text) - - class SQLiteTableSource(DBTableSource): """A read-only Source backed by a table in a SQLite database. @@ -75,8 +64,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 +98,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 +109,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, self._access_path = source_paths( + db_path, passthrough=lambda path: path in {"", ":memory:"} + ) + 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 +192,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 +201,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 +211,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 +225,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 +244,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_