diff --git a/changelog.d/ITL-1361.md b/changelog.d/ITL-1361.md new file mode 100644 index 000000000..168f03c39 --- /dev/null +++ b/changelog.d/ITL-1361.md @@ -0,0 +1,16 @@ +### Changed + +- **Function and side-effect job nodes work on their input's Arrow table** — on the sync + path, where its input's table is provably its rows' (exactly a table stream, in the + node's data context, with system tags and columns its rows would not retype), a + function job node computes each input row's instance id from slices of that table, + using the same entry and instance preimages and the same input data hash + (`data_table_content_hash`) as the row path; hands the library's row-blind + observers views of its input rows, made only when read (any other observer receives + the rows themselves); gives a stored result the id it was stored under by a shallow + copy; and builds its output with the rows of stored results taken from the stored + table. A side-effect job node hands on its input's table at the rows it passed on, + under the same condition. Any other input takes the row path as before. Every output, + stored row, row id, observer event and error is as before. Third and fourth + stages of the table transport between job nodes + (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1361) diff --git a/docs/dev/scripts/itl_1347/cross_version_entry_ids.py b/docs/dev/scripts/itl_1347/cross_version_entry_ids.py new file mode 100644 index 000000000..f87671a3e --- /dev/null +++ b/docs/dev/scripts/itl_1347/cross_version_entry_ids.py @@ -0,0 +1,255 @@ +"""Cross-version check of a function node's instance ids (ITL-1361). + +Run once per Orcapod version, each with its own environment, over the same inputs: + + PYTHONPATH= /bin/python cross_version_entry_ids.py write + PYTHONPATH= /bin/python cross_version_entry_ids.py load + +(not ``-I``: it ignores ``PYTHONPATH``, which the fixture import needs). + +``write`` runs a function job node over each input and stores its results in a Delta +store; ``load`` runs the same node load-only over the same store. A store written by one +version must be hit, row for row, by the other: same stored instance ids, every row +from the store, no call of the function. The inputs cover the several-items family +(tag order, layout, tag roles), list-valued columns after ``Batch`` and ``GroupBy``, +nested source info, nullable and logical values, and raw streams whose rows type their +system tags or columns otherwise (an ``int32`` system tag, a nullable one, an untyped +``null`` data column), each as a job hands it on and as a raw ``ArrowTableStream``. +Needs the repository root on ``PYTHONPATH`` (for ``tests.test_core.operators.several_items``). +""" + +from __future__ import annotations + +import json +import sys +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import function_pod +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import DeltaTableDatabase +from orcapod.operators import Batch, GroupBy +from orcapod.pipeline.observer import NoOpObserver +from orcapod.sources import DictSource +from tests.test_core.operators.several_items import MAIN, arrangements, make_source + +warnings.simplefilter("ignore") +CALLS: list[Any] = [] +DECLARED: dict[str, Any] = {} + + +@function_pod(output_keys="y") +def flat(d1: int | None) -> int: + CALLS.append(d1) + return -1 if d1 is None else d1 + 1 + + +@function_pod(output_keys="y") +def listed(d1: list[int | None] | None) -> int: + CALLS.append(d1) + return -1 if d1 is None else len(d1) + + +@function_pod(output_keys="y") +def nullable(i: int | None) -> int: + CALLS.append(i) + return -1 if i is None else i + + +@function_pod(output_keys="y") +def untyped(x: Any) -> int: + CALLS.append(x) + return -1 if x is None else x + + +class Cached(NoOpObserver): + def __init__(self) -> None: + self.cached: list[bool] = [] + # Each input (its own tag and data) with the result it received, in order. + self.received: list[list[str]] = [] + + def contextualize(self, *identity_path: str) -> Cached: + return self + + def on_data_end( + self, node_label: str, tag: Any, input_data: Any, output_data: Any, cached: bool + ) -> None: + self.cached.append(bool(cached)) + self.received.append( + [ + repr(tag.as_dict(columns={"system_tags": True})), + repr(input_data.as_dict()), + repr(None if output_data is None else output_data.as_dict()), + ] + ) + + +def forms(stream: Any) -> dict[str, Any]: + rows = list(stream.iter_data()) + handed_on = StaticOutputOperatorPod._materialize_upstream(rows, stream) + raw = ArrowTableStream( + stream.as_table(columns={"system_tags": True, "source": True}), + tag_columns=stream.keys()[0], + data_tags=stream_data_tags(stream), + ) + return {"handed_on": handed_on, "raw": raw} + + +def cases() -> dict[str, tuple[Any, Any]]: + out: dict[str, tuple[Any, Any]] = {} + for arrangement in arrangements(MAIN): + stream = make_source(MAIN, arrangement).select_data_columns(["d1"]) + for name, form in forms(stream).items(): + out[f"family/{arrangement.id}/{name}"] = (flat, form) + for arrangement in arrangements(MAIN)[::4]: + source = make_source(MAIN, arrangement) + for kind, stream in ( + ("batch", Batch(batch_size=2)(source)), + ("group_by", GroupBy(by=[arrangement.tag_order[0]])(source)), + ): + selected = stream.select_data_columns(["d1"]) + for name, form in forms(selected).items(): + out[f"{kind}/{arrangement.id}/{name}"] = (listed, form) + values = DictSource( + [{"a": 1, "b": "x", "i": 1}, {"a": 2, "b": "y", "i": None}], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="values", + ) + for name, form in forms(values).items(): + out[f"nullable/{name}"] = (nullable, form) + raw_tables = { + "int32_system_tag": pa.table( + {"k": ["a", "b"], "d1": [1, 2], "e": pa.array([10, 11], pa.int32())} + ), + "nullable_system_tag": pa.table( + { + "k": ["a", "b"], + "d1": [1, 2], + "e": pa.array(["s", None], pa.large_string()), + } + ), + } + for name, table in raw_tables.items(): + out[f"raw/{name}"] = ( + flat, + ArrowTableStream(table, tag_columns=["k"], system_tag_columns=["e"]), + ) + out["raw/meta_column"] = ( + flat, + ArrowTableStream( + pa.table({"k": ["a", "b"], "d1": [1, 2], "__review": [10, 11]}), + tag_columns=["k"], + ), + ) + # The node is declared against the clean input and executed on the raw one. + DECLARED["raw/meta_column"] = ArrowTableStream( + pa.table({"k": ["a", "b"], "d1": [1, 2]}), tag_columns=["k"] + ) + extension = {b"ARROW:extension:name": b"file", b"ARROW:extension:metadata": b""} + out["raw/extension_metadata_system_tag"] = ( + flat, + ArrowTableStream( + pa.Table.from_arrays( + [ + pa.array(["a", "b"]), + pa.array([1, 2]), + pa.array(["s", "t"], pa.large_string()), + ], + schema=pa.schema( + [ + pa.field("k", pa.large_string()), + pa.field("d1", pa.int64()), + pa.field( + "_tag_s", + pa.large_string(), + nullable=False, + metadata=extension, + ), + ] + ), + ), + tag_columns=["k"], + ), + ) + out["raw/null_in_non_null_system_tag"] = ( + flat, + ArrowTableStream( + pa.Table.from_arrays( + [ + pa.array(["a", "b"]), + pa.array([1, 2]), + pa.array(["s", None], pa.large_string()), + ], + schema=pa.schema( + [ + pa.field("k", pa.large_string()), + pa.field("d1", pa.int64()), + pa.field("_tag_extra", pa.large_string(), nullable=False), + ] + ), + ), + tag_columns=["k"], + ), + ) + out["raw/null_data_column"] = ( + untyped, + ArrowTableStream( + pa.table({"k": ["a", "b"], "x": pa.nulls(2)}), tag_columns=["k"] + ), + ) + return out + + +def main() -> None: + store, mode, report = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]) + if mode not in ("write", "load"): + # Checked before any store is opened: anything else would compute and write. + raise SystemExit(f"mode must be 'write' or 'load', not {mode!r}") + results: dict[str, Any] = {} + for index, (label, (pod, stream)) in enumerate(sorted(cases().items())): + database = DeltaTableDatabase(store / f"case_{index:03d}") + observer = Cached() + CALLS.clear() + try: + node = FunctionJobNode( + pod.pod, DECLARED.get(label, stream), pipeline_database=database + ) + node.execute(stream, observer=observer, load_only=(mode == "load")) + database.flush() + ids: list[str] = [] + for path in database.list_table_paths(): + records = database.get_all_records(path) + if ( + records is None + or "__pipeline_instance_id" not in records.column_names + ): + continue + ids += [ + value.hex() + for value in records["__pipeline_instance_id"].to_pylist() + if isinstance(value, bytes) + ] + ids.sort() + results[label] = { + "ids": ids, + "cached": observer.cached, + "calls": len(CALLS), + # The inputs as the node was given them, each with its result (not the + # stored entry's own tag): the write and load reports must be the same. + "received": observer.received, + } + except Exception as error: # noqa: BLE001 # the outcome is compared across versions + results[label] = {"error": f"{type(error).__name__}: {error}"} + report.write_text(json.dumps(results, indent=1, sort_keys=True)) + print(len(results), "cases") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 21769a847..7c85edf8c 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -816,6 +816,24 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: The function is still called once per row. Everything around the call is Arrow data. +**The one precondition (stage 2's, ITL-1361 review).** Every fast path of stages 3 and 4 +(the entry ids from the input table's slices, the output's rows of stored results taken +from their stored table, a side-effect node's pass-through as F of its input table) is +used only where the table is provably its rows': the stream is exactly an +`ArrowTableStream` (or the row-built stream a job hands a node), with no member replaced on +the instance, in the node's data context, with system tags that are what rows give +(`system_tags_as_rows_give`: non-null `large_string` fields without field metadata, +holding no null; stage 2's source and operator routes use the same helper), no meta +(`__`) column, and no column a datagram would retype (`_slices_are_rows`; a stored table +is checked the same way). A row's data hash is computed once, when its entry id is +prepared, and a datagram built later for the row keeps it +(`Datagram._keep_content_hash`): the full input datagram is not hashed again for its entry +id or pipeline record. A projection of it (`function_input(...)`, the result cache's input +when data-tags fall through) is another datagram with its own content hash, as on `main`. +Anything else takes `main`'s row path. The entry id has one definition on both paths: the preimage's last +column is `_with_input_data_hash`, and the input data hash is `data_table_content_hash`, a +data datagram's content hash. + 1. **Input as Arrow data.** For each input row, the node computes the base entry id from that row's slice of the Arrow table or record batch: the tag side with system tags, plus the input data hash. This is the same one-row preimage `_build_record_id_preimage` builds @@ -872,10 +890,12 @@ view**: one internal class, `RowView`, that satisfies `TagProtocol` or `DataProt Arrow table or record batch and a row index. It builds the datagram only when it is first read. -- `RunCountingObserver` reads only the label and the `cached` flag, so it makes no row. -- The status and logging observers read tag values, so they make the tag datagram of the - rows they report. -- A user's observer gets what it gets today. +- Only the library observers that read no input row, a closed set of exact classes + (`NoOpObserver`, `RunCountingObserver`, and a `CompositeObserver` of only such; + `_reads_no_rows`, never a subclass and never anything an observer states about + itself), receive row views (`_TagView`, `_DataView`, every protocol member declared on + the class). Every other observer receives the rows themselves, as on `main` (ITL-1361 + review: a view is not a `Tag`). Event order stays as today: - sync: input order; diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e05ee87b3..aedea5fe4 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -343,8 +343,8 @@ test session with `-p tests.test_hashing.hash_site_trace`. | schema identity | the `arrow_schema_v1` hashes of a source's or slot's Arrow tag and data schemas, or of a function's output Arrow schema | a source's content and pipeline identity, system-tag column names, the function `uri` | the `ContentHash` objects, nested | `utils/schema_utils.py:arrow_schema_identity`, `utils/schema_utils.py:compute_schema_hash`, `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | union and generic alias arguments | argument type hashes, sorted by digest, then label (ordering only) | the type hash, via the nested form | as above | `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes`, `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes..` | | logical-type cell, scalar and container | a value-hashed cell's value hash | the Arrow table hash | `::