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

- Python function result records include `__pf_var_output_keys`, the output names in declared order (ITL-1253). Older result rows read with null in this column. Cache reuse still matches the function identity and input data hash.
4 changes: 2 additions & 2 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ reads SpiralDB only. The full list,
type by type, is [Data types per database](../reference/database-types.md).

Orcapod's own stored tables hold such columns. A function node's result table holds
list-valued executor columns and `__`-prefixed columns. A side-effect node's log holds a UTC
list-valued columns for the declared output names and executor details. A side-effect node's log holds a UTC
timestamp and `__data_context`. An operator cache holds `__data_context`, the row's entry id
and a UTC timestamp, the time the row was first stored (`__recorded_at`). A cached source
holds `__data_context` too. So a job refuses these nodes when it is built, or when a database
Expand Down Expand Up @@ -299,7 +299,7 @@ try:
compute_bmi.pod(mice(cohort_a), label="bmi")
except UnstorableColumnError as exc:
print(exc)
# node 'bmi': a SQLiteConnector database cannot store column '__pf_exec_executor_info' of Arrow type large_list<...>: SQLite has no column type for it. Use an InMemoryArrowDatabase instead; docs/reference/database-types.md lists what each database keeps.
# node 'bmi': a SQLiteConnector database cannot store column '__pf_var_output_keys' of Arrow type large_list<...>: SQLite has no column type for it. Use an InMemoryArrowDatabase instead; docs/reference/database-types.md lists what each database keeps.
```

## What a re-run computes
Expand Down
6 changes: 3 additions & 3 deletions docs/dev/design_issues/ITL-1244-OK1.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ a cache hit is not checked, ITL-1253). No code changed. The
behaviour is pinned in `tests/test_core/function_pod/test_output_keys_identity.py` (two and
three keys in every order, sync and async, in memory and in a job on an in-memory and a
Delta database, plain tags and data-tags; input parameters pinned as outside the uri) and
documented in `docs/concepts/identity.md` (*Change detection*). A cache hit whose stored
function variation data differs from the current function is still served silently: that
check is ITL-1253 (a strict xfail test states it).
documented in `docs/concepts/identity.md` (*Change detection*). ITL-1253 records the declared
output order in the function record for a future opt-in check. The test suite pins silent
reuse as the default.
6 changes: 5 additions & 1 deletion docs/reference/data-function-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ Each result row holds these columns about the function (`__pf_var_` prefix):
| `function_signature_hash` | `bytes` | `large_binary` | yes | the hash of the function's declared interface |
| `function_content_hash` | `bytes \| None` | `large_binary` | yes | the hash of the function as written (a lambda: its enclosing lines); absent when its source cannot be read (a plain REPL, `python -c`, `exec`) or, for a function other than a lambda, does not start at a `def` statement |
| `git_hash` | `str` | `large_string` | yes | the git commit of the function's file or working directory, with `-dirty`, `-untracked` and `-<source>` suffixes; `unknown` outside git |
| `output_keys` | `list[str] \| None` | `large_list<item: large_string>` | yes | the output names in declared order on every new row. Null means the row predates this column. Nothing compares this column today |

and these about how it was computed (`__pf_exec_` prefix):

Expand All @@ -138,6 +139,9 @@ The two hashes, each stored as `<label>:` followed by its digest:

Results are reused by the function's identity (its uri) and the input data hash alone;
these columns record what produced each row and are not compared on a cache hit.
Metadata reads supply a null `__pf_var_output_keys` for older prerelease results, including
when the table was written entirely before that column existed. Use a new result table with
the current schema when adding results to a prerelease store that lacks the column.

## The common columns, `rdb_v1`

Expand Down Expand Up @@ -183,7 +187,7 @@ stored = types_store.get_all_records(next(p for p in types_store.list_sources()
print([name for name in stored.column_names if not name.startswith("__pf_")])
# ['__input_data_hash', 'total', 'label', '_source_total', '_source_label', '__pod_ts', '__data_context']
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']
# ['__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_var_output_keys']
```

## The pipeline columns, `pdb_v2`
Expand Down
3 changes: 2 additions & 1 deletion docs/tutorial/inspecting-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,15 @@ For each function, the database holds one record per computed result.
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', '__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']
# ['__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_var_output_keys', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts']
```

Some important columns:

| Column | Meaning |
|---|---|
| `__pf_var_function_name` | The function that produced the result |
| `__pf_var_output_keys` | The output names in the order the function declared them, or null for a result written before this column existed |
| `__pod_ts` | When the result was computed |
| `__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 |
Expand Down
4 changes: 3 additions & 1 deletion src/orcapod/core/cached_function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@ def __init__(
**kwargs,
) -> None:
super().__init__(function_pod, **kwargs)
declaration = function_pod.data_function.declaration
self._cache = ResultCache(
result_database=result_database,
record_path=context_result_path(self.uri, self.ctx_arg_name),
revision=function_pod.data_function.declaration.revision_component,
revision=declaration.revision_component,
variation_columns=declaration.variation,
auto_flush=auto_flush,
# A pod that takes the invocation context performs an external action.
delivers_side_effects=function_pod.ctx_arg_name is not None,
Expand Down
12 changes: 10 additions & 2 deletions src/orcapod/core/data_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
default_value_refused,
hash_default_value,
)
from orcapod.core.result_cache import ResultCache, context_result_path
from orcapod.core.result_cache import (
OUTPUT_KEYS_COLUMN,
ResultCache,
context_result_path,
)
from orcapod.errors import (
NoOutputsDeclaredError,
OutputContainerTypeError,
Expand Down Expand Up @@ -724,6 +728,7 @@ def function_content_hash(
"the git commit of the function's file or working directory, with "
+ "-dirty, -untracked and -<source> suffixes; unknown outside git",
),
OUTPUT_KEYS_COLUMN,
),
execution=(
StoredColumn(
Expand Down Expand Up @@ -960,6 +965,7 @@ def get_function_variation_data(self) -> dict[str, Any]:
"function_signature_hash": self._function_signature_hash,
"function_content_hash": self._function_content_hash,
"git_hash": self._git_hash,
"output_keys": list(self._output_keys),
}

def get_function_variation_data_schema(self) -> Schema:
Expand Down Expand Up @@ -1598,12 +1604,14 @@ def __init__(
self._record_path_prefix = record_path_prefix
if context_parameter is not None:
record_path_prefix += ("side_effect_function",)
declaration = self.declaration
self._cache = ResultCache(
result_database=result_database,
record_path=context_result_path(
record_path_prefix + self.uri, context_parameter
),
revision=self.declaration.revision_component,
revision=declaration.revision_component,
variation_columns=declaration.variation,
auto_flush=True,
delivers_side_effects=context_parameter is not None,
# The first uri component is the function's name; no hash before it.
Expand Down
13 changes: 11 additions & 2 deletions src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
from orcapod.channels import Channel, ReadableChannel, WritableChannel
from orcapod.config import OrcapodConfig
from orcapod.core.cached_function_pod import CachedFunctionPod
from orcapod.core.data_function import declaration_for
from orcapod.core.data_function import PYTHON_FUNCTION, declaration_for
from orcapod.core.result_cache import with_recorded_output_keys
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.core.streams.base import (
ZERO_ROW_INPUT_COLUMNS,
Expand Down Expand Up @@ -3637,6 +3638,8 @@ def _stored_provenance(
path, record_id_column=constants.DATA_RECORD_ID
)
if stored is not None:
if path[-3:-2] == (PYTHON_FUNCTION.type_id,):
stored = with_recorded_output_keys(stored)
found.append(keep_rows_of_data_context(stored, context_key))
result_table = (
None
Expand Down Expand Up @@ -3726,13 +3729,15 @@ def _fetch_joined_records(
# ------------------------------------------------------------------
# Persistent join
# ------------------------------------------------------------------
record_path = self._cached_function_pod.record_path
has_output_keys = record_path[-3:-2] == (PYTHON_FUNCTION.type_id,)
results_schema = None
results: pa.Table | None = None
eph_results: pa.Table | None = None
persistent_df = pl.DataFrame()
if persistent_taginfo_df.height > 0:
results = self._cached_function_pod.result_database.get_all_records(
self._cached_function_pod.record_path,
record_path,
record_id_column=constants.DATA_RECORD_ID,
)
if results is not None:
Expand All @@ -3742,6 +3747,8 @@ def _fetch_joined_records(
results = keep_rows_of_data_context(results, context_key).drop(
[constants.DATA_CONTEXT_COL]
)
if has_output_keys:
results = with_recorded_output_keys(results)
results_schema = results.schema
persistent_df = persistent_taginfo_df.join(
_row_frame(results, (constants.DATA_RECORD_ID,), _RESULT_ROW),
Expand Down Expand Up @@ -3770,6 +3777,8 @@ def _fetch_joined_records(
eph_results = keep_rows_of_data_context(eph_results, context_key).drop(
[constants.DATA_CONTEXT_COL]
)
if has_output_keys:
eph_results = with_recorded_output_keys(eph_results)
if results_schema is None:
results_schema = eph_results.schema
eph_frame = _row_frame(
Expand Down
47 changes: 45 additions & 2 deletions src/orcapod/core/result_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,32 @@ def pod_timestamp_type() -> pa.DataType:
output of the row is refused. Custom token types are not supported.
"""

_OUTPUT_KEYS_TYPE = pa.large_list(pa.large_string())
OUTPUT_KEYS_COLUMN = StoredColumn(
"output_keys",
list[str] | None,
str(_OUTPUT_KEYS_TYPE),
True,
"the output names in declared order on every new row. Null means the row "
+ "predates this column. Nothing compares this column today",
)
_OUTPUT_KEYS_FIELD = pa.field(
f"{constants.PF_VARIATION_PREFIX}{OUTPUT_KEYS_COLUMN.name}", _OUTPUT_KEYS_TYPE
)


def with_recorded_output_keys(table: pa.Table) -> pa.Table:
"""Supply null output-key metadata for rows from before the column existed."""
index = table.schema.get_field_index(_OUTPUT_KEYS_FIELD.name)
if index == -1:
return table.append_column(
_OUTPUT_KEYS_FIELD, pa.nulls(table.num_rows, type=_OUTPUT_KEYS_TYPE)
)
field = table.schema.field(index)
if not field.nullable:
return table.set_column(index, field.with_nullable(True), table.column(index))
return table


def _with_declared_token_columns(
data_table: pa.Table, output_keys: tuple[str, ...], carried: pa.Schema
Expand Down Expand Up @@ -216,6 +242,8 @@ def __init__(
auto_flush: bool = True,
delivers_side_effects: bool = False,
name_path: tuple[str, ...] | None = None,
*,
variation_columns: tuple[StoredColumn, ...] = (),
) -> None:
"""Create a result cache over one result table.

Expand All @@ -235,13 +263,19 @@ def __init__(
the part that holds no hash. Result tables written before v0.3 are
looked for under it, whatever hashes their paths hold (ITL-954).
``None`` looks at the paths computed from ``record_path`` only.
variation_columns: The type's declared variation columns and their
stored nullability. Undeclared columns are nullable.
"""
self._result_database = result_database
self._record_path = record_path
self._revision = revision
self._auto_flush = auto_flush
self._delivers_side_effects = delivers_side_effects
self._name_path = name_path
self._variation_nullability = {
column.name: column.nullable for column in variation_columns
}
self._records_output_keys = OUTPUT_KEYS_COLUMN in variation_columns
# Set once a read has reported the stored rows it skipped.
self._skipped_rows_reported = False
# Set once stored results of other generations have been accounted for.
Expand Down Expand Up @@ -412,6 +446,8 @@ def lookup(
c for c in constraints if c in result_table.column_names
]
result_table = result_table.drop_columns(drop_cols)
if self._records_output_keys:
result_table = with_recorded_output_keys(result_table)

return Data(
result_table,
Expand Down Expand Up @@ -464,10 +500,15 @@ def store(
# Use a running counter for insertion position since add_column shifts indices.
col_idx = 0
var_table = variation_datagram.as_table()
for name in var_table.column_names:
for field in var_table.schema:
name = field.name
data_table = data_table.add_column(
col_idx,
f"{constants.PF_VARIATION_PREFIX}{name}",
pa.field(
f"{constants.PF_VARIATION_PREFIX}{name}",
field.type,
nullable=self._variation_nullability.get(name, True),
),
var_table.column(name),
)
col_idx += 1
Expand Down Expand Up @@ -619,4 +660,6 @@ def get_all_records(
)
if result_table.num_rows == 0:
return None
if self._records_output_keys:
result_table = with_recorded_output_keys(result_table)
return result_table.drop([constants.DATA_CONTEXT_COL])
7 changes: 7 additions & 0 deletions src/orcapod/data_function_types/python.function/v1-rev1.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@
"name": "git_hash",
"nullable": true,
"python_type": "str"
},
{
"arrow_type": "large_list<item: large_string>",
"meaning": "the output names in declared order on every new row. Null means the row predates this column. Nothing compares this column today",
"name": "output_keys",
"nullable": true,
"python_type": "list[str] | None"
}
]
}
1 change: 1 addition & 0 deletions tests/test_core/data_function/test_data_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,7 @@ def test_returns_expected_keys(self, add_pf):
"function_signature_hash",
"function_content_hash",
"git_hash",
"output_keys",
}

def test_function_version_is_the_full_declared_version(self):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_core/data_function/test_function_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Every result row records, beside the function's name and version:

* ``function_module``: the function's ``__module__``;
* ``output_keys``: the output names in declared order;
* ``function_signature_hash`` (``function_signature_v1``): the declared interface, one
hash over ``{"inputs": {<name>: {"type", "default"?}}, "outputs": [{"key", "type"}]}``
from the effective types: inputs by name in no order, outputs in declared order; no
Expand Down Expand Up @@ -520,6 +521,7 @@ def test_swapped_same_typed_keys_store_different_signature_hashes(
"function_signature_hash"
]
row = by_signature[expected_signature]
assert row["__pf_var_output_keys"] == list(order)
values = fn(index + 1, 2)
assert {key: row[key] for key in order} == dict(zip(order, values)), order

Expand Down
Loading
Loading