From 149addd740b451ca74f054fc4202f5a1a0df7d9d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 17:39:07 -0800 Subject: [PATCH 1/3] fix(function_node): a cross-session miss row's tag is built from the stored Arrow row (ITL-1298) A function node whose ephemeral results are gone in a later session rebuilt the stored rows' tags from Python values: int8 and float32 came back as 64-bit types (another tag hash) and a struct tag could not be read. The miss row's tag is now its stored one-row Arrow table's tag and system-tag columns. No presented row, stored row, hash or golden value changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1298.md | 8 + docs/dev/design_issues/ITL-1298-FN4.md | 23 ++ .../dev/scripts/itl_1298/measure_miss_rows.py | 201 +++++++++++++++ src/orcapod/core/nodes/function_node.py | 45 +++- .../test_cross_session_miss_tags.py | 237 ++++++++++++++++++ 5 files changed, 501 insertions(+), 13 deletions(-) create mode 100644 changelog.d/ITL-1298.md create mode 100644 docs/dev/design_issues/ITL-1298-FN4.md create mode 100644 docs/dev/scripts/itl_1298/measure_miss_rows.py create mode 100644 tests/test_pipeline/test_cross_session_miss_tags.py diff --git a/changelog.d/ITL-1298.md b/changelog.d/ITL-1298.md new file mode 100644 index 000000000..fa990d5fd --- /dev/null +++ b/changelog.d/ITL-1298.md @@ -0,0 +1,8 @@ +### 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. The node computes such rows again before showing or storing anything, + so no presented row, stored row or hash changes. (ITL-1298) diff --git a/docs/dev/design_issues/ITL-1298-FN4.md b/docs/dev/design_issues/ITL-1298-FN4.md new file mode 100644 index 000000000..6af94f210 --- /dev/null +++ b/docs/dev/design_issues/ITL-1298-FN4.md @@ -0,0 +1,23 @@ +## `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 +measurement found the wrong tag reached no presented row and no stored table: every public +read computes the row again first, on the same base entry, or leaves the placeholder out. + +**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: the miss row's tag has the +first session's 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` (the placeholder's tag is visible +only in the loaded entries, which the test reads directly). diff --git a/docs/dev/scripts/itl_1298/measure_miss_rows.py b/docs/dev/scripts/itl_1298/measure_miss_rows.py new file mode 100644 index 000000000..35a10698a --- /dev/null +++ b/docs/dev/scripts/itl_1298/measure_miss_rows.py @@ -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() diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 302cc0b89..58adc3b10 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -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. """ @@ -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, ...] @@ -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 @@ -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 ( @@ -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 @@ -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, ) @@ -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, ) @@ -3755,14 +3766,22 @@ 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. + row_table = 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 diff --git a/tests/test_pipeline/test_cross_session_miss_tags.py b/tests/test_pipeline/test_cross_session_miss_tags.py new file mode 100644 index 000000000..9c410fa00 --- /dev/null +++ b/tests/test_pipeline/test_cross_session_miss_tags.py @@ -0,0 +1,237 @@ +"""A row recomputed in a later session keeps its stored tag (ITL-1298). + +A function job node whose results are ephemeral stores its pipeline entries in the +pipeline database and its results in an ephemeral database. In a later session (a new +job over the same database, with a new, empty ephemeral database) every such result +is gone: a cross-session miss. The node loads the stored entry and holds an +``EmptyData`` placeholder for it, with the row's tag. That tag used to be rebuilt from +the stored row's Python values with no schema, so its types were inferred again: an +``int8`` tag became ``int64`` (another tag hash), and a struct tag could not be read at +all. It is now built from the stored one-row Arrow table, with the stored types. + +The placeholder's tag is visible only in the node's loaded entries: in every public +read the node computes the row again first (a run), or leaves the placeholder out +(``head``, a cache-only send, a load-only run). So the tests read the loaded entries +through ``_load_cached_entries``, the one place that shows them, and check through the +public interface that nothing a user sees or stores changes: the run counts, the +presented rows (tag types, tag hash, record id, values), and the stored pipeline rows +(each recomputed row on its own base entry, as the next recomputation). + +The source has tags of several types (``int8``, ``float32``, ``large_string``, a struct, +a ``large_list`` and the logical ``Path``), two or more at a time and in more than one +tag order, as plain tags and as data-tags; one ``int64`` data column ``x``. The graph is +``inc`` (node ``one``) then ``dbl`` (node ``two``): both nodes ephemeral, or only +``one``. Every case runs on the sync and the async orchestrator. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context +from orcapod.core.datagrams import EmptyData +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import TagProtocol +from orcapod.system_constants import constants +from orcapod.types import NodeConfig + +CTX = get_default_context() +PATH_TYPE = cast( + pa.BaseExtensionType, CTX.type_converter.python_type_to_arrow_type(Path) +) + +TAG_COLUMNS: dict[str, "pa.Array[Any]"] = { + "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()) + ), +} +# Two or more tags at a time, each set in two tag orders. +TAG_SETS = [ + ("i8", "f32", "s"), + ("s", "f32", "i8"), + ("st", "l", "p", "i8"), + ("i8", "p", "l", "st"), +] +PLAIN, DATA_TAGS = "plain", "data_tags" +BOTH_EPHEMERAL, ONE_EPHEMERAL = "both_ephemeral", "one_ephemeral" +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + + +@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(tags: tuple[str, ...], role: str) -> ArrowTableSource: + arrays = {**{name: TAG_COLUMNS[name] for name in tags}, "x": pa.array([10, 20])} + 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=list(tags), + tag_only_columns=True if role == PLAIN else [], + source_id="s", + ) + + +def _job( + database: Any, + ephemeral: InMemoryArrowDatabase, + tags: tuple[str, ...], + role: str, + config: str, +) -> PipelineJob: + job = PipelineJob(name="itl1298", database=database) + with job: + dbl.pod(inc.pod(_source(tags, role), label="one"), label="two") + job.set_ephemeral_database(ephemeral) + if config == BOTH_EPHEMERAL: + job.apply_node_config(NodeConfig(is_result_ephemeral=True)) + else: + job.nodes["one"].node_config = NodeConfig(is_result_ephemeral=True) # pyright: ignore[reportAttributeAccessIssue] + return job + + +def _record_id(tag: TagProtocol) -> str: + return next( + str(value) + for name, value in tag.system_tags().items() + if name.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) + ) + + +def _type_text(arrow_type: pa.DataType) -> str: + """An Arrow type as text, a list's child field name left out. + + The Delta store reads a list's child field back as ``element`` where it was written + as ``item`` (the store's own type changes, ITL-890 and ITL-999); the name enters no + hash, and the tag hash is compared too. + """ + if pa.types.is_large_list(arrow_type): + return f"large_list<{_type_text(arrow_type.value_type)}>" + return str(arrow_type) + + +def _tag_facts(tag: TagProtocol) -> tuple[str, dict[str, str], str, str]: + """(record id, tag Arrow types, tag hash, tag values): the struct tag must read.""" + return ( + _record_id(tag), + {f.name: _type_text(f.type) for f in tag.arrow_schema()}, + tag.content_hash().to_string(), + repr(sorted(tag.as_dict().items(), key=lambda item: item[0])), + ) + + +def _presented(job: PipelineJob, label: str) -> dict[str, tuple[Any, ...]]: + return { + _record_id(tag): (*_tag_facts(tag)[1:], repr(sorted(data.as_dict().items()))) + for tag, data in job.nodes[label].iter_data() + } + + +def _stored(database: Any, function: str) -> list[tuple[Any, ...]]: + """The stored pipeline rows of ``function``: (base entry, recomputation index).""" + database.flush() + [path] = [ + p + for p in database.list_table_paths() + if p[1] == function and p[-1].startswith("pdb") + ] + table = database.get_all_records(path) + return sorted( + zip( + table.column("__pipeline_base_entry_id").to_pylist(), + table.column("__pipeline_recomputation_index").to_pylist(), + ) + ) + + +@pytest.mark.parametrize("store", ["memory", "delta"]) +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("config", [BOTH_EPHEMERAL, ONE_EPHEMERAL]) +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS]) +@pytest.mark.parametrize("tags", TAG_SETS, ids=lambda t: "-".join(t)) +def test_a_cross_session_miss_keeps_its_stored_tag( + tags: tuple[str, ...], + role: str, + config: str, + orchestrator: str, + store: str, + tmp_path: Path, +) -> None: + """The pipeline database is in memory or a Delta store; the ephemeral one is in + memory, new in each session.""" + database: Any = ( + InMemoryArrowDatabase() + if store == "memory" + else DeltaTableDatabase(base_path=tmp_path / "store") + ) + ephemeral_nodes = ["one", "two"] if config == BOTH_EPHEMERAL else ["one"] + + # Session 1: every row computed and stored. + first = _job(database, InMemoryArrowDatabase(), tags, role, config) + summary = first.run(orchestrator=ORCHESTRATORS[orchestrator]()) + assert { + label: (summary.nodes[label].computed, summary.nodes[label].reused) + for label in ("one", "two") + } == {"one": (2, 0), "two": (2, 0)} + presented = {label: _presented(first, label) for label in ("one", "two")} + stored = {function: _stored(database, function) for function in ("inc", "dbl")} + assert sorted(presented["one"]) == ["row_0", "row_1"] + for label in ("one", "two"): + for types, *_ in presented[label].values(): + assert types == {name: _type_text(TAG_COLUMNS[name].type) for name in tags} + + # Session 2: a new job over the same database, a new empty ephemeral database. + second = _job(database, InMemoryArrowDatabase(), tags, role, config) + for label in ephemeral_nodes: + # Only the node's loaded entries show a miss row's tag (see the module). + loaded = second.nodes[label]._load_cached_entries() # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType] # the test is about it + assert len(loaded) == 2 + for tag, data in cast(dict[bytes, tuple[TagProtocol, Any]], loaded).values(): + assert isinstance(data, EmptyData) + record_id, types, tag_hash, values = _tag_facts(tag) + want_types, want_hash, want_values, _ = presented[label][record_id] + assert types == want_types, (label, record_id) + assert tag_hash == want_hash, (label, record_id) + assert values == want_values, (label, record_id) + + summary = second.run(orchestrator=ORCHESTRATORS[orchestrator]()) + assert { + label: (summary.nodes[label].computed, summary.nodes[label].reused) + for label in ("one", "two") + } == { + "one": (2, 0), + "two": (2, 0) if config == BOTH_EPHEMERAL else (0, 2), + } + for label in ("one", "two"): + assert _presented(second, label) == presented[label], label + # Each recomputed row lands on its own base entry, as the next recomputation; a + # persistent node's rows are reused and nothing new is stored. + for function, label in (("inc", "one"), ("dbl", "two")): + now = _stored(database, function) + if label in ephemeral_nodes: + assert now == sorted( + [*stored[function], *[(entry, 1) for entry, _ in stored[function]]] + ) + else: + assert now == stored[function] From b297571ea7e6362d5b11171914b733730609715e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 18:59:16 -0800 Subject: [PATCH 2/3] fix(function_node): a miss row's tag drops the storage-only data-tag mark; test through get_cached_results (ITL-1298) The tag built from the stored row kept the data-tag mark the stored table carries; it is removed as for a stored row read into a stream. The tests read the tag through the public cache facade, get_cached_results, in an all-missing and a mixed hit/miss load, and compare every field (type, nullability, metadata, system tags). The texts no longer say the tag is invisible: get_cached_results returns it. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1298.md | 6 +- docs/dev/design_issues/ITL-1298-FN4.md | 17 +-- src/orcapod/core/nodes/function_node.py | 5 +- .../test_cross_session_miss_tags.py | 105 +++++++++++++----- 4 files changed, 97 insertions(+), 36 deletions(-) diff --git a/changelog.d/ITL-1298.md b/changelog.d/ITL-1298.md index fa990d5fd..e5f881fb8 100644 --- a/changelog.d/ITL-1298.md +++ b/changelog.d/ITL-1298.md @@ -4,5 +4,7 @@ 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. The node computes such rows again before showing or storing anything, - so no presented row, stored row or hash changes. (ITL-1298) + 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) diff --git a/docs/dev/design_issues/ITL-1298-FN4.md b/docs/dev/design_issues/ITL-1298-FN4.md index 6af94f210..0c112a55d 100644 --- a/docs/dev/design_issues/ITL-1298-FN4.md +++ b/docs/dev/design_issues/ITL-1298-FN4.md @@ -11,13 +11,16 @@ results are gone: cross-session misses. `_load_cached_entries` held an `EmptyDat 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 -measurement found the wrong tag reached no presented row and no stored table: every public -read computes the row again first, on the same base entry, or leaves the placeholder out. +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: the miss row's tag has the -first session's 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` (the placeholder's tag is visible -only in the loaded entries, which the test reads directly). +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`. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 58adc3b10..b392343b5 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3769,8 +3769,9 @@ def _load_cached_entries( # 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. - row_table = fetched.empty_taginfo_tables[base_eid] + # 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( [ diff --git a/tests/test_pipeline/test_cross_session_miss_tags.py b/tests/test_pipeline/test_cross_session_miss_tags.py index 9c410fa00..6cd727639 100644 --- a/tests/test_pipeline/test_cross_session_miss_tags.py +++ b/tests/test_pipeline/test_cross_session_miss_tags.py @@ -7,15 +7,17 @@ ``EmptyData`` placeholder for it, with the row's tag. That tag used to be rebuilt from the stored row's Python values with no schema, so its types were inferred again: an ``int8`` tag became ``int64`` (another tag hash), and a struct tag could not be read at -all. It is now built from the stored one-row Arrow table, with the stored types. - -The placeholder's tag is visible only in the node's loaded entries: in every public -read the node computes the row again first (a run), or leaves the placeholder out -(``head``, a cache-only send, a load-only run). So the tests read the loaded entries -through ``_load_cached_entries``, the one place that shows them, and check through the -public interface that nothing a user sees or stores changes: the run counts, the -presented rows (tag types, tag hash, record id, values), and the stored pipeline rows -(each recomputed row on its own base entry, as the next recomputation). +all. It is now built from the stored one-row Arrow table, with the stored types and +without the storage-only data-tag mark. + +The node's cache facade, ``get_cached_results``, returns such a row as +``(tag, EmptyData)`` without computing it: that is where the placeholder's tag shows, +and where the tests read it, beside row 0's cached result in a mixed load. A run +computes the row again first, and ``head``, a cache-only send and a load-only run leave +the placeholder out. So the tests check that the tag ``get_cached_results`` returns has +the first session's fields (types, nullability, metadata, system tags), hash and values, +and that the run counts, the presented rows and the stored pipeline rows (each +recomputed row on its own base entry, as the next recomputation) are unchanged. The source has tags of several types (``int8``, ``float32``, ``large_string``, a struct, a ``large_list`` and the logical ``Path``), two or more at a time and in more than one @@ -82,8 +84,11 @@ def dbl(y: int) -> int: return 2 * y -def _source(tags: tuple[str, ...], role: str) -> ArrowTableSource: - arrays = {**{name: TAG_COLUMNS[name] for name in tags}, "x": pa.array([10, 20])} +def _source(tags: tuple[str, ...], role: str, rows: int = 2) -> ArrowTableSource: + arrays = { + **{name: TAG_COLUMNS[name].slice(0, rows) for name in tags}, + "x": pa.array([10, 20][:rows]), + } 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), @@ -99,10 +104,11 @@ def _job( tags: tuple[str, ...], role: str, config: str, + rows: int = 2, ) -> PipelineJob: job = PipelineJob(name="itl1298", database=database) with job: - dbl.pod(inc.pod(_source(tags, role), label="one"), label="two") + dbl.pod(inc.pod(_source(tags, role, rows), label="one"), label="two") job.set_ephemeral_database(ephemeral) if config == BOTH_EPHEMERAL: job.apply_node_config(NodeConfig(is_result_ephemeral=True)) @@ -141,6 +147,17 @@ def _tag_facts(tag: TagProtocol) -> tuple[str, dict[str, str], str, str]: ) +def _fields(tag: TagProtocol) -> list[tuple[Any, ...]]: + """Every field of the tag (system tags included): name, type, nullability and + metadata (a list's child field name left out, see ``_type_text``). Empty metadata + is no metadata, as Arrow's own ``equals(..., check_metadata=True)`` holds it (the + Delta store reads a logical field back with ``{}``).""" + return [ + (f.name, _type_text(f.type), f.nullable, f.metadata or None) + for f in tag.arrow_schema(columns={"system_tags": True}) + ] + + def _presented(job: PipelineJob, label: str) -> dict[str, tuple[Any, ...]]: return { _record_id(tag): (*_tag_facts(tag)[1:], repr(sorted(data.as_dict().items()))) @@ -165,6 +182,10 @@ def _stored(database: Any, function: str) -> list[tuple[Any, ...]]: ) +ALL_MISSING, MIXED_LOAD = "all_missing", "mixed" + + +@pytest.mark.parametrize("scenario", [ALL_MISSING, MIXED_LOAD]) @pytest.mark.parametrize("store", ["memory", "delta"]) @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) @pytest.mark.parametrize("config", [BOTH_EPHEMERAL, ONE_EPHEMERAL]) @@ -176,52 +197,86 @@ def test_a_cross_session_miss_keeps_its_stored_tag( config: str, orchestrator: str, store: str, + scenario: str, tmp_path: Path, ) -> None: """The pipeline database is in memory or a Delta store; the ephemeral one is in - memory, new in each session.""" + memory. In session 2 every result is gone (``all_missing``), or row 0's result is + there and row 1's is gone (``mixed``: a session in between ran row 0 alone over + session 2's ephemeral database).""" database: Any = ( InMemoryArrowDatabase() if store == "memory" else DeltaTableDatabase(base_path=tmp_path / "store") ) ephemeral_nodes = ["one", "two"] if config == BOTH_EPHEMERAL else ["one"] + run = ORCHESTRATORS[orchestrator] # Session 1: every row computed and stored. first = _job(database, InMemoryArrowDatabase(), tags, role, config) - summary = first.run(orchestrator=ORCHESTRATORS[orchestrator]()) + summary = first.run(orchestrator=run()) assert { label: (summary.nodes[label].computed, summary.nodes[label].reused) for label in ("one", "two") } == {"one": (2, 0), "two": (2, 0)} presented = {label: _presented(first, label) for label in ("one", "two")} + first_fields = { + label: { + _record_id(tag): _fields(tag) for tag, _ in first.nodes[label].iter_data() + } + for label in ("one", "two") + } stored = {function: _stored(database, function) for function in ("inc", "dbl")} assert sorted(presented["one"]) == ["row_0", "row_1"] for label in ("one", "two"): for types, *_ in presented[label].values(): assert types == {name: _type_text(TAG_COLUMNS[name].type) for name in tags} - # Session 2: a new job over the same database, a new empty ephemeral database. - second = _job(database, InMemoryArrowDatabase(), tags, role, config) - for label in ephemeral_nodes: - # Only the node's loaded entries show a miss row's tag (see the module). - loaded = second.nodes[label]._load_cached_entries() # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType] # the test is about it - assert len(loaded) == 2 - for tag, data in cast(dict[bytes, tuple[TagProtocol, Any]], loaded).values(): - assert isinstance(data, EmptyData) + ephemeral = InMemoryArrowDatabase() + if scenario == MIXED_LOAD: + # Row 0 alone, over session 2's ephemeral database: its results are there. + _ = _job(database, ephemeral, tags, role, config, rows=1).run( + orchestrator=run() + ) + before = {function: _stored(database, function) for function in ("inc", "dbl")} + + # Session 2: a new job over the same database. + second = _job(database, ephemeral, tags, role, config) + for label, function in (("one", "inc"), ("two", "dbl")): + if label not in ephemeral_nodes: + continue + # The public cache facade returns a miss row as (tag, EmptyData), without + # computing it. + entries = sorted({entry for entry, _ in before[function]}) + cached = second.nodes[label].get_cached_results(entries) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType] + pairs = cast(dict[bytes, tuple[TagProtocol, Any]], cached) + assert len(pairs) == 2 + misses = { + _record_id(tag) + for tag, data in pairs.values() + if isinstance(data, EmptyData) + } + assert misses == ( + {"row_0", "row_1"} if scenario == ALL_MISSING else {"row_1"} + ), label + for tag, _ in pairs.values(): + # Hit or miss, the tag is session 1's: types, nullability, metadata (no + # storage-only data-tag mark), system tags, hash and values. record_id, types, tag_hash, values = _tag_facts(tag) want_types, want_hash, want_values, _ = presented[label][record_id] assert types == want_types, (label, record_id) assert tag_hash == want_hash, (label, record_id) assert values == want_values, (label, record_id) + assert _fields(tag) == first_fields[label][record_id], (label, record_id) - summary = second.run(orchestrator=ORCHESTRATORS[orchestrator]()) + summary = second.run(orchestrator=run()) + recomputed = 2 if scenario == ALL_MISSING else 1 assert { label: (summary.nodes[label].computed, summary.nodes[label].reused) for label in ("one", "two") } == { - "one": (2, 0), - "two": (2, 0) if config == BOTH_EPHEMERAL else (0, 2), + "one": (recomputed, 2 - recomputed), + "two": (recomputed, 2 - recomputed) if config == BOTH_EPHEMERAL else (0, 2), } for label in ("one", "two"): assert _presented(second, label) == presented[label], label From 8eac6c92c9630cdc79fd871065a54007869813c4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 19:31:12 -0800 Subject: [PATCH 3/3] test(function_node): two data columns and three table layouts in the cross-session miss test (ITL-1298) Co-Authored-By: Claude Opus 5.5 --- .../test_cross_session_miss_tags.py | 48 ++++++++++++++----- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/tests/test_pipeline/test_cross_session_miss_tags.py b/tests/test_pipeline/test_cross_session_miss_tags.py index 6cd727639..b2e18305d 100644 --- a/tests/test_pipeline/test_cross_session_miss_tags.py +++ b/tests/test_pipeline/test_cross_session_miss_tags.py @@ -21,7 +21,8 @@ The source has tags of several types (``int8``, ``float32``, ``large_string``, a struct, a ``large_list`` and the logical ``Path``), two or more at a time and in more than one -tag order, as plain tags and as data-tags; one ``int64`` data column ``x``. The graph is +tag order, as plain tags and as data-tags; two ``int64`` data columns ``x`` and ``w``, the +table laid out tags first, data first, or tags and data interleaved. The graph is ``inc`` (node ``one``) then ``dbl`` (node ``two``): both nodes ephemeral, or only ``one``. Every case runs on the sync and the async orchestrator. """ @@ -75,8 +76,8 @@ @function_pod(output_keys="y") -def inc(x: int) -> int: - return x + 1 +def inc(x: int, w: int) -> int: + return x + w + 1 @function_pod(output_keys="z") @@ -84,11 +85,31 @@ def dbl(y: int) -> int: return 2 * y -def _source(tags: tuple[str, ...], role: str, rows: int = 2) -> ArrowTableSource: - arrays = { - **{name: TAG_COLUMNS[name].slice(0, rows) for name in tags}, - "x": pa.array([10, 20][:rows]), - } +TAGS_FIRST, DATA_FIRST, INTERLEAVED = "tags_first", "data_first", "interleaved" +LAYOUTS = (TAGS_FIRST, DATA_FIRST, INTERLEAVED) + + +def _source( + tags: tuple[str, ...], role: str, layout: str, rows: int = 2 +) -> ArrowTableSource: + """Tags ``tags`` (in this order) and two data columns ``x`` and ``w``, the table + laid out tags first, data first, or tags and data interleaved.""" + tag_arrays = [(name, TAG_COLUMNS[name].slice(0, rows)) for name in tags] + data_arrays = [ + ("x", pa.array([10, 20][:rows])), + ("w", pa.array([100, 200][:rows])), + ] + if layout == TAGS_FIRST: + ordered = [*tag_arrays, *data_arrays] + elif layout == DATA_FIRST: + ordered = [*data_arrays, *tag_arrays] + else: + ordered = [] + for index, tag in enumerate(tag_arrays): + ordered.append(tag) + if index < len(data_arrays): + ordered.append(data_arrays[index]) + arrays = dict(ordered) 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), @@ -104,11 +125,12 @@ def _job( tags: tuple[str, ...], role: str, config: str, + layout: str, rows: int = 2, ) -> PipelineJob: job = PipelineJob(name="itl1298", database=database) with job: - dbl.pod(inc.pod(_source(tags, role, rows), label="one"), label="two") + dbl.pod(inc.pod(_source(tags, role, layout, rows), label="one"), label="two") job.set_ephemeral_database(ephemeral) if config == BOTH_EPHEMERAL: job.apply_node_config(NodeConfig(is_result_ephemeral=True)) @@ -185,6 +207,7 @@ def _stored(database: Any, function: str) -> list[tuple[Any, ...]]: ALL_MISSING, MIXED_LOAD = "all_missing", "mixed" +@pytest.mark.parametrize("layout", LAYOUTS) @pytest.mark.parametrize("scenario", [ALL_MISSING, MIXED_LOAD]) @pytest.mark.parametrize("store", ["memory", "delta"]) @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) @@ -198,6 +221,7 @@ def test_a_cross_session_miss_keeps_its_stored_tag( orchestrator: str, store: str, scenario: str, + layout: str, tmp_path: Path, ) -> None: """The pipeline database is in memory or a Delta store; the ephemeral one is in @@ -213,7 +237,7 @@ def test_a_cross_session_miss_keeps_its_stored_tag( run = ORCHESTRATORS[orchestrator] # Session 1: every row computed and stored. - first = _job(database, InMemoryArrowDatabase(), tags, role, config) + first = _job(database, InMemoryArrowDatabase(), tags, role, config, layout) summary = first.run(orchestrator=run()) assert { label: (summary.nodes[label].computed, summary.nodes[label].reused) @@ -235,13 +259,13 @@ def test_a_cross_session_miss_keeps_its_stored_tag( ephemeral = InMemoryArrowDatabase() if scenario == MIXED_LOAD: # Row 0 alone, over session 2's ephemeral database: its results are there. - _ = _job(database, ephemeral, tags, role, config, rows=1).run( + _ = _job(database, ephemeral, tags, role, config, layout, rows=1).run( orchestrator=run() ) before = {function: _stored(database, function) for function in ("inc", "dbl")} # Session 2: a new job over the same database. - second = _job(database, ephemeral, tags, role, config) + second = _job(database, ephemeral, tags, role, config, layout) for label, function in (("one", "inc"), ("two", "dbl")): if label not in ephemeral_nodes: continue