diff --git a/changelog.d/ITL-1408.md b/changelog.d/ITL-1408.md new file mode 100644 index 000000000..be3c3818c --- /dev/null +++ b/changelog.d/ITL-1408.md @@ -0,0 +1,57 @@ +### Added + +- `PipelineJob` takes a separate database for function results, `result_database=` + (keyword-only, on the constructor, `from_pipeline`, `bind` and `load`; read back as + `job.result_database`). Results are stored in it as given, at `/...` with no job + name, so jobs of different names that share it share function results: a job computes + only the inputs no job sharing it has stored. Pipeline records, operator caches and + side-effect logs stay under each job's own database and name, so each job still reads + only its own rows; a `CachedSource` keeps its cache in its own cache database and path, + whatever job reads it. A function that takes the invocation context (`ctx_arg`) shares + its record of performed actions the same way. `job.bind(result_database=None)` puts the + results back in the job's own database. A saved job records the result database + (`bindings.result_database`, `null` when none was given) and loading rebuilds it as it + rebuilds the job's database; `PipelineJob.load(path, result_database=...)` overrides + it. A saved in-memory result database is not rebuilt (a new one would be empty). When + the file names one that is not available and none is given, the loaded job's function + nodes get no database, with a warning, rather than the job's own `_result` location, and + saving that job writes the binding back as it was. +- A run reads each function node's stored tables (result and pipeline tables) from the + store's current version when the node starts, and a read of what is stored + (`as_source()`, `get_all_records()`) does at every read call, so results committed + through another `DeltaTableDatabase` handle on the same directory (another job, another + process) since the handle loaded the table are reused and read, and a function that + takes the invocation context does not perform those actions again. + +### Changed + +- An active function node on a `DeltaTableDatabase` now reads its tables' current version + at the start of every run, also with the default placement (no `result_database`): it + sees results another handle committed between runs. This costs one extra Delta log open + per table and node at each run (and at each stored read); a node holding a current run, + which runs nothing, opens nothing. + +### Fixed + +- Several pipelines could not share function results (ITL-1408): an earlier `Pipeline` + took a `result_database`, but when the database moved to `PipelineJob` the argument was + dropped and every job stored its results under `/_result`. With no + `result_database` every stored path is as before. +- A node that takes the invocation context (`ctx_arg`) looks for completions of another + data context in its current tables at the start of every run, not only the first: rows + marked with another data context after its first run are refused before anything is + delivered (`SideEffectLogDataContextError`). +- With a separate result database, pipeline records are published only after the results + they name commit, as with one database (ITL-1412's pending commits work across the two + databases), a run flushes the result database before the pipeline database at its end + and after a failure, and `commit_every_rows` is checked against the result database's + `batch_size` too. + +### Known limitations + +- A result committed by another job while a node runs (after it read its tables at its + start) is not seen by that run: the input is computed again, and a function that takes + the invocation context can be delivered by each of two jobs that run at the same time + over the same input. Nothing reserves an input yet. +- A Delta table deleted and recreated at the same path with the same version number is + not noticed by a handle that loaded the old table (ITL-1413). diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 25460e959..cfbbbc79f 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -1109,6 +1109,17 @@ from that database, and no rows under that key is an empty result, not an error. `ArrowTableSource(stream.as_table(), tag_columns=[...])`. - The results are read from the database recorded in the file. Pass `PipelineJob.load(path, database=...)` if the database has moved. +- A job given a separate result database + ([Sharing function results between jobs](pipeline-job.md#sharing-function-results-between-jobs)) + records it in the file too, and loading rebuilds it the same way; pass + `PipelineJob.load(path, result_database=...)` if it has moved or cannot be rebuilt from + the file. An `InMemoryArrowDatabase` holds nothing after its process ends, so it is never + rebuilt (a new one would be empty), as a connector database is not. When the file names a + result database that is not available and none is given, the loaded job's function nodes + get no database (a warning says what to pass): they are never pointed at the job's own + `_result` location, which holds none of their results. `job.bind(result_database=...)` + gives it later, and saving the loaded job before that writes the saved result database + back as it was, so loading that file refuses it the same way. - The job file may also hold an optional, advisory section, `run.expected_rows`: for each node, how many rows the database held under its run's key when the job was saved (written only when that is certain: after a run that finished). Reading a loaded node's stored diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 50159ae81..4444730f6 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -121,7 +121,8 @@ lists every type for every database. On disk the layout is `///...` for each function, plus `//_result/...`. The job's `name` is the top level, so jobs with -different names over one directory do not see each other's results. Deleting the directory, +different names over one directory do not see each other's results, unless they are given +one result database (below). Deleting the directory, or a job's subdirectory, is safe: the next run of a newly built job, for example in a new Python session, recomputes what is missing. A job object that has already run holds its run and computes nothing on a second `run()`. @@ -129,10 +130,88 @@ run and computes nothing on a second `run()`. A job created without a database can be recorded but not run. Give it one later with `job.bind(database=...)`; `run()` without a database raises `ValueError`. +### Sharing function results between jobs + +A function's results depend only on the function and its input values, not on the job +that computed them. Give several jobs one **result database** and they share them: +`PipelineJob(name=..., database=..., result_database=...)`. The function results are +stored in the result database as it is given, at `/...`, with no job name, so +a job computes only the inputs no job sharing it has stored. Pass a view, such as +`results.at("shared")`, to put them under a folder of your choice. + +```python +results = InMemoryArrowDatabase() +shared_calls = [] + + +@function_pod(output_keys="bmi") +def shared_bmi(weight: float, height: float) -> float: + shared_calls.append(weight) + return weight / height**2 + + +for study_name in ["study_1", "study_2"]: + study = PipelineJob( + name=study_name, database=InMemoryArrowDatabase(), result_database=results + ) + with study: + shared_bmi.pod(mice(cohort_a), label="bmi") + study.run() + print(study_name, study.nodes["bmi"].as_table().num_rows, len(shared_calls)) +# study_1 2 2 +# study_2 2 2 + +print(sorted({path[0] for path in results.list_table_paths(())})) +# ['shared_bmi'] +``` + +`study_2` computed nothing: both rows were in the result database. Without +`result_database` (the default) the results are kept in the job's own database at +`/_result/...`, as above. `job.bind(result_database=other)` changes it, and +`job.bind(result_database=None)` puts the results back in the job's own database. + +Only function results are shared. What the job's nodes store stays the job's own, under +its database and name, whatever `result_database` is: each function node's pipeline records +(which rows the job read), an operator's cache and a side-effect pod's log. So a job still +reads only its own rows: two jobs over different sources share one result table, and each +job's nodes, their `as_source()` and a loaded job show the rows of that job's inputs only. +A `CachedSource` is not a node of the job: its cache is kept in the cache database and at +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. + +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 +process), committed before then are reused, not computed again. A read of what is stored +(`as_source()`, `get_all_records()`) likewise reads the tables as they are at that read. +For a `DeltaTableDatabase` each costs one read of each of the node's tables' logs: once +per node and run, or per read call, never per row. Each node looks at its own tables, so +two nodes of one job that share a result table each read its log once in a run. + +Results committed **while** a node runs are another matter. The window opens when the node +starts and reads its tables, and closes at its next run or stored read, or when it +commits that table itself: a result another job commits in between is not seen by this +run, which computes that input again. For an ordinary function this costs only time +(both jobs store the same result). For a function that takes the invocation context, it +means **each of two jobs that run at the same time over the same input can perform the +action**: nothing reserves an input while it is being computed. Do not run two such jobs +over the same inputs at once. + +A `DeltaTableDatabase` notices a newer version of a table, but not a table deleted and +recreated at the same path that happens to have the same version number: a handle that +had loaded the old table keeps reading it (ITL-1413). Open a new database object after +replacing a table. + +A function that takes the invocation context (`ctx_arg`) performs an external action, and +its result table records which inputs it was performed for. Jobs that share a result +database share that record too: a job performs the action only for inputs no job sharing +the database has performed it for. + ### Result commit ordering A function node publishes its pipeline records after the referenced results -commit. Failed result batches withdraw their pending pipeline records. +commit, also when the results are in a separate result database. Failed result batches +withdraw their pending pipeline records. `NoOpArrowDatabase` explicitly discards results and still allows pipeline bookkeeping to be written. @@ -199,8 +278,8 @@ except UnstorableColumnError as exc: ## What a re-run computes A stored result is reused when the function's identity (its name, its output schema and its -**major** version), the input values of the row, and the job's name and database are all -unchanged. Which source, and which steps before the function, the values came through does +**major** version), the input values of the row, and the job's name and database (or the +result database it shares, see above) are all unchanged. Which source, and which steps before the function, the values came through does not matter. ```python @@ -380,11 +459,12 @@ 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 how -each source was configured. `PipelineJob.load(path)` reads it back, for example in a later +`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. The file records each node's own Arrow types, so saving types +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 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. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 8880c5432..d7a4ae803 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -14,6 +14,9 @@ A function stores each result in its result table, at /_result///v/python.function.v1/rev1/rdb_v1 ``` +For a job given a separate result database (`PipelineJob(..., result_database=...)`), the +path starts at ``, in that database, with no `/_result`. + The first four components after `_result` are the function's uri. The last three each have one owner: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ce12e65d7..9313abd8b 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1817,7 +1817,8 @@ layouts above was written by another build of Orcapod. Orcapod does not read it and never modifies it. The path of a table holds hashes (of the function's output schema, of the pipeline), and another build can compute other hashes, so such a table is not looked for at a computed path. The beginning of a path holds no hash: the job, then the name of the -function (`//...` and `/_result//...`; +function (`//...` and `/_result//...`, or `/...` in +a separate result database; `side_effect_function/` for a function pod that takes the invocation context; `side_effects/` for a side-effect pod; `/source` for a cached source without an explicit `cache_path`). A node lists the tables stored under that beginning diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3c6b714cb..592ce404d 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -1514,28 +1514,67 @@ def _delivers_side_effects(self) -> bool: ) def _begin_run(self) -> None: - """Make a node that delivers side effects look for older completions again. + """Start a run: see the stored results as they are now, then check for stale ones. - Tables written before v0.3 can appear in a database between two runs of one - node object. Such a node must find them before it delivers anything, so it - looks for them at the start of every run, also when every input is already - held in memory; other nodes report once, when they first read the database. + The stored tables are read from the store's current version + (``_refresh_stored_tables``), so the run reuses every result committed before + it started, also through another database handle or by another job sharing + the result database, and the stale-completion check below reads what is + stored now (ITL-1408). + + Tables written before v0.3, and completions of another data context, can + appear in a database between two runs of one node object. A node that + delivers side effects must find them before it delivers anything, so it looks + for them at the start of every run, its current tables included, also when + every input is already held in memory; other nodes report once, when they + first read the database. Raises: SideEffectLogDataContextError: If this node delivers side effects and completions it cannot match exist; nothing has been delivered then. """ + self._refresh_stored_tables() if self._delivers_side_effects: self._stale_tables_checked = False + self._current_tables_checked = False self._account_for_stale_tables() + def _refresh_stored_tables(self) -> None: + """Read this node's stored tables from the store's current version (ITL-1408). + + The one place a node looks at its stored tables again: its pipeline table and + its result tables (persistent and ephemeral), every table its reads and its + stale-completion check read. Called at the start of every run (``_begin_run``, + and a load-only run) and at every read of what is stored + (``get_all_records``, so ``as_source()``): once per run or per read call and + per table, never per row. Each node refreshes its own tables, so two nodes + of one job that share a result table each look at it once in a run. + + Every database implements ``refresh_table`` (``ArrowDatabaseProtocol``). A + handle that keeps what it loaded of a table (the Delta database) would otherwise miss rows + committed since through another handle; for it this costs one read of each + table's log, and the table's index is rebuilt only when its version moved. + Other databases read the store on every read: their ``refresh_table`` does + nothing. + """ + tables: list[tuple[ArrowDatabaseProtocol, tuple[str, ...]]] = [] + if self._pipeline_database is not None: + tables.append((self._pipeline_database, self._versioned_pipeline_path)) + for pod in (self._cached_function_pod, self._ephemeral_cached_pod): + if pod is not None and pod.record_path: + tables.append((pod.result_database, pod.record_path)) + for database, record_path in tables: + database.refresh_table(record_path) + def _account_for_stale_tables(self) -> None: """Report or refuse stored rows of other generations. Done once per node object; a node that delivers side effects does it at - the start of every run (``_begin_run``). Its current tables are read and - counted by data context the first time only: the later runs list the database - for tables at an older layout, which reads no table. + the start of every run (``_begin_run``), its current tables included: they are + read and counted by data context at every run, as they are stored then (the + run refreshes them first), so completions marked with another data context + since the last run are found before anything is delivered (ITL-1408). Other + nodes read their current tables the first time only. A pipeline table written by an earlier version of Orcapod (``pdb_v1``) holds no ``__data_context`` column: its rows are not read as results and are left @@ -2042,6 +2081,7 @@ def _execute_load_only( try: if self.load_status == LoadStatus.UNAVAILABLE: raise self._no_database_error() + self._refresh_stored_tables() require_same_data_context( input_stream.data_context_key, self._stored_data_context_key ) @@ -2090,6 +2130,7 @@ async def _async_execute_load_only( try: if self.load_status == LoadStatus.UNAVAILABLE: raise self._no_database_error() + self._refresh_stored_tables() require_same_data_context( self._input_stream.data_context_key, self._stored_data_context_key ) @@ -3277,6 +3318,8 @@ def get_all_records( """ if self._function_pod is None: self._require_readable_stub() + # A read of what is stored reads the store as it is now (ITL-1408). + self._refresh_stored_tables() fetched = self._fetch_joined_records() if fetched is None: return None diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 664957b35..38a05d1ab 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -690,6 +690,9 @@ def flush(self) -> None: for record_key in list(self._pending_batches): self._flush_by_key(record_key) + def refresh_table(self, record_path: tuple[str, ...]) -> None: + """Nothing to refresh: every read queries the connector's backend (ITL-1408).""" + def flush_result_batch( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index e7e2b4b9f..e9fa4019e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2861,6 +2861,38 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: record_key = self._get_record_key(record_path) self._flush_by_key(record_key) + def refresh_table(self, record_path: tuple[str, ...]) -> None: + """Read the table at ``record_path`` from the store's current version next time. + + A handle keeps the table version it loaded (and an index of its rows) and + serves reads from it, so rows another handle or process committed since are + not seen (ITL-1408). This looks at the table's latest version once: when it + moved, the loaded table and its index are replaced (rebuilt on the next read); + when it did not, both are kept. A table remembered as absent is looked for + again. The cost is one read of the table's log; no data is read here. + + Args: + record_path: Tuple of path components (relative to this instance's prefix) + """ + record_key = self._get_record_key(record_path) + self._absent_tables.discard(record_key) + cached = self._delta_table_cache.get(record_key) + if cached is None: + return + try: + latest = deltalake.DeltaTable( + self._get_table_uri(record_path), + storage_options=self._storage_options or None, + ) + except Exception: + # The next read loads the table again and reports a failure itself. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + return + if latest.version() != cached.version(): + self._delta_table_cache[record_key] = latest + self._snapshots.pop(record_key, None) + def _flush_by_key(self, record_key: str) -> None: """Flush a pending batch identified by its absolute record_key (prefix + path). diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 74a4aa218..1c834accc 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -241,6 +241,10 @@ def storage_location(self) -> str: """The wrapped database's storage location, if it names one.""" return getattr(self._db, "storage_location") # noqa: B009 # optional capability + def refresh_table(self, record_path: tuple[str, ...]) -> None: + """Refresh the wrapped database's table (ITL-1408).""" + self._db.refresh_table(record_path) + @property def require_storable(self) -> Callable[[pa.Schema], None]: """The wrapped database's ``require_storable`` (ITL-1162). diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2a6de2bf0..f8d466310 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -384,6 +384,13 @@ def flush(self) -> None: for record_key in list(self._pending_batches): self._flush_by_key(record_key) + def refresh_table(self, record_path: tuple[str, ...]) -> None: + """Nothing to refresh: every view reads the one shared store (ITL-1408). + + All views of an in-memory database share its tables, and two separate + in-memory databases never share data, so no handle can hold an older version. + """ + def flush_result_batch( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 3c60c020b..05b9c01a0 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -108,6 +108,9 @@ def flush(self) -> None: def fail_pending_result(self, record_path: tuple[str, ...]) -> None: """There are no buffered writes to withdraw.""" + def refresh_table(self, record_path: tuple[str, ...]) -> None: + """Nothing to refresh: the no-op store holds no table (ITL-1408).""" + def flush_result_batch( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index c7c570326..960b4a60c 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -3,6 +3,7 @@ from __future__ import annotations import contextlib +import enum import logging import sys from collections.abc import Iterator @@ -60,6 +61,17 @@ logger = logging.getLogger(__name__) + +class _Unchanged(enum.Enum): + """The default of ``PipelineJob.bind(result_database=...)``: keep the binding. + + ``None`` there means something else: store results in the job's own database + again (ITL-1408). + """ + + UNCHANGED = "unchanged" + + _PENDING_BEFORE_RUN_NOTE = ( "These writes were left pending in the database before this run started (written " "without a flush, or by a run that failed). The run stopped before computing " @@ -130,11 +142,17 @@ class PipelineJob(AbstractPipelineBase[JobNode]): Args: name: Pipeline name (string or tuple). Used as the path prefix for all cache/pipeline paths when the pipeline is run. - database: Database for result caching and operator records. + database: Database for the job's records: pipeline records, operator + caches, side-effect logs and, unless ``result_database`` is given, + function results (under ``/_result``). execution_context: Optional execution configuration. tracker_manager: Optional tracker manager override. auto_compile: If ``True`` (default), ``compile()`` is called automatically when the context manager exits. + result_database: Optional database for function results, used as given (no + job name is added to its paths), so jobs that share it share function + results (ITL-1408). ``None`` (the default) stores them under the job's + own database, at ``/_result``. """ # ------------------------------------------------------------------ @@ -153,9 +171,18 @@ def __init__( execution_context: "ExecutionContext | None" = None, tracker_manager: cp.TrackerManagerProtocol | None = None, auto_compile: bool = True, + *, + result_database: "ArrowDatabaseProtocol | None" = None, ) -> None: super().__init__(name=name, tracker_manager=tracker_manager) self._database = database + 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: + # that saved configuration. Its function nodes get no database rather than the + # job's own ``_result`` location, which holds none of their results, and a save + # writes the configuration back as it was (ITL-1408). + self._unresolved_result_database: dict[str, Any] | None = None self._execution_context = execution_context self._auto_compile = auto_compile # name → bound concrete source (user-facing API: job.sources). @@ -298,9 +325,21 @@ def sources(self) -> dict[str, cp.StreamProtocol]: @property def database(self) -> "ArrowDatabaseProtocol | None": - """The database used for result caching.""" + """The job's database: pipeline records, operator caches, side-effect logs. + + It also holds the function results unless ``result_database`` is set. + """ return self._database + @property + def result_database(self) -> "ArrowDatabaseProtocol | None": + """The separate database for function results, or ``None`` when not given. + + ``None`` means the results are stored in the job's own database, under + ``/_result`` (ITL-1408). + """ + return self._result_database + @property def execution_context(self) -> "ExecutionContext | None": """The execution configuration, or ``None`` if unset.""" @@ -317,6 +356,8 @@ def from_pipeline( database: "ArrowDatabaseProtocol | None" = None, sources: "dict[str, cp.StreamProtocol] | None" = None, execution_context: "ExecutionContext | None" = None, + *, + result_database: "ArrowDatabaseProtocol | None" = None, ) -> "PipelineJob": """Create a runnable ``PipelineJob`` from a compiled ``Pipeline``. @@ -332,6 +373,8 @@ def from_pipeline( database: Database for result caching and operator records. sources: Mapping of ``SourceNode.name`` → concrete source. execution_context: Optional execution configuration. + result_database: Optional separate database for function results, as + for the constructor. Returns: A new ``PipelineJob`` ready to run (or ``bind()`` further). @@ -376,6 +419,7 @@ def from_pipeline( job = cls.from_invocations(pipeline.to_invocations(), name=pipeline._name) job._database = database # pyright: ignore[reportAttributeAccessIssue] # from_invocations is typed as the base class; the instance is a PipelineJob job._execution_context = execution_context + job._result_database = result_database # pyright: ignore[reportAttributeAccessIssue] # as for _database above # Bind concrete sources and distribute databases. if bound_sources: @@ -394,6 +438,8 @@ def bind( sources: "dict[str, cp.StreamProtocol] | None" = None, database: "ArrowDatabaseProtocol | None" = None, execution_context: "ExecutionContext | None" = None, + *, + result_database: "ArrowDatabaseProtocol | None | _Unchanged" = _Unchanged.UNCHANGED, ) -> None: """Update bindings in place. Returns ``None``. @@ -408,14 +454,18 @@ def bind( validated before anything is changed: a refused source leaves the job's bindings and database as they were. - When *database* is provided and differs from the current database, - ``_distribute_databases()`` is called so that all job nodes receive - live DB references immediately. + When *database* or *result_database* is provided and differs from the + current one, ``_distribute_databases()`` is called (once a database is set) + so that all job nodes receive live DB references immediately. Args: sources: Mapping of ``SourceNode.name`` → concrete source. database: Replaces the current database and triggers DB redistribution. execution_context: Replaces the current execution context. + result_database: Replaces the separate database for function results + (see the constructor) and triggers DB redistribution. Leave it out to + keep the current binding; pass ``None`` to store function results in + the job's own database again, at ``/_result`` (ITL-1408). Raises: SourceSpecMismatchError: If any source's columns differ from its slot's @@ -424,12 +474,21 @@ def bind( operator node that caches (``LOG`` or ``REPLAY``) would read a restricted source, one this bind binds or one already bound (ITL-1218); the job is left as it was. - UnstorableColumnError: If *database* cannot store a table of a node - (ITL-1162); the job is left as it was. + UnstorableColumnError: If *database* or *result_database* cannot store + a table of a node (ITL-1162); the job is left as it was. """ from orcapod.core.nodes.source_node import SourceNodeBase - database_changed = database is not None and database is not self._database + result_database_given = not isinstance(result_database, _Unchanged) + database_changed = ( + database is not None and database is not self._database + ) or ( + result_database_given + and ( + result_database is not self._result_database + or self._unresolved_result_database is not None + ) + ) if sources is not None: source_names = { @@ -463,13 +522,21 @@ def bind( refuse_restriction_conflicts( (self._persistent_node_map or {}).values(), rebinding=rebinding ) - if database_changed and database is not None: - self._require_storable_tables(database) + new_database = database if database is not None else self._database + new_result_database = ( + self._result_database + if isinstance(result_database, _Unchanged) + else result_database + ) + if database_changed and new_database is not None: + self._require_storable_tables(new_database, new_result_database) # Every source is validated before anything changes: a refused source leaves # the job as it was, its database included (ITL-1112). - if database is not None: - self._database = database + self._database = new_database + self._result_database = new_result_database + if result_database_given: + self._unresolved_result_database = None if sources is not None: # Update bound_source on SourceJobNodes and maintain both dicts. @@ -494,30 +561,61 @@ def bind( if execution_context is not None: self._execution_context = execution_context - if database_changed: + if database_changed and self._database is not None: self._distribute_databases() # ------------------------------------------------------------------ # _distribute_databases() # ------------------------------------------------------------------ - def _require_storable_tables(self, database: "ArrowDatabaseProtocol") -> None: - """Refuse ``database`` if it cannot store a table of one of the job's nodes. + def _database_views( + self, + database: "ArrowDatabaseProtocol", + result_database: "ArrowDatabaseProtocol | None", + ) -> "tuple[ArrowDatabaseProtocol, ArrowDatabaseProtocol]": + """The job's two views: its pipeline database and its function-result database. + + The one place that decides where a job stores (ITL-1408): the pipeline view is + ``database`` under the job's name; function results go to ``result_database`` + as given, or, when none is given, under the pipeline view at ``_result``. + + Args: + database: The job's database. + result_database: The separate database for function results, if any. + + Returns: + ``(pipeline view, result view)``. + """ + pipeline_db = database.at(*self._name) + if result_database is not None: + return pipeline_db, result_database + return pipeline_db, pipeline_db.at("_result") + + def _require_storable_tables( + self, + database: "ArrowDatabaseProtocol", + result_database: "ArrowDatabaseProtocol | None", + ) -> None: + """Refuse databases that cannot store a table of one of the job's nodes. The same views as ``_distribute_databases`` gives the nodes. Nothing changes (ITL-1162). Args: database: The job database to check. + result_database: The separate function-result database to check, if any. Raises: - UnstorableColumnError: For the first node whose table the database + UnstorableColumnError: For the first node whose table a database cannot store, naming the node. """ - pipeline_db = database.at(*self._name) - result_db = pipeline_db.at("_result") + pipeline_db, result_db = self._database_views(database, result_database) for node in (self._persistent_node_map or {}).values(): if isinstance(node, FunctionJobNode): + # Checked against the candidate databases only, never the job's + # current binding state: a loaded job (the only one whose result + # database can be unavailable) has function nodes without a function, + # which this check skips by itself. node.require_storable_tables(pipeline_db, result_db) elif isinstance(node, OperatorJobNode): node.require_storable_tables(pipeline_db, node.cache_mode) @@ -543,12 +641,16 @@ def _distribute_databases(self) -> None: # leaves every node as it was (ITL-1162), and so is a caching operator over # a restricted source (ITL-1218). refuse_restricted_operator_caches((self._persistent_node_map or {}).values()) - self._require_storable_tables(self._database) - pipeline_db = self._database.at(*self._name) - result_db = pipeline_db.at("_result") + self._require_storable_tables(self._database, self._result_database) + pipeline_db, result_db = self._database_views( + self._database, self._result_database + ) for node in (self._persistent_node_map or {}).values(): if isinstance(node, FunctionJobNode): + if self._unresolved_result_database is not None: + # Left without a database (see ``load``), never given ``_result``. + continue node.attach_databases( pipeline_database=pipeline_db, result_database=result_db, @@ -1131,18 +1233,27 @@ def _prepare_run( # Until this run finishes, what the database holds for a node is not certain. self._last_run_finished = False - table_committing = as_table_committing(self._database) - if ( - table_committing is not None - and commit_every_rows >= table_committing.batch_size - ): - raise ValueError( - f"commit_every_rows={commit_every_rows} must be smaller than the " - f"database's batch_size={table_committing.batch_size}: the database commits a " - "table by itself once it holds batch_size pending rows, which could " - "commit pipeline records before their results. Use a smaller " - "commit_every_rows, or create the database with a larger batch_size." + # The job's database, then a separate result database (ITL-1408): each one + # that commits table by table. + committing = [ + committing_db + for committing_db in ( + as_table_committing(self._database), + as_table_committing(self._result_database), ) + if committing_db is not None + ] + table_committing = committing[0] if committing else None + for committing_db in committing: + if commit_every_rows >= committing_db.batch_size: + raise ValueError( + f"commit_every_rows={commit_every_rows} must be smaller than the " + + f"database's batch_size={committing_db.batch_size}: the database " + + "commits a table by itself once it holds batch_size pending rows, " + + "which could commit pipeline records before their results. Use a " + + "smaller commit_every_rows, or create the database with a larger " + + "batch_size." + ) if self._database is None: raise ValueError( "PipelineJob.run() requires a database. " @@ -1261,8 +1372,9 @@ def _prepare_run( snapshot_hash = hashlib.sha256("\n".join(leaf_hashes).encode()).hexdigest()[:16] pipeline_uri = "/".join(self._name) + "@" + snapshot_hash - pipeline_db = self._database.at(*self._name) - result_db = pipeline_db.at("_result") + pipeline_db, result_db = self._database_views( + self._database, self._result_database + ) # 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 @@ -1283,17 +1395,24 @@ def _prepare_run( # A load-only run writes nothing, and a run that runs no node touches no database, # so neither commits anything, not even pending writes of earlier operations. if table_committing is not None and not load_only and plan.to_run: - try: - pipeline_db.flush() - except OrcapodDatabaseError as exc: - exc.add_note(_PENDING_BEFORE_RUN_NOTE) - raise - except Exception as exc: - flush_error = OrcapodDatabaseWriteError( - pipeline_db.base_path, flush=True - ) - flush_error.add_note(_PENDING_BEFORE_RUN_NOTE) - raise flush_error from exc + # A separate result database (ITL-1408) is committed too, results first. + pending_dbs = ( + (result_db, pipeline_db) + if self._result_database is not None + else (pipeline_db,) + ) + for pending_db in pending_dbs: + try: + pending_db.flush() + except OrcapodDatabaseError as exc: + exc.add_note(_PENDING_BEFORE_RUN_NOTE) + raise + except Exception as exc: + flush_error = OrcapodDatabaseWriteError( + pending_db.base_path, flush=True + ) + flush_error.add_note(_PENDING_BEFORE_RUN_NOTE) + raise flush_error from exc return _PreparedRun( exec_dag=exec_dag, @@ -1340,7 +1459,17 @@ def _executing( # been withdrawn, and pending results still gate their dependent records. # A cancelled or interrupted run clears its nodes without flushing here. if isinstance(run_error, Exception) and not load_only: - flush_best_effort(run_error, prepared.pipeline_db, prepared.result_db) + flush_best_effort( + run_error, + prepared.pipeline_db, + prepared.result_db, + # Records a separate result database's flush released (ITL-1408). + *( + (prepared.pipeline_db,) + if self._result_database is not None + else () + ), + ) clear_run_rows(plan.to_run) raise @@ -1386,9 +1515,17 @@ def _finish_run( if not load_only and plan.to_run: # A load-only run writes nothing and commits nothing, and a run that # ran no node touches no database (ITL-1095). + # Pending results gate the pipeline records that name them (ITL-1412), + # across databases too, so no order of these flushes publishes a record + # before its result. database.flush() database = result_db database.flush() + if self._result_database is not None: + # A separate result database (ITL-1408): records the result flush + # just released are still queued in the pipeline database. + database = pipeline_db + database.flush() except OrcapodDatabaseReadError as exc: # A stored table could not be read: report the read failure itself. exc.add_note(pending_note) @@ -1500,6 +1637,13 @@ def save(self, path: "str | Path") -> None: database_block = None 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 + # the results are in the job's own database (``/_result``). + # A loaded job's binding that was not available is written back as it was, so + # the next load refuses it again rather than reading ``_result``. + result_database_block = self._unresolved_result_database + if self._result_database is not None: + result_database_block = self._result_database.to_config() if not self._has_run: status = "pending" @@ -1555,6 +1699,7 @@ def save(self, path: "str | Path") -> None: "bindings": { "sources": sources_block, "database": database_block, + "result_database": result_database_block, }, } @@ -1566,6 +1711,8 @@ def load( cls, path: "str | Path", database: "ArrowDatabaseProtocol | None" = None, + *, + result_database: "ArrowDatabaseProtocol | None" = None, ) -> "PipelineJob": """Deserialize a ``PipelineJob`` from a JSON file to read its stored results. @@ -1589,6 +1736,14 @@ def load( path: Path to the JSON file produced by ``save()``. database: Optional database override. When provided, takes precedence over any database configuration in the file. + result_database: Optional override of the separate function-result + database (ITL-1408). When provided, it is used whatever the file + says. Otherwise the one the file names is rebuilt from its saved + configuration, as the job's database is; a file that names none + keeps the results in the job's database (``/_result``). When + the file names one that cannot be rebuilt, the function nodes get no + database (a warning says what to pass) rather than the job's own + ``_result`` location, which holds none of their results. Returns: A read-only ``PipelineJob`` whose nodes' stored views serve their stored @@ -1750,7 +1905,48 @@ def load( # that cannot compute content hashes, so the to_invocations() → from_invocations() # path used by from_pipeline() would fail. Instead, attach the loaded # pipeline directly as the compiled blueprint and set up source bindings. - job = cls(name=pipeline._name, database=effective_database) + # Reconstruct the separate result database (ITL-1408), by the same rule. + 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") + 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. + unresolved_result_database = result_config + logger.warning( + "The job's separate result database (bindings.result_database) " + "was an in-memory database, which keeps no data after its process " + "ends. The function nodes' results cannot be read until it is " + "given: PipelineJob.load(path, result_database=...) or " + "job.bind(result_database=...)." + ) + elif result_config: + try: + from orcapod.pipeline.serialization import ( + resolve_database_from_config, + ) + + effective_result_database = resolve_database_from_config( + result_config + ) + except Exception as exc: + unresolved_result_database = result_config + logger.warning( + "Could not reconstruct the job's separate result database " + "(bindings.result_database) from its saved config: %s. The " + "function nodes' results cannot be read until it is given: " + "PipelineJob.load(path, result_database=...) or " + "job.bind(result_database=...).", + exc, + ) + + job = cls( + name=pipeline._name, + database=effective_database, + result_database=effective_result_database, + ) + job._unresolved_result_database = unresolved_result_database job._loaded = True job._compiled_pipeline = pipeline # Mark compiled so save() / compiled_pipeline can be accessed. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 3457ad8d9..2620fe346 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -128,13 +128,18 @@ def refuse_unloadable_inputs(node: Any) -> None: def _databases(nodes: list[Any]) -> list[ArrowDatabaseProtocol]: - """The distinct databases the given nodes write to: pipeline and result databases.""" + """The distinct databases the given nodes write to, each node's results first. + + A function node's result database comes before its pipeline database, so the + end-of-run commit stores results before the records that point at them (ITL-919), + also when the results are in a separate database (ITL-1408). + """ found: list[ArrowDatabaseProtocol] = [] for node in nodes: pipeline_database = getattr(node, "_pipeline_database", None) cached_pod = getattr(node, "_cached_function_pod", None) result_database = getattr(cached_pod, "result_database", None) - for database in (pipeline_database, result_database): + for database in (result_database, pipeline_database): if database is not None and not any(database is d for d in found): found.append(database) return found diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index be9903977..6b8e26d5e 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -60,6 +60,18 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: """ ... + def refresh_table(self, record_path: tuple[str, ...]) -> None: + """Read the table at ``record_path`` from the store's current version next time. + + A function node calls it for each of its stored tables at the start of every + run and at every read of what it stored, so it sees rows another handle, + job or process committed since (ITL-1408). A database whose handle keeps + what it loaded of a table (``DeltaTableDatabase``) looks at the store again; + one that reads the store on every read (in memory, connector-backed, no-op) + has nothing to refresh and does nothing. + """ + ... + def add_record( self, record_path: tuple[str, ...], diff --git a/tests/test_databases/test_refresh_table.py b/tests/test_databases/test_refresh_table.py new file mode 100644 index 000000000..227884cbe --- /dev/null +++ b/tests/test_databases/test_refresh_table.py @@ -0,0 +1,121 @@ +"""Every database implements ``refresh_table``, a required protocol member (ITL-1408). + +A function node calls it unconditionally on each of its stored tables at the start of +every run and at every stored read. ``DeltaTableDatabase`` looks at the store again; +the in-memory, connector-backed and no-op databases read the store on every read and +do nothing. Protocols are internal: a capability is a required method, never an +optional protocol plus a check. +""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable +from pathlib import Path + +import pyarrow as pa +import pytest + +import orcapod.databases as databases +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, + SQLiteConnector, +) +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + +FACTORIES: dict[str, Callable[[Path], ArrowDatabaseProtocol]] = { + "in_memory": lambda _: InMemoryArrowDatabase(), + "delta": lambda path: DeltaTableDatabase(path / "delta"), + "connector": lambda _: ConnectorArrowDatabase(SQLiteConnector(":memory:")), + "noop": lambda _: NoOpArrowDatabase(), + "extension_aware": lambda _: ExtensionAwareDatabase.from_config( + InMemoryArrowDatabase().to_config() + ), +} + +DATABASE_CLASSES = ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) + + +def test_every_exported_database_class_is_covered() -> None: + """A new database class the library exports must be added here.""" + exported = { + getattr(databases, name) + for name in databases.__all__ + if inspect.isclass(getattr(databases, name)) + and hasattr(getattr(databases, name), "add_record") + } + assert exported == set(DATABASE_CLASSES) + + +@pytest.mark.parametrize("cls", DATABASE_CLASSES, ids=lambda c: c.__name__) +def test_each_class_defines_refresh_table(cls: type) -> None: + """Defined on the class itself: no attribute lookup decides whether it exists.""" + assert "refresh_table" in vars(cls) + assert callable(vars(cls)["refresh_table"]) + + +@pytest.mark.parametrize("kind", sorted(FACTORIES)) +def test_each_database_conforms_and_refreshes_any_path( + tmp_path: Path, kind: str +) -> None: + """Conforms to the protocol; refreshing a table that does not exist is harmless.""" + database = FACTORIES[kind](tmp_path) + assert isinstance(database, ArrowDatabaseProtocol) + database.refresh_table(("no", "such", "table")) + database.at("scoped").refresh_table(("no", "such", "table")) + + +def _rows(ids: list[int]) -> pa.Table: + return pa.table( + { + "__rid": pa.array([str(i).encode() for i in ids], pa.large_binary()), + "x": pa.array(ids, pa.int64()), + } + ) + + +def test_delta_refresh_sees_another_handles_commit(tmp_path: Path) -> None: + """The real refresh: a warm handle reads another handle's commit after it.""" + warm = DeltaTableDatabase(tmp_path / "store") + other = DeltaTableDatabase(tmp_path / "store") + path = ("t",) + warm.add_records(path, _rows([1]), record_id_column="__rid") + warm.flush() + stored = warm.get_all_records(path) + assert stored is not None and stored.num_rows == 1 + other.add_records(path, _rows([2]), record_id_column="__rid") + other.flush() + stale = warm.get_all_records(path) + assert stale is not None and stale.num_rows == 1 # the loaded version + warm.refresh_table(path) + fresh = warm.get_all_records(path) + assert fresh is not None + assert sorted(fresh.column("x").to_pylist(), key=lambda v: v or 0) == [1, 2] + + +def test_extension_aware_forwards_to_the_wrapped_database(tmp_path: Path) -> None: + """The wrapper refreshes the Delta database it wraps.""" + from orcapod.semantic_types.universal_converter import UniversalTypeConverter + + inner = DeltaTableDatabase(tmp_path / "store") + wrapped = ExtensionAwareDatabase(inner, UniversalTypeConverter()) + refreshed: list[tuple[str, ...]] = [] + original = inner.refresh_table + + def record(record_path: tuple[str, ...]) -> None: + refreshed.append(record_path) + original(record_path) + + inner.refresh_table = record # pyright: ignore[reportAttributeAccessIssue] # instance spy + wrapped.refresh_table(("t",)) + assert refreshed == [("t",)] diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 03182fff7..98fd6598a 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -461,6 +461,9 @@ def flush_result_batch( def flush_batch(self, record_path: tuple[str, ...]) -> None: self._inner.flush_batch(record_path) + def refresh_table(self, record_path: tuple[str, ...]) -> None: + self._inner.refresh_table(record_path) + def test_library_databases_conform_to_the_commit_protocol(tmp_path: Path) -> None: """Built-in stores conform, and an incomplete store fails the runtime check.""" diff --git a/tests/test_pipeline/test_result_database.py b/tests/test_pipeline/test_result_database.py new file mode 100644 index 000000000..315929dd6 --- /dev/null +++ b/tests/test_pipeline/test_result_database.py @@ -0,0 +1,1002 @@ +"""A job stores function results in a separate result database when given one (ITL-1408). + +With no ``result_database`` every path is as before: results under +``/_result``. With one, results are stored in it as given, with no job name, +so several jobs share them: a second job computes nothing that a first job stored. +Pipeline records, operator caches and side-effect logs stay under each job's own +database and name. +""" + +from __future__ import annotations + +import json +import logging +import pathlib +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import SelectDataColumns +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import SideEffectLogDataContextError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import ArrowTableSource + +Orchestrator = SyncPipelineOrchestrator | AsyncPipelineOrchestrator + +calls: list[tuple[str, Any]] = [] +delivered: list[float] = [] + + +@function_pod(output_keys="doubled") +def double(x: float) -> float: + """First step: counted.""" + calls.append(("double", x)) + return x * 2 + + +@function_pod(output_keys=["shifted", "label"]) +def shift(doubled: float) -> tuple[float, str]: + """Second step, two outputs: counted.""" + calls.append(("shift", doubled)) + return doubled + 1, f"v{doubled}" + + +@function_pod(output_keys="doubled", function_name="double") +def double_as_text(x: float) -> str: + """Same function name as ``double``, another output schema: another uri.""" + calls.append(("double_as_text", x)) + return str(x * 2) + + +@function_pod(output_keys="sent", ctx_arg="ctx") +def notify(x: float, ctx: Any) -> float: + """A function that takes the invocation context: its call is an external action.""" + delivered.append(x) + return x + + +@pytest.fixture(autouse=True) +def _reset() -> None: + calls.clear() + delivered.clear() + + +@pytest.fixture(params=["sync", "async"]) +def orchestrator(request: pytest.FixtureRequest) -> Orchestrator: + if request.param == "sync": + return SyncPipelineOrchestrator() + return AsyncPipelineOrchestrator() + + +def make_source(xs: list[float], source_id: str = "s") -> ArrowTableSource: + """Two tag columns and two data columns; ``x`` is what the functions read.""" + n = len(xs) + schema = pa.schema( + [ + pa.field("subject", pa.large_string(), nullable=False), + pa.field("session", pa.int64(), nullable=False), + pa.field("x", pa.float64(), nullable=False), + pa.field("note", pa.large_string(), nullable=False), + ] + ) + table = pa.table( + [ + pa.array([f"m{i}" for i in range(n)], pa.large_string()), + pa.array(list(range(n)), pa.int64()), + pa.array(xs, pa.float64()), + pa.array([f"n{i}" for i in range(n)], pa.large_string()), + ], + schema=schema, + ) + return ArrowTableSource( + table, + tag_columns=["subject", "session"], + tag_only_columns=True, + source_id=source_id, + ) + + +def two_step_job( + name: str, + database: ArrowDatabaseProtocol, + xs: list[float], + result_database: ArrowDatabaseProtocol | None = None, + source_id: str = "s", +) -> PipelineJob: + """A job of two chained function nodes, then an operator.""" + job = PipelineJob(name=name, database=database, result_database=result_database) + with job: + doubled = double.pod(make_source(xs, source_id), label="double") + shifted = shift.pod(doubled, label="shift") + _ = SelectDataColumns(["shifted"])(shifted) + return job + + +def table_paths(database: ArrowDatabaseProtocol) -> list[str]: + return sorted("/".join(path) for path in database.list_table_paths(())) + + +def rows(job: PipelineJob, label: str, column: str) -> list[Any]: + """A node's values of ``column``, sorted (no order is promised).""" + return sorted(job.nodes[label].as_table().column(column).to_pylist()) + + +def stored_rows(job: PipelineJob, label: str, column: str) -> list[Any]: + """The values of ``column`` in a node's stored view, sorted.""" + return sorted(job.nodes[label].as_source().as_table().column(column).to_pylist()) + + +class TestPaths: + def test_without_a_result_database_results_are_under_the_job(self) -> None: + db = InMemoryArrowDatabase() + job = two_step_job("a", db, [1.0, 2.0]) + _ = job.run() + assert job.result_database is None + result_tables = [p for p in table_paths(db) if p.endswith("rdb_v1")] + assert len(result_tables) == 2 + assert all(p.startswith("a/_result/") for p in result_tables) + + def test_with_a_result_database_results_carry_no_job_name(self) -> None: + db = InMemoryArrowDatabase() + results = InMemoryArrowDatabase() + job = two_step_job("a", db, [1.0, 2.0], result_database=results) + _ = job.run() + assert job.result_database is results + assert sorted(p.split("/")[0] for p in table_paths(results)) == [ + "double", + "shift", + ] + assert all(p.endswith("rev1/rdb_v1") for p in table_paths(results)) + # Pipeline records stay under the job's own name. + own = table_paths(db) + assert own and all(p.startswith("a/") for p in own) + assert not any("_result" in p or p.endswith("rdb_v1") for p in own) + + def test_a_scoped_view_is_used_as_given(self) -> None: + results = InMemoryArrowDatabase() + job = two_step_job( + "a", InMemoryArrowDatabase(), [1.0], result_database=results.at("shared") + ) + _ = job.run() + assert all(p.startswith("shared/") for p in table_paths(results)) + + +class TestSharing: + @pytest.mark.parametrize("names", [("a", "b"), ("b", "a")]) + def test_a_second_job_computes_nothing_the_first_stored( + self, names: tuple[str, str], orchestrator: Orchestrator + ) -> None: + db = InMemoryArrowDatabase() + results = InMemoryArrowDatabase() + first = two_step_job(names[0], db, [1.0, 2.0, 3.0], result_database=results) + _ = first.run(orchestrator=orchestrator) + assert len(calls) == 6 + calls.clear() + + second = two_step_job(names[1], db, [1.0, 2.0, 3.0], result_database=results) + _ = second.run(orchestrator=orchestrator) + assert calls == [] + assert rows(second, "shift", "shifted") == [3.0, 5.0, 7.0] + # Each job keeps its own pipeline records. + assert {p.split("/")[0] for p in table_paths(db)} == {"a", "b"} + + def test_only_inputs_not_stored_are_computed( + self, orchestrator: Orchestrator + ) -> None: + results = InMemoryArrowDatabase() + _ = two_step_job( + "a", InMemoryArrowDatabase(), [1.0, 2.0], result_database=results + ).run(orchestrator=orchestrator) + calls.clear() + second = two_step_job( + "b", InMemoryArrowDatabase(), [2.0, 1.0, 4.0], result_database=results + ) + _ = second.run(orchestrator=orchestrator) + assert sorted(calls) == [("double", 4.0), ("shift", 8.0)] + assert rows(second, "double", "doubled") == [2.0, 4.0, 8.0] + + def test_without_a_result_database_jobs_do_not_share(self) -> None: + db = InMemoryArrowDatabase() + _ = two_step_job("a", db, [1.0, 2.0]).run() + calls.clear() + _ = two_step_job("b", db, [1.0, 2.0]).run() + assert len(calls) == 4 + + def test_another_output_schema_is_another_table( + self, orchestrator: Orchestrator + ) -> None: + results = InMemoryArrowDatabase() + _ = two_step_job( + "a", InMemoryArrowDatabase(), [1.0, 2.0], result_database=results + ).run(orchestrator=orchestrator) + calls.clear() + job = PipelineJob( + name="b", database=InMemoryArrowDatabase(), result_database=results + ) + with job: + double_as_text.pod(make_source([1.0, 2.0]), label="double") + _ = job.run(orchestrator=orchestrator) + assert sorted(calls) == [("double_as_text", 1.0), ("double_as_text", 2.0)] + assert rows(job, "double", "doubled") == ["2.0", "4.0"] + double_tables = [p for p in table_paths(results) if p.startswith("double/")] + assert len(double_tables) == 2 + assert double_tables[0].split("/")[1] != double_tables[1].split("/")[1] + + +class TestEachJobReadsItsOwnRows: + """Two jobs over different sources share one result table; each reads its own.""" + + @pytest.fixture + def jobs( + self, tmp_path: pathlib.Path, orchestrator: Orchestrator + ) -> tuple[PipelineJob, PipelineJob, pathlib.Path]: + db = DeltaTableDatabase(tmp_path / "jobs") + results = DeltaTableDatabase(tmp_path / "results") + a = two_step_job("a", db, [1.0, 2.0], result_database=results, source_id="sa") + b = two_step_job( + "b", db, [2.0, 10.0, 20.0], result_database=results, source_id="sb" + ) + _ = a.run(orchestrator=orchestrator) + _ = b.run(orchestrator=orchestrator) + assert len([p for p in table_paths(results) if "double" in p]) == 1 + return a, b, tmp_path + + def test_as_table_and_as_source( + self, jobs: tuple[PipelineJob, PipelineJob, pathlib.Path] + ) -> None: + a, b, _ = jobs + assert rows(a, "double", "doubled") == [2.0, 4.0] + assert rows(b, "double", "doubled") == [4.0, 20.0, 40.0] + assert stored_rows(a, "shift", "shifted") == [3.0, 5.0] + assert stored_rows(b, "shift", "shifted") == [5.0, 21.0, 41.0] + + def test_a_loaded_job( + self, jobs: tuple[PipelineJob, PipelineJob, pathlib.Path] + ) -> None: + a, b, tmp_path = jobs + a.save(tmp_path / "a.json") + b.save(tmp_path / "b.json") + loaded_a = PipelineJob.load(tmp_path / "a.json") + loaded_b = PipelineJob.load(tmp_path / "b.json") + assert isinstance(loaded_a.result_database, DeltaTableDatabase) + assert stored_rows(loaded_a, "shift", "shifted") == [3.0, 5.0] + assert stored_rows(loaded_b, "shift", "shifted") == [5.0, 21.0, 41.0] + + def test_a_load_only_run( + self, jobs: tuple[PipelineJob, PipelineJob, pathlib.Path] + ) -> None: + a, b, tmp_path = jobs + a.save(tmp_path / "a.json") + b.save(tmp_path / "b.json") + loaded_a = PipelineJob.load(tmp_path / "a.json") + loaded_b = PipelineJob.load(tmp_path / "b.json") + calls.clear() + _ = loaded_a.bind(sources={"sa": make_source([1.0, 2.0], "sa")}) + _ = loaded_b.bind(sources={"sb": make_source([2.0, 10.0, 20.0], "sb")}) + _ = loaded_a.run(load_only=True) + _ = loaded_b.run(load_only=True) + assert calls == [] + assert rows(loaded_a, "shift", "shifted") == [3.0, 5.0] + assert rows(loaded_b, "shift", "shifted") == [5.0, 21.0, 41.0] + + +class TestSaveAndLoad: + def test_without_a_result_database_the_file_names_none( + self, tmp_path: pathlib.Path + ) -> None: + job = two_step_job("a", DeltaTableDatabase(tmp_path / "db"), [1.0]) + _ = job.run() + job.save(tmp_path / "job.json") + saved = json.loads((tmp_path / "job.json").read_text()) + assert saved["bindings"]["result_database"] is None + loaded = PipelineJob.load(tmp_path / "job.json") + assert loaded.result_database is None + assert stored_rows(loaded, "double", "doubled") == [2.0] + + def test_an_explicit_result_database_wins_over_the_file( + self, tmp_path: pathlib.Path + ) -> None: + results = DeltaTableDatabase(tmp_path / "results") + job = two_step_job( + "a", DeltaTableDatabase(tmp_path / "db"), [1.0], result_database=results + ) + _ = job.run() + job.save(tmp_path / "job.json") + # The results moved: the file's location now holds none. + (tmp_path / "results").rename(tmp_path / "moved") + loaded = PipelineJob.load( + tmp_path / "job.json", + result_database=DeltaTableDatabase(tmp_path / "moved"), + ) + assert stored_rows(loaded, "shift", "shifted") == [3.0] + + def test_a_result_database_that_cannot_be_rebuilt_is_not_replaced( + self, tmp_path: pathlib.Path, caplog: pytest.LogCaptureFixture + ) -> None: + results = DeltaTableDatabase(tmp_path / "results") + job = two_step_job( + "a", DeltaTableDatabase(tmp_path / "db"), [1.0], result_database=results + ) + _ = job.run() + job.save(tmp_path / "job.json") + saved = json.loads((tmp_path / "job.json").read_text()) + saved["bindings"]["result_database"] = {"type": "no_such_database"} + (tmp_path / "job.json").write_text(json.dumps(saved)) + + with caplog.at_level(logging.WARNING, logger="orcapod.pipeline.job"): + loaded = PipelineJob.load(tmp_path / "job.json") + assert "bindings.result_database" in caplog.text + assert "result_database=" in caplog.text + # The function nodes get no database, never the job's own _result location. + with pytest.raises(RuntimeError): + loaded.nodes["double"].as_source() + _ = loaded.bind(result_database=results) + assert stored_rows(loaded, "shift", "shifted") == [3.0] + + +class TestBind: + def test_bind_a_result_database(self) -> None: + db = InMemoryArrowDatabase() + results = InMemoryArrowDatabase() + _ = two_step_job("a", db, [1.0], result_database=results).run() + calls.clear() + job = two_step_job("b", db, [1.0]) + _ = job.bind(result_database=results) + _ = job.run() + assert calls == [] + assert not any(p.startswith("b/_result") for p in table_paths(db)) + + def test_the_batch_size_of_a_result_database_is_checked( + self, tmp_path: pathlib.Path + ) -> None: + job = two_step_job( + "a", + InMemoryArrowDatabase(), + [1.0], + result_database=DeltaTableDatabase(tmp_path / "r", batch_size=5), + ) + with pytest.raises(ValueError, match="batch_size=5"): + _ = job.run(commit_every_rows=10) + + +class TestSideEffectingFunctions: + """A function that takes the invocation context shares its completions.""" + + @staticmethod + def notify_job( + name: str, xs: list[float], results: ArrowDatabaseProtocol + ) -> PipelineJob: + job = PipelineJob( + name=name, database=InMemoryArrowDatabase(), result_database=results + ) + with job: + notify.pod(make_source(xs), label="notify") + return job + + def test_only_inputs_no_job_delivered_are_delivered( + self, orchestrator: Orchestrator + ) -> None: + results = InMemoryArrowDatabase() + _ = self.notify_job("a", [1.0, 2.0], results).run(orchestrator=orchestrator) + assert sorted(delivered) == [1.0, 2.0] + delivered.clear() + job = self.notify_job("b", [2.0, 3.0, 1.0], results) + _ = job.run(orchestrator=orchestrator) + assert delivered == [3.0] + assert rows(job, "notify", "sent") == [1.0, 2.0, 3.0] + + def test_an_old_result_table_in_the_result_database_refuses(self) -> None: + written = InMemoryArrowDatabase() + _ = self.notify_job("a", [1.0], written).run() + delivered.clear() + # The same results as an earlier build laid them out (no revision, rdb_v2). + old = InMemoryArrowDatabase() + for path in written.list_table_paths(()): + stored = written.get_all_records(path, record_id_column="__rid") + assert stored is not None + assert path[-2:] == ("rev1", "rdb_v1") + old.add_records(path[:-2] + ("rdb_v2",), stored, record_id_column="__rid") + old.flush() + + with pytest.raises(SideEffectLogDataContextError) as info: + _ = self.notify_job("b", [1.0], old).run() + assert delivered == [] + assert [path[-1] for path in info.value.record_paths] == ["rdb_v2"] + + +# --------------------------------------------------------------------------- +# Review findings (PR 507): each has a test that fails without its fix, or pins +# the behaviour stated for it. +# --------------------------------------------------------------------------- + + +@function_pod(output_keys="doubled", function_name="double") +def double_changed(x: float) -> float: + """``double``'s name, output schema and major with another body: one uri.""" + calls.append(("double_changed", x)) + return x * 3 + + +def one_step_job( + name: str, + database: ArrowDatabaseProtocol, + xs: list[float], + pod: Any = double, + result_database: ArrowDatabaseProtocol | None = None, + source_id: str = "s", +) -> PipelineJob: + """A job of one function node, labelled ``out``.""" + job = PipelineJob(name=name, database=database, result_database=result_database) + with job: + pod.pod(make_source(xs, source_id), label="out") + return job + + +class TestEveryRunSeesCommittedResults: + """B1: two handles on one Delta directory; a warm handle sees the other's commits. + + The run reads the result tables from the store's current version when it starts. + Parametrized over where the results are: a separate result database, or the job's + own database (one job name, two handles; the same staleness before ITL-1408). + """ + + @pytest.fixture(params=["result_database", "job_database"]) + def placement(self, request: pytest.FixtureRequest) -> str: + return request.param + + def handles_job( + self, + placement: str, + handle: DeltaTableDatabase, + name: str, + xs: list[float], + pod: Any = double, + ) -> PipelineJob: + if placement == "result_database": + return one_step_job(name, InMemoryArrowDatabase(), xs, pod, handle) + return one_step_job("shared", handle, xs, pod) + + def test_a_changed_body_reuses_what_another_handle_committed( + self, tmp_path: pathlib.Path, placement: str, orchestrator: Orchestrator + ) -> None: + warm = DeltaTableDatabase(tmp_path / "store") + other = DeltaTableDatabase(tmp_path / "store") + _ = self.handles_job(placement, warm, "warm", [1.0]).run( + orchestrator=orchestrator + ) + _ = self.handles_job(placement, other, "writer", [2.0, 3.0]).run( + orchestrator=orchestrator + ) + calls.clear() + job = self.handles_job(placement, warm, "reader", [2.0, 3.0], double_changed) + _ = job.run(orchestrator=orchestrator) + # The stored results of the same uri are reused, not computed by the new body. + assert calls == [] + assert rows(job, "out", "doubled") == [4.0, 6.0] + + def test_a_ctx_function_does_not_deliver_again( + self, tmp_path: pathlib.Path, placement: str, orchestrator: Orchestrator + ) -> None: + warm = DeltaTableDatabase(tmp_path / "store") + other = DeltaTableDatabase(tmp_path / "store") + for handle, name, xs in ( + (warm, "warm", [1.0]), + (other, "writer", [3.0]), + (warm, "reader", [3.0, 1.0]), + ): + _ = self.handles_job(placement, handle, name, xs, notify).run( + orchestrator=orchestrator + ) + assert sorted(delivered) == [1.0, 3.0] + + +class TestForeignCompletionsAfterTheFirstRun: + """M1: completions marked with another data context after a node's first run. + + The check holds on every run, before anything is delivered. Parametrized over the + store kind and where the results are. + """ + + @pytest.mark.parametrize("store", ["in_memory", "delta"]) + @pytest.mark.parametrize("separate", [True, False]) + def test_a_later_run_refuses_before_delivering( + self, + tmp_path: pathlib.Path, + store: str, + separate: bool, + orchestrator: Orchestrator, + ) -> None: + def new_store(name: str) -> ArrowDatabaseProtocol: + if store == "delta": + return DeltaTableDatabase(tmp_path / name) + return InMemoryArrowDatabase() + + database = new_store("db") + results = new_store("results") if separate else None + job = one_step_job("ctx", database, [1.0, 2.0], notify, results) + _ = job.run(orchestrator=orchestrator) + assert sorted(delivered) == [1.0, 2.0] + delivered.clear() + + # Every stored completion is now marked with another data context. + holder = results if results is not None else database + (path,) = [p for p in holder.list_table_paths(()) if p[-1] == "rdb_v1"] + stored = holder.get_all_records(path, record_id_column="__rid") + assert stored is not None + column = stored.schema.get_field_index("__data_context") + foreign = stored.set_column( + column, + stored.schema.field(column), + pa.array(["std:v0.9:other"] * stored.num_rows, pa.large_string()), + ) + if store == "delta": + # The Delta database appends; rewrite the table with the foreign rows. + import deltalake + + deltalake.write_deltalake( + str(tmp_path / ("results" if separate else "db") / "/".join(path)), + foreign, + mode="overwrite", + schema_mode="overwrite", + ) + else: + holder.add_records(path, foreign, record_id_column="__rid") + holder.flush() + + job.bind(sources={"s": make_source([1.0, 2.0, 3.0], "new")}) + with pytest.raises(SideEffectLogDataContextError): + _ = job.run(orchestrator=orchestrator) + assert delivered == [] + + +class TestUnavailableSavedResultDatabase: + """M2 and M3: a saved result database that is not available at load.""" + + @pytest.fixture(params=["unknown_type", "in_memory"]) + def saved( + self, request: pytest.FixtureRequest, tmp_path: pathlib.Path + ) -> tuple[pathlib.Path, ArrowDatabaseProtocol]: + """A job file whose result database cannot be had from the file alone.""" + if request.param == "in_memory": + results: ArrowDatabaseProtocol = InMemoryArrowDatabase() + else: + results = DeltaTableDatabase(tmp_path / "results") + job = one_step_job( + "a", + DeltaTableDatabase(tmp_path / "db"), + [1.0, 2.0], + result_database=results, + ) + _ = job.run() + path = tmp_path / "job.json" + job.save(path) + if request.param == "unknown_type": + saved = json.loads(path.read_text()) + saved["bindings"]["result_database"] = {"type": "no_such_database"} + _ = path.write_text(json.dumps(saved)) + return path, results + + def test_load_refuses_and_says_what_to_pass( + self, + saved: tuple[pathlib.Path, ArrowDatabaseProtocol], + caplog: pytest.LogCaptureFixture, + ) -> None: + path, results = saved + with caplog.at_level(logging.WARNING, logger="orcapod.pipeline.job"): + loaded = PipelineJob.load(path) + assert "bindings.result_database" in caplog.text + assert "result_database=" in caplog.text + assert loaded.result_database is None + with pytest.raises(RuntimeError): + _ = loaded.nodes["out"].as_source() + given = PipelineJob.load(path, result_database=results) + assert stored_rows(given, "out", "doubled") == [2.0, 4.0] + + def test_saving_the_loaded_job_keeps_the_binding( + self, + saved: tuple[pathlib.Path, ArrowDatabaseProtocol], + tmp_path: pathlib.Path, + ) -> None: + path, _ = saved + before = json.loads(path.read_text())["bindings"]["result_database"] + loaded = PipelineJob.load(path) + again = tmp_path / "again.json" + loaded.save(again) + assert json.loads(again.read_text())["bindings"]["result_database"] == before + reloaded = PipelineJob.load(again) + with pytest.raises(RuntimeError): + _ = reloaded.nodes["out"].as_source() + + @pytest.mark.parametrize("candidate", ["original", "connector", "fresh_in_memory"]) + def test_binding_a_replacement_is_checked_as_the_candidate( + self, + saved: tuple[pathlib.Path, ArrowDatabaseProtocol], + candidate: str, + ) -> None: + """CodeRabbit (PR 507): a bind is validated against what it binds. + + The only job whose result database can be unavailable is a loaded one; its + function nodes carry no function and store nothing, so no candidate is + refused for them. Any candidate is bound, the unavailable binding is gone, + and reads go through the candidate. + """ + from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector + + path, results = saved + replacement: ArrowDatabaseProtocol = { + "original": lambda: results, + "connector": lambda: ConnectorArrowDatabase(SQLiteConnector(":memory:")), + "fresh_in_memory": InMemoryArrowDatabase, + }[candidate]() + loaded = PipelineJob.load(path) + loaded.bind(result_database=replacement) + assert loaded.result_database is replacement + records = loaded.nodes["out"].get_all_records() + values = [] if records is None else records.column("doubled").to_pylist() + expected = [2.0, 4.0] if candidate == "original" else [] + assert sorted(values) == expected + again = path.with_name("rebound.json") + loaded.save(again) + assert json.loads(again.read_text())["bindings"]["result_database"] == ( + replacement.to_config() + ) + + +class TestClearingTheResultDatabase: + """M4: ``bind(result_database=None)`` puts the results back in the job's database.""" + + def test_before_a_run(self) -> None: + db = InMemoryArrowDatabase() + results = InMemoryArrowDatabase() + job = one_step_job("a", db, [1.0], result_database=results) + job.bind(result_database=None) + assert job.result_database is None + _ = job.run() + assert table_paths(results) == [] + assert any(p.startswith("a/_result/") for p in table_paths(db)) + + def test_after_a_run(self) -> None: + db = InMemoryArrowDatabase() + results = InMemoryArrowDatabase() + job = one_step_job("a", db, [1.0], result_database=results) + _ = job.run() + calls.clear() + job.bind(result_database=None) + assert job.result_database is None + _ = job.run() + # The job's own database held no result: computed again, stored there. + assert calls == [("double", 1.0)] + assert any(p.startswith("a/_result/") for p in table_paths(db)) + assert rows(job, "out", "doubled") == [2.0] + + def test_leaving_it_out_keeps_the_binding(self) -> None: + results = InMemoryArrowDatabase() + job = one_step_job("a", InMemoryArrowDatabase(), [1.0], result_database=results) + job.bind(sources={"s": make_source([1.0])}) + assert job.result_database is results + + +class TestACachedSourceIsNotTheJobs: + """Docs item: a ``CachedSource`` keeps its cache where it was created to, for any job.""" + + def test_two_jobs_share_one_cached_source(self) -> None: + from orcapod.sources import CachedSource + + db = InMemoryArrowDatabase() + cache = InMemoryArrowDatabase() + cached = CachedSource( + make_source([1.0, 2.0]), cache_database=cache, cache_path_prefix=("c",) + ) + for name in ("a", "b"): + job = PipelineJob( + name=name, database=db, result_database=InMemoryArrowDatabase() + ) + with job: + double.pod(cached, label="out") + _ = job.run() + cache_tables = table_paths(cache) + assert len(cache_tables) == 1 and cache_tables[0].startswith("c/") + assert not any(p.endswith("sdb_v1") for p in table_paths(db)) + + +# B2 and B3 were fixed on main for every case by ITL-1412: these check that the order +# holds across two databases (a separate result database). + + +def _dangling_record_ids(pipeline_root: pathlib.Path, result_root: pathlib.Path) -> int: + """Pipeline record ids, read through fresh handles, with no committed result.""" + from orcapod.system_constants import constants + + pipeline = DeltaTableDatabase(pipeline_root) + results = DeltaTableDatabase(result_root) + result_ids: set[Any] = set() + for path in results.list_table_paths(()): + if path[-1] == "rdb_v1": + stored = results.get_all_records(path, record_id_column="__rid") + assert stored is not None + result_ids.update(stored.column("__rid").to_pylist()) + record_ids: set[Any] = set() + for path in pipeline.list_table_paths(()): + if path[-1] == "pdb_v1": + stored = pipeline.get_all_records(path) + assert stored is not None + record_ids.update(stored.column(constants.DATA_RECORD_ID).to_pylist()) + return len(record_ids - result_ids) + + +class TestCommitOrderAcrossTwoDatabases: + """B2 (async) and B3: results are committed before the records naming them.""" + + @pytest.mark.parametrize("mode", ["sync", "async"]) + def test_no_record_is_published_before_its_result( + self, tmp_path: pathlib.Path, mode: str + ) -> None: + from unittest.mock import patch + + pipeline_root = tmp_path / "pipeline" + result_root = tmp_path / "results" + job = PipelineJob( + name="two", + database=DeltaTableDatabase(pipeline_root), + result_database=DeltaTableDatabase(result_root), + ) + with job: + stream = make_source([0.0, 1.0, 2.0, 3.0]) + double.pod(stream, label="first") + double_as_text.pod(stream, label="second") + flush = DeltaTableDatabase.flush + dangling: list[int] = [] + + def checked_flush(self: DeltaTableDatabase) -> None: + flush(self) + if self.to_config()["root_uri"] == str(pipeline_root): + dangling.append(_dangling_record_ids(pipeline_root, result_root)) + + orchestrator = ( + SyncPipelineOrchestrator() + if mode == "sync" + else AsyncPipelineOrchestrator() + ) + with patch.object(DeltaTableDatabase, "flush", checked_flush): + _ = job.run(orchestrator=orchestrator) + assert dangling and not any(dangling) + + def test_a_failed_result_commit_publishes_no_record( + self, tmp_path: pathlib.Path, orchestrator: Orchestrator + ) -> None: + from unittest.mock import patch + + from orcapod.errors import OrcapodDatabaseWriteError + + pipeline_root = tmp_path / "pipeline" + result_root = tmp_path / "results" + job = one_step_job( + "bad", + DeltaTableDatabase(pipeline_root), + [7.0, 8.0], + result_database=DeltaTableDatabase(result_root), + ) + flush_by_key = DeltaTableDatabase._flush_by_key # pyright: ignore[reportPrivateUsage] # fault injection + + def failing(self: DeltaTableDatabase, record_key: str) -> None: + if self.to_config()["root_uri"] == str(result_root): + raise OSError("result store unavailable") + flush_by_key(self, record_key) + + with patch.object(DeltaTableDatabase, "_flush_by_key", failing): + with pytest.raises(OrcapodDatabaseWriteError) as info: + _ = job.run(orchestrator=orchestrator) + published = DeltaTableDatabase(pipeline_root) + assert [p for p in published.list_table_paths(()) if p[-1] == "pdb_v1"] == [] + assert "result" in str(info.value) and "rdb_v1" in "/".join( + info.value.record_path + ) + + +# --------------------------------------------------------------------------- +# Second review round (PR 507): R1-R5. +# --------------------------------------------------------------------------- + + +class TestForeignPipelineRowsFromAnotherHandle: + """R1: completions marked with another data context, written to the node's + PIPELINE table through another handle after its first run, are found before + anything is delivered: the run refreshes every table the check reads. + """ + + @pytest.mark.parametrize("separate", [True, False]) + def test_a_later_run_refuses_before_delivering( + self, tmp_path: pathlib.Path, separate: bool, orchestrator: Orchestrator + ) -> None: + import uuid + + pipeline = DeltaTableDatabase(tmp_path / "db") + results = InMemoryArrowDatabase() if separate else None + job = one_step_job("ctx", pipeline, [1.0, 2.0], notify, results) + _ = job.run(orchestrator=orchestrator) + delivered.clear() + + (path,) = [p for p in pipeline.list_table_paths(()) if p[-1] == "pdb_v1"] + stored = pipeline.get_all_records(path, record_id_column="__rid") + assert stored is not None + context = stored.schema.get_field_index("__data_context") + foreign = stored.set_column( + context, + stored.schema.field(context), + pa.array(["std:v0.9:other"] * stored.num_rows, pa.large_string()), + ) + ids = foreign.schema.get_field_index("__rid") + foreign = foreign.set_column( + ids, + foreign.schema.field(ids), + pa.array( + [uuid.uuid4().bytes for _ in range(foreign.num_rows)], + foreign.schema.field(ids).type, + ), + ) + other_handle = DeltaTableDatabase(tmp_path / "db") + other_handle.add_records(path, foreign, record_id_column="__rid") + other_handle.flush() + + job.bind(sources={"s": make_source([1.0, 2.0, 3.0])}) + with pytest.raises(SideEffectLogDataContextError): + _ = job.run(orchestrator=orchestrator) + assert delivered == [] + + +class TestStoredViewsReadTheStoreNow: + """R2: a read of what is stored reads the store's current version, per read call.""" + + def test_both_views_before_and_after_an_external_append( + self, tmp_path: pathlib.Path + ) -> None: + pipeline_root = tmp_path / "db" + result_root = tmp_path / "results" + warm = DeltaTableDatabase(result_root) + # The warm handle has loaded the result table before the writer commits. + _ = one_step_job( + "warm", DeltaTableDatabase(pipeline_root), [1.0], result_database=warm + ).run() + + def write(xs: list[float]) -> PipelineJob: + job = one_step_job( + "load", + DeltaTableDatabase(pipeline_root), + xs, + result_database=DeltaTableDatabase(result_root), + source_id="other", + ) + _ = job.run() + return job + + written = write([2.0, 3.0]) + written.save(tmp_path / "job.json") + loaded = PipelineJob.load(tmp_path / "job.json", result_database=warm) + node = loaded.nodes["out"] + + def views() -> tuple[list[Any], list[Any]]: + records = node.get_all_records() + assert records is not None + return ( + sorted(node.as_source().as_table().column("doubled").to_pylist()), + sorted(records.column("doubled").to_pylist()), + ) + + assert views() == ([4.0, 6.0], [4.0, 6.0]) + _ = write([2.0, 3.0, 5.0]) # appended through other handles + assert views() == ([4.0, 6.0, 10.0], [4.0, 6.0, 10.0]) + + +class TestRefreshIsPerNodePerRun: + """R3: each node refreshes its own tables once per run, never per row. + + Two nodes of one job that share a result table each look at it once (the + documented cost); a job run does not share the refresh between nodes. + """ + + def test_two_nodes_sharing_a_result_table(self, tmp_path: pathlib.Path) -> None: + from unittest.mock import patch + + results = DeltaTableDatabase(tmp_path / "results") + job = PipelineJob( + name="two", database=InMemoryArrowDatabase(), result_database=results + ) + xs = [float(x) for x in range(50)] + with job: + double.pod(make_source(xs, "a"), label="first") + double.pod(make_source(xs, "b"), label="second") + refresh = DeltaTableDatabase.refresh_table + refreshed: list[tuple[str, ...]] = [] + + def counted(self: DeltaTableDatabase, record_path: tuple[str, ...]) -> None: + refreshed.append(record_path) + refresh(self, record_path) + + with patch.object(DeltaTableDatabase, "refresh_table", counted): + _ = job.run() + (result_table,) = {p for p in refreshed if p[-1] == "rdb_v1"} + assert refreshed.count(result_table) == 2 # one per node, not per row + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1413: a Delta table deleted and recreated at the same path with the " + "same version number is not seen by a handle that loaded the old one", +) +def test_a_recreated_table_at_the_same_version_is_seen(tmp_path: pathlib.Path) -> None: + """R4: the refresh compares versions, not the table's identity (limit, ITL-1413).""" + import shutil + + import deltalake + + warm = DeltaTableDatabase(tmp_path / "shared") + _ = one_step_job("warm", InMemoryArrowDatabase(), [1.0], result_database=warm).run() + replacement = DeltaTableDatabase(tmp_path / "replacement") + _ = one_step_job( + "write", InMemoryArrowDatabase(), [1.0], double_changed, replacement + ).run() + (path,) = [p for p in warm.list_table_paths(()) if p[-1] == "rdb_v1"] + old = tmp_path / "shared" / "/".join(path) + new = tmp_path / "replacement" / "/".join(path) + assert deltalake.DeltaTable(str(old)).version() == 0 + assert deltalake.DeltaTable(str(new)).version() == 0 + # Recreate the table at the old path (its old data files left behind). + _ = shutil.move(str(old / "_delta_log"), str(tmp_path / "old_log")) + for item in new.iterdir(): + _ = shutil.move(str(item), str(old / item.name)) + calls.clear() + job = one_step_job("read", InMemoryArrowDatabase(), [1.0], double_changed, warm) + _ = job.run() + assert calls == [] + assert rows(job, "out", "doubled") == [3.0] # the stored value now at that path + + +class TestTwoOverlappingJobs: + """R5: a row another job commits after this node refreshed is not seen in this run. + + The window opens when the node refreshes its tables at its start and closes at + its next refresh (its next run or stored read) or its own commit of that table. + A side-effecting function can be delivered by each of two overlapping jobs. + This pins that documented behaviour; reserving an input is not designed yet. + """ + + @pytest.mark.parametrize("separate", [True, False]) + def test_a_ctx_action_committed_during_the_run_is_delivered_again( + self, tmp_path: pathlib.Path, separate: bool, orchestrator: Orchestrator + ) -> None: + from orcapod.pipeline.observer import NoOpObserver + + warm = DeltaTableDatabase(tmp_path / "store") + writer = DeltaTableDatabase(tmp_path / "store") + + def job(handle: DeltaTableDatabase, name: str, xs: list[float]) -> PipelineJob: + if separate: + return one_step_job( + name, InMemoryArrowDatabase(), xs, notify, handle, source_id=name + ) + return one_step_job("same", handle, xs, notify, source_id=name) + + _ = job(warm, "warm", [1.0]).run(orchestrator=orchestrator) + reader = job(warm, "reader", [3.0]) + other = job(writer, "writer", [3.0]) + + class CommitsAfterTheRefresh(NoOpObserver): + committed: bool = False + + def contextualize(self, *identity_path: str) -> CommitsAfterTheRefresh: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + if node_label == "out" and not self.committed: + self.committed = True + _ = other.run() + + _ = reader.run(orchestrator=orchestrator, observer=CommitsAfterTheRefresh()) + assert sorted(delivered) == [1.0, 3.0, 3.0]