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

- **A function node keeps a stored row's tag types in a later session.** When a node's
results are ephemeral and a later session no longer has them, the node rebuilt the
stored rows' tags from Python values: an `int8` or `float32` tag came back as a 64-bit
type (another tag hash), and a struct tag could not be read. It now builds them from the
stored Arrow rows. Runs, iteration, the preview and what is stored are unchanged: the node
computes such rows again before showing or storing them. What changes is the tag
`get_cached_results` returns for such a row (with `EmptyData`): it now has the stored
types, the first session's tag hash and no storage-only data-tag mark. (ITL-1298)
26 changes: 26 additions & 0 deletions docs/dev/design_issues/ITL-1298-FN4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
## `src/orcapod/core/nodes/function_node.py`

### FN4 — A row recomputed in a later session rebuilt its tag from Python values
**Status:** resolved
**Severity:** high
**Issue:** ITL-1298 (related: ITL-1295)

A function job node whose results are ephemeral finds, in a later session (a new job over
the same database with a new, empty ephemeral database), stored pipeline entries whose
results are gone: cross-session misses. `_load_cached_entries` held an `EmptyData`
placeholder for each, with a `Tag` rebuilt from the stored row's Python values and no
schema, so the tag's types were inferred again: `int8` and `float32` came back as 64-bit
types (another tag hash), and a struct tag raised when read ("Complex unions ..."). The
wrong tag reached no presented row and no stored table: a run computes the row again first,
on the same base entry, and `head`, a cache-only send and a load-only run leave the
placeholder out. It was visible through the public cache facade, `get_cached_results`,
which returns the placeholder's `(tag, EmptyData)` without computing.

**Fix:** `_fetch_joined_records` keeps each miss row's one-row Arrow table from the pipeline
table (`_JoinedRecords.empty_taginfo_tables`), and `_load_cached_entries` builds the tag
from its tag and system-tag columns, with the stored types and without the storage-only
data-tag mark (`without_tag_kind_marks`, as for a stored row read into a stream): the miss
row's tag, as `get_cached_results` returns it, has the first session's fields, types and
tag hash, and a struct tag reads. Runs, counts, presented and stored rows, record ids,
entry ids and paths are unchanged; no golden value moves. Tests:
`tests/test_pipeline/test_cross_session_miss_tags.py`, through `get_cached_results`.
201 changes: 201 additions & 0 deletions docs/dev/scripts/itl_1298/measure_miss_rows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
"""ITL-1298: a cross-session miss row's tag (ephemeral results gone in a later session).

usage: uv run python docs/dev/scripts/itl_1298/measure_miss_rows.py

Session 1: a job over an in-memory database with an ephemeral in-memory database, the
nodes' results ephemeral (``NodeConfig(is_result_ephemeral=True)``): source (tags
``i8: int8``, ``f32: float32``, ``s: large_string``, ``st: struct``, ``l: large_list``,
``p: Path``; data ``x``) -> ``inc`` (node ``one``) -> ``dbl`` (node ``two``). Session 2: a
new job over the same database with a NEW, empty ephemeral database: every ephemeral
result is a cross-session miss. For each session: the run's computed / reused counts;
per row of node ``one`` and ``two`` as presented: the tag's Arrow types, tag content
hash, record id and base entry id; the stored pipeline rows (count, base entry ids,
recomputation indices); and, in session 2 before the run, the rows ``one`` loads from
storage (``_load_cached_entries``: the miss rows' tags as rebuilt), then a
``run(load_only=True)`` in yet another job.

Measured on 2026-11-19 on ``main`` (the miss rows' tags were rebuilt from Python values:
``int8`` and ``float32`` came back as 64-bit types with another tag hash, and a struct tag
raised when read) and with a prototype of the fix; run here with the fix (ITL-1298), the
miss rows' tags have the stored types and session 1's tag hashes.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, cast

import pyarrow as pa

from orcapod import PipelineJob, function_pod
from orcapod.contexts import get_default_context
from orcapod.core.sources import ArrowTableSource
from orcapod.databases import InMemoryArrowDatabase
from orcapod.pipeline import SyncPipelineOrchestrator
from orcapod.system_constants import constants
from orcapod.types import NodeConfig

CTX = get_default_context()


@function_pod(output_keys="y")
def inc(x: int) -> int:
return x + 1


@function_pod(output_keys="z")
def dbl(y: int) -> int:
return 2 * y


def source(with_struct: bool = True) -> ArrowTableSource:
path_type = cast(
pa.BaseExtensionType, CTX.type_converter.python_type_to_arrow_type(Path)
)
arrays = {
"i8": pa.array([1, 2], pa.int8()),
"f32": pa.array([0.5, 1.5], pa.float32()),
"s": pa.array(["é", "b"], pa.large_string()),
"st": pa.array(
[{"a": 1, "b": "u"}, {"a": 2, "b": "v"}],
pa.struct([("a", pa.int64()), ("b", pa.large_string())]),
),
"l": pa.array([[1, 2], [3]], pa.large_list(pa.int64())),
"p": pa.ExtensionArray.from_storage(
path_type, pa.array(["/a", "/b"], pa.large_string())
),
"x": pa.array([10, 20], pa.int64()),
}
if not with_struct:
del arrays["st"]
schema = pa.schema(pa.field(n, a.type, nullable=False) for n, a in arrays.items())
return ArrowTableSource(
pa.Table.from_arrays(list(arrays.values()), schema=schema),
tag_columns=[c for c in ("i8", "f32", "s", "st", "l", "p") if c in arrays],
tag_only_columns=True,
source_id="s",
)


def build(
db: Any, ephemeral: Any, with_struct: bool, only_one: bool = False
) -> PipelineJob:
"""``only_one``: only node ``one``'s results are ephemeral; ``two``'s persist."""
job = PipelineJob(name="itl1298", database=db)
with job:
dbl.pod(inc.pod(source(with_struct), label="one"), label="two")
job.set_ephemeral_database(ephemeral)
if only_one:
job.nodes["one"].node_config = NodeConfig(is_result_ephemeral=True) # pyright: ignore[reportAttributeAccessIssue]
else:
job.apply_node_config(NodeConfig(is_result_ephemeral=True))
return job


def describe_tag(tag: Any) -> dict[str, Any]:
try:
schema = tag.arrow_schema()
system = tag.system_tags()
return {
"types": {f.name: str(f.type) for f in schema},
"hash": tag.content_hash().to_string()[:24],
"record id": next(
v for k, v in system.items() if k.startswith("_tag_record_id")
),
}
except Exception as error: # noqa: BLE001
return {"RAISES": f"{type(error).__name__}: {str(error)[:90]}"}


def presented(job: PipelineJob, label: str) -> list[dict[str, Any]]:
out = []
for tag, data in job.nodes[label].iter_data():
info = describe_tag(tag)
info["data"] = sorted(data.as_dict().items())
out.append(info)
return out


def stored(db: Any, function: str) -> list[tuple[Any, ...]]:
db.flush()
[path] = [
p for p in db.list_table_paths() if p[1] == function and p[-1].startswith("pdb")
]
table = db.get_all_records(path)
return sorted(
zip(
[str(table.column("i8").type)] * table.num_rows,
table.column("i8").to_pylist(),
[
b.hex()[-12:]
for b in table.column("__pipeline_base_entry_id").to_pylist()
],
table.column("__pipeline_recomputation_index").to_pylist(),
table.column(constants.IS_EPHEMERAL_COL).to_pylist(),
)
)


def main() -> None:
for with_struct, only_one in (
(True, False),
(False, False),
(False, True),
(True, True),
):
print(
f"######## tags {'with' if with_struct else 'without'} the struct tag; "
+ (
"only 'one' ephemeral, 'two' persistent"
if only_one
else "both ephemeral"
)
)
run_sessions(with_struct, only_one)


def run_sessions(with_struct: bool, only_one: bool) -> None:
db = InMemoryArrowDatabase()
sessions = [
("session 1", InMemoryArrowDatabase()),
("session 2 (new ephemeral)", InMemoryArrowDatabase()),
]
for name, ephemeral in sessions:
job = build(db, ephemeral, with_struct, only_one)
if name.startswith("session 2"):
loaded = job.nodes["one"]._load_cached_entries() # noqa: SLF001
print(f"== {name}: rows 'one' loads from storage before the run")
for base, (tag, data) in sorted(loaded.items()):
print(
f" {base.hex()[-12:]} {type(data).__name__:10} {describe_tag(tag)}"
)
other = build(db, InMemoryArrowDatabase(), with_struct, only_one)
try:
other.run(orchestrator=SyncPipelineOrchestrator(), load_only=True)
print(f" load_only run: one presents {presented(other, 'one')}")
print(f" load_only run: two presents {presented(other, 'two')}")
except Exception as error: # noqa: BLE001
print(
f" load_only run RAISES {type(error).__name__}: {str(error)[:150]}"
)
try:
summary = job.run(orchestrator=SyncPipelineOrchestrator())
counts = {
lbl: (summary.nodes[lbl].computed, summary.nodes[lbl].reused)
for lbl in ("one", "two")
}
except Exception as error: # noqa: BLE001
print(f"== {name}: run RAISES {type(error).__name__}: {str(error)[:200]}")
continue
print(f"== {name}: (computed, reused) {counts}")
for label in ("one", "two"):
for row in presented(job, label):
print(f" {label} presents {row}")
for function in ("inc", "dbl"):
print(
f" stored {function} (i8 type, i8, base entry, recomputation, ephemeral): {stored(db, function)}"
)


if __name__ == "__main__":
main()
46 changes: 33 additions & 13 deletions src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -1231,8 +1231,12 @@ class _JoinedRecords(NamedTuple):
was not found in either database (cross-session miss). Empty dict
when no ephemeral misses occurred.
empty_taginfo_rows: Mapping from ``base_entry_id`` bytes to the raw
taginfo row dict for each entry in ``empty_data_tokens``. Used
by ``_load_cached_entries`` to reconstruct the tag for each token.
taginfo row dict for each entry in ``empty_data_tokens``: its
bookkeeping columns (the recomputation index) are read from it.
empty_taginfo_tables: Mapping from ``base_entry_id`` bytes to the same
taginfo row as a one-row Arrow table, with its stored Arrow types.
``_load_cached_entries`` builds the tag of each token from it, never
from Python values (ITL-1298).
data_tags: The data-tags the pipeline table marks (ITL-1019),
checked against the node's pod when it has one.
"""
Expand All @@ -1241,6 +1245,7 @@ class _JoinedRecords(NamedTuple):
taginfo_columns: tuple[str, ...]
empty_data_tokens: dict[bytes, EmptyData]
empty_taginfo_rows: dict[bytes, dict]
empty_taginfo_tables: dict[bytes, pa.Table]
data_tags: tuple[str, ...]


Expand Down Expand Up @@ -3446,6 +3451,7 @@ def _fetch_joined_records(
ephemeral_df = pl.DataFrame()
empty_data_tokens: dict[bytes, EmptyData] = {}
empty_taginfo_rows: dict[bytes, dict] = {}
empty_taginfo_tables: dict[bytes, pa.Table] = {}

if ephemeral_taginfo_df.height > 0:
eph_frame: pl.DataFrame | None = None
Expand Down Expand Up @@ -3481,10 +3487,12 @@ def _fetch_joined_records(
# No ephemeral database or empty database — all ephemeral rows are misses.
unmatched_df = ephemeral_taginfo_df
# The rows themselves are read from the pipeline table, not from Polars.
unmatched_rows = taginfo.take(
# Each is kept as its one-row Arrow table too: its tag is built from
# that, with the stored types (ITL-1298).
unmatched_table = taginfo.take(
unmatched_df.get_column(_TAGINFO_ROW).to_arrow()
).to_pylist()
for row in unmatched_rows:
)
for index, row in enumerate(unmatched_table.to_pylist()):
base_eid = row[_PIPELINE_BASE_ENTRY_ID_COL]
previous = empty_taginfo_rows.get(base_eid)
if (
Expand Down Expand Up @@ -3517,6 +3525,7 @@ def _fetch_joined_records(
data_context=self.data_context,
)
empty_taginfo_rows[base_eid] = row
empty_taginfo_tables[base_eid] = unmatched_table.slice(index, 1)

# ------------------------------------------------------------------
# Keep both databases' rows until latest-recomputation selection. Persistent
Expand All @@ -3536,6 +3545,7 @@ def _fetch_joined_records(
taginfo_columns=taginfo_columns,
empty_data_tokens=empty_data_tokens,
empty_taginfo_rows=empty_taginfo_rows,
empty_taginfo_tables=empty_taginfo_tables,
data_tags=data_tags,
)

Expand Down Expand Up @@ -3574,6 +3584,7 @@ def _fetch_joined_records(
taginfo_columns=taginfo_columns,
empty_data_tokens=empty_data_tokens,
empty_taginfo_rows=empty_taginfo_rows,
empty_taginfo_tables=empty_taginfo_tables,
data_tags=data_tags,
)

Expand Down Expand Up @@ -3755,14 +3766,23 @@ def _load_cached_entries(
if base_eid in loaded:
# A matched result at least as recent as the missing one wins.
continue
raw_row = fetched.empty_taginfo_rows[base_eid]
tag_data = {k: v for k, v in raw_row.items() if k in tag_keys}
system_tags = {
k: v
for k, v in raw_row.items()
if k.startswith(constants.SYSTEM_TAG_PREFIX)
}
tag = Tag(tag_data, system_tags=system_tags, data_context=self.data_context)
# The stored row with its stored Arrow types, never Python values: a
# type inferred again (int8 as int64) would give the tag another hash,
# and a struct tag could not be read at all (ITL-1298). The columns
# keep the stored row's order, tags and system tags. The storage-only
# data-tag mark is dropped, as for a stored row read into a stream.
row_table = without_tag_kind_marks(fetched.empty_taginfo_tables[base_eid])
tag = Tag(
row_table.select(
[
name
for name in row_table.column_names
if name in tag_keys
or name.startswith(constants.SYSTEM_TAG_PREFIX)
]
),
data_context=self.data_context,
)
loaded[base_eid] = (tag, empty_data)

return loaded
Expand Down
Loading
Loading