From 5b1b578a1cd9cf8873be0466ac004f90f753d8f8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 15:31:45 -0800 Subject: [PATCH 01/34] feat(hashing): hash every schema that enters an identity as its Arrow schema (ITL-640, WIP) Co-Authored-By: Claude Opus 5.5 --- .../q1_q2_logical_types_and_metadata.py | 191 ++++++++++++++++ .../itl_640/q3i_storage_round_trips.py | 176 +++++++++++++++ docs/dev/scripts/itl_640/q3ii_builders.py | 159 ++++++++++++++ docs/dev/scripts/itl_640/q3iii_operators.py | 118 ++++++++++ .../itl_640/q4_sources_without_rows.py | 203 ++++++++++++++++++ .../scripts/itl_640/q5_saved_schema_text.py | 85 ++++++++ docs/dev/scripts/itl_640/q9_golden_moves.py | 160 ++++++++++++++ src/orcapod/core/data_function.py | 22 +- src/orcapod/core/nodes/source_node.py | 71 +++++- src/orcapod/core/sources/base.py | 36 +++- src/orcapod/core/sources/cached_source.py | 12 +- src/orcapod/core/sources/derived_source.py | 71 +++++- src/orcapod/core/sources/polling_source.py | 8 +- src/orcapod/core/sources/stream_builder.py | 12 +- .../core/streams/arrow_table_stream.py | 7 +- src/orcapod/core/streams/base.py | 34 +++ src/orcapod/hashing/arrow_hashers.py | 22 +- src/orcapod/utils/schema_utils.py | 89 +++++--- tests/test_hashing/golden/cases.py | 20 +- 19 files changed, 1413 insertions(+), 83 deletions(-) create mode 100644 docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py create mode 100644 docs/dev/scripts/itl_640/q3i_storage_round_trips.py create mode 100644 docs/dev/scripts/itl_640/q3ii_builders.py create mode 100644 docs/dev/scripts/itl_640/q3iii_operators.py create mode 100644 docs/dev/scripts/itl_640/q4_sources_without_rows.py create mode 100644 docs/dev/scripts/itl_640/q5_saved_schema_text.py create mode 100644 docs/dev/scripts/itl_640/q9_golden_moves.py diff --git a/docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py b/docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py new file mode 100644 index 000000000..fa233318b --- /dev/null +++ b/docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py @@ -0,0 +1,191 @@ +"""ITL-640 Q1/Q2: does ``StarfixArrowHasher.hash_schema`` cover a logical type's whole +identifier, and does it ignore field metadata? + +Run: ``uv run python docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py`` + +Q1. For every logical type a schema can hold, the field's Arrow type (from the data +context's converter) is hashed, and then the same field with only the extension +METADATA changed (name kept) and only the extension NAME changed (metadata kept): both +must hash differently from the original. + +Q2. Field metadata and schema metadata that are not ``ARROW:extension:*`` are ignored: +this script shows it, so that nothing identity-bearing may be carried only that way. +""" + +from __future__ import annotations + +import dataclasses +import uuid +import warnings +from pathlib import Path + +import numpy as np +import pyarrow as pa + +import orcapod as op +from orcapod.contexts import get_default_context +from orcapod.logical_types.numpy_type import LogicalNumpyArray +from orcapod.utils.arrow_utils import normalize_extension_columns + +warnings.simplefilter("ignore") + +ctx = get_default_context() +conv = ctx.type_converter +hasher = ctx.arrow_hasher + + +@dataclasses.dataclass +class Exact: + a: int + b: str + + +@op.dataclass +class Structural: + a: int + b: str + + +@op.dataclass(name="Structural") +class StructuralOtherFields: + a: int + b: float + + +TYPES: dict[str, object] = { + "Path": Path, + "uuid.UUID": uuid.UUID, + "File": op.File if hasattr(op, "File") else None, + "np.ndarray": np.ndarray, + "Exact (dataclass)": Exact, + "Structural (orcapod.dataclass)": Structural, + "list[Path]": list[Path], + "set[int]": set[int], + "set[Path]": set[Path], + "list[Exact]": list[Exact], +} + + +def h(schema: pa.Schema) -> str: + return hasher.hash_schema(schema).to_hex()[:16] + + +def ipc_field(field: pa.Field) -> pa.Field: + """The field in IPC form: storage type plus ``ARROW:extension:*`` metadata.""" + return normalize_extension_columns(pa.schema([field]).empty_table()).schema.field(0) + + +def with_ext(field: pa.Field, *, name: bytes | None = None, meta: bytes | None = None): + md = dict(field.metadata or {}) + if name is not None: + md[b"ARROW:extension:name"] = name + if meta is not None: + md[b"ARROW:extension:metadata"] = meta + return field.with_metadata(md) + + +print("Q1: logical types") +print(f"{'type':34} {'arrow type':48} {'hash':16} meta-changed name-changed") +for label, py_type in TYPES.items(): + if py_type is None: + continue + try: + # Hashing a type registers a class a factory covers (a dataclass), as a + # source or a function pod does before it converts the type. + ctx.semantic_hasher.hash_object(py_type) + arrow_type = conv.python_type_to_arrow_type(py_type) + except Exception as exc: # noqa: BLE001 + print(f"{label:34} NOT CONVERTIBLE: {type(exc).__name__}: {exc}") + continue + field = pa.field("x", arrow_type) + base = h(pa.schema([field])) + # Rebuild the field in IPC form, then change the extension metadata or name only. + ipc = ipc_field(field) + md = dict(ipc.metadata or {}) + if b"ARROW:extension:name" in md: + same_ipc = h(pa.schema([ipc])) + changed_meta = h( + pa.schema( + [with_ext(ipc, meta=md.get(b"ARROW:extension:metadata", b"") + b" ")] + ) + ) + changed_name = h( + pa.schema([with_ext(ipc, name=md[b"ARROW:extension:name"] + b"x")]) + ) + verdict = ( + f"{'DIFFERS' if changed_meta != base else 'SAME!!'} " + f"{'DIFFERS' if changed_name != base else 'SAME!!'}" + f" (ipc form hashes {'equal' if same_ipc == base else 'DIFFERENTLY'})" + ) + else: + verdict = "(no extension at top level)" + print(f"{label:34} {str(arrow_type)[:48]:48} {base} {verdict}") + +print() +print("Q1b: two numpy ignore lists (two logical types, one extension name)") +t_strict = LogicalNumpyArray().get_arrow_extension_type() +t_ignore = LogicalNumpyArray(ignore=["memory_order"]).get_arrow_extension_type() +print(" strict :", t_strict, t_strict.__arrow_ext_serialize__()) +print(" ignore :", t_ignore, t_ignore.__arrow_ext_serialize__()) +try: + print( + " hash_schema equal:", + h(pa.schema([pa.field("x", t_strict)])) + == h(pa.schema([pa.field("x", t_ignore)])), + ) +except Exception as exc: # noqa: BLE001 + # A data context reads only columns stored under its own list (CLAUDE.md). + print(f" hash_schema of the other list raises {type(exc).__name__}") + +print() +print("Q1c: structural classes, one name, other fields (identity records differ)") +ctx.semantic_hasher.hash_object(Structural) +ctx.semantic_hasher.hash_object(StructuralOtherFields) +a = conv.python_type_to_arrow_type(Structural) +b = conv.python_type_to_arrow_type(StructuralOtherFields) +print(" A:", a) +print(" B:", b) +print( + " hash_schema equal:", + h(pa.schema([pa.field("x", a)])) == h(pa.schema([pa.field("x", b)])), +) + +print() +print("Q1d: a logical type against its storage type") +for label, py_type in ( + ("Path", Path), + ("uuid.UUID", uuid.UUID), + ("set[int]", set[int]), +): + t = conv.python_type_to_arrow_type(py_type) + storage = t.storage_type if isinstance(t, pa.ExtensionType) else t + print( + f" {label}: {t} vs storage {storage}: equal =", + h(pa.schema([pa.field("x", t)])) == h(pa.schema([pa.field("x", storage)])), + ) + +print() +print("Q2: field and schema metadata (not ARROW:extension:*)") +plain = pa.schema([pa.field("x", pa.int64())]) +print( + " field metadata {'k': 'v'} ignored:", + h(plain) == h(pa.schema([pa.field("x", pa.int64(), metadata={"k": "v"})])), +) +print( + " schema metadata {'pandas': ...} ignored:", + h(plain) == h(plain.with_metadata({"pandas": "{}"})), +) +print( + " nested field metadata ignored:", + h(pa.schema([pa.field("x", pa.large_list(pa.field("item", pa.int64())))])) + == h( + pa.schema( + [ + pa.field( + "x", + pa.large_list(pa.field("item", pa.int64(), metadata={"k": "v"})), + ) + ] + ) + ), +) diff --git a/docs/dev/scripts/itl_640/q3i_storage_round_trips.py b/docs/dev/scripts/itl_640/q3i_storage_round_trips.py new file mode 100644 index 000000000..9937ebb86 --- /dev/null +++ b/docs/dev/scripts/itl_640/q3i_storage_round_trips.py @@ -0,0 +1,176 @@ +"""ITL-640 Q3 (i): does a column read back from each database have the Arrow schema it +was written with, as ``StarfixArrowHasher.hash_schema`` sees it? + +Run: ``uv run python docs/dev/scripts/itl_640/q3i_storage_round_trips.py [tmpdir]`` + +For every database class (in-memory, Delta Lake, the connector database over SQLite) +and every column type below, one table ``(id, x)`` is written with ``add_records``, +flushed and read back with ``get_all_records``. The hash of the schema of ``x`` read +back is compared with the hash of the schema written. ``REFUSED`` means the database +refuses the type when it is written (``require_storable``), which is not a silent +change. Every ``DIFFERS`` is a place where something stored and read again (a node's +stored view, ``as_source``, a cached source, a loaded job) would get another identity +than the same rows in memory. +""" + +from __future__ import annotations + +import datetime as dt +import decimal +import sys +import tempfile +import uuid +import warnings +from pathlib import Path + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector + +warnings.simplefilter("ignore") + +ctx = get_default_context() +conv = ctx.type_converter +hasher = ctx.arrow_hasher +D = decimal.Decimal +ts = [dt.datetime(2026, 1, 1, 0, 0, 1), dt.datetime(2026, 1, 2)] +tsz = [t.replace(tzinfo=dt.timezone.utc) for t in ts] +dates = [dt.date(2026, 1, 1), dt.date(2026, 1, 2)] + + +def col(values, arrow_type, nullable=True): + return pa.field("x", arrow_type, nullable=nullable), pa.array(values, arrow_type) + + +def logical(py_type, values): + ctx.semantic_hasher.hash_object(py_type) + arrow_type = conv.python_type_to_arrow_type(py_type) + return pa.field("x", arrow_type), conv.python_values_to_arrow_array( + values, py_type + ) if hasattr(conv, "python_values_to_arrow_array") else None + + +def logical_column(py_type, values): + """A logical-type column built by the converter, as a source builds it.""" + ctx.semantic_hasher.hash_object(py_type) + table = conv.python_dicts_to_arrow_table( + [{"x": v} for v in values], python_schema={"x": py_type} + ) + return table.schema.field("x"), table.column("x").combine_chunks() + + +COLUMNS = { + "int8": lambda: col([1, 2], pa.int8()), + "int16": lambda: col([1, 2], pa.int16()), + "int32": lambda: col([1, 2], pa.int32()), + "int64": lambda: col([1, 2], pa.int64()), + "uint8": lambda: col([1, 200], pa.uint8()), + "uint16": lambda: col([1, 2], pa.uint16()), + "uint32": lambda: col([1, 2], pa.uint32()), + "uint64": lambda: col([1, 2], pa.uint64()), + "float32": lambda: col([1.5, 2.5], pa.float32()), + "float64": lambda: col([1.5, 2.5], pa.float64()), + "int64 not null": lambda: col([1, 2], pa.int64(), nullable=False), + "bool": lambda: col([True, False], pa.bool_()), + "string": lambda: col(["a", "b"], pa.string()), + "binary": lambda: col([b"a", b"b"], pa.binary()), + "ts[s]": lambda: col(ts, pa.timestamp("s")), + "ts[ms]": lambda: col(ts, pa.timestamp("ms")), + "ts[us]": lambda: col(ts, pa.timestamp("us")), + "ts[ns]": lambda: col(ts, pa.timestamp("ns")), + "ts[us,UTC]": lambda: col(tsz, pa.timestamp("us", tz="UTC")), + "ts[ns,UTC]": lambda: col(tsz, pa.timestamp("ns", tz="UTC")), + "ts[us,Europe/Berlin]": lambda: col(tsz, pa.timestamp("us", tz="Europe/Berlin")), + "date32": lambda: col(dates, pa.date32()), + "date64": lambda: col(dates, pa.date64()), + "decimal(10,2)": lambda: col([D("1.25"), D("2.50")], pa.decimal128(10, 2)), + "decimal(38,4)": lambda: col([D("1.25"), D("2.50")], pa.decimal128(38, 4)), + "large_list": lambda: col( + [[1, 2], [3]], pa.large_list(pa.field("item", pa.int64())) + ), + "large_list": lambda: col( + [[1, 2], [3]], pa.large_list(pa.field("item", pa.int64(), nullable=False)) + ), + "large_list": lambda: col([[1, 2], [3]], pa.large_list(pa.int8())), + "large_list>": lambda: col( + [[[1], [2]], [[3]]], pa.large_list(pa.large_list(pa.int64())) + ), + "struct": lambda: col( + [{"a": 1, "b": "x"}, {"a": 2, "b": "y"}], + pa.struct([("a", pa.int32()), ("b", pa.string())]), + ), + "struct": lambda: col( + [{"a": 1}, {"a": 2}], pa.struct([pa.field("a", pa.int64(), nullable=False)]) + ), + "fixed_size_list[2]": lambda: col([[1, 2], [3, 4]], pa.list_(pa.int64(), 2)), + "dictionary": lambda: ( + pa.field("x", pa.dictionary(pa.int32(), pa.string())), + pa.array(["a", "b"]).dictionary_encode(), + ), + "Path": lambda: logical_column(Path, [Path("/a"), Path("/b")]), + "uuid.UUID": lambda: logical_column(uuid.UUID, [uuid.uuid4(), uuid.uuid4()]), + "list[Path]": lambda: logical_column(list[Path], [[Path("/a")], [Path("/b")]]), + "set[int]": lambda: logical_column(set[int], [{1, 2}, {3}]), + "dict[str,int]": lambda: logical_column(dict[str, int], [{"a": 1}, {"b": 2}]), +} + + +def databases(root: Path): + return { + "InMemory": InMemoryArrowDatabase(), + "Delta": DeltaTableDatabase(root / "delta"), + "SQLite": ConnectorArrowDatabase(SQLiteConnector(str(root / "store.db"))), + } + + +def describe(field: pa.Field) -> str: + return f"{field.type}{'' if field.nullable else ' not null'}" + + +def main(root: Path) -> None: + dbs = databases(root) + ids = pa.array([b"r1", b"r2"], pa.large_binary()) + print(f"{'column':34}" + "".join(f"{name:44}" for name in dbs)) + for i, (label, make) in enumerate(COLUMNS.items()): + try: + field, values = make() + except Exception as exc: # noqa: BLE001 + print(f"{label:34}cannot build: {type(exc).__name__}: {exc}") + continue + written = pa.Table.from_arrays( + [ids, values], + schema=pa.schema( + [pa.field("id", pa.large_binary(), nullable=False), field] + ), + ) + h_written = hasher.hash_schema(pa.schema([written.schema.field("x")])) + cells = [] + for name, db in dbs.items(): + path = ("t", f"c{i}") + try: + db.add_records(path, written, record_id_column="id", flush=True) + back = db.get_all_records(path, record_id_column="id") + assert back is not None + read_field = back.schema.field("x") + h_back = hasher.hash_schema(pa.schema([read_field])) + same_values = ( + back.column("x").to_pylist() == written.column("x").to_pylist() + ) + if h_back == h_written: + cells.append("same" + ("" if same_values else " (VALUES DIFFER)")) + else: + cells.append(f"DIFFERS -> {describe(read_field)}"[:42]) + except Exception as exc: # noqa: BLE001 + cells.append(f"REFUSED {type(exc).__name__}: {exc}"[:42]) + print(f"{label:34}" + "".join(f"{c:44}" for c in cells)) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + main(Path(sys.argv[1])) + else: + with tempfile.TemporaryDirectory() as tmp: + main(Path(tmp)) diff --git a/docs/dev/scripts/itl_640/q3ii_builders.py b/docs/dev/scripts/itl_640/q3ii_builders.py new file mode 100644 index 000000000..a5fc88dc8 --- /dev/null +++ b/docs/dev/scripts/itl_640/q3ii_builders.py @@ -0,0 +1,159 @@ +"""ITL-640 Q3 (ii): the same Python data through every source builder: which Arrow +types result, column by column, and which builders would give one table two +identities under an Arrow schema hash. + +Run: ``uv run python docs/dev/scripts/itl_640/q3ii_builders.py [tmpdir]`` + +Builders: ``DictSource``, ``DataFrameSource`` over a pandas and over a polars frame, +``CSVSource`` (a CSV written from the same rows), ``ArrowTableSource`` over +``pa.Table.from_pylist`` and ``ListSource`` (one column per element value). +""" + +from __future__ import annotations + +import csv +import datetime as dt +import sys +import tempfile +import warnings +from pathlib import Path + +import pandas as pd +import polars as pl +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.sources import ( + ArrowTableSource, + CSVSource, + DataFrameSource, + DictSource, + ListSource, +) + +warnings.simplefilter("ignore") + +ctx = get_default_context() + +ROWS = [ + { + "k": "a", + "i": 1, + "f": 1.5, + "s": "x", + "b": True, + "ts": dt.datetime(2026, 1, 1, 12, 0), + "tsz": dt.datetime(2026, 1, 1, 12, 0, tzinfo=dt.timezone.utc), + "d": dt.date(2026, 1, 1), + "li": [1, 2], + "n": None, + }, + { + "k": "b", + "i": 2, + "f": 2.5, + "s": "y", + "b": False, + "ts": dt.datetime(2026, 1, 2, 12, 0), + "tsz": dt.datetime(2026, 1, 2, 12, 0, tzinfo=dt.timezone.utc), + "d": dt.date(2026, 1, 2), + "li": [3], + "n": 5, + }, +] +CSV_COLUMNS = ["k", "i", "f", "s", "b", "n"] + + +def build(root: Path) -> dict[str, object]: + kw = {"tag_columns": ["k"], "tag_only_columns": True, "source_id": "s"} + out: dict[str, object] = {} + for label, make in ( + ("DictSource", lambda: DictSource(ROWS, **kw)), + ("DataFrameSource(pandas)", lambda: DataFrameSource(pd.DataFrame(ROWS), **kw)), + ("DataFrameSource(polars)", lambda: DataFrameSource(pl.DataFrame(ROWS), **kw)), + ( + "ArrowTableSource(from_pylist)", + lambda: ArrowTableSource(pa.Table.from_pylist(ROWS), **kw), + ), + ): + try: + out[label] = make() + except Exception as exc: # noqa: BLE001 + out[label] = f"REFUSED {type(exc).__name__}: {exc}"[:160] + path = root / "rows.csv" + with path.open("w", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=CSV_COLUMNS) + writer.writeheader() + for row in ROWS: + writer.writerow( + {c: ("" if row[c] is None else row[c]) for c in CSV_COLUMNS} + ) + try: + out["CSVSource"] = CSVSource(str(path), **kw) + except Exception as exc: # noqa: BLE001 + out["CSVSource"] = f"REFUSED {type(exc).__name__}: {exc}"[:160] + return out + + +def field_text(f: pa.Field) -> str: + return f"{f.type}{'' if f.nullable else ' nn'}" + + +def main(root: Path) -> None: + sources = build(root) + columns = list(ROWS[0]) + tables = {} + for label, src in sources.items(): + if isinstance(src, str): + print(f"{label}: {src}") + continue + tables[label] = src.as_table() # type: ignore[attr-defined] + labels = list(tables) + print(f"{'col':5}" + "".join(f"{lab[:30]:32}" for lab in labels)) + for c in columns: + cells = [] + for lab in labels: + t = tables[lab] + cells.append(field_text(t.schema.field(c)) if c in t.column_names else "-") + print(f"{c:5}" + "".join(f"{cell[:30]:32}" for cell in cells)) + print() + print(f"Per column, the builders whose Arrow field hashes like {labels[0]}'s:") + base = tables[labels[0]] + for c in columns: + h0 = ctx.arrow_hasher.hash_schema(pa.schema([base.schema.field(c)])) + same, diff = [], [] + for lab in labels[1:]: + t = tables[lab] + if c not in t.column_names: + continue + h = ctx.arrow_hasher.hash_schema(pa.schema([t.schema.field(c)])) + (same if h == h0 else diff).append(lab) + print(f" {c:5} same: {same} DIFFERENT: {diff}") + + print() + print("ListSource vs DictSource, one data column 'v' of Python ints / datetimes:") + utc = dt.timezone.utc + for values in ( + [1, 2], + [dt.datetime(2026, 1, 1, tzinfo=utc), dt.datetime(2026, 1, 2, tzinfo=utc)], + ): + ls = ListSource("v", values) + ds = DictSource( + [{"element_index": i, "v": v} for i, v in enumerate(values)], + tag_columns=["element_index"], + tag_only_columns=True, + ) + lf = ls.as_table().schema.field("v") + df = ds.as_table().schema.field("v") + print( + f" {type(values[0]).__name__}: ListSource {field_text(lf)} / DictSource {field_text(df)}" + f" -> hash equal: {ctx.arrow_hasher.hash_schema(pa.schema([lf])) == ctx.arrow_hasher.hash_schema(pa.schema([df]))}" + ) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + main(Path(sys.argv[1])) + else: + with tempfile.TemporaryDirectory() as tmp: + main(Path(tmp)) diff --git a/docs/dev/scripts/itl_640/q3iii_operators.py b/docs/dev/scripts/itl_640/q3iii_operators.py new file mode 100644 index 000000000..323011ad7 --- /dev/null +++ b/docs/dev/scripts/itl_640/q3iii_operators.py @@ -0,0 +1,118 @@ +"""ITL-640 Q3 (iii): is every operator's Arrow schema the same in zero-row form +(``typed_zero_row_table``, ITL-912) as in its populated result, and what does the +Python prediction say about list item nullability (ITL-1136)? + +Run: ``uv run python docs/dev/scripts/itl_640/q3iii_operators.py`` + +The async path is not measured here: ``tests/test_core/operators/test_async_sync_equivalence.py`` +asserts, for every operator, that the async rows have the sync rows' Arrow types, +nullability (item level included) and column order, over int8, float32, string, +list and large_list with nullable and non-null items, a struct and a logical type. + +The inputs have two tags (``k`` str, ``g`` str) and two data columns: ``x`` int8 with a +null, ``y`` large_list. +""" + +from __future__ import annotations + +import warnings + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.core.operators import ( + AddTags, + Batch, + DropNulls, + GroupBy, + Join, + MapData, + MergeJoin, + PolarsFilter, + SelectDataColumns, + SemiJoin, +) +from orcapod.core.streams.base import typed_zero_row_table +from orcapod.sources import ArrowTableSource + +warnings.simplefilter("ignore") +ctx = get_default_context() +NN_ITEMS = pa.large_list(pa.field("item", pa.int8(), nullable=False)) + + +def source(source_id: str, other: str = "z") -> ArrowTableSource: + table = pa.Table.from_arrays( + [ + pa.array(["r1", "r2", "r3"], pa.large_string()), + pa.array(["g1", "g1", "g2"], pa.large_string()), + pa.array([1, None, 3], pa.int8()), + pa.array([[1], [2, 3], []], NN_ITEMS), + pa.array([1.5, 2.5, 3.5], pa.float32()), + ], + schema=pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("g", pa.large_string(), nullable=False), + pa.field("x", pa.int8()), + pa.field("y", NN_ITEMS, nullable=False), + pa.field(other, pa.float32(), nullable=False), + ] + ), + ) + return ArrowTableSource( + table, tag_columns=["k", "g"], tag_only_columns=True, source_id=source_id + ) + + +def user(stream, schema: pa.Schema) -> pa.Schema: + tags, data = stream.keys() + return pa.schema([schema.field(n) for n in dict.fromkeys([*tags, *data])]) + + +def text(schema: pa.Schema) -> str: + return "; ".join(f"{f.name}: {f.type}{'' if f.nullable else ' nn'}" for f in schema) + + +CASES = { + "Batch()": lambda: Batch()(source("a")), + "GroupBy('g')": lambda: GroupBy("g")(source("a")), + "MergeJoin(a, b) over a null in x": lambda: MergeJoin()(source("a"), source("b")), + "MergeJoin(a, b) on y only": lambda: MergeJoin()( + SelectDataColumns(["y", "z"])(source("a")), + SelectDataColumns(["y"])(source("b", "w")), + ), + "Join(a, b')": lambda: Join()( + source("a"), source("b", "w").map_data({"x": "x2", "y": "y2"}) + ), + "SemiJoin(a, b)": lambda: SemiJoin()(source("a"), source("b")), + "SelectDataColumns(x, y)": lambda: SelectDataColumns(["y", "x"])(source("a")), + "MapData": lambda: MapData({"x": "x1", "y": "y1"})(source("a")), + "PolarsFilter": lambda: PolarsFilter(constraints={"g": "g1"})(source("a")), + "DropNulls(x)": lambda: DropNulls(["x"])(source("a")), + "AddTags": lambda: AddTags({"cohort": "A", "run": 3})(source("a")), +} + +for label, make in CASES.items(): + try: + stream = make() + populated = user(stream, stream.as_table().schema) + zero = typed_zero_row_table(stream) + zero_user = None if zero is None else user(stream, zero.schema) + equal = zero_user is not None and ctx.arrow_hasher.hash_schema( + populated + ) == ctx.arrow_hasher.hash_schema(zero_user) + print(f"== {label}: zero-row == populated: {equal}") + print(f" populated: {text(populated)}") + if not equal: + print(f" zero-row : {None if zero_user is None else text(zero_user)}") + print(f" Python : {stream.output_schema()}") + converted = ctx.type_converter.python_schema_to_arrow_schema( + stream.output_schema()[0] + stream.output_schema()[1] + ) + print( + " converter(Python) == populated:", + ctx.arrow_hasher.hash_schema(user(stream, converted)) + == ctx.arrow_hasher.hash_schema(populated), + ) + except Exception as exc: # noqa: BLE001 + print(f"== {label}: FAILED {type(exc).__name__}: {exc}") diff --git a/docs/dev/scripts/itl_640/q4_sources_without_rows.py b/docs/dev/scripts/itl_640/q4_sources_without_rows.py new file mode 100644 index 000000000..fe34117b3 --- /dev/null +++ b/docs/dev/scripts/itl_640/q4_sources_without_rows.py @@ -0,0 +1,203 @@ +"""ITL-640 Q4: where does a source's Arrow schema come from before it holds rows, and +does it equal the Arrow schema of the rows that arrive? + +Run: ``uv run python docs/dev/scripts/itl_640/q4_sources_without_rows.py [tmpdir]`` + +For each kind of source, three Arrow schemas of its (tag, data) columns are compared +with ``StarfixArrowHasher.hash_schema``: + +* ``zero-row``: ``typed_zero_row_table`` (ITL-912), before any row is read; +* ``converter``: the data context's converter applied to the declared Python schema; +* ``rows``: the schema of ``as_table()`` once rows exist. + +The source table has an ``int32`` tag ``k``, an ``int8`` data column ``x`` and a +``timestamp[ns]`` data column ``t``: three types the converter does not produce from +``int`` and ``datetime``. +""" + +from __future__ import annotations + +import datetime as dt +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.source_node import SourceNode +from orcapod.core.streams.base import typed_zero_row_table +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.core.sources.polling_source import PollingSource +from orcapod.types import Cursor, Schema + +warnings.simplefilter("ignore") + +TS = [dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 2)] + + +def table() -> pa.Table: + return pa.Table.from_arrays( + [ + pa.array([1, 2], pa.int32()), + pa.array([1, 2], pa.int8()), + pa.array(TS, pa.timestamp("ns")), + ], + schema=pa.schema( + [ + pa.field("k", pa.int32(), nullable=False), + pa.field("x", pa.int8(), nullable=False), + pa.field("t", pa.timestamp("ns"), nullable=False), + ] + ), + ) + + +@function_pod(output_keys="y") +def double(x: int) -> int: + return x * 2 + + +def user_schema(stream: Any, arrow_schema: pa.Schema) -> pa.Schema: + tag_keys, data_keys = stream.keys() + names = [*tag_keys, *[n for n in data_keys if n not in tag_keys]] + return pa.schema([arrow_schema.field(n) for n in names]) + + +def describe(schema: pa.Schema | None) -> str: + if schema is None: + return "None" + return "; ".join( + f"{f.name}: {f.type}{'' if f.nullable else ' not null'}" for f in schema + ) + + +def schemas(stream: Any, with_rows: bool = True) -> dict[str, pa.Schema | None]: + ctx = stream.data_context + out: dict[str, pa.Schema | None] = {} + z = typed_zero_row_table(stream) + out["zero-row"] = None if z is None else user_schema(stream, z.schema) + tag, data = stream.output_schema() + out["converter"] = ctx.type_converter.python_schema_to_arrow_schema( + Schema({**dict(tag), **dict(data)}) + ) + if with_rows: + try: + t = stream.as_table() + out["rows"] = user_schema(stream, t.schema) + except Exception as exc: # noqa: BLE001 + print(f" as_table FAILED: {type(exc).__name__}: {exc}") + out["rows"] = None + return out + + +def report(label: str, stream: Any, with_rows: bool = True) -> None: + ctx = stream.data_context + found = schemas(stream, with_rows) + print(f"== {label}") + hashes = {} + for name, schema in found.items(): + print(f" {name:10} {describe(schema)}") + hashes[name] = None if schema is None else ctx.arrow_hasher.hash_schema(schema) + keys = [k for k, v in hashes.items() if v is not None] + for i, a in enumerate(keys): + for b in keys[i + 1 :]: + print(f" {a} == {b}: {hashes[a] == hashes[b]}") + + +class Impl: + """A polling implementation declaring Python types, fetching a fixed table.""" + + def __init__(self, fetched: Any) -> None: + self._fetched = fetched + + def identity(self) -> Any: + return ("q4", 1) + + def to_config(self) -> dict[str, Any] | None: + return None + + @classmethod + def from_config(cls, config: dict[str, Any]) -> "Impl": + raise NotImplementedError + + def schema(self) -> Any: + return Schema({"k": int, "x": int, "t": dt.datetime}) + + async def poll(self, cursor: Any = None) -> bool: + return cursor is None + + async def fetch(self, cursor: Any = None) -> Any: + return Cursor.now(1), self._fetched + + async def close(self) -> None: + return None + + +def main(root: Path) -> None: + source = ArrowTableSource( + table(), tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + report("ArrowTableSource (holds its table)", source) + + for kind in ("mem", "delta"): + db = ( + InMemoryArrowDatabase() + if kind == "mem" + else DeltaTableDatabase(root / kind) + ) + job = PipelineJob(name="j", database=db) + with job: + double.pod(source, label="f") + source.map_data({"x": "z"}, label="op") + f, opn = job.nodes["f"], job.nodes["op"] + report(f"[{kind}] function job node, before run", f, with_rows=False) + report(f"[{kind}] operator job node, before run", opn, with_rows=False) + report(f"[{kind}] f.as_source(), before run", f.as_source()) + report(f"[{kind}] op.as_source(), before run", opn.as_source()) + job.run() + report(f"[{kind}] function job node, after run", f) + report(f"[{kind}] operator job node, after run", opn) + report(f"[{kind}] f.as_source(), after run", f.as_source()) + report(f"[{kind}] op.as_source(), after run", opn.as_source()) + slot = job.nodes.get("s") + if slot is not None: + report(f"[{kind}] input slot of the job (bound)", slot) + cache_db = ( + InMemoryArrowDatabase() + if kind == "mem" + else DeltaTableDatabase(root / "cache") + ) + cached = CachedSource(source, cache_database=cache_db) + report(f"[{kind}] CachedSource over the ArrowTableSource", cached) + cached_derived = CachedSource(f.as_source(), cache_database=cache_db) + report(f"[{kind}] CachedSource over f.as_source()", cached_derived) + + slot = SourceNode( + name="declared", tag_schema=Schema({"k": int}), data_schema=Schema({"x": int}) + ) + report("SourceNode declared by hand (unbound)", slot, with_rows=False) + + print() + print("PollingSource: declared {k: int, x: int, t: datetime}") + for label, fetched in ( + ("pa.Table int32/int8/ts[ns]", table()), + ("Python dicts", {"k": [1, 2], "x": [1, 2], "t": TS}), + ): + p = PollingSource(Impl(fetched), tag_columns="k", record_id_columns="k") + report(f"PollingSource before poll, fetch returns {label}", p, with_rows=False) + before = p.pipeline_hash() + report(f"PollingSource after poll, fetch returned {label}", p) + print(" pipeline_hash unchanged by the poll:", before == p.pipeline_hash()) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + main(Path(sys.argv[1])) + else: + with tempfile.TemporaryDirectory() as tmp: + main(Path(tmp)) diff --git a/docs/dev/scripts/itl_640/q5_saved_schema_text.py b/docs/dev/scripts/itl_640/q5_saved_schema_text.py new file mode 100644 index 000000000..56d669b74 --- /dev/null +++ b/docs/dev/scripts/itl_640/q5_saved_schema_text.py @@ -0,0 +1,85 @@ +"""ITL-640 Q5: does the saved schema text of a job rebuild the same Arrow type? + +Run: ``uv run python docs/dev/scripts/itl_640/q5_saved_schema_text.py`` + +Each Arrow type is written with the saved-job writer (``_serialize_arrow_type``) and +read with the reader (``parse_arrow_type_string``); the two are compared with +``StarfixArrowHasher.hash_schema``. Top-level nullability is saved apart, as the +``nullable`` record of a saved schema pair, so it is not part of this text. +""" + +from __future__ import annotations + +import uuid +import warnings +from pathlib import Path + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.pipeline.serialization import ( + _serialize_arrow_type, + parse_arrow_type_string, +) + +warnings.simplefilter("ignore") +ctx = get_default_context() +conv = ctx.type_converter + + +def lt(py_type): + ctx.semantic_hasher.hash_object(py_type) + return conv.python_type_to_arrow_type(py_type) + + +TYPES = { + "int8": pa.int8(), + "uint64": pa.uint64(), + "float32": pa.float32(), + "ts[s]": pa.timestamp("s"), + "ts[ns]": pa.timestamp("ns"), + "ts[us, UTC]": pa.timestamp("us", tz="UTC"), + "ts[ms, Europe/Berlin]": pa.timestamp("ms", tz="Europe/Berlin"), + "date32": pa.date32(), + "date64": pa.date64(), + "decimal128(10,2)": pa.decimal128(10, 2), + "decimal256(50,4)": pa.decimal256(50, 4), + "large_list": pa.large_list( + pa.field("item", pa.int8(), nullable=False) + ), + "large_list>": pa.large_list( + pa.large_list(pa.field("item", pa.int64(), nullable=False)) + ), + "fixed_size_list[2]": pa.list_(pa.int64(), 2), + "struct>": pa.struct( + [ + pa.field("a", pa.int32(), nullable=False), + pa.field("b", pa.large_list(pa.timestamp("ns"))), + ] + ), + "dictionary": pa.dictionary(pa.int32(), pa.string()), + "map": pa.map_(pa.string(), pa.int64()), + "Path": lt(Path), + "uuid.UUID": lt(uuid.UUID), + "list[Path]": lt(list[Path]), + "set[int]": lt(set[int]), + "dict[str, int]": lt(dict[str, int]), +} + +for label, arrow_type in TYPES.items(): + text = _serialize_arrow_type(arrow_type) + try: + back = parse_arrow_type_string(text) + except Exception as exc: # noqa: BLE001 + print( + f"{label:52} text {text!r}: READ FAILED {type(exc).__name__}: {exc}"[:220] + ) + continue + same = ctx.arrow_hasher.hash_schema( + pa.schema([pa.field("x", arrow_type)]) + ) == ctx.arrow_hasher.hash_schema(pa.schema([pa.field("x", back)])) + print( + f"{label:52} {'same' if same else 'DIFFERS -> ' + str(back)} text {text!r}"[ + :240 + ] + ) diff --git a/docs/dev/scripts/itl_640/q9_golden_moves.py b/docs/dev/scripts/itl_640/q9_golden_moves.py new file mode 100644 index 000000000..d3f0eb7fe --- /dev/null +++ b/docs/dev/scripts/itl_640/q9_golden_moves.py @@ -0,0 +1,160 @@ +"""ITL-640 Q9: which golden entries move under the Arrow schema hash, by group, case +and kind of entry; which do not. Writes nothing to the golden folder. + +Run: ``uv run python docs/dev/scripts/itl_640/q9_golden_moves.py [--list]`` + +An entry whose NAME holds a system-tag column name (``row[...]._tag_source_id::``) +is renamed when the schema hash moves; such a pair (pinned name gone, computed name new) +is matched by the name with every 64-hex digest blanked, and counted as ``renamed`` +(value unchanged) or ``renamed+moved``. ``--list`` prints every changed entry. +""" + +from __future__ import annotations + +import collections +import json +import pathlib +import re +import sys +import warnings + +ROOT = pathlib.Path(__file__).resolve().parents[4] +# The cases import as ``tests.test_hashing.golden.cases``, as the generator imports them: +# fixtures hash with their module path. +sys.path.insert(0, str(ROOT)) +warnings.simplefilter("ignore") + +from tests.test_hashing.golden import cases # noqa: E402 + +GROUPS = ["semantic", "schema", "arrow", "datagram", "pipeline", "torch"] +HEX = re.compile(r"[0-9a-f]{64,70}") + + +def pinned_entries() -> dict[str, dict[str, object]]: + folder = ROOT / "tests" / "test_hashing" / "golden" / "data" / "v1" + out: dict[str, dict[str, object]] = collections.defaultdict(dict) + for path in sorted(folder.glob("*.json")): + group = path.name.split("-")[0] + out[group].update(json.loads(path.read_text())) + return out + + +def blank(name: str) -> str: + return HEX.sub("H", name) + + +def case_of(entry: str) -> str: + return entry.split(".")[0] + + +def kind_of(entry: str) -> str: + name = re.sub(r"\[[^\]]*\]", "[]", blank(entry)) + last = name.split(".")[-1] + if last.startswith("_tag_record_id"): + return "row record id (value)" + if last.startswith("_tag_source_id"): + return "row source id (value)" + return last + + +def label_only(old: object, new: object) -> bool: + """Whether only the label of a ``