From 1f5259d7d10323c6797fcbe8e734e5da46a38da5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Thu, 19 Nov 2026 06:42:17 -0800 Subject: [PATCH 1/3] fix(function_node): read stored results from Arrow; Polars only matches rows (ITL-1295) Every read of a function node's stored results joined the pipeline and result tables in Polars and carried every column through it: a date64 tag came back at midnight (also in lists and structs), a decimal256 tag made Polars panic, a join of a reused node found nothing, and every reuse recorded new pipeline entries under the changed tag. Polars now sees only the bookkeeping columns and row numbers; every column is taken from the stored tables, in the layout Polars gave. No hash, entry id, stored path or column moves. The sort fallback of sort_by_tag_columns (part 2) waits for arrow_keys (PR 459) and is pinned by strict expected failures. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1295.md | 12 + docs/dev/design_issues/ITL-1295-FN3.md | 34 ++ docs/dev/scripts/itl_1295/dump_reads.py | 193 +++++++++ .../scripts/itl_1295/measure_loaded_job.py | 52 +++ .../measure_outputs_and_downstream.py | 176 ++++++++ .../dev/scripts/itl_1295/measure_read_path.py | 280 +++++++++++++ .../scripts/itl_1295/measure_reuse_rows.py | 41 ++ .../itl_1295/measure_stored_downstream.py | 86 ++++ src/orcapod/core/nodes/function_node.py | 135 +++++- .../test_function_node_stored_values.py | 385 ++++++++++++++++++ 10 files changed, 1381 insertions(+), 13 deletions(-) create mode 100644 changelog.d/ITL-1295.md create mode 100644 docs/dev/design_issues/ITL-1295-FN3.md create mode 100644 docs/dev/scripts/itl_1295/dump_reads.py create mode 100644 docs/dev/scripts/itl_1295/measure_loaded_job.py create mode 100644 docs/dev/scripts/itl_1295/measure_outputs_and_downstream.py create mode 100644 docs/dev/scripts/itl_1295/measure_read_path.py create mode 100644 docs/dev/scripts/itl_1295/measure_reuse_rows.py create mode 100644 docs/dev/scripts/itl_1295/measure_stored_downstream.py create mode 100644 tests/test_pipeline/test_function_node_stored_values.py diff --git a/changelog.d/ITL-1295.md b/changelog.d/ITL-1295.md new file mode 100644 index 000000000..84938674d --- /dev/null +++ b/changelog.d/ITL-1295.md @@ -0,0 +1,12 @@ +### Fixed + +- **A function node's stored results read back exactly as they were stored.** Every read + of stored results (`node.as_source()`, a second run of a job over the same database, + `run(load_only=True)`, a saved and loaded job) carried every column through Polars. + A user could see a `date64` tag read back at midnight (also inside a list or a + struct); a join of the reused node's results with another input finding no rows on the + second run although it found them on the first; a node added downstream storing the + changed value; duplicate pipeline entries recorded on every such run; and, with a + `decimal256` tag, the second run crashing the process. Now only the bookkeeping columns + pass through Polars, and every value is taken from the stored tables. No hash, entry id + or stored table changes. (ITL-1295) diff --git a/docs/dev/design_issues/ITL-1295-FN3.md b/docs/dev/design_issues/ITL-1295-FN3.md new file mode 100644 index 000000000..f3b587107 --- /dev/null +++ b/docs/dev/design_issues/ITL-1295-FN3.md @@ -0,0 +1,34 @@ +## `src/orcapod/core/nodes/function_node.py` + +### FN3 — Reading a function node's stored results carried every column through Polars +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1295 (related: ITL-1284, ITL-1249) + +`FunctionJobNode._fetch_joined_records` joined the stored pipeline table and result +table as `pl.DataFrame` and converted the result back to Arrow. Every column went +through Polars, which changes or refuses some Arrow types: a `date64` tag off midnight +came back at midnight (also in a list or a struct), and a `decimal256` tag made Polars +panic, which no caller can catch. The stored tables were exact and a node's first run +showed exact values; every read of stored results did not: `node.as_source()`, a run of +a new job over the same database (results reused), `run(load_only=True)` and a saved and +loaded job. Downstream, a join of a reused node with a fresh source on the same tags found +nothing; a node added over a reused node stored the changed tag; and because a pipeline +entry id includes the tag values, every reuse run recorded new entries for the same +inputs under the changed tag (a downstream node's table grew from 2 to 4 rows). With a +`decimal256` tag, the reuse run itself crashed. + +**Fix:** Polars only decides which stored rows belong together. It sees the bookkeeping +columns it filters and joins on (node content hash, ephemeral flag, record id, base +entry id, recomputation index) and a row number per table (`_row_frame`); every column +of the joined records is taken from the stored Arrow tables by those row numbers +(`_joined_from_stored`), in the layout Polars gave (a result column the pipeline table +also names takes `_right`), and the rows of a cross-session ephemeral miss are read from +the pipeline table. For every type Polars held exactly the result is what it was: +columns, order, names, types, nullability, rows (`docs/dev/scripts/itl_1295/dump_reads.py` +compares two checkouts). No hash, entry id, stored path or column moves. Tests: +`tests/test_pipeline/test_function_node_stored_values.py`. Remaining: the sort fallback of +`arrow_utils.sort_by_tag_columns` (list and struct tags, `as_table(sort_by_tags=True)`, +`head().sort_by_tags()`) still sorts through Polars; it needs the key preparation of +`core/operators/arrow_keys.py` (ITL-1284) and is the second part of ITL-1295 (strict +expected failures name it). diff --git a/docs/dev/scripts/itl_1295/dump_reads.py b/docs/dev/scripts/itl_1295/dump_reads.py new file mode 100644 index 000000000..b1e8490ab --- /dev/null +++ b/docs/dev/scripts/itl_1295/dump_reads.py @@ -0,0 +1,193 @@ +"""ITL-1295: dump every read of stored function results, to compare two checkouts. + +usage: uv run python docs/dev/scripts/itl_1295/dump_reads.py + uv run python docs/dev/scripts/itl_1295/dump_reads.py --compare + +Run it on ``main`` and on the fix (one process at a time), then compare: every table +must be equal with its schema metadata (types, nullability, field metadata, column order, +row order, values), and every ephemeral-miss row and loaded tag the same. Only types +Polars held exactly are used, so ``main`` is the reference. + +Scenarios, each over an in-memory database (pipeline and results) and a separate +in-memory ephemeral database: + +* ``persistent``: one job run, read back by a new job; +* ``mixed``: a first run stores two inputs persistently; a second run, with the + ephemeral database attached, adds two inputs whose results go to it; read back by a + new job with the same ephemeral database (both parts of the fetch); +* ``ephemeral miss``: the same, read back by a new job with a NEW, empty ephemeral + database (cross-session miss: ``EmptyData`` rows). + +Reads: ``_fetch_joined_records()`` (table, ephemeral-miss rows), ``get_all_records()`` +with every column, ``as_source().as_table()`` with every column, and the tags and data +of ``_load_cached_entries()`` as Arrow tables. +""" + +from __future__ import annotations + +import pickle +import sys +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.types import NodeConfig + +CTX = get_default_context() + + +@function_pod(output_keys=("y", "w")) +def two_outputs(x: int) -> tuple[int, float]: + return x + 1, -0.0 if x % 2 else float(x) + + +def source(rows: list[int]) -> ArrowTableSource: + path_type = cast( + pa.BaseExtensionType, CTX.type_converter.python_type_to_arrow_type(Path) + ) + arrays = { + "k": pa.array([r % 3 for r in rows], pa.int8()), + "s": pa.array([f"é{r}" for r in rows], pa.large_string()), + "l": pa.array([[r, None] for r in rows], pa.large_list(pa.int64())), + "st": pa.array( + [{"a": r, "b": str(r)} for r in rows], + pa.struct([("a", pa.int64()), ("b", pa.large_string())]), + ), + "p": pa.ExtensionArray.from_storage( + path_type, pa.array([f"/d/{r}" for r in rows], pa.large_string()) + ), + "x": pa.array(rows, pa.int64()), + "rid": pa.array([f"r{r}" for r in rows], pa.large_string()), + } + schema = pa.schema( + pa.field(name, a.type, nullable=False) for name, a in arrays.items() + ) + return ArrowTableSource( + pa.Table.from_arrays(list(arrays.values()), schema=schema), + tag_columns=["k", "s", "l", "st", "p"], + tag_only_columns=True, + source_id="s", + record_id_columns=["rid"], + ) + + +def build(db: Any, rows: list[int], ephemeral: Any | None) -> PipelineJob: + job = PipelineJob(name="itl1295dump", database=db) + with job: + two_outputs.pod(source(rows), label="node") + if ephemeral is not None: + job.set_ephemeral_database(ephemeral) + job.apply_node_config(NodeConfig(is_result_ephemeral=True)) + return job + + +# Values that differ between any two runs (a random record id, the source-info tokens +# naming it, a time stamp, the checkout's git state): compared by type, not value. +PER_RUN = ("__data_id", "__pod_ts", "__pf_var_git_hash", "_source_y", "_source_w") + + +def plain(table: pa.Table) -> tuple[Any, ...]: + """A table as comparable plain values: each field (name, type, nullability, + metadata) and its values (a logical column as its storage), and the schema metadata.""" + fields = [] + for field, column in zip(table.schema, table.columns): + chunks = [ + c.storage if isinstance(c, pa.ExtensionArray) else c for c in column.chunks + ] + values = [repr(v) for chunk in chunks for v in chunk.to_pylist()] + if field.name in PER_RUN: + values = [f"<{len(values)} per-run values>"] + fields.append( + (field.name, str(field.type), field.nullable, field.metadata, values) + ) + return (tuple(fields), table.schema.metadata) + + +def reads(job: PipelineJob) -> dict[str, Any]: + node: Any = job.nodes["node"] + fetched = node._fetch_joined_records() # noqa: SLF001 + loaded = node._load_cached_entries() # noqa: SLF001 + + def attempt(read: Any) -> Any: + try: + return read() + except Exception as error: # noqa: BLE001 # the same error on both checkouts is the same read + return f"RAISES {type(error).__name__}: {error}" + + tags = [ + ( + base, + attempt(lambda: plain(tag.as_table(columns={"system_tags": True}))), + attempt(lambda: plain(data.as_table(columns={"source": True}))) + if hasattr(data, "as_table") + else repr(data), + ) + for base, (tag, data) in sorted(loaded.items()) + ] + return { + "fetched": plain(fetched.table), + "fetched taginfo columns": fetched.taginfo_columns, + "ephemeral miss rows": { + k: repr( + sorted((c, "" if c in PER_RUN else x) for c, x in v.items()) + ) + for k, v in fetched.empty_taginfo_rows.items() + }, + "get_all_records": plain(node.get_all_records(all_info=True)), + "as_source": plain(node.as_source().as_table(all_info=True)), + "loaded": tags, + } + + +def dump(path: str) -> None: + out: dict[str, Any] = {} + sync = SyncPipelineOrchestrator + db, eph = InMemoryArrowDatabase(), InMemoryArrowDatabase() + build(db, [1, 2, 3], None).run(orchestrator=sync()) + out["persistent"] = reads(build(db, [1, 2, 3], None)) + build(db, [1, 2, 3, 4, 5], eph).run(orchestrator=sync()) + out["mixed"] = reads(build(db, [1, 2, 3, 4, 5], eph)) + out["ephemeral miss"] = reads(build(db, [1, 2, 3, 4, 5], InMemoryArrowDatabase())) + with open(path, "wb") as file: + pickle.dump(out, file) + for scenario, values in out.items(): + flags = next(f[4] for f in values["fetched"][0] if f[0] == "__is_ephemeral") + print( + f"{scenario}: fetched rows={len(flags)} ephemeral={flags.count('True')} " + + f"ephemeral misses={len(values['ephemeral miss rows'])} loaded={len(values['loaded'])} " + + f"loaded reads raising={sum('RAISES' in repr(t) for t in values['loaded'])}" + ) + + +def same(a: Any, b: Any) -> bool: + if isinstance(a, pa.Table): + return isinstance(b, pa.Table) and bool(a.equals(b, check_metadata=True)) + if isinstance(a, (list, tuple)): + return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) + if isinstance(a, dict): + return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a) + return a == b + + +def compare(first: str, second: str) -> None: + with open(first, "rb") as file: + a = pickle.load(file) # noqa: S301 + with open(second, "rb") as file: + b = pickle.load(file) # noqa: S301 + for scenario in a: + for key in a[scenario]: + verdict = "same" if same(a[scenario][key], b[scenario][key]) else "DIFFER" + print(f"{scenario:15} {key:25} {verdict}") + + +if __name__ == "__main__": + if sys.argv[1] == "--compare": + compare(sys.argv[2], sys.argv[3]) + else: + dump(sys.argv[1]) diff --git a/docs/dev/scripts/itl_1295/measure_loaded_job.py b/docs/dev/scripts/itl_1295/measure_loaded_job.py new file mode 100644 index 000000000..8e2440524 --- /dev/null +++ b/docs/dev/scripts/itl_1295/measure_loaded_job.py @@ -0,0 +1,52 @@ +"""ITL-1295: a saved and loaded job reads its function node's stored results. + +usage: uv run python docs/dev/scripts/itl_1295/measure_loaded_job.py + +Runs node ``one`` of ``measure_read_path.py`` over an in-memory database, saves the job, +loads it over the same database and reads ``one``'s stored view (``as_source``) and +``get_all_records()``; ``k`` is compared with the input exactly. +""" + +from __future__ import annotations + +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measure_read_path as m # noqa: E402 # pyright: ignore[reportImplicitRelativeImport] # a sibling script + +from orcapod import PipelineJob # noqa: E402 +from orcapod.databases import InMemoryArrowDatabase # noqa: E402 +from orcapod.pipeline import SyncPipelineOrchestrator # noqa: E402 + +for name in ( + "int64 (control)", + "date64 off midnight", + "decimal256(76,40)", + "large_list", +): + values = m.CASES[name] + db = InMemoryArrowDatabase() + job = m.build(values, db) + job.run(orchestrator=SyncPipelineOrchestrator()) + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "job.json" + job.save(path) + loaded = PipelineJob.load(path, database=db) + out = [] + for read, action in ( + ( + "as_source", + lambda: loaded.nodes["one"].as_source().as_table().column("k"), + ), + ( + "get_all_records", + lambda: loaded.nodes["one"].get_all_records().column("k"), + ), + ): + try: + out.append(f"{read}: {m.verdict(m.exact(action()), m.exact(values))}") + except BaseException as error: # noqa: BLE001 + out.append(f"{read}: {type(error).__name__}: {str(error)[:60]}") + print(f"{name:22} " + " | ".join(out)) diff --git a/docs/dev/scripts/itl_1295/measure_outputs_and_downstream.py b/docs/dev/scripts/itl_1295/measure_outputs_and_downstream.py new file mode 100644 index 000000000..793dd9ee9 --- /dev/null +++ b/docs/dev/scripts/itl_1295/measure_outputs_and_downstream.py @@ -0,0 +1,176 @@ +"""ITL-1295: function OUTPUT values, and what a changed tag does downstream after a reuse. + +usage: uv run python docs/dev/scripts/itl_1295/measure_outputs_and_downstream.py + +Part 1, outputs: functions returning values of the types a Python annotation gives (the +type converter decides the Arrow type); each node is run, then read again by a NEW job +over the same in-memory database (a reuse run). The output column is compared with what +the function returned, exactly (floats as bits). + +Part 2, downstream: node ``one`` (``inc``) over a source tagged ``k: date64`` off +midnight, then ``Join`` of ``one`` with another source keyed on the same ``k`` values, +and a ``GroupBy("k")``. The rows of the join and of the grouping are counted on the +first run and on a reuse run of a new job object. +""" + +from __future__ import annotations + +import datetime +import struct +import uuid +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import SyncPipelineOrchestrator + +SNAN64 = struct.unpack(" float: + return SNAN64 if x == 10 else NEG_ZERO + + +@function_pod(output_keys="y") +def as_path(x: int) -> Path: + return Path(f"/data/{x}") + + +@function_pod(output_keys="y") +def as_uuid(x: int) -> uuid.UUID: + return uuid.UUID(int=x) + + +@function_pod(output_keys="y") +def as_date(x: int) -> datetime.date: + return datetime.date(2020, 1, x // 10) + + +@function_pod(output_keys="y") +def as_datetime(x: int) -> datetime.datetime: + return datetime.datetime(2020, 1, 1, 0, 0, 0, x, tzinfo=datetime.timezone.utc) + + +@function_pod(output_keys="y") +def as_float_list(x: int) -> list[float]: + return [SNAN64, NEG_ZERO, float(x)] + + +@function_pod(output_keys="y") +def as_int(x: int) -> int: + return x + 1 + + +@function_pod(output_keys="y") +def inc(x: int) -> int: + return x + 1 + + +def exact(array: Any) -> list[Any]: + if isinstance(array, pa.ChunkedArray): + array = array.combine_chunks() + if isinstance(array, pa.ExtensionArray): + return exact(array.storage) + t = array.type + if pa.types.is_large_list(t) or pa.types.is_list(t): + values = exact(array.values) + offsets = array.offsets.to_pylist() + return [values[offsets[i] : offsets[i + 1]] for i in range(len(array))] + if pa.types.is_floating(t): + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[t.bit_width] + return [hex(b) for b in array.view(unsigned).to_pylist()] + if pa.types.is_temporal(t): + return array.view(pa.int32() if t.bit_width == 32 else pa.int64()).to_pylist() + if pa.types.is_decimal(t): + return [str(x) for x in array.to_pylist()] + return array.to_pylist() + + +def int_source(name: str = "s") -> ArrowTableSource: + arrays = [pa.array([1, 2], pa.int64()), pa.array([10, 20], pa.int64())] + schema = pa.schema( + pa.field(n, a.type, nullable=False) for n, a in zip("kx", arrays) + ) + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=schema), + tag_columns=["k"], + tag_only_columns=True, + source_id=name, + ) + + +def outputs() -> None: + print("== Part 1: function outputs (in-memory database)") + for name, pod in ( + ("as_int", as_int), + ("as_float", as_float), + ("as_path", as_path), + ("as_uuid", as_uuid), + ("as_date", as_date), + ("as_datetime", as_datetime), + ("as_float_list", as_float_list), + ): + db = InMemoryArrowDatabase() + reads: dict[str, Any] = {} + for attempt in ("run", "reuse"): + job = PipelineJob(name="itl1295out", database=db) + with job: + pod.pod(int_source(), label="node") + try: + job.run(orchestrator=SyncPipelineOrchestrator()) + column = job.nodes["node"].as_table().column("y") + reads[attempt] = (str(column.type), exact(column)) + except BaseException as error: # noqa: BLE001 + reads[attempt] = f"RAISES {type(error).__name__}: {str(error)[:80]}" + memory = pod.pod(int_source()).as_table().column("y") + reads["in_memory"] = (str(memory.type), exact(memory)) + same = reads["run"] == reads["reuse"] == reads["in_memory"] + print(f" {name:14} {'exact' if same else 'DIFFER'} {reads}") + + +def date_source(name: str, extra: str) -> ArrowTableSource: + arrays = [ + pa.array([1, 86_400_001], pa.int64()).cast(pa.date64()), + pa.array([10, 20], pa.int64()), + ] + schema = pa.schema( + pa.field(n, a.type, nullable=False) for n, a in zip(["k", extra], arrays) + ) + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=schema), + tag_columns=["k"], + tag_only_columns=True, + source_id=name, + ) + + +def downstream() -> None: + print("== Part 2: downstream of a changed tag (in-memory database)") + db = InMemoryArrowDatabase() + for attempt in ("run", "reuse"): + job = PipelineJob(name="itl1295down", database=db) + with job: + one = inc.pod(date_source("s", "x"), label="one") + Join()(one, date_source("other", "w"), label="joined") + # Two rows on two days: two groups; truncated to midnight they stay two. + try: + job.run(orchestrator=SyncPipelineOrchestrator()) + joined = job.nodes["joined"].as_table() + print( + f" {attempt:5} one.k={exact(job.nodes['one'].as_table().column('k'))} " + + f"joined rows={joined.num_rows} joined.k={exact(joined.column('k'))}" + ) + except BaseException as error: # noqa: BLE001 + print(f" {attempt:5} RAISES {type(error).__name__}: {str(error)[:120]}") + + +if __name__ == "__main__": + outputs() + downstream() diff --git a/docs/dev/scripts/itl_1295/measure_read_path.py b/docs/dev/scripts/itl_1295/measure_read_path.py new file mode 100644 index 000000000..0ced9b75f --- /dev/null +++ b/docs/dev/scripts/itl_1295/measure_read_path.py @@ -0,0 +1,280 @@ +"""ITL-1295: does a function node present (and store) the values that went in? + +usage: uv run python docs/dev/scripts/itl_1295/measure_read_path.py [memory|delta] [name] + +For each Arrow type T, a source with tags ``k`` (T) and ``n`` (int64) and data ``x`` +(int64); ``inc(x) -> y`` (node ``one``), ``dbl(y) -> z`` over it (node ``two``). Then: + +* ``run``: a job run (sync orchestrator); ``k`` as node ``one`` and ``two`` present it + (``as_table``) and as ``iter_data`` tags hold it; +* ``stored``: ``k`` in every stored table of the database that has a ``k`` column, read + directly; +* ``as_source``: ``node.as_source().as_table()``; +* ``reuse``: a NEW job object over the same database, same graph, run again: the run + summary's computed / reused counts, and ``k`` as presented; +* ``load_only``: another new job, ``run(load_only=True)``; +* ``in_memory``: the same graph without a job (``FunctionPodStream``), no database; +* ``head_sorted``: ``as_table(sort_by_tags=True)`` of the source (``sort_by_tag_columns`` + falls back to Polars for types Arrow cannot sort). + +Each value is compared with the input exactly (temporal values as integers, floats as +bits, decimals as text, logical types through storage, lists and structs recursively). +A Polars panic is a ``BaseException`` and is reported. +""" + +from __future__ import annotations + +import decimal +import sys +import tempfile +import uuid +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 DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline import SyncPipelineOrchestrator + +CTX = get_default_context() +D = decimal.Decimal + + +@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 exact(array: Any) -> list[Any]: + if isinstance(array, pa.ChunkedArray): + array = array.combine_chunks() + if isinstance(array, pa.ExtensionArray): + return exact(array.storage) + if isinstance(array, pa.DictionaryArray): + return exact(array.dictionary_decode()) + t = array.type + if pa.types.is_large_list(t) or pa.types.is_list(t): + values = exact(array.values) + offsets = array.offsets.to_pylist() + return [ + values[offsets[i] : offsets[i + 1]] if array[i].is_valid else None + for i in range(len(array)) + ] + if pa.types.is_struct(t): + fields = [exact(array.field(i)) for i in range(t.num_fields)] + return [ + tuple(f[j] for f in fields) if array[j].is_valid else None + for j in range(len(array)) + ] + if pa.types.is_floating(t): + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[t.bit_width] + return [None if b is None else hex(b) for b in array.view(unsigned).to_pylist()] + if pa.types.is_temporal(t) and not pa.types.is_interval(t): + return array.view(pa.int32() if t.bit_width == 32 else pa.int64()).to_pylist() + if pa.types.is_decimal(t): + return [None if x is None else str(x) for x in array.to_pylist()] + return array.to_pylist() + + +def ints(values: list[int], arrow_type: pa.DataType) -> Any: + return pa.array(values, pa.int64()).cast(arrow_type) + + +def floats(bits: list[int], width: int) -> Any: + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + floating = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()}[width] + return pa.array(bits, unsigned).view(floating) + + +def logical(python_type: type, storage: list[Any]) -> Any: + t = cast( + pa.BaseExtensionType, CTX.type_converter.python_type_to_arrow_type(python_type) + ) + return pa.ExtensionArray.from_storage(t, pa.array(storage, t.storage_type)) + + +def one_list_each(values: Any) -> Any: + return pa.LargeListArray.from_arrays( + pa.array(range(len(values) + 1), pa.int64()), values + ) + + +DEC = pa.decimal256(76, 40) +DATES = ints([1, 86_400_001], pa.date64()) +DECS = pa.array([D("1." + "0" * 39 + "1"), D("-3")], DEC) + +CASES: dict[str, Any] = { + "int64 (control)": pa.array([1, 2], pa.int64()), + "date64 off midnight": DATES, + "decimal256(76,40)": DECS, + "large_list": one_list_each(DATES), + "large_list": one_list_each(DECS), + "struct": pa.StructArray.from_arrays([DATES], names=["a"]), + "struct": pa.StructArray.from_arrays([DECS], names=["a"]), + "time64[ns]": ints([1, 1001], pa.time64("ns")), + "timestamp[ns, UTC]": ints([1, 1001], pa.timestamp("ns", "UTC")), + "float32 sNaN": floats([0x7F800001, 0x3F800000], 32), + "float16 -0.0": floats([0x8000, 0x3C00], 16), + "float64 payload NaN": floats([0x7FF8000000000001, 0x8000000000000000], 64), + "logical Path": logical(Path, ["a", "b"]), + "logical UUID": logical( + uuid.UUID, [uuid.UUID(int=1).bytes, uuid.UUID(int=2).bytes] + ), +} + + +def source(values: Any) -> ArrowTableSource: + arrays = [values, pa.array([1, 2], pa.int64()), pa.array([10, 20], pa.int64())] + schema = pa.schema( + pa.field(name, a.type, nullable=False) for name, a in zip("knx", arrays) + ) + table = pa.Table.from_arrays(arrays, schema=schema) + return ArrowTableSource( + table, tag_columns=["k", "n"], tag_only_columns=True, source_id="s" + ) + + +def build(values: Any, db: Any) -> PipelineJob: + job = PipelineJob(name="itl1295", database=db) + with job: + one = inc.pod(source(values), label="one") + dbl.pod(one, label="two") + return job + + +def verdict(got: Any, want: list[Any]) -> str: + return ( + "exact" + if sorted(map(repr, got)) == sorted(map(repr, want)) + else f"CHANGED {got}" + ) + + +def attempt(label: str, action: Any, want: list[Any]) -> str: + try: + return verdict(action(), want) + except BaseException as error: # noqa: BLE001 # a Polars panic is a BaseException + kind = "PANIC" if "Panic" in type(error).__name__ else "RAISES" + return f"{kind} {type(error).__name__}: {str(error)[:80]}" + + +def node_k(job: PipelineJob, label: str) -> list[Any]: + return exact(job.nodes[label].as_table().column("k")) + + +def iter_k(job: PipelineJob, label: str) -> list[Any]: + out: list[Any] = [] + for tag, _ in job.nodes[label].iter_data(): + out.extend(exact(tag.as_table().column("k"))) + return out + + +def stored_k(db: Any) -> list[str]: + lines = [] + for path in db.list_table_paths(): + table = db.get_all_records(path) + if table is not None and "k" in table.column_names: + lines.append(f"{'/'.join(path)[-40:]}: {exact(table.column('k'))}") + return lines + + +def measure(name: str, values: Any, kind: str) -> None: + want = exact(values) + results: dict[str, str] = {} + with tempfile.TemporaryDirectory() as tmp: + db = ( + InMemoryArrowDatabase() + if kind == "memory" + else DeltaTableDatabase(Path(tmp) / "db") + ) + job = build(values, db) + try: + job.run(orchestrator=SyncPipelineOrchestrator()) + results["run"] = "ok" + except BaseException as error: # noqa: BLE001 + results["run"] = f"RAISES {type(error).__name__}: {str(error)[:100]}" + for label in ("one", "two"): + results[f"run {label} as_table"] = attempt( + label, lambda: node_k(job, label), want + ) + results[f"run {label} iter_data"] = attempt( + label, lambda: iter_k(job, label), want + ) + results[f"run {label} as_source"] = attempt( + label, + lambda: exact(job.nodes[label].as_source().as_table().column("k")), + want, + ) + try: + for line in stored_k(db): + stored_values = line.split(": ", 1)[1] + results[f"stored {line.split(':')[0]}"] = ( + "exact" + if stored_values == repr(want) + or sorted(eval(stored_values), key=repr) == sorted(want, key=repr) + else f"CHANGED {stored_values}" # noqa: S307 + ) + except BaseException as error: # noqa: BLE001 + results["stored"] = f"RAISES {type(error).__name__}: {str(error)[:80]}" + reuse = build(values, db) + try: + summary = reuse.run(orchestrator=SyncPipelineOrchestrator()) + results["reuse counts"] = ", ".join( + f"{label}: computed {summary.nodes[label].computed} reused {summary.nodes[label].reused}" + for label in ("one", "two") + ) + except BaseException as error: # noqa: BLE001 + results["reuse counts"] = ( + f"RAISES {type(error).__name__}: {str(error)[:100]}" + ) + for label in ("one", "two"): + results[f"reuse {label} as_table"] = attempt( + label, lambda: node_k(reuse, label), want + ) + loaded = build(values, db) + try: + loaded.run(orchestrator=SyncPipelineOrchestrator(), load_only=True) + results["load_only one as_table"] = attempt( + "one", lambda: node_k(loaded, "one"), want + ) + except BaseException as error: # noqa: BLE001 + results["load_only"] = f"RAISES {type(error).__name__}: {str(error)[:100]}" + stream = dbl.pod(inc.pod(source(values))) + results["in_memory as_table"] = attempt( + "mem", lambda: exact(stream.as_table().column("k")), want + ) + results["head_sorted source"] = attempt( + "sorted", + lambda: exact( + source(values).as_table(columns={"sort_by_tags": True}).column("k") + ), + want, + ) + print(f"== {name} [{kind}]") + for key, value in results.items(): + if value not in ("exact", "ok"): + print(f" {key:28} {value}") + print( + f" ({sum(v in ('exact', 'ok') for v in results.values())} of {len(results)} exact/ok)" + ) + + +def main() -> None: + args = sys.argv[1:] + kind = args[0] if args else "memory" + only = args[1] if len(args) > 1 else None + for name, values in CASES.items(): + if only is None or only in name: + measure(name, values, kind) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1295/measure_reuse_rows.py b/docs/dev/scripts/itl_1295/measure_reuse_rows.py new file mode 100644 index 000000000..557a951ca --- /dev/null +++ b/docs/dev/scripts/itl_1295/measure_reuse_rows.py @@ -0,0 +1,41 @@ +"""ITL-1295: how many pipeline rows each node stores after runs and reuse runs. + +usage: uv run python docs/dev/scripts/itl_1295/measure_reuse_rows.py + +``one`` (``inc``) and ``two`` (``dbl``) over a source of 2 rows tagged ``k`` (int64 +control, ``date64`` off midnight). Three jobs over one in-memory database run the same +graph. After each, the stored pipeline rows of each node (count and ``k``) and the run +summary's computed / reused counts are printed. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measure_read_path as m # noqa: E402 # pyright: ignore[reportImplicitRelativeImport] # a sibling script + +from orcapod.databases import InMemoryArrowDatabase # noqa: E402 +from orcapod.pipeline import SyncPipelineOrchestrator # noqa: E402 + +for name in ("int64 (control)", "date64 off midnight"): + db = InMemoryArrowDatabase() + print(name) + for attempt in range(3): + job = m.build(m.CASES[name], db) + summary = job.run(orchestrator=SyncPipelineOrchestrator()) + line = [] + for pod, label in (("inc", "one"), ("dbl", "two")): + [table] = [ + db.get_all_records(p) + for p in db.list_table_paths() + if p[1] == pod and p[-1] == "pdb_v1" + ] + assert table is not None + node = summary.nodes[label] + line.append( + f"{label}: computed {node.computed} reused {node.reused}, " + + f"stored {table.num_rows} rows k={m.exact(table.column('k'))}" + ) + print(f" job {attempt + 1}: " + " | ".join(line)) diff --git a/docs/dev/scripts/itl_1295/measure_stored_downstream.py b/docs/dev/scripts/itl_1295/measure_stored_downstream.py new file mode 100644 index 000000000..b2e5ccf34 --- /dev/null +++ b/docs/dev/scripts/itl_1295/measure_stored_downstream.py @@ -0,0 +1,86 @@ +"""ITL-1295: does a changed tag get STORED by a node that computes after a reuse? + +usage: uv run python docs/dev/scripts/itl_1295/measure_stored_downstream.py + +Job 1 runs only node ``one`` over a source tagged ``k: date64`` off midnight. Job 2, a new +job over the same in-memory database, runs ``one`` (reused) and a NEW node ``two`` +(``dbl``) over it, which computes. ``k`` in ``two``'s stored pipeline table (read from +the database directly) and as ``two`` presents it in that run are compared with the input. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measure_read_path as m # noqa: E402 # pyright: ignore[reportImplicitRelativeImport] # a sibling script + +from orcapod import PipelineJob # noqa: E402 +from orcapod.databases import InMemoryArrowDatabase # noqa: E402 +from orcapod.pipeline import SyncPipelineOrchestrator # noqa: E402 + +for name in ("int64 (control)", "date64 off midnight", "struct"): + values = m.CASES[name] + want = m.exact(values) + db = InMemoryArrowDatabase() + first = PipelineJob(name="itl1295", database=db) + with first: + m.inc.pod(m.source(values), label="one") + first.run(orchestrator=SyncPipelineOrchestrator()) + second = PipelineJob(name="itl1295", database=db) + with second: + one = m.inc.pod(m.source(values), label="one") + m.dbl.pod(one, label="two") + summary = second.run(orchestrator=SyncPipelineOrchestrator()) + counts = { + lbl: (summary.nodes[lbl].computed, summary.nodes[lbl].reused) + for lbl in ("one", "two") + } + stored = [ + m.exact(table.column("k")) + for p in db.list_table_paths() + if p[1] == "dbl" + and p[-1] == "pdb_v1" + and (table := db.get_all_records(p)) is not None + ] + presented = m.exact(second.nodes["two"].as_table().column("k")) + print( + f"{name:22} (computed, reused)={counts} two stored k={stored} " + + f"two presented k={presented} input={want}" + ) + + +def stored_two(db: InMemoryArrowDatabase) -> dict[str, list[str]]: + [table] = [ + db.get_all_records(p) + for p in db.list_table_paths() + if p[1] == "dbl" and p[-1] == "pdb_v1" + ] + assert table is not None + return { + c: sorted(map(repr, m.exact(table.column(c)))) + for c in table.column_names + if c != "__pod_ts" and "timestamp" not in c + } + + +print("Entries of 'two' stored after a reuse of 'one' vs. in one fresh job (date64):") +values = m.CASES["date64 off midnight"] +db_a = InMemoryArrowDatabase() +first = PipelineJob(name="itl1295", database=db_a) +with first: + m.inc.pod(m.source(values), label="one") +first.run(orchestrator=SyncPipelineOrchestrator()) +second = PipelineJob(name="itl1295", database=db_a) +with second: + m.dbl.pod(m.inc.pod(m.source(values), label="one"), label="two") +second.run(orchestrator=SyncPipelineOrchestrator()) +db_b = InMemoryArrowDatabase() +fresh = PipelineJob(name="itl1295", database=db_b) +with fresh: + m.dbl.pod(m.inc.pod(m.source(values), label="one"), label="two") +fresh.run(orchestrator=SyncPipelineOrchestrator()) +a, b = stored_two(db_a), stored_two(db_b) +for column in a: + print(f" {column[:60]:60} {'same' if a[column] == b.get(column) else 'DIFFER'}") diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index d48aa1a1f..b3cbf0627 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -1239,6 +1239,100 @@ class _JoinedRecords(NamedTuple): data_tags: tuple[str, ...] +# ``_fetch_joined_records`` decides which stored rows belong together with Polars, +# and takes every column of its result from the stored Arrow tables (ITL-1295): +# Polars changed some types on the way through (a ``date64`` value came back at +# midnight) and panicked on others (``decimal256``). Polars sees only the +# bookkeeping columns below and a row number per table; the row-number columns are +# meta-prefixed, so no stored column has their names. +_TAGINFO_ROW = "__fetch_taginfo_row" +_RESULT_ROW = "__fetch_result_row" +_EPHEMERAL_RESULT_ROW = "__fetch_ephemeral_result_row" + +# The pipeline-table columns the fetch filters, joins and reads entries by. +_TAGINFO_MATCH_COLUMNS = ( + constants.NODE_CONTENT_HASH_COL, + constants.IS_EPHEMERAL_COL, + constants.DATA_RECORD_ID, + _PIPELINE_BASE_ENTRY_ID_COL, + _PIPELINE_RECOMPUTATION_INDEX_COL, +) + + +def _row_frame(table: "pa.Table", columns: Sequence[str], row: str) -> "pl.DataFrame": + """Return a Polars frame of some of a table's columns and its row numbers. + + Args: + table: A stored table. + columns: The columns to include; those the table lacks are left out. + row: The name of the row-number column (``int64``). + + Returns: + The frame: the present ``columns``, in their order, then ``row``. + """ + names = [name for name in columns if name in table.column_names] + arrays = [table.column(name) for name in names] + arrays.append(pa.chunked_array([pa.array(range(table.num_rows), pa.int64())])) + return cast( + "pl.DataFrame", pl.from_arrow(pa.Table.from_arrays(arrays, names=[*names, row])) + ) + + +def _joined_from_stored( + matched: "pl.DataFrame", + taginfo: "pa.Table", + parts: Sequence[tuple[str, "pa.Table"]], +) -> "pa.Table": + """Build the joined records from the stored tables, by the rows Polars matched. + + The layout is the one Polars' join and diagonal concatenation gave: every + pipeline-table column, then each result column other than the record id (a name + the pipeline table also has takes the suffix ``_right``), in order of first + appearance across ``parts``; a column a part lacks is null in that part's rows. + + Args: + matched: The matched rows, in output order: a ``_TAGINFO_ROW`` column and, + per part, its row-number column (null in the other parts' rows). The + rows of each part are contiguous, in the order of ``parts``. + taginfo: The stored pipeline table. + parts: Per result table, in concatenation order: its row-number column in + ``matched`` and the table. + + Returns: + The joined table, every value taken from the stored tables. + """ + taginfo_rows = matched.get_column(_TAGINFO_ROW).to_arrow() + names = list(taginfo.column_names) + columns: list[Any] = [taginfo.column(name).take(taginfo_rows) for name in names] + # Output name -> stored column name, per part. + result_names: dict[str, str] = {} + for _, results in parts: + for name in results.column_names: + if name == constants.DATA_RECORD_ID: + continue + out = f"{name}_right" if name in taginfo.column_names else name + result_names.setdefault(out, name) + part_rows = [] + for row_column, _ in parts: + rows = matched.get_column(row_column) + part_rows.append(rows.drop_nulls().to_arrow()) + for out, name in result_names.items(): + chunks: list[Any] = [] + arrow_type = next( + results.schema.field(name).type + for _, results in parts + if name in results.column_names + ) + for (_, results), rows in zip(parts, part_rows): + if name in results.column_names: + chunks.extend(results.column(name).take(rows).chunks) + else: + chunks.append(pa.nulls(len(rows), arrow_type)) + names.append(out) + columns.append(pa.chunked_array(chunks, type=arrow_type)) + return pa.Table.from_arrays(columns, names=names) + + class FunctionJobNode(RunHoldingNode, FunctionNodeBase): """DB-backed execution node for function pod invocations. @@ -3273,7 +3367,8 @@ def _fetch_joined_records( data_tags = self._stored_data_tags(taginfo_schema) is_ephemeral_col = constants.IS_EPHEMERAL_COL - taginfo_df = pl.DataFrame(taginfo) + # Polars sees only the bookkeeping columns and row numbers (ITL-1295). + taginfo_df = _row_frame(taginfo, _TAGINFO_MATCH_COLUMNS, _TAGINFO_ROW) # Per-node isolation: when sharing a pipeline table in pipeline_hash scope, # filter to rows written by this node to prevent cross-node contamination. @@ -3299,6 +3394,8 @@ def _fetch_joined_records( # Persistent join # ------------------------------------------------------------------ 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( @@ -3323,7 +3420,7 @@ def _fetch_joined_records( else: results_schema = results.schema full_persistent_df = persistent_taginfo_df.join( - pl.DataFrame(results), + _row_frame(results, (constants.DATA_RECORD_ID,), _RESULT_ROW), on=constants.DATA_RECORD_ID, how="inner", ) @@ -3346,7 +3443,7 @@ def _fetch_joined_records( empty_taginfo_rows: dict[bytes, dict] = {} if ephemeral_taginfo_df.height > 0: - eph_results = None + eph_frame: pl.DataFrame | None = None if self._ephemeral_cached_pod is not None: eph_results = ( self._ephemeral_cached_pod.result_database.get_all_records( @@ -3360,24 +3457,29 @@ def _fetch_joined_records( ) if results_schema is None: results_schema = eph_results.schema + eph_frame = _row_frame( + eph_results, (constants.DATA_RECORD_ID,), _EPHEMERAL_RESULT_ROW + ) ephemeral_df = ephemeral_taginfo_df.join( - pl.DataFrame(eph_results), + eph_frame, on=constants.DATA_RECORD_ID, how="inner", ) # Emit EmptyData tokens for unmatched ephemeral rows # (cross-session miss: ephemeral data is gone). - if eph_results is not None: + if eph_frame is not None: unmatched_df = ephemeral_taginfo_df.join( - pl.DataFrame(eph_results), - on=constants.DATA_RECORD_ID, - how="anti", + eph_frame, on=constants.DATA_RECORD_ID, how="anti" ) else: # No ephemeral database or empty database — all ephemeral rows are misses. unmatched_df = ephemeral_taginfo_df - for row in unmatched_df.iter_rows(named=True): + # The rows themselves are read from the pipeline table, not from Polars. + unmatched_rows = taginfo.take( + unmatched_df.get_column(_TAGINFO_ROW).to_arrow() + ).to_pylist() + for row in unmatched_rows: base_eid = row[_PIPELINE_BASE_ENTRY_ID_COL] previous = empty_taginfo_rows.get(base_eid) if ( @@ -3438,10 +3540,17 @@ def _fetch_joined_records( pl.col(_PIPELINE_BASE_ENTRY_ID_COL).is_in(base_entry_ids) ) - joined = merged_df.to_arrow() - # Polars drops field metadata and nullable flags: restore them from the - # pipeline table in every case (its data-tag marker included), and from - # the result table when one was read. + # Every column comes from the stored tables, by the rows Polars matched; the + # ephemeral rows come first, as concatenated above. + parts: list[tuple[str, pa.Table]] = [] + if ephemeral_df.height > 0: + parts.append((_EPHEMERAL_RESULT_ROW, cast("pa.Table", eph_results))) + if persistent_df.height > 0: + parts.append((_RESULT_ROW, cast("pa.Table", results))) + joined = _joined_from_stored(merged_df, taginfo, parts) + # The table is built from arrays, with no field flags: restore them from the + # pipeline table in every case (its data-tag marker included), and from the + # result table when one was read. joined = arrow_utils.restore_schema_nullability( joined, *( diff --git a/tests/test_pipeline/test_function_node_stored_values.py b/tests/test_pipeline/test_function_node_stored_values.py new file mode 100644 index 000000000..8450cc118 --- /dev/null +++ b/tests/test_pipeline/test_function_node_stored_values.py @@ -0,0 +1,385 @@ +"""A function node's stored results read back exactly as they went in (ITL-1295). + +Every read of stored results joined the pipeline table and the result table in Polars, +carrying every column through it and back: a ``date64`` tag came back at midnight (also +in a list or a struct), and a ``decimal256`` tag made Polars panic, so a second run over +the same database crashed. The reads are ``node.as_source()``, a run of a new job over +the same database (results reused), ``run(load_only=True)`` and a saved and loaded job. +Downstream, a join of a reused node found nothing, a node added over a reused node +stored the changed tag, and every reuse added pipeline entries under the changed tag. + +Now Polars sees only the bookkeeping columns and row numbers, and every column is taken +from the stored tables. The graph here is a source with two tags, ``k`` (the type under +test) and ``n``, -> ``split`` (two outputs) -> ``double``; each read is compared with +the input bit for bit (temporal values as integers, floats as bits, decimals as text, +logical types through their storage, lists and structs element by element), on the +sync and the async orchestrator, over an in-memory database and over Delta Lake for the +types Delta can store. +""" + +from __future__ import annotations + +import decimal +import uuid +from collections.abc import Callable +from pathlib import Path +from typing import Any, TypeAlias, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + +Column: TypeAlias = "pa.Array[Any]" +D = decimal.Decimal +CONTEXT = get_default_context() + + +@function_pod(output_keys=("y", "w")) +def split(x: int) -> tuple[int, str]: + """Return ``x + 1`` and a text naming ``x``.""" + return x + 1, f"w{x}" + + +@function_pod(output_keys="z") +def double(y: int) -> int: + """Return ``2 * y``.""" + return 2 * y + + +# ── exact values ───────────────────────────────────────────────────────────── + + +def _exact(array: "Column | pa.ChunkedArray[Any]") -> list[Any]: + """Return a column's values exactly, as plain Python values.""" + if isinstance(array, pa.ChunkedArray): + array = array.combine_chunks() + if isinstance(array, pa.ExtensionArray): + return _exact(array.storage) + arrow_type = array.type + if pa.types.is_large_list(arrow_type) or pa.types.is_list(arrow_type): + lists = cast("pa.LargeListArray[Any]", array) + values = _exact(lists.values) + offsets = cast(list[int], lists.offsets.to_pylist()) + return [values[offsets[i] : offsets[i + 1]] for i in range(len(lists))] + if pa.types.is_struct(arrow_type): + struct = cast("pa.StructArray", array) + fields = [_exact(struct.field(i)) for i in range(arrow_type.num_fields)] + return [tuple(f[j] for f in fields) for j in range(len(struct))] + if pa.types.is_floating(arrow_type): + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + return array.view(unsigned[arrow_type.bit_width]).to_pylist() + if pa.types.is_temporal(arrow_type): + width = cast(int, arrow_type.bit_width) + return array.view(pa.int32() if width == 32 else pa.int64()).to_pylist() + if pa.types.is_decimal(arrow_type): + return [str(value) for value in array.to_pylist()] + return array.to_pylist() + + +def _ints(values: list[int], arrow_type: pa.DataType) -> Column: + return pa.array(values, pa.int64()).cast(arrow_type) + + +def _floats(bits: list[int], width: int) -> Column: + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + floating = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()}[width] + return pa.array(bits, unsigned).view(floating) + + +def _logical(python_type: type, storage: list[Any]) -> Column: + arrow_type = cast( + pa.BaseExtensionType, + CONTEXT.type_converter.python_type_to_arrow_type(python_type), + ) + return pa.ExtensionArray.from_storage( + arrow_type, pa.array(storage, arrow_type.storage_type) + ) + + +def _lists(values: Column) -> Column: + return pa.LargeListArray.from_arrays( + pa.array(range(len(values) + 1), pa.int64()), values + ) + + +DATES = _ints([1, 86_400_001], pa.date64()) +DECIMALS = pa.array([D("1." + "0" * 39 + "1"), D("-3")], pa.decimal256(76, 40)) + +AFFECTED: dict[str, Column] = { + "date64 off midnight": DATES, + "decimal256(76,40)": DECIMALS, + "large_list": _lists(DATES), + "large_list": _lists(DECIMALS), + "struct": pa.StructArray.from_arrays( + [DATES, DECIMALS], names=["a", "b"] + ), + "struct": pa.StructArray.from_arrays([DATES], names=["a"]), +} +EXACT_ON_MAIN: dict[str, Column] = { + "time64[ns]": _ints([1, 1001], pa.time64("ns")), + "float32 signaling NaN": _floats([0x7F800001, 0x3F800000], 32), + "float16 -0.0": _floats([0x8000, 0x3C00], 16), + "uint64 max": pa.array([2**64 - 1, 0], pa.uint64()), + "fixed_size_binary(3)": pa.array([b"abc", b"\x00\x00\x00"], pa.binary(3)), + "timestamp[ns, America/New_York]": _ints( + [1, 1001], pa.timestamp("ns", "America/New_York") + ), + "duration[ns]": _ints([1, 1001], pa.duration("ns")), + "decimal128(38,10)": pa.array([D("1.0000000001"), D("-2")], pa.decimal128(38, 10)), + "logical Path": _logical(Path, ["a", "é"]), + "logical UUID": _logical(uuid.UUID, [uuid.UUID(int=n).bytes for n in (1, 2)]), +} +TYPES = {**AFFECTED, **EXACT_ON_MAIN} +# Delta Lake has no decimal256 and no float16 ("Invalid data type for Delta Lake"). +NOT_IN_DELTA = { + "decimal256(76,40)", + "large_list", + "struct", + "float16 -0.0", +} + +ORCHESTRATORS: dict[str, Callable[[], Any]] = { + "sync": SyncPipelineOrchestrator, + "async": AsyncPipelineOrchestrator, +} + + +# Delta Lake stores fixed_size_binary as large_binary: a reused node's tag comes back +# with another type, so a node over it records new entries (also on main; not this +# read path). +DELTA_CHANGES_TYPE = pytest.mark.xfail( + strict=True, + reason="Delta Lake stores fixed_size_binary as large_binary, so the downstream node's " + + "entries repeat on a reuse run; a type the database does not keep (reported " + + "with ITL-1295, not the Polars read)", +) + + +def _cases() -> list[Any]: + params = [] + for name in TYPES: + for database in ("memory", "delta"): + marks = [] + if database == "delta" and name in NOT_IN_DELTA: + marks = [pytest.mark.skip(reason="Delta Lake cannot store this type")] + elif database == "delta" and name == "fixed_size_binary(3)": + marks = [DELTA_CHANGES_TYPE] + params.append( + pytest.param(name, database, id=f"{name}-{database}", marks=marks) + ) + return params + + +def _database(kind: str, tmp_path: Path) -> Any: + return ( + InMemoryArrowDatabase() + if kind == "memory" + else DeltaTableDatabase(tmp_path / "db") + ) + + +# ── the graph ──────────────────────────────────────────────────────────────── + + +def _source(values: Column, name: str = "s", data: str = "x") -> ArrowTableSource: + """Tags ``k`` (``values``) and ``n``; data ``data``; record ids by position.""" + arrays = [values, pa.array([1, 2], pa.int64()), pa.array([10, 20], pa.int64())] + schema = pa.schema( + pa.field(column, array.type, nullable=False) + for column, array in zip(["k", "n", data], arrays) + ) + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=schema), + tag_columns=["k", "n"], + tag_only_columns=True, + source_id=name, + ) + + +def _job(database: Any, values: Column, *, with_two: bool = True) -> PipelineJob: + job = PipelineJob(name="itl1295", database=database) + with job: + one = split.pod(_source(values), label="one") + if with_two: + double.pod(one, label="two") + return job + + +def _k(stream: Any) -> list[Any]: + """``k`` of a stream's table, and of its rows' tags: both must be one list.""" + table_k = sorted(map(repr, _exact(stream.as_table().column("k")))) + rows_k = sorted( + repr(value) + for tag, _ in stream.iter_data() + for value in _exact(tag.as_table().column("k")) + ) + assert table_k == rows_k + return table_k + + +def _want(values: Column) -> list[Any]: + return sorted(map(repr, _exact(values))) + + +def _stored_rows(database: Any, function: str) -> pa.Table: + """The function's stored pipeline table, read from the database directly.""" + [path] = [ + p + for p in database.list_table_paths() + if p[1] == function and p[-1].startswith("pdb") + ] + return database.get_all_records(path) + + +# ── every read ─────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize(("type_name", "database_kind"), _cases()) +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_every_read_of_stored_results_gives_the_tag_exactly( + type_name: str, database_kind: str, orchestrator: str, tmp_path: Path +) -> None: + values = TYPES[type_name] + want = _want(values) + database = _database(database_kind, tmp_path) + make = ORCHESTRATORS[orchestrator] + + first = _job(database, values) + first.run(orchestrator=make()) + for label in ("one", "two"): + assert _k(first.nodes[label]) == want, f"after a run: {label}" + assert _k(first.nodes[label].as_source()) == want, f"as_source: {label}" + + reuse = _job(database, values) + summary = reuse.run(orchestrator=make()) + for label in ("one", "two"): + assert (summary.nodes[label].computed, summary.nodes[label].reused) == (0, 2) + assert _k(reuse.nodes[label]) == want, f"reuse run: {label}" + + loading = _job(database, values) + loading.run(orchestrator=make(), load_only=True) + for label in ("one", "two"): + assert _k(loading.nodes[label]) == want, f"load_only: {label}" + + saved = tmp_path / "job.json" + reuse.save(saved) + loaded = PipelineJob.load(saved, database=database) + for label in ("one", "two"): + assert _k(loaded.nodes[label].as_source()) == want, f"loaded job: {label}" + records = loaded.nodes[label].get_all_records() + assert sorted(map(repr, _exact(records.column("k")))) == want + + # The outputs are the function's results, on every read. + outputs = reuse.nodes["one"].as_table() + assert sorted(outputs.column("y").to_pylist()) == [11, 21] + assert sorted(outputs.column("w").to_pylist()) == ["w10", "w20"] + assert sorted(reuse.nodes["two"].as_table().column("z").to_pylist()) == [22, 42] + + +# ── downstream consequences ────────────────────────────────────────────────── + +DOWNSTREAM = pytest.mark.parametrize("type_name", list(AFFECTED)) + + +@DOWNSTREAM +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_a_node_added_over_a_reused_node_stores_the_exact_tag( + type_name: str, orchestrator: str +) -> None: + values = TYPES[type_name] + database = InMemoryArrowDatabase() + _job(database, values, with_two=False).run( + orchestrator=ORCHESTRATORS[orchestrator]() + ) + second = _job(database, values) + summary = second.run(orchestrator=ORCHESTRATORS[orchestrator]()) + assert (summary.nodes["one"].computed, summary.nodes["one"].reused) == (0, 2) + assert (summary.nodes["two"].computed, summary.nodes["two"].reused) == (2, 0) + stored = _stored_rows(database, "double") + assert sorted(map(repr, _exact(stored.column("k")))) == _want(values) + assert _k(second.nodes["two"]) == _want(values) + + +@DOWNSTREAM +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_a_reuse_run_adds_no_pipeline_entry(type_name: str, orchestrator: str) -> None: + values = TYPES[type_name] + database = InMemoryArrowDatabase() + _job(database, values).run(orchestrator=ORCHESTRATORS[orchestrator]()) + before = {f: _stored_rows(database, f).num_rows for f in ("split", "double")} + for _ in range(2): + _job(database, values).run(orchestrator=ORCHESTRATORS[orchestrator]()) + after = {f: _stored_rows(database, f).num_rows for f in ("split", "double")} + assert before == after == {"split": 2, "double": 2} + + +@pytest.mark.parametrize( + "type_name", ["date64 off midnight", "struct", "large_list"] +) +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_a_join_of_a_reused_node_finds_the_rows_of_the_first_run( + type_name: str, orchestrator: str +) -> None: + """A join of a node's results with a fresh source on the same tag values: the + same rows on the first run and on a run that reuses the node.""" + values = TYPES[type_name] + database = InMemoryArrowDatabase() + rows = [] + for _ in range(2): + job = PipelineJob(name="itl1295join", database=database) + with job: + one = split.pod(_source(values), label="one") + Join()(one, _source(values, name="other", data="v"), label="joined") + job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + joined = job.nodes["joined"].as_table() + rows.append( + sorted( + zip( + joined.column("n").to_pylist(), + joined.column("y").to_pylist(), + joined.column("v").to_pylist(), + ) + ) + ) + assert rows[0] == rows[1] == [(1, 11, 10), (2, 21, 20)] + + +# ── the sort fallback: part 2, after PR 459 (arrow_keys) ───────────────────── + +SORT_FALLBACK = pytest.mark.xfail( + strict=True, + reason="ITL-1295 part 2: arrow_utils.sort_by_tag_columns falls back to a Polars " + + "sort for list and struct tags, which carries every column through Polars " + + "(a date64 comes back at midnight, a decimal256 panics); it needs the key " + + "preparation of arrow_keys (PR 459).", +) + + +def _no_panic(read: Callable[[], Any]) -> Any: + """Run ``read``; a Polars panic (a ``BaseException``) becomes an assertion error.""" + try: + return read() + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as error: + raise AssertionError(f"{type(error).__name__}: {error}") from None + + +@SORT_FALLBACK +@pytest.mark.parametrize("type_name", ["large_list", "large_list"]) +@pytest.mark.parametrize("read", ["as_table", "view"]) +def test_a_sorted_read_of_a_list_tag_is_exact(type_name: str, read: str) -> None: + """``as_table(columns={"sort_by_tags": True})`` and ``head().sort_by_tags()``.""" + values = TYPES[type_name] + source = _source(values) + if read == "view": + table = _no_panic(lambda: source.head(10).sort_by_tags().as_table()) + else: + table = _no_panic(lambda: source.as_table(columns={"sort_by_tags": True})) + assert sorted(map(repr, _exact(table.column("k")))) == _want(values) From 04d3bdc31155a2527d5562e782113767a19063c8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Thu, 19 Nov 2026 06:58:25 -0800 Subject: [PATCH 2/3] test(itl_1295): compare stored entries row by row, keyed by record id (ITL-1295) Comparing each column sorted on its own would not see two entries swap their tags (CodeRabbit review of PR 460). Co-Authored-By: Claude Opus 5.5 --- .../itl_1295/measure_stored_downstream.py | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/dev/scripts/itl_1295/measure_stored_downstream.py b/docs/dev/scripts/itl_1295/measure_stored_downstream.py index b2e5ccf34..277174a61 100644 --- a/docs/dev/scripts/itl_1295/measure_stored_downstream.py +++ b/docs/dev/scripts/itl_1295/measure_stored_downstream.py @@ -51,18 +51,31 @@ ) -def stored_two(db: InMemoryArrowDatabase) -> dict[str, list[str]]: +# Columns that differ between any two runs: a random data id, the source-info tokens +# naming it, a time stamp. +PER_RUN = ("__data_id", "_source_y", "__pod_ts") + + +def stored_two(db: InMemoryArrowDatabase) -> dict[str, dict[str, str]]: + """Node two's stored entries: per record id (the stable identity of an input row), + every column's exact value; columns that differ between runs are left out.""" [table] = [ db.get_all_records(p) for p in db.list_table_paths() if p[1] == "dbl" and p[-1] == "pdb_v1" ] assert table is not None - return { - c: sorted(map(repr, m.exact(table.column(c)))) + [record_id] = [c for c in table.column_names if c.startswith("_tag_record_id")] + columns = { + c: m.exact(table.column(c)) for c in table.column_names - if c != "__pod_ts" and "timestamp" not in c + if c not in PER_RUN and "timestamp" not in c } + rows: dict[str, dict[str, str]] = {} + for i, key in enumerate(table.column(record_id).to_pylist()): + assert key not in rows, f"two entries for record {key}" + rows[key] = {c: repr(values[i]) for c, values in columns.items()} + return rows print("Entries of 'two' stored after a reuse of 'one' vs. in one fresh job (date64):") @@ -82,5 +95,8 @@ def stored_two(db: InMemoryArrowDatabase) -> dict[str, list[str]]: m.dbl.pod(m.inc.pod(m.source(values), label="one"), label="two") fresh.run(orchestrator=SyncPipelineOrchestrator()) a, b = stored_two(db_a), stored_two(db_b) -for column in a: - print(f" {column[:60]:60} {'same' if a[column] == b.get(column) else 'DIFFER'}") +print(f" records: {sorted(a)} vs {sorted(b)}") +for record in sorted(a): + for column, value in a[record].items(): + verdict = "same" if b.get(record, {}).get(column) == value else "DIFFER" + print(f" {record} {column[:50]:50} {verdict}") From 793494a2b44bec3ea9839d5d37e9c4b41820c4b2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Thu, 19 Nov 2026 07:22:41 -0800 Subject: [PATCH 3/3] test(function_node): name ITL-999 in the Delta fixed_size_binary expected failure (ITL-1295) Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_function_node_stored_values.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/test_pipeline/test_function_node_stored_values.py b/tests/test_pipeline/test_function_node_stored_values.py index 8450cc118..f6342109c 100644 --- a/tests/test_pipeline/test_function_node_stored_values.py +++ b/tests/test_pipeline/test_function_node_stored_values.py @@ -151,13 +151,13 @@ def _lists(values: Column) -> Column: # Delta Lake stores fixed_size_binary as large_binary: a reused node's tag comes back -# with another type, so a node over it records new entries (also on main; not this -# read path). +# with another type, so a node over it records new entries (ITL-999; also on main; not +# this read path). DELTA_CHANGES_TYPE = pytest.mark.xfail( strict=True, - reason="Delta Lake stores fixed_size_binary as large_binary, so the downstream node's " - + "entries repeat on a reuse run; a type the database does not keep (reported " - + "with ITL-1295, not the Polars read)", + reason="ITL-999: Delta Lake stores fixed_size_binary as large_binary, so the " + + "downstream node's entries repeat on a reuse run (a type the database does not " + + "keep, not the Polars read)", )