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
15 changes: 15 additions & 0 deletions changelog.d/ITL-1433.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### Added

- Function-node pipeline records now include the recording job's run ID
(`__pipeline_run_id`) and the UTC recording time (`__recorded_at`). Standalone
node runs store a null run ID. Entries require an output. Recomputing a lost
result creates a new entry with its own recording metadata. Within a run,
sync execution reuses the first entry for an identical input without system
tags. Async execution can schedule both copies before either entry is
available and record them separately.

### Breaking changes and migration

- Pipeline tables written by 0.4.0rc1 through 0.4.0rc3 lack these columns and
must be rebuilt before appending, even if they contain no rows. The layout
remains `pdb_v1`.
29 changes: 29 additions & 0 deletions docs/reference/data-function-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,35 @@ print([name for name in stored.column_names if name.startswith("__pf_var_")])
# ['__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash']
```

## The pipeline columns, `pdb_v1`

A function node's pipeline table stores the input tags and source-info tokens,
the input and output hashes, the referenced result record ID, and bookkeeping
for the entry, including:

| Column | Arrow type | Nullable | Meaning |
|---|---|---|---|
| `__pipeline_run_id` | `large_string` | yes | The ID of the job run that recorded the entry. A node run outside a job stores null. |
| `__recorded_at` | `timestamp[us, tz=UTC]` | no | The UTC time the node recorded the entry. |

The node writes a pipeline entry only when processing yields an output. The
output can come from a new function call or from a result already in the result
database. A null value in a declared nullable output still counts as an output.
Reusing a pipeline entry preserves its original run ID and recording
time. If the result is lost and the node recomputes it, the new entry has its
own run ID and recording time.

During a sync run, a repeated identical input without system tags reuses the
first entry. During an async run, both copies can be scheduled before either
entry is available, producing two entries with successive recomputation indices.
A load-only run writes nothing. Neither recording column enters any hash.

Read these columns on joined records with
`node.get_all_records(columns={"meta": True})` or `node.get_all_records(all_info=True)`.
Pipeline tables written by 0.4.0rc1 through 0.4.0rc3 lack these columns. Rebuild
those tables before appending, even if their rows have been deleted. The layout
name stays `pdb_v1`.

## Where it is declared, and how a released declaration is kept

The declaration is code: `PYTHON_FUNCTION` in `orcapod.core.data_function`, beside the
Expand Down
4 changes: 3 additions & 1 deletion docs/tutorial/08-inspecting-and-tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ call. `get_all_records` returns them; ask for the `meta` columns to see the deta
records = pl.from_arrow(job.nodes["rates"].get_all_records(columns={"meta": True}))
meta = [c for c in records.columns if c.startswith("__")]
print(meta)
# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts']
# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__pipeline_run_id', '__recorded_at', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts']
```

The ones you are most likely to want:
Expand All @@ -170,6 +170,8 @@ The ones you are most likely to want:
| `__pf_exec_python_version` | The Python version it ran under |
| `__pf_var_git_hash` | The git commit of the code, when run inside a git repository |
| `__computed` | `True` if this row was computed, `False` if it reused the result of an identical input |
| `__pipeline_run_id` | The job run that recorded the pipeline entry |
| `__recorded_at` | When the pipeline entry was recorded, in UTC |
| `__input_data_hash` | The hash of the input values: the key the result is stored under (Part 6) |

```python
Expand Down
118 changes: 101 additions & 17 deletions src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
from abc import abstractmethod
from collections import Counter
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from datetime import datetime, timezone
from functools import partial
from typing import Any, Literal, NamedTuple, cast

import polars as pl
Expand Down Expand Up @@ -73,6 +75,7 @@
OrcapodDatabaseError,
TypeIdentityError,
OrcapodDatabaseWriteError,
StoredTableSchemaError,
UnstorableColumnError,
)
from orcapod.contexts.stored import (
Expand Down Expand Up @@ -134,6 +137,14 @@
# 0 for the first computation, N+1 for each miss-triggered recompute.
_PIPELINE_RECOMPUTATION_INDEX_COL = "__pipeline_recomputation_index"

PIPELINE_RUN_ID_COL = "__pipeline_run_id"
PIPELINE_RECORDED_AT_COL = "__recorded_at"

_PIPELINE_RECORDING_FIELDS = (
pa.field(PIPELINE_RUN_ID_COL, pa.large_string()),
pa.field(PIPELINE_RECORDED_AT_COL, pa.timestamp("us", tz="UTC"), nullable=False),
)


def _pipeline_meta_schema() -> pa.Schema:
"""The bookkeeping columns of a function node's pipeline record (``pdb_v1``).
Expand All @@ -153,6 +164,7 @@ def _pipeline_meta_schema() -> pa.Schema:
pa.field(constants.IS_EPHEMERAL_COL, pa.bool_()),
pa.field(_PIPELINE_BASE_ENTRY_ID_COL, pa.large_binary()),
pa.field(_PIPELINE_RECOMPUTATION_INDEX_COL, pa.int32()),
*_PIPELINE_RECORDING_FIELDS,
]
)

Expand Down Expand Up @@ -1409,6 +1421,8 @@ class FunctionJobNode(RunHoldingNode, FunctionNodeBase):
_stale_tables_checked: bool = False
# Set once the rows of the current tables were counted by data context.
_current_tables_checked: bool = False
# Preflight the first miss before invoking user code. Each commit checks again.
_pipeline_preflight_checked: bool = False
# Set once a database that cannot list its tables was reported.
_unlisted_store_reported: bool = False
# Base entry ids of the inputs of the last completed run in this process, each with
Expand Down Expand Up @@ -1530,7 +1544,7 @@ def _delivers_side_effects(self) -> bool:
)

def _begin_run(self) -> None:
"""Start a run: see the stored results as they are now, then check for stale ones.
"""Reset schema preflight and refresh the stored tables for this run.

The stored tables are read from the store's current version
(``_refresh_stored_tables``), so the run reuses every result committed before
Expand All @@ -1549,6 +1563,7 @@ def _begin_run(self) -> None:
SideEffectLogDataContextError: If this node delivers side effects and
completions it cannot match exist; nothing has been delivered then.
"""
self._pipeline_preflight_checked = False
self._refresh_stored_tables()
if self._delivers_side_effects:
self._stale_tables_checked = False
Expand Down Expand Up @@ -1733,6 +1748,7 @@ def attach_databases(
# Another database has its own tables of other generations to account for.
self._stale_tables_checked = False
self._current_tables_checked = False
self._pipeline_preflight_checked = False
self._unlisted_store_reported = False
self._skipped_rows_reported = False
# ... and its own rows to compare with the job file's expected count.
Expand Down Expand Up @@ -2447,6 +2463,7 @@ def _write_pipeline_record(
database = self._require_pipeline_database()
path = self._versioned_pipeline_path
pod = self._ephemeral_cached_pod if is_ephemeral else self._cached_function_pod
dependency = None
if self._commit_every_rows is not None and isinstance(pod, CachedFunctionPod):
result_database = pod.result_database
try:
Expand All @@ -2460,11 +2477,14 @@ def _write_pipeline_record(
flush=True,
table_flush=True,
) from exc
if dependency is not None:
with database.guard_record(path, record_id, dependency):
database.add_record(path, record_id, record, skip_duplicates=True)
return
database.add_record(path, record_id, record, skip_duplicates=True)
check = partial(self._check_pipeline_write_schema, database, path)
result_guard = (
contextlib.nullcontext()
if dependency is None
else database.guard_record(path, record_id, dependency)
)
with database.guard_table_schema(path, check), result_guard:
database.add_record(path, record_id, record, skip_duplicates=True)

def _row_processed(self) -> None:
"""Count a processed row; commit once a batch is full (only inside a job run)."""
Expand Down Expand Up @@ -2831,15 +2851,12 @@ def _process_data_internal(
When ``node_config.is_result_ephemeral=True``:
- Uses ``_ephemeral_cached_pod`` for both compute and storage.
- Raises ``RuntimeError`` if no ephemeral database has been set.
- Calls ``add_pipeline_record`` which computes the next recomputation
index (``max_index + 1``) and writes with ``skip_duplicates=True``
so concurrent coroutines are safely serialised.

When ``node_config.is_result_ephemeral=False`` (default):
- Uses ``_cached_function_pod`` (persistent DB) or raw function pod.
- Calls ``add_pipeline_record`` which computes the next recomputation
index (``max_index + 1``) and writes with ``skip_duplicates=True``
so concurrent coroutines are safely serialised.

When a pipeline database is attached, a result produced here is recorded
at the next recomputation index, using ``skip_duplicates=True``.

Returns:
A ``(tag, output_data)`` 2-tuple.
Expand All @@ -2859,6 +2876,7 @@ def _process_data_internal(
if isinstance(data, EmptyData):
return self._empty_data_cache_hit(tag, data, base_entry_id)

self._preflight_pipeline_write_schema()
ephemeral_result = bool(self._node_config.is_result_ephemeral)

if ephemeral_result:
Expand Down Expand Up @@ -2889,6 +2907,7 @@ def _process_data_internal(
computed=result_computed,
is_ephemeral=True,
output_data_hash=output_data.content_hash(),
run_id=run_id,
)
elif self._cached_function_pod is not None:
tag_out, output_data = self._cached_function_pod.process_data(
Expand All @@ -2910,6 +2929,7 @@ def _process_data_internal(
data_record_id=output_data.datagram_uuid,
computed=result_computed,
output_data_hash=output_data.content_hash(),
run_id=run_id,
)
else:
tag_out, output_data = self._function_pod.process_data(
Expand Down Expand Up @@ -2997,6 +3017,7 @@ async def _async_process_data_internal(
if isinstance(data, EmptyData):
return self._empty_data_cache_hit(tag, data, base_entry_id)

self._preflight_pipeline_write_schema()
ephemeral_result = bool(self._node_config.is_result_ephemeral)

if ephemeral_result:
Expand Down Expand Up @@ -3152,15 +3173,18 @@ def add_pipeline_record(
computed: bool,
is_ephemeral: bool = False,
output_data_hash: ContentHash | None = None,
*,
run_id: str | None = None,
) -> None:
"""Add a pipeline record to the database for a processed data.
"""Add a pipeline record for a row that produced output.

Computes the next recomputation index by querying existing rows in the
pipeline DB that share the same ``base_entry_id``, then writes at
``max_index + 1``. The write uses ``skip_duplicates=True`` so that
concurrent asyncio coroutines competing for the same versioned entry ID
are safely serialised: the first writer lands, subsequent writers whose
compute happened to produce the same hash are silently no-oped.
``max_index + 1``. The database skips duplicate versioned entry IDs.
Sync execution ordinarily reuses the first recorded result for an
identical input in the same run. Async execution can schedule both
copies of an identical input without system tags before either entry is
available, and can write separate entries with successive indices.

The pipeline record stores:

Expand All @@ -3172,6 +3196,7 @@ def add_pipeline_record(
- Whether the result is stored in the ephemeral database
- Input data context key
- Whether the result was freshly computed or cached
- The run ID and the UTC recording time
- Output data content hash (``OUTPUT_DATA_HASH_COL``) — used by downstream
``EmptyData`` flow-through to look up the downstream result cache.

Expand All @@ -3186,6 +3211,7 @@ def add_pipeline_record(
``input_data``. When provided, stored as ``OUTPUT_DATA_HASH_COL``
so that downstream ``EmptyData`` flow-through can locate its cached
result keyed by the same hash (= the downstream's ``INPUT_DATA_HASH_COL``).
run_id: ID of the run recording the entry, if any.
"""
self._add_pipeline_record(
tag,
Expand All @@ -3195,6 +3221,7 @@ def add_pipeline_record(
computed=computed,
is_ephemeral=is_ephemeral,
output_data_hash=output_data_hash,
run_id=run_id,
)

def _add_pipeline_record(
Expand All @@ -3206,6 +3233,8 @@ def _add_pipeline_record(
computed: bool,
is_ephemeral: bool = False,
output_data_hash: ContentHash | None = None,
*,
run_id: str | None = None,
) -> None:
"""``add_pipeline_record`` with the row's base entry id already computed.

Expand All @@ -3217,6 +3246,7 @@ def _add_pipeline_record(
computed: Whether the result was freshly computed.
is_ephemeral: Whether the result is stored in the ephemeral database.
output_data_hash: Content hash of the output, if any.
run_id: ID of the run recording the entry, if any.
"""
pipeline_database = self._require_pipeline_database()
# The row key combines the input's hash with this node's hasher: an input
Expand All @@ -3225,6 +3255,7 @@ def _add_pipeline_record(
input_data.data_context_key, self._stored_data_context_key
)
self._account_for_stale_tables()
self._preflight_pipeline_write_schema()

# Determine the next recomputation index by querying all existing rows
# for this base_entry_id. No await is used here, so within a single-threaded
Expand Down Expand Up @@ -3273,6 +3304,8 @@ def _add_pipeline_record(
constants.IS_EPHEMERAL_COL: [is_ephemeral],
_PIPELINE_BASE_ENTRY_ID_COL: [base_entry_id],
_PIPELINE_RECOMPUTATION_INDEX_COL: [new_index],
PIPELINE_RUN_ID_COL: [run_id],
PIPELINE_RECORDED_AT_COL: [datetime.now(timezone.utc)],
},
schema=_pipeline_meta_schema(),
)
Expand Down Expand Up @@ -3303,6 +3336,55 @@ def _add_pipeline_record(
tag=tag.as_dict(),
) from exc

def _preflight_pipeline_write_schema(self) -> None:
"""Refuse an incompatible table before the first computation in this run."""
database = self._pipeline_database
if database is None or self._pipeline_preflight_checked:
return
path = self._versioned_pipeline_path
existing = database.get_table_schema(path)
if existing is not None:
self._check_pipeline_write_schema(database, path, existing)
self._pipeline_preflight_checked = True

def _check_pipeline_write_schema(
self,
database: ArrowDatabaseProtocol,
path: tuple[str, ...],
schema: pa.Schema,
) -> None:
"""Report missing or incompatible recording columns and name their table."""
issues: list[str] = []
for expected in _PIPELINE_RECORDING_FIELDS:
index = schema.get_field_index(expected.name)
if index < 0:
issues.append(f"missing {expected.name}")
continue
actual = schema.field(index)
actual_type = arrow_utils.normalize_to_large_types(
actual.type, keep_null=True
)
if actual_type != expected.type:
issues.append(
f"{expected.name} has type {actual_type}, expected {expected.type}"
)
if actual.nullable != expected.nullable:
actual_nullability = "nullable" if actual.nullable else "non-nullable"
expected_nullability = (
"nullable" if expected.nullable else "non-nullable"
)
issues.append(
f"{expected.name} is {actual_nullability}, expected {expected_nullability}"
)
if issues:
raise StoredTableSchemaError(
f"Cannot append a pipeline record to the "
f"{describe_database_table(database, path)}: "
f"{', '.join(issues)}. Rebuild the pipeline table "
"with the current version of Orcapod.",
node_label=self.label,
)

# ------------------------------------------------------------------
# Records and sources
# ------------------------------------------------------------------
Expand Down Expand Up @@ -4413,6 +4495,7 @@ async def route_inputs() -> None:
run_entry_ids.append(base_entry_id)
await output.send((cached_tag, cached_data))
else:
self._preflight_pipeline_write_schema()
correlation_key = uuid.uuid4().bytes
input_store[correlation_key] = (
tag,
Expand Down Expand Up @@ -4454,6 +4537,7 @@ async def record_and_forward() -> None:
computed=result_computed,
is_ephemeral=is_ephemeral,
output_data_hash=output_data.content_hash(),
run_id=run_id,
)
except OrcapodDatabaseError as exc:
# This runs outside the pod's per-row handler: name the
Expand Down
Loading
Loading