Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions changelog.d/ITL-1408.md
Original file line number Diff line number Diff line change
@@ -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 `<function>/...` 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 `<job name>/_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).
11 changes: 11 additions & 0 deletions docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
94 changes: 87 additions & 7 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,97 @@ lists every type for every database.

On disk the layout is `<directory>/<job name>/<function name>/...` for each function, plus
`<directory>/<job name>/_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()`.

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 `<function name>/...`, 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
`<job name>/_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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions docs/reference/data-function-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ A function stores each result in its result table, at
<job>/_result/<function>/<output schema hash>/v<function major>/python.function.v1/rev1/rdb_v1
```

For a job given a separate result database (`PipelineJob(..., result_database=...)`), the
path starts at `<function>`, in that database, with no `<job>/_result`.

The first four components after `_result` are the function's uri. The last three each
have one owner:

Expand Down
3 changes: 2 additions & 1 deletion docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<job>/<function>/...` and `<job>/_result/<function>/...`;
function (`<job>/<function>/...` and `<job>/_result/<function>/...`, or `<function>/...` in
a separate result database;
`side_effect_function/<function>` for a function pod that takes the invocation context;
`side_effects/<pod>` for a side-effect pod; `<prefix>/source` for a cached source without
an explicit `cache_path`). A node lists the tables stored under that beginning
Expand Down
59 changes: 51 additions & 8 deletions src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/orcapod/databases/connector_arrow_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading