diff --git a/.zed/rules b/.zed/rules index 83fdcec30..92b99300b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1050,7 +1050,7 @@ data. The rules: to large_list, recursively). Width, nullability and logical (extension) types are never changed; int8 stays int8, and null stays null (operators and the type converter pass keep_null=True; only Data maps null to large_string, the function's default). An - operator that round-trips through Polars casts its columns back + operator that round-trips its columns through Polars casts them back to the normalized input types (arrow_utils.restore_column_types, or restore_schema_nullability when nullability is restored too). This holds for every operator, also one that passes its rows through unchanged (select, @@ -1200,6 +1200,19 @@ data. The rules: - DerivedSource over a job node with nothing stored → presents zero rows with the origin's columns (no computed records; no error), in the plain form and with tags_as_data. - Join requires non-overlapping data columns; raises InputValidationError on collision. +- `Join` and `SemiJoin` give Polars only their key columns and row numbers (ITL-1284): Polars + decides which rows match, and every output column is taken from the input tables by row + number (`take`), so every value is the input's, bit for bit (they used to carry every column + through Polars: a `date64` off midnight came back at midnight, a `decimal256` made Polars + panic). Keys are prepared in one place, `core/operators/arrow_keys.py` (`polars_ready`: a + logical type as its storage, a dictionary decoded, a temporal value as its integer, `float16` + as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, through lists, + fixed-size lists and structs; `part_without_rule` says what may reach Polars). A key whose + type has no rule (a map, an interval, a union, a list view) is refused with + `InputValidationError` naming the column (`base.require_matchable_key`) on both paths, + before rows are matched (never at validation, which would derive every input's zero-row + table on each graph build). `GroupBy` keeps its own copy of the preparation until ITL-1281, which also + moves `MergeJoin` off its round trip. - MergeJoin requires colliding data columns to have identical Python types; merges into sorted large_list with source columns reordered to match, where T is the large-normalized input Arrow type; inputs whose Arrow types still differ after normalization raise diff --git a/CLAUDE.md b/CLAUDE.md index 9473e07b7..e7acd1ae8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1094,7 +1094,7 @@ data. The rules: to `large_list`, recursively). Width, nullability and logical (extension) types are never changed; `int8` stays `int8`, and `null` stays `null` (operators and the type converter pass `keep_null=True`; only `Data` maps `null` to `large_string`, the function's default). An - operator that round-trips through Polars casts its columns back + operator that round-trips its columns through Polars casts them back to the normalized input types (`arrow_utils.restore_column_types`, or `restore_schema_nullability` when nullability is restored too). This holds for every operator, also one that passes its rows through unchanged (select, @@ -1244,6 +1244,19 @@ data. The rules: - `DerivedSource` over a job node with nothing stored → presents zero rows with the origin's columns (no computed records; no error), in the plain form and with `tags_as_data`. - Join requires non-overlapping data columns; raises `InputValidationError` on collision. +- `Join` and `SemiJoin` give Polars only their key columns and row numbers (ITL-1284): Polars + decides which rows match, and every output column is taken from the input tables by row + number (`take`), so every value is the input's, bit for bit (they used to carry every column + through Polars: a `date64` off midnight came back at midnight, a `decimal256` made Polars + panic). Keys are prepared in one place, `core/operators/arrow_keys.py` (`polars_ready`: a + logical type as its storage, a dictionary decoded, a temporal value as its integer, `float16` + as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, through lists, + fixed-size lists and structs; `part_without_rule` says what may reach Polars). A key whose + type has no rule (a map, an interval, a union, a list view) is refused with + `InputValidationError` naming the column (`base.require_matchable_key`) on both paths, + before rows are matched (never at validation, which would derive every input's zero-row + table on each graph build). `GroupBy` keeps its own copy of the preparation until ITL-1281, which also + moves `MergeJoin` off its round trip. - MergeJoin requires colliding data columns to have identical Python types; merges into sorted `large_list` with source columns reordered to match, where `T` is the large-normalized input Arrow type; inputs whose Arrow types still differ after normalization raise diff --git a/changelog.d/ITL-1284.md b/changelog.d/ITL-1284.md new file mode 100644 index 000000000..8dd874438 --- /dev/null +++ b/changelog.d/ITL-1284.md @@ -0,0 +1,19 @@ +### Breaking changes and migration + +- **`Join` and `SemiJoin` refuse a join key whose type has no rule for matching** (a map, + an interval, a union, a list view, or a list or struct holding one) with + `InputValidationError` naming the column, on both the sync and the async path (when + rows are matched; also by `head()` of a stream with no rows). Before, the sync path + failed with an error from Polars or Arrow, while the async path matched such keys. Join + on other tags (drop the tag from one input, `drop_tag_columns`). (ITL-1284) + +### Fixed + +- **`Join` and `SemiJoin` emit every value exactly on the sync path.** Polars now only + decides which rows match, from the prepared join keys and row numbers; every output + column is taken from the input's Arrow tables. Before, every column went through Polars + and back: a `date64` value off midnight came back at midnight (as data and as a key, in + a list and in a struct), and a `decimal256` column made Polars panic, ending the process; + a map or interval data column failed. The sync path now agrees with the async path for + these types. Results change only for inputs holding such values; no golden value moves. + (ITL-1284) diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 536c523ba..16b802314 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -73,13 +73,21 @@ Takes one or more streams. Used for `Join`, which performs an N-ary inner join. N-ary inner join on shared tag columns. Requires that input streams have non-overlapping data columns (raises `InputValidationError` on collision). Join is **commutative** -- the order of input streams does not affect the result. Like every operator, Join drops its -inputs' meta (`__`-prefixed) columns, so they never collide. Rows match on equality of every shared tag column, whatever -its type (lists and structs compare element by element). A row with a null in any shared tag +inputs' meta (`__`-prefixed) columns, so they never collide. Rows match on equality of every shared tag column +(lists and structs compare element by element). A row with a null in any shared tag column matches nothing, a null list or struct included, and rows with null on both sides do not match each other (the SQL convention for nulls; `MergeJoin` and `SemiJoin` follow it too, on the sync and the async path, while `GroupBy` is the exception by design and puts null keys in one group); a null *inside* a list or struct is an ordinary element that equals another null, an empty list is not a null, and NaN equals NaN. The async path gives the same rows. +`Join` and `SemiJoin` keep every value exactly: each output column is taken from the inputs +as it is, bit for bit (a `time64[ns]` keeps its nanoseconds, a `date64` its time of day, a +`decimal256` its 76 digits), and a data column of any Arrow type passes through. A shared tag +column must be a type they can compare: an integer, float, decimal, boolean, string, binary, +date, time, timestamp or duration, a logical type stored as one, or a list or struct of +those. A key that holds a map, an interval or a union is refused with `InputValidationError` +naming the column; drop it from one input (`drop_tag_columns`) to join on the other tags. + Because a null key matches nothing, a shared tag column may differ between the inputs in nullability alone: `T` in one input and `T | None` in another is accepted by `Join`, `MergeJoin` and `SemiJoin`. In the output of `Join` and `MergeJoin` the column is `T` when any input has it diff --git a/docs/dev/design_issues/ITL-1284-SJ4.md b/docs/dev/design_issues/ITL-1284-SJ4.md new file mode 100644 index 000000000..f102f5125 --- /dev/null +++ b/docs/dev/design_issues/ITL-1284-SJ4.md @@ -0,0 +1,30 @@ +## `src/orcapod/core/operators/semijoin.py` — nested columns and string/large_string keys + +### SJ4 — `Join` and `SemiJoin` (sync) changed values by carrying every column through Polars +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1284 (related: ITL-1250, ITL-1281) + +The sync paths of `Join` (`static_process`) and `SemiJoin` (`binary_static_process`) +joined `pl.DataFrame(table)` with the other input and converted the result back to Arrow, +then cast it to the input types. Every column went through Polars, and Polars changes or +refuses some Arrow types on the way: a `date64` value off midnight came back at midnight +(1 ms became 0 ms), as data and as a key, in a list and in a struct; a `decimal256` column, +at the top level or nested, made Polars panic ("operator does not support primitive +`Int256`"), which no caller can catch; a map or interval column, even as data only, failed. +Key matching was correct. The async paths do not use Polars and were exact, so the two +paths disagreed for these types. + +**Fix:** Polars only decides which rows match. It is given the key columns, prepared by +`core/operators/arrow_keys.py` (the one place: a logical type as its storage, a dictionary +decoded, a temporal value as its integer, `float16` as `float32`, a view as its large +variant, `decimal256` as four 64-bit limbs, through lists, fixed-size lists and structs), +and row numbers; every output column is taken from the input tables by those row numbers +(`take`), so every value is the input's, bit for bit, and a data column of any type passes +through. A key whose type has no rule there (a map, an interval, a union, a list view) is +refused with `InputValidationError` naming the column (`base.require_matchable_key`) on +both paths, before rows are matched, never passed to Polars. Output layout, row order, system +tags, key nullability and the type-disagreement refusals are unchanged; no golden value +moves. Tests: `tests/test_core/operators/test_join_arrow_values.py` and the +`*_exact_values` cases of `test_async_sync_equivalence.py`. `GroupBy` keeps its own copy +of the preparation until ITL-1281; `MergeJoin` is ITL-1281. diff --git a/docs/dev/scripts/itl_1284/join_audit.py b/docs/dev/scripts/itl_1284/join_audit.py new file mode 100644 index 000000000..9ac8578fb --- /dev/null +++ b/docs/dev/scripts/itl_1284/join_audit.py @@ -0,0 +1,244 @@ +"""ITL-1284: which Arrow types ``Join`` and ``SemiJoin`` change or fail on, in this checkout. + +usage: uv run python docs/dev/scripts/itl_1284/join_audit.py + +For each Arrow type T (two values) and each operator, two roles: ``data`` (a non-key +data column of T on the left input, for ``Join`` also on the right) and ``key`` (a +shared tag of T, the only key). Each runs on the sync path (``op(left, right)``) and the +async path (``async_execute`` over channels). The values out are compared with the +values in exactly: temporal values as their integers, floats as their bits, decimals as +text, logical types through their storage, lists and structs element by element. A +line is printed for every case that is not exact (``CHANGED`` or ``ERROR``), then a +count. A Polars panic is a ``BaseException``, so it is caught and printed too. + +Measured on ``main`` at ``1015c268`` (Polars 1.41.2, PyArrow 23.0.1), the sync path +truncates ``date64`` to midnight (top level, in a list, in a struct) and panics on +``decimal256``; with ITL-1284 every case is exact, and a key type with no rule (a map, +an interval, a union) is refused with ``InputValidationError`` on both paths. +""" + +from __future__ import annotations + +import asyncio +import decimal +import uuid +from pathlib import Path +from typing import Any, TypeAlias, cast + +import pyarrow as pa + +from orcapod.channels import Channel +from orcapod.contexts import get_default_context +from orcapod.core.operators import Join, SemiJoin +from orcapod.core.streams import ArrowTableStream +from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + +Column: TypeAlias = "pa.Array[Any]" +Row: TypeAlias = "tuple[TagProtocol, DataProtocol]" +CTX = get_default_context() +D = decimal.Decimal + + +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) + if isinstance(array, pa.DictionaryArray): + return exact(array.dictionary_decode()) + 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]] if lists[i].is_valid else None + for i in range(len(lists)) + ] + if pa.types.is_fixed_size_list(arrow_type): + fixed = cast("pa.FixedSizeListArray[Any]", array) + return exact(fixed.cast(pa.large_list(arrow_type.value_type))) + 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) if struct[j].is_valid else None + for j in range(len(struct)) + ] + if pa.types.is_map(arrow_type): + return [repr(x) for x in array.to_pylist()] + if pa.types.is_floating(arrow_type): + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + bits = cast( + list[int | None], array.view(unsigned[arrow_type.bit_width]).to_pylist() + ) + return [None if b is None else hex(b) for b in bits] + if pa.types.is_interval(arrow_type): + return [repr(x) for x in array.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 [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) -> 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, CTX.type_converter.python_type_to_arrow_type(python_type) + ) + return pa.ExtensionArray.from_storage( + arrow_type, pa.array(storage, arrow_type.storage_type) + ) + + +def cases() -> dict[str, Column]: + dec256 = pa.decimal256(76, 40) + date64s = ints([1, 86_400_001], pa.date64()) + return { + "int8": pa.array([-128, 127], pa.int8()), + "uint64 max": pa.array([2**64 - 1, 0], pa.uint64()), + "float16 (1.0, -0.0)": floats([0x3C00, 0x8000], 16), + "float32 (sNaN, 1.0)": floats([0x7F800001, 0x3F800000], 32), + "float64 (payload NaN, -0.0)": floats( + [0x7FF8000000000001, 0x8000000000000000], 64 + ), + "bool": pa.array([True, False]), + "large_string (precomposed and decomposed é)": pa.array( + ["\u00e9", "e\u0301"], pa.large_string() + ), + "fixed_size_binary(3)": pa.array([b"abc", b"\x00\x00\x00"], pa.binary(3)), + "date32": pa.array([0, 1], pa.int32()).cast(pa.date32()), + "date64 off midnight": date64s, + "time32[s]": pa.array([1, 2], pa.int32()).cast(pa.time32("s")), + "time64[ns]": ints([1, 1001], pa.time64("ns")), + "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) + ), + "decimal256(76,40)": pa.array([D("1." + "0" * 39 + "1"), D("-3")], dec256), + "large_list": pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), date64s + ), + "large_list": pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), ints([1, 1001], pa.time64("ns")) + ), + "large_list": pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), floats([0x7F800001, 0], 32) + ), + "struct": pa.StructArray.from_arrays([date64s], names=["a"]), + "large_list": pa.array( + [[D(1)], [D(2)]], pa.large_list(pa.decimal256(76, 2)) + ), + "struct": pa.StructArray.from_arrays( + [pa.array([D(1), D(2)], dec256)], names=["a"] + ), + "fixed_size_list": pa.FixedSizeListArray.from_arrays( + pa.array([D(1), D(2)], dec256), 1 + ), + "logical Path": logical(Path, ["a", "b"]), + "logical UUID": logical( + uuid.UUID, [uuid.UUID(int=1).bytes, uuid.UUID(int=2).bytes] + ), + "map": pa.array( + [[("a", 1)], [("b", 2)]], pa.map_(pa.large_string(), pa.int64()) + ), + "month_day_nano_interval": pa.array( + [(1, 2, 3), (4, 5, 6)], pa.month_day_nano_interval() + ), + } + + +async def _run_async( + operator: Join | SemiJoin, streams: list[ArrowTableStream] +) -> list[Row]: + channels: list[Channel[Row]] = [Channel(buffer_size=64) for _ in streams] + output: Channel[Row] = Channel(buffer_size=64) + for stream, channel in zip(streams, channels): + for row in stream.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await operator.async_execute( + [c.reader for c in channels], + output.writer, + input_pipeline_hashes=[s.pipeline_hash() for s in streams], + ) + return await output.reader.collect() + + +def _column_of_rows(rows: list[Row], name: str) -> list[Any]: + out: list[Any] = [] + for tag, data in rows: + table = tag.as_table() if name in tag.keys() else data.as_table() + out.extend(exact(table.column(name))) + return out + + +def check(operator_name: str, role: str, values: Column, path: str) -> str: + """Return ``same``, or what changed, or the error raised.""" + numbers = pa.array([1, 2], pa.int64()) + if role == "data": + left = pa.Table.from_arrays([numbers, values], names=["k", "y"]) + right = pa.Table.from_arrays( + [numbers, pa.array([0, 0], pa.int64())], names=["k", "z"] + ) + name = "y" + else: + left = pa.Table.from_arrays( + [values, pa.array([0, 1], pa.int64())], names=["k", "x"] + ) + right = pa.Table.from_arrays( + [values, pa.array([2, 3], pa.int64())], names=["k", "z"] + ) + name = "k" + streams = [ + ArrowTableStream(left, tag_columns=["k"]), + ArrowTableStream(right, tag_columns=["k"]), + ] + operator = Join() if operator_name == "Join" else SemiJoin() + try: + if path == "sync": + got = exact(operator(*streams).as_table().column(name)) + else: + got = _column_of_rows(asyncio.run(_run_async(operator, streams)), name) + except BaseException as error: # noqa: BLE001 # a Polars panic is a BaseException + while isinstance(error, BaseExceptionGroup) and len(error.exceptions) == 1: + error = error.exceptions[0] # the async path's task group + return f"ERROR {type(error).__name__}: {str(error)[:90]}" + want = exact(values) + if sorted(map(repr, got)) == sorted(map(repr, want)): + return "same" + return f"CHANGED {want} -> {got}" + + +def main() -> None: + total = exact_count = 0 + for name, values in cases().items(): + for operator_name in ("Join", "SemiJoin"): + for role in ("data", "key"): + for path in ("sync", "async"): + total += 1 + result = check(operator_name, role, values, path) + if result == "same": + exact_count += 1 + else: + print(f"{name:32} {operator_name:8} {role:4} {path:5} {result}") + print(f"{exact_count} of {total} cases exact") + + +if __name__ == "__main__": + main() diff --git a/src/orcapod/core/operators/arrow_keys.py b/src/orcapod/core/operators/arrow_keys.py new file mode 100644 index 000000000..0313d4a0b --- /dev/null +++ b/src/orcapod/core/operators/arrow_keys.py @@ -0,0 +1,308 @@ +"""Key columns prepared for Polars: the one place (ITL-1284, from ITL-1250). + +An operator that matches, groups or orders rows with Polars gives Polars only its key +columns (and row numbers), prepared here, and takes every value of its output from its +input's Arrow tables. Polars changes some Arrow types on the way in and out (a +``date64`` value comes back at midnight) and panics on others (``decimal256``: a panic +is not an error a caller can catch), so no column reaches Polars unprepared, and none +that has no rule here. + +Prepared for equality and order alike: + +* a logical type is its storage and a dictionary its values, alternately until + neither applies; +* a date, time, timestamp or duration is its integer (the unit and the zone are the + column's type, so the integers compare and order as the values do); +* a ``float16`` becomes ``float32`` (exact; the Polars this library allows may lack + ``Float16``), a string or binary view its large variant; +* a ``decimal256`` becomes its four 64-bit limbs; +* a list, large list or fixed-size list becomes a large list over its prepared values; +* a struct (matching only: ``structs=True``) a struct of its prepared children. + +Every other type (a map, an interval, a union, a list view, ...) has no rule: +``part_without_rule`` names it, and the caller refuses the column, naming it. + +``Join`` and ``SemiJoin`` use this module. ``GroupBy`` keeps its own copy until +ITL-1281 makes it import this one (its rule refuses structs: ``structs=False``). +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, cast + +from orcapod.utils.lazy_module import LazyModule + +if TYPE_CHECKING: + import numpy as np + import polars as pl + import pyarrow as pa +else: + np = LazyModule("numpy") + pl = LazyModule("polars") + pa = LazyModule("pyarrow") + + +def _is_list_kind(arrow_type: "pa.DataType") -> bool: + """Return whether a type is a list, a large list or a fixed-size list.""" + return ( + pa.types.is_list(arrow_type) + or pa.types.is_large_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + ) + + +def value_type(arrow_type: "pa.DataType") -> "pa.DataType": + """Return the type a column's values are read as. + + A logical type's storage and a dictionary's values, alternately, until neither + applies (at the top level; ``part_without_rule`` goes down). + + Args: + arrow_type: The Arrow type of a column, or of a list's or struct's values. + + Returns: + The type of the plain values. + """ + while True: + if isinstance(arrow_type, pa.BaseExtensionType): + arrow_type = arrow_type.storage_type + elif pa.types.is_dictionary(arrow_type): + arrow_type = arrow_type.value_type + else: + return arrow_type + + +def _is_prepared_scalar(arrow_type: "pa.DataType") -> bool: + """Return whether a scalar (storage) type has a rule here. + + Every integer, float, decimal, boolean, string, binary, date, time, timestamp + and duration type, and the null type. + """ + types = pa.types + return ( + types.is_null(arrow_type) + or types.is_boolean(arrow_type) + or types.is_integer(arrow_type) + or types.is_floating(arrow_type) + or types.is_decimal(arrow_type) + or types.is_string(arrow_type) + or types.is_large_string(arrow_type) + or types.is_string_view(arrow_type) + or types.is_binary(arrow_type) + or types.is_large_binary(arrow_type) + or types.is_binary_view(arrow_type) + or types.is_fixed_size_binary(arrow_type) + or types.is_date(arrow_type) + or types.is_time(arrow_type) + or types.is_timestamp(arrow_type) + or types.is_duration(arrow_type) + ) + + +def part_without_rule( + arrow_type: "pa.DataType", *, structs: bool +) -> "pa.DataType | None": + """Return the part of a key column's type this module has no rule for, or ``None``. + + The one rule for what may reach Polars, used from a schema (validation) and from + a table (before ``polars_ready``), so nothing reaches Polars unprepared. A list + of any kind goes down to its values, a struct (when ``structs``) to its + children, through logical storage and dictionary values at every depth. + + Args: + arrow_type: The Arrow type of a key column. + structs: Whether a struct is prepared (matching, field by field) or has no + rule (an order, which nobody has decided for a struct). + + Returns: + The first type found that has no rule, or ``None``. + """ + plain = value_type(arrow_type) + if _is_list_kind(plain): + lists = cast( + "pa.LargeListType[Any] | pa.ListType[Any] | pa.FixedSizeListType[Any, Any]", + plain, + ) + return part_without_rule(lists.value_type, structs=structs) + if structs and pa.types.is_struct(plain): + struct = cast("pa.StructType", plain) + for index in range(struct.num_fields): + part = part_without_rule(struct.field(index).type, structs=structs) + if part is not None: + return part + return None + return None if _is_prepared_scalar(plain) else plain + + +def _without_dictionary(array: "pa.Array[Any]") -> "pa.Array[Any]": + """Decode a dictionary-encoded array to its values; any other array as it is. + + The one place a dictionary-encoded key is decoded: the values each index points + at, bits as stored. + + Args: + array: A column, or its storage. + + Returns: + The decoded array. + """ + if isinstance(array, pa.DictionaryArray): + return array.dictionary_decode() + return array + + +def values_of(array: "pa.Array[Any]") -> "pa.Array[Any]": + """Return an array as its values are read: through logical types and dictionaries. + + The array twin of ``value_type``: a logical type's storage and a dictionary's + values, alternately, until neither applies, so a dictionary over a logical type + (or a logical type over a dictionary) is read as its type is. + + Args: + array: A column, or the values of one. + + Returns: + The array of plain values. + """ + while True: + if isinstance(array, pa.ExtensionArray): + array = array.storage + elif isinstance(array, pa.DictionaryArray): + array = _without_dictionary(array) + else: + return array + + +def _decimal256_limbs(array: "pa.Array[Any]") -> "pa.Array[Any]": + """Return a decimal256 array as a struct of four 64-bit limbs. + + Polars has no 256-bit decimal. The limbs of the two's-complement value, most + significant first (that one signed, the others unsigned), compare and order as + the decimals of one column do: the scale is part of the column's type. + + Args: + array: A ``decimal256`` array. + + Returns: + A struct array with the limbs, null where ``array`` is null. + """ + count = len(array) + nulls = array.is_null().to_numpy(zero_copy_only=False) + buffer = array.buffers()[1] + # A pyarrow Buffer has the buffer protocol; its stub does not declare it. + words = ( + np.frombuffer(buffer, dtype=" "pa.Array[Any]": + """Return a key column in a form Polars reads without changing it. + + Two prepared values are equal (and order) as the values are. Only the frame + Polars matches, groups or orders sees it; the output takes every value from the + input. Every type ``part_without_rule`` accepts is prepared (see the module). + + Args: + array: A key column, or the values of one. + + Returns: + The prepared array. + + Raises: + TypeError: For a type with no rule. A caller checks ``part_without_rule`` + first and refuses the column, naming it. + """ + array = values_of(array) + arrow_type = array.type + types = pa.types + if types.is_large_list(arrow_type) or types.is_list(arrow_type): + lists = cast("pa.LargeListArray[Any] | pa.ListArray[Any]", array) + # The offsets of a sliced array start where the slice does; Arrow refuses + # such offsets with a null mask, so they are rebased to the values used. + offsets = lists.offsets.cast(pa.int64()).to_numpy() + start = int(offsets[0]) + values = lists.values.slice(start, int(offsets[-1]) - start) + return pa.LargeListArray.from_arrays( + cast("pa.Int64Array", pa.array(offsets - start, pa.int64())), + polars_ready(values), + mask=array.is_null(), + ) + if types.is_fixed_size_list(arrow_type): + fixed = cast("pa.FixedSizeListArray[Any]", array) + size = cast(int, arrow_type.list_size) + values = fixed.values.slice(fixed.offset * size, len(fixed) * size) + offsets = pa.array(np.arange(len(fixed) + 1, dtype=np.int64) * size, pa.int64()) + return pa.LargeListArray.from_arrays( + cast("pa.Int64Array", offsets), + polars_ready(values), + mask=array.is_null(), + ) + if types.is_struct(arrow_type): + struct = cast("pa.StructArray", array) + struct_type = cast("pa.StructType", arrow_type) + return pa.StructArray.from_arrays( + [polars_ready(struct.field(i)) for i in range(struct_type.num_fields)], + names=[struct_type.field(i).name for i in range(struct_type.num_fields)], + mask=array.is_null(), + ) + if types.is_decimal256(arrow_type): + return _decimal256_limbs(array) + if types.is_float16(arrow_type): + return array.cast(pa.float32()) + if ( + types.is_date(arrow_type) + or types.is_time(arrow_type) + or types.is_timestamp(arrow_type) + or types.is_duration(arrow_type) + ): + # Not ``is_temporal``, which also takes an interval: that has no rule. + width = cast(int, arrow_type.bit_width) + return array.view(pa.int32() if width == 32 else pa.int64()) + if types.is_string_view(arrow_type): + return array.cast(pa.large_string()) + if types.is_binary_view(arrow_type): + return array.cast(pa.large_binary()) + if _is_prepared_scalar(arrow_type): + return array + raise TypeError(f"no rule prepares {arrow_type} for Polars") + + +def polars_key_frame( + table: "pa.Table", keys: Sequence[str], row: str | None = None +) -> "pl.DataFrame": + """Return a Polars frame of a table's key columns, prepared, and its row numbers. + + The frame an operator matches rows on: nothing but the prepared keys (in + ``keys`` order) and, when ``row`` is given, each row's number in ``table`` + (``int64``), by which the operator then takes its output from ``table``. + + Args: + table: The input table. + keys: The key columns, each checked with ``part_without_rule`` first. + row: The name of the row-number column, one no key has; ``None`` for none. + + Returns: + The frame. + """ + names = list(keys) + arrays = [polars_ready(table.column(name).combine_chunks()) for name in names] + if row is not None: + names.append(row) + arrays.append(pa.array(np.arange(table.num_rows, dtype=np.int64), pa.int64())) + return cast( + "pl.DataFrame", pl.from_arrow(pa.Table.from_arrays(arrays, names=names)) + ) diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index 2d1341a14..a70cb65e5 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -11,6 +11,7 @@ ) from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import data_tags_first +from orcapod.core.operators.arrow_keys import part_without_rule from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( @@ -63,6 +64,38 @@ def require_shared_arrow_type( return shared +def require_matchable_key(operator: str, name: str, arrow_type: pa.DataType) -> None: + """Raise if a join key's type has no rule for matching rows in Polars. + + The rule is ``arrow_keys.part_without_rule`` (structs allowed: a struct + matches field by field); this adds the error an operator raises for a key + column it cannot match. Called with the input tables (the sync path, also + on zero-row tables) or the first rows (an async path) before rows are + matched, so no such column reaches Polars. Not at validation: that would + derive every input's zero-row table each time a graph is built + (``tests/test_pipeline/test_graph_walk_cost.py``). + + Args: + operator: The operator's name, for the error message. + name: The key column's name, for the error message. + arrow_type: The key column's Arrow type. + + Raises: + InputValidationError: If a part of the type (at the top level, or inside + a list or a struct) has no rule, such as a map, an interval or a + union. The message names the operator, the column and the type. + """ + part = part_without_rule(arrow_type, structs=True) + if part is not None: + raise InputValidationError( + f"{operator} cannot match rows on the tag {name!r}: its type " + + f"{arrow_type} holds {part}, which has no rule for comparing values " + + "(a map, an interval, a union or a list view has none). Match on " + + "other tags: drop this one from one input " + + f"(stream.drop_tag_columns([{name!r}]))." + ) + + def require_tag_data_roles_agree( first_tags: Collection[str], first_data: Collection[str], diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index be4fa6659..1463cbe85 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -13,8 +13,10 @@ ) from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.match_keys import frozen_scalar +from orcapod.core.operators.arrow_keys import polars_key_frame from orcapod.core.operators.base import ( NonZeroInputOperator, + require_matchable_key, require_shared_arrow_type, require_tag_data_roles_agree, ) @@ -50,6 +52,11 @@ pl = LazyModule("polars") +# The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a +# key, never starts with the meta prefix ``__``. +_LEFT_ROW = "__join_left_row" +_RIGHT_ROW = "__join_right_row" + # Temporary name of the right input's source info of a merged data-tag column # during the join (``static_process``); never in an output. _MERGED_SOURCE_PREFIX = "__join_merged_source__" @@ -63,6 +70,45 @@ _PENDING_MEMBERS = "\x00join-pending-members\x00" +def _inner_join(left: "pa.Table", right: "pa.Table", keys: list[str]) -> "pa.Table": + """Inner-join two tables on their key columns, every value taken from the tables. + + Polars decides which rows match, from the prepared keys and the row numbers + only (``arrow_keys``, ITL-1284); every output column is taken from ``left`` or + ``right`` by those row numbers, so each value is the input's, bit for bit. The + layout is the one Polars' join gives: the left columns (one of each key, the + left row's value), then the right columns that are not keys, a name the left + table also has taking the suffix ``_right``. The rows are in the order of + Polars' join. + + Args: + left: The left table. + right: The right table. + keys: The key columns, in both tables, each checked by + ``require_matchable_key``. + + Returns: + The joined table. Its fields carry no flags of the inputs (every field + nullable); the caller restores them. + """ + pairs = polars_key_frame(left, keys, _LEFT_ROW).join( + polars_key_frame(right, keys, _RIGHT_ROW), on=keys, how="inner" + ) + left_rows = pairs.get_column(_LEFT_ROW).to_arrow() + right_rows = pairs.get_column(_RIGHT_ROW).to_arrow() + names: list[str] = [] + arrays: list[Any] = [] + for name in left.column_names: + names.append(name) + arrays.append(left.column(name).take(left_rows)) + for name in right.column_names: + if name in keys: + continue + names.append(f"{name}_right" if name in left.column_names else name) + arrays.append(right.column(name).take(right_rows)) + return pa.Table.from_arrays(arrays, names=names) + + def _members(token: str | None) -> list[str | None]: """The member tokens a token position holds so far (itself, if not pending).""" if token is not None and token.startswith(_PENDING_MEMBERS): @@ -429,27 +475,24 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: next_table = next_table.rename_columns( [right_source.get(c, c) for c in next_table.column_names] ) - # Polars sets every field nullable; capture the schema before the join. + # The joined table is built from arrays, with no field flags; capture + # the schemas before the join. next_ref_schema = next_table.schema # A shared tag key must have one Arrow type in both inputs (up to - # layout); otherwise Polars would join and keep one side's type. + # layout); otherwise Polars would join and keep one side's type. And + # it must be a type Polars can be given (``arrow_keys``). for key in sorted(common_tag_keys): - _ = require_shared_arrow_type( + key_type = require_shared_arrow_type( "Join", key, arrow_utils.column_arrow_type(table.schema, key), arrow_utils.column_arrow_type(next_table.schema, key), ) + require_matchable_key("Join", key, key_type) common_tag_keys.add(COMMON_JOIN_KEY) - # Capture the left-side schema before the Polars join, which sets all - # fields to nullable=True regardless of the original schema. table_ref_schema = table.schema - table = ( - pl.DataFrame(table) - .join(pl.DataFrame(next_table), on=list(common_tag_keys), how="inner") - .to_arrow() - ) + table = _inner_join(table, next_table, list(common_tag_keys)) table = arrow_utils.restore_schema_nullability( table, table_ref_schema, next_ref_schema ) @@ -953,8 +996,9 @@ def _check_shared_key_types( ) -> None: """Raise if a shared tag key has disagreeing Arrow types in two inputs. - The async counterpart of the check ``static_process`` runs on the input - tables before its join, applied to the first row of each side. + The async counterpart of the checks ``static_process`` runs on the input + tables before its join, applied to the first row of each side: one Arrow + type in both, and one the sync join can match on. Args: first: A tag from one input. @@ -963,16 +1007,18 @@ def _check_shared_key_types( Raises: InputValidationError: If a key's large-normalized Arrow types differ - (``require_shared_arrow_type``). + (``require_shared_arrow_type``), or its type has no rule for + matching (``require_matchable_key``). """ first_schema, second_schema = first.arrow_schema(), second.arrow_schema() for key in keys: - _ = require_shared_arrow_type( + key_type = require_shared_arrow_type( "Join", key, arrow_utils.column_arrow_type(first_schema, key), arrow_utils.column_arrow_type(second_schema, key), ) + require_matchable_key("Join", key, key_type) @staticmethod async def _rename_sys_tags( diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index 0b671596b..26dc27734 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -8,7 +8,12 @@ from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.core.data_tags import stream_data_tags -from orcapod.core.operators.base import BinaryOperator, require_shared_arrow_type +from orcapod.core.operators.arrow_keys import polars_key_frame +from orcapod.core.operators.base import ( + BinaryOperator, + require_matchable_key, + require_shared_arrow_type, +) from orcapod.core.operators.key_nullability import reconcile_key_nullability from orcapod.core.operators.match_keys import frozen_scalar from orcapod.core.streams import ArrowTableStream @@ -29,6 +34,10 @@ pc = LazyModule("pyarrow.compute") pl = LazyModule("polars") +# The row-number column of the left frame Polars matches; a tag, so a key, never +# starts with the meta prefix ``__``. +_LEFT_ROW = "__semi_join_left_row" + class SemiJoin(BinaryOperator): """ @@ -201,14 +210,16 @@ def binary_static_process( right_table = right_stream.as_table().select(list(common_keys)) # A key must have one Arrow type on both sides (up to large layouts); - # otherwise Polars would silently unify, e.g., int8 with int16. + # otherwise Polars would silently unify, e.g., int8 with int16. And it + # must be a type Polars can be given (``arrow_keys``). for key in common_keys: - _ = require_shared_arrow_type( + key_type = require_shared_arrow_type( "SemiJoin", key, arrow_utils.column_arrow_type(left_table.schema, key), arrow_utils.column_arrow_type(right_table.schema, key), ) + require_matchable_key("SemiJoin", key, key_type) # Only the right side's keys take part. A null key never matches: # Polars already applies that to scalar keys but treats a null struct or @@ -219,23 +230,18 @@ def binary_static_process( valid = pc.and_(valid, right_keys.column(index).is_valid()) right_keys = right_keys.filter(valid) - # Polars, unlike Arrow's hash join, accepts nested (list, struct, - # struct-backed logical) columns as keys and as passed-through columns, - # and matches a string key against a large_string one. - semi_joined_table = ( - pl.DataFrame(left_table) - .join( - pl.DataFrame(right_keys), - on=list(common_keys), - how="semi", - maintain_order="left", - ) - .to_arrow() + # Polars, unlike Arrow's hash join, accepts nested (list, struct) keys. + # It decides which left rows match from the prepared keys and the left + # row numbers only (``arrow_keys``, ITL-1284); the kept rows are taken + # from the left table, so every value and field is the input's, bit for + # bit, in the left input's order. + kept = polars_key_frame(left_table, common_keys, _LEFT_ROW).join( + polars_key_frame(right_keys, common_keys), + on=list(common_keys), + how="semi", + maintain_order="left", ) - # The round-trip yields large layouts, nullable fields at every depth and - # Polars' own types; give every column back the left input's exact field - # (type, top-level and nested nullability, logical type). - semi_joined_table = semi_joined_table.cast(left_table.schema) + semi_joined_table = left_table.take(kept.get_column(_LEFT_ROW).to_arrow()) return ArrowTableStream( semi_joined_table, @@ -269,6 +275,10 @@ def validate_binary_inputs( Stores the common keys so that ``async_execute`` can use them to determine the correct empty-right behavior without data. + Raises: + InputValidationError: If a match key's types differ beyond + nullability. + Warns: SemiJoinIgnoredColumnWarning: Once per operator and set of names, when the inputs share a name that is not a tag on both sides (ITL-1088). @@ -387,12 +397,13 @@ async def async_execute( right_tag, right_data = right_rows[0] for key in common_keys: - _ = require_shared_arrow_type( + key_type = require_shared_arrow_type( "SemiJoin", key, self._key_arrow_type(tag, data, key), self._key_arrow_type(right_tag, right_data, key), ) + require_matchable_key("SemiJoin", key, key_type) # Build right-side lookup; a row with a null key never matches. for rt, rp in right_rows: diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 123daaa06..0af7408b5 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -14,6 +14,7 @@ from __future__ import annotations import asyncio +import decimal import re from collections.abc import Callable, Sequence from dataclasses import dataclass @@ -239,6 +240,40 @@ def source_shared_data() -> ArrowTableSource: ) +def source_exact( + source_id: str, offset: int, with_data_tags: bool = False +) -> ArrowTableSource: + """Tags ``k: date64`` (off midnight) and ``kd: decimal256``; data of both, in a + list and in a struct (ITL-1284): the sync ``Join`` and ``SemiJoin`` used to + move a ``date64`` to midnight and panic on ``decimal256``.""" + dates = pa.array([1, 86_400_001, 2], pa.int64()).cast(pa.date64()) + decimals = pa.array( + [decimal.Decimal(f"{n}.{offset + n:040d}") for n in range(3)], + pa.decimal256(76, 40), + ) + lists = pa.LargeListArray.from_arrays(pa.array([0, 1, 2, 3], pa.int64()), decimals) + return _source( + { + "k": dates, + "kd": pa.array( + [decimal.Decimal(f"0.{n:040d}") for n in (1, 2, 3)], + pa.decimal256(76, 40), + ), + f"date_{source_id}": pa.array( + [1 + offset, 86_400_001 + offset, 3], pa.int64() + ).cast(pa.date64()), + f"dec_{source_id}": decimals, + f"list_{source_id}": lists, + f"struct_{source_id}": pa.StructArray.from_arrays( + [dates, decimals], names=["a", "b"] + ), + }, + tags=("k", "kd"), + source_id=source_id, + with_data_tags=with_data_tags, + ) + + def merge_source( source_id: str, offset: int, with_data_tags: bool = False ) -> ArrowTableSource: @@ -408,6 +443,26 @@ class Case: SemiJoin, lambda: (source_b(nested=False), source_shared_data()), ), + # Values Polars changed or could not read on the sync path (ITL-1284). + Case( + "join_exact_values", + Join, + lambda: (source_exact("e", 0), source_exact("f", 5)), + ), + Case( + "join_3_exact_values_data_tags", + Join, + lambda: ( + source_exact("e", 0, with_data_tags=True), + source_exact("f", 5, with_data_tags=True), + source_exact("g", 9, with_data_tags=True), + ), + ), + Case( + "semijoin_exact_values", + SemiJoin, + lambda: (source_exact("e", 0, with_data_tags=True), source_exact("f", 5)), + ), Case("batch_2", lambda: Batch(batch_size=2), lambda: (source_a(),)), Case("batch_all", Batch, lambda: (source_a(),)), Case("group_by", lambda: GroupBy(["ta"]), lambda: (source_a(),)), @@ -964,6 +1019,11 @@ def _zero_row_cases() -> list[Any]: """Every case with all inputs empty, and each multi-input case with one input empty.""" params: list[Any] = [] for case in CASES: + if "exact_values" in case.label: + # ``no_rows`` filters with ``PolarsFilter``, which carries every column + # through Polars and panics on ``decimal256``; these cases' zero-row + # inputs are tested in ``test_join_arrow_values.py``. + continue n_inputs = len(case.make_sources()) empty_sets = [tuple(range(n_inputs))] if n_inputs > 1: diff --git a/tests/test_core/operators/test_join_arrow_values.py b/tests/test_core/operators/test_join_arrow_values.py new file mode 100644 index 000000000..545477211 --- /dev/null +++ b/tests/test_core/operators/test_join_arrow_values.py @@ -0,0 +1,670 @@ +"""``Join`` and ``SemiJoin`` emit every value of their input bit for bit (ITL-1284). + +The sync path used to carry every column through Polars and back: a ``date64`` value +off midnight came back at midnight (as data, as a key, in a list, in a struct), and a +``decimal256`` column made Polars panic (an error no caller can catch). Now Polars only +decides which rows match, from the prepared keys (``arrow_keys``) and row numbers, and +every output column is taken from the input tables. + +Each type below is a key and a data column at once, with a second key and a second +data column (an ``int64`` tag, a ``large_string`` data column), in plain-tag, data-tag +and mixed roles and in two tag orders, on the sync and the async path, for two and +three ``Join`` inputs and for ``SemiJoin``. Keys repeat on both sides (many to many), +and a null key matches nothing. Values are compared exactly: temporal values as their +integers, floats as their bits, decimals as text, logical types through their storage, +lists and structs element by element. +""" + +from __future__ import annotations + +import decimal +import uuid +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any, TypeAlias, cast + +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.core.operators import Join, SemiJoin +from orcapod.core.operators.arrow_keys import ( + part_without_rule, + polars_key_frame, + polars_ready, +) +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError +from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol + +from .several_items import async_rows, ordered_rows_fingerprint + +Column: TypeAlias = "pa.Array[Any]" +Row: TypeAlias = "tuple[TagProtocol, DataProtocol]" +D = decimal.Decimal +CONTEXT = get_default_context() + +PLAIN, DATA_TAGS, MIXED = "plain", "data_tags", "mixed" +ROLES = (PLAIN, DATA_TAGS, MIXED) + + +# ── 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]] if lists[i].is_valid else None + for i in range(len(lists)) + ] + if pa.types.is_fixed_size_list(arrow_type): + return _exact(array.cast(pa.large_list(arrow_type.value_type))) + 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) if struct[j].is_valid else None + 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_map(arrow_type) or pa.types.is_interval(arrow_type): + return [repr(value) for value in array.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 [None if value is None else str(value) for value in array.to_pylist()] + return array.to_pylist() + + +def _ints(values: list[int | None], arrow_type: pa.DataType) -> Column: + return pa.array(values, pa.int64()).cast(arrow_type) + + +def _floats(bits: list[int | None], 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 _dec(units: int, tiny: int) -> D: + """``units`` plus ``tiny`` at the 40th decimal place, built from text.""" + sign = "-" if units < 0 else "" + return D(f"{sign}{abs(units)}.{tiny:040d}") + + +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 _list_of(values: Column) -> Column: + """One one-element large list per value; a null value gives a null list.""" + offsets = pa.array(range(len(values) + 1), pa.int64()) + return pa.LargeListArray.from_arrays(offsets, values, mask=values.is_null()) + + +DEC256 = pa.decimal256(76, 40) + + +def _date64(values: list[int | None]) -> Column: + return _ints(values, pa.date64()) + + +def _decimal256(values: list[tuple[int, int] | None]) -> Column: + return pa.array([None if v is None else _dec(*v) for v in values], DEC256) + + +# Each builder gives four distinct values for a list of indices 0 to 3 (``None``: null). +Builder: TypeAlias = Callable[[list[int | None]], Column] + + +def _pick(values: list[Any]) -> Callable[[list[int | None]], list[Any]]: + return lambda indices: [None if i is None else values[i] for i in indices] + + +DATE64 = _pick([1, 86_400_001, 2, 86_400_002]) +DECIMALS = _pick([(1, 1), (1, 2), (-3, 1), (0, 7)]) + +AFFECTED: dict[str, Builder] = { + "date64 off midnight": lambda ix: _date64(DATE64(ix)), + "decimal256(76,40)": lambda ix: _decimal256(DECIMALS(ix)), + "large_list": lambda ix: _list_of(_date64(DATE64(ix))), + "large_list": lambda ix: _list_of(_decimal256(DECIMALS(ix))), + "struct": lambda ix: pa.StructArray.from_arrays( + [_date64(DATE64(ix)), _decimal256(DECIMALS(ix))], + names=["a", "b"], + mask=pa.array([i is None for i in ix], pa.bool_()), + ), + "fixed_size_list": lambda ix: pa.FixedSizeListArray.from_arrays( + _decimal256([DECIMALS(ix)[k] or (0, 0) for k in range(len(ix))]), + 1, + mask=pa.array([i is None for i in ix], pa.bool_()), + ), +} + +EXACT_ON_MAIN: dict[str, Builder] = { + "time64[ns]": lambda ix: _ints( + _pick([1, 1001, 2, 1_000_000_001])(ix), pa.time64("ns") + ), + "float32 signaling NaN": lambda ix: _floats( + _pick([0x7F800001, 0x3F800000, 0x40000000, 0xC0000000])(ix), 32 + ), + "float16 -0.0": lambda ix: _floats(_pick([0x8000, 0x3C00, 0x4000, 0x7E01])(ix), 16), + "uint64 max": lambda ix: pa.array(_pick([2**64 - 1, 0, 1, 2**63])(ix), pa.uint64()), + "fixed_size_binary(3)": lambda ix: pa.array( + _pick([b"abc", b"\x00\x00\x00", b"abd", b"\xff\x00\x01"])(ix), pa.binary(3) + ), + "timestamp[ns, America/New_York]": lambda ix: _ints( + _pick([1, 1001, -5, 1_700_000_000_000_000_001])(ix), + pa.timestamp("ns", "America/New_York"), + ), + "duration[ns]": lambda ix: _ints(_pick([1, 1001, -1, 7])(ix), pa.duration("ns")), + "decimal128(38,10)": lambda ix: pa.array( + _pick([D("1.0000000001"), D("-2"), D("0.0000000002"), D("3")])(ix), + pa.decimal128(38, 10), + ), + "logical Path": lambda ix: _logical(Path, _pick(["a", "b", "c", "é"])(ix)), + "logical UUID": lambda ix: _logical( + uuid.UUID, _pick([uuid.UUID(int=n).bytes for n in (1, 2, 3, 4)])(ix) + ), +} + +TYPES = {**AFFECTED, **EXACT_ON_MAIN} +TYPE = pytest.mark.parametrize("type_name", list(TYPES)) + + +# ── inputs ─────────────────────────────────────────────────────────────────── + + +def _source( + columns: dict[str, Column], + tags: Sequence[str], + roles: str, + source_id: str, +) -> ArrowTableSource: + """A source of ``columns`` with ``tags`` (in this order) in ``roles``. + + A column is nullable exactly when it holds a null. + """ + schema = pa.schema( + pa.field(name, column.type, nullable=column.null_count > 0) + for name, column in columns.items() + ) + table = pa.Table.from_arrays(list(columns.values()), schema=schema) + tag_only: bool | list[str] + if roles == PLAIN: + tag_only = True + elif roles == DATA_TAGS: + tag_only = [] + else: + tag_only = [tags[-1]] + return ArrowTableSource( + table, + tag_columns=list(tags), + source_id=source_id, + tag_only_columns=tag_only, + ) + + +def _side( + build: Builder, + keys: list[int | None], + numbers: list[int], + name: str, + roles: str, + tag_order: tuple[str, ...], + values: list[int | None], +) -> ArrowTableSource: + """One input: tags ``k`` (the type) and ``n`` (``int64``); data of the type and + a ``large_string``, named after the input so no two inputs share a data column. + + The table interleaves tags and data, the tags in ``tag_order``. (A table whose + tags are laid out in another order than ``tag_columns`` gives the sync and the + async path different tag column orders, on ``main`` too: not this issue.)""" + tag_values = {"k": build(keys), "n": pa.array(numbers, pa.int64())} + columns = { + f"x_{name}": build(values), + tag_order[0]: tag_values[tag_order[0]], + f"s_{name}": pa.array( + [f"{name}{i}" for i in range(len(keys))], pa.large_string() + ), + tag_order[1]: tag_values[tag_order[1]], + } + return _source(columns, tag_order, roles, name) + + +# Left rows: (k, n); the data of each row is its own index, so each output row shows +# which input rows it came from. Keys repeat on both sides: many to many. +LEFT_KEYS: list[int | None] = [0, 1, 1, 2, None] +LEFT_NUMBERS = [1, 1, 1, 2, 1] +RIGHT_KEYS: list[int | None] = [1, 3, 1, 2, None] +RIGHT_NUMBERS = [1, 1, 1, 2, 1] +# (left row, right row) pairs that match: k and n equal, never on a null key. +MATCHES = {(1, 0), (1, 2), (2, 0), (2, 2), (3, 3)} + +TAG_ORDERS = (("k", "n"), ("n", "k")) + + +def _left(build: Builder, roles: str, tag_order: tuple[str, ...]) -> ArrowTableSource: + values: list[int | None] = [0, 1, 2, 3, 0] + return _side(build, LEFT_KEYS, LEFT_NUMBERS, "l", roles, tag_order, values) + + +def _right(build: Builder, roles: str, tag_order: tuple[str, ...]) -> ArrowTableSource: + values: list[int | None] = [3, 2, 1, 0, 1] + return _side(build, RIGHT_KEYS, RIGHT_NUMBERS, "r", roles, tag_order, values) + + +def _third(build: Builder, roles: str) -> ArrowTableSource: + """A third ``Join`` input: tag ``k`` only, rows for key values 1 and 2.""" + columns = { + "k": build([1, 2, 1]), + "x_t": build([2, 3, 0]), + "s_t": pa.array(["t0", "t1", "t2"], pa.large_string()), + } + return _source(columns, ("k",), roles, "t") + + +def _rows_of(stream: StreamProtocol) -> list[Row]: + return list(stream.iter_data()) + + +def _exact_rows(rows: Sequence[Row], names: Sequence[str]) -> list[tuple[str, ...]]: + """Each row's values of ``names``, exactly, read from its Arrow tables; sorted.""" + out: list[tuple[str, ...]] = [] + for tag, data in rows: + tag_table, data_table = tag.as_table(), data.as_table() + out.append( + tuple( + repr( + _exact( + ( + tag_table if name in tag_table.column_names else data_table + ).column(name) + ) + ) + for name in names + ) + ) + return sorted(out) + + +# ── Join, two inputs ───────────────────────────────────────────────────────── + + +@TYPE +@pytest.mark.parametrize("roles", ROLES) +@pytest.mark.parametrize("tag_order", TAG_ORDERS) +def test_join_emits_every_value_exactly( + type_name: str, roles: str, tag_order: tuple[str, ...] +) -> None: + """Keys and data of the type, on both inputs, come out bit for bit, sync and + async; the async rows equal the sync rows.""" + build = TYPES[type_name] + left, right = _left(build, roles, tag_order), _right(build, roles, tag_order) + names = ["k", "n", "x_l", "s_l", "x_r", "s_r"] + left_values: list[int | None] = [0, 1, 2, 3, 0] + right_values: list[int | None] = [3, 2, 1, 0, 1] + want = sorted( + ( + repr(_exact(build([LEFT_KEYS[li]]))), + repr([LEFT_NUMBERS[li]]), + repr(_exact(build([left_values[li]]))), + repr([f"l{li}"]), + repr(_exact(build([right_values[ri]]))), + repr([f"r{ri}"]), + ) + for li, ri in MATCHES + ) + sync = _rows_of(Join()(left, right)) + asynchronous = async_rows(Join(), left, right) + assert _exact_rows(sync, names) == want + assert _exact_rows(asynchronous, names) == want + assert ordered_rows_fingerprint(asynchronous) == ordered_rows_fingerprint(sync) + + +@TYPE +def test_join_table_columns_are_the_inputs_values(type_name: str) -> None: + """The sync table itself (not only its rows) holds the input's values and types.""" + build = TYPES[type_name] + left, right = _left(build, PLAIN, ("k", "n")), _right(build, PLAIN, ("k", "n")) + table = Join()(left, right).as_table() + assert table.schema.field("k").type == left.as_table().schema.field("k").type + assert table.schema.field("x_l").type == left.as_table().schema.field("x_l").type + assert table.schema.field("x_r").type == right.as_table().schema.field("x_r").type + assert table.num_rows == len(MATCHES) + assert sorted(map(repr, _exact(table.column("x_l")))) == sorted( + repr(_exact(build([[0, 1, 2, 3, 0][li]]))[0]) for li, _ in MATCHES + ) + + +@TYPE +@pytest.mark.parametrize("roles", ROLES) +def test_three_inputs_join_exactly_in_every_order(type_name: str, roles: str) -> None: + """Three inputs, in two argument orders: one result, every value exact, sync and + async alike.""" + build = TYPES[type_name] + left, right = _left(build, roles, ("k", "n")), _right(build, roles, ("n", "k")) + third = _third(build, roles) + names = ["k", "n", "x_l", "s_l", "x_r", "s_r", "x_t", "s_t"] + results = [] + for order in ((left, right, third), (third, right, left)): + sync = _rows_of(Join()(*order)) + asynchronous = async_rows(Join(), *order) + assert _exact_rows(asynchronous, names) == _exact_rows(sync, names) + assert ordered_rows_fingerprint(asynchronous) == ordered_rows_fingerprint(sync) + results.append(_exact_rows(sync, names)) + assert results[0] == results[1] + # Third rows: k=1 (twice: t0, t2) and k=2 (t1). Left/right pairs on k=1 are four, + # on k=2 one: 4 * 2 + 1 * 1 rows. + assert len(results[0]) == 9 + third_keys = {0: 1, 1: 2, 2: 1} + want_x_t = sorted( + repr(_exact(build([[2, 3, 0][t]]))) + for li, _ in MATCHES + for t in third_keys + if third_keys[t] == LEFT_KEYS[li] + ) + assert sorted(row[6] for row in results[0]) == want_x_t + + +# ── SemiJoin ───────────────────────────────────────────────────────────────── + + +@TYPE +@pytest.mark.parametrize("roles", ROLES) +@pytest.mark.parametrize("tag_order", TAG_ORDERS) +def test_semi_join_emits_every_value_exactly( + type_name: str, roles: str, tag_order: tuple[str, ...] +) -> None: + """The kept left rows are the input's, bit for bit, in the left input's order; + the async rows equal the sync rows.""" + build = TYPES[type_name] + left, right = _left(build, roles, tag_order), _right(build, roles, tag_order) + kept = sorted({li for li, _ in MATCHES}) + stream = SemiJoin()(left, right) + table = stream.as_table() + want = left.as_table().take(kept) + for name in ("k", "n", "x_l", "s_l"): + assert table.schema.field(name) == want.schema.field(name) + assert _exact(table.column(name)) == _exact(want.column(name)) + names = ["k", "n", "x_l", "s_l"] + sync = _rows_of(stream) + asynchronous = async_rows(SemiJoin(), left, right) + assert _exact_rows(asynchronous, names) == _exact_rows(sync, names) + assert ordered_rows_fingerprint(asynchronous) == ordered_rows_fingerprint(sync) + + +# ── null keys, no match, zero rows ─────────────────────────────────────────── + + +@TYPE +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_a_null_key_matches_nothing( + type_name: str, operator: Callable[[], Join | SemiJoin] +) -> None: + """Row 4 of each side has a null ``k`` and equal ``n``: it matches nothing.""" + build = TYPES[type_name] + left, right = _left(build, PLAIN, ("k", "n")), _right(build, PLAIN, ("k", "n")) + for rows in ( + _rows_of(operator()(left, right)), + async_rows(operator(), left, right), + ): + assert all(tag.as_table().column("k").null_count == 0 for tag, _ in rows) + assert "['l4']" not in { + repr(_exact(data.as_table().column("s_l"))) for _, data in rows + } + + +@TYPE +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_no_match_keeps_the_types( + type_name: str, operator: Callable[[], Join | SemiJoin] +) -> None: + """No key matches: zero rows, with the inputs' Arrow types.""" + build = TYPES[type_name] + left = _side(build, [0, 1], [1, 1], "l", PLAIN, ("k", "n"), [0, 1]) + right = _side(build, [2, 3], [1, 1], "r", PLAIN, ("k", "n"), [2, 3]) + table = operator()(left, right).as_table() + assert table.num_rows == 0 + for name in ("k", "x_l"): + assert table.schema.field(name).type == left.as_table().schema.field(name).type + assert async_rows(operator(), left, right) == [] + + +@TYPE +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_zero_row_inputs_keep_the_types( + type_name: str, operator: Callable[[], Join | SemiJoin] +) -> None: + """Inputs with no rows give zero rows with the inputs' Arrow types.""" + build = TYPES[type_name] + + def empty(name: str) -> ArrowTableStream: + table = pa.Table.from_arrays( + [ + build([]), + pa.array([], pa.int64()), + build([]), + pa.array([], pa.large_string()), + ], + names=["k", "n", f"x_{name}", f"s_{name}"], + ) + return ArrowTableStream(table, tag_columns=["k", "n"]) + + left, right = empty("l"), empty("r") + table = operator()(left, right).as_table() + assert table.num_rows == 0 + for name in ("k", "x_l"): + assert table.schema.field(name).type == left.as_table().schema.field(name).type + + +# ── key types with no rule ─────────────────────────────────────────────────── + +NO_RULE: dict[str, Column] = { + "map": pa.array( + [[("a", 1)], [("b", 2)]], pa.map_(pa.large_string(), pa.int64()) + ), + "month_day_nano_interval": pa.array( + [(1, 2, 3), (4, 5, 6)], pa.month_day_nano_interval() + ), + "dense_union": pa.UnionArray.from_dense( + pa.array([0, 1], pa.int8()), + pa.array([0, 0], pa.int32()), + [pa.array([1], pa.int64()), pa.array(["a"], pa.large_string())], + ), + "large_list": _list_of( + pa.array([[("a", 1)], [("b", 2)]], pa.map_(pa.large_string(), pa.int64())) + ), + "struct": pa.StructArray.from_arrays( + [pa.array([(1, 2, 3), (4, 5, 6)], pa.month_day_nano_interval())], names=["a"] + ), +} +NO_RULE_CASE = pytest.mark.parametrize("type_name", list(NO_RULE)) + + +def _no_rule_streams(type_name: str) -> tuple[ArrowTableStream, ArrowTableStream]: + """Two raw streams sharing tags ``n`` and ``k`` (the type with no rule).""" + key = NO_RULE[type_name] + numbers = pa.array([1, 2], pa.int64()) + + def side(data: str) -> ArrowTableStream: + table = pa.Table.from_arrays( + [numbers, key, pa.array([0, 1], pa.int64()), pa.array(["a", "b"])], + names=["n", "k", data, f"s_{data}"], + ) + return ArrowTableStream(table, tag_columns=["n", "k"]) + + return side("x"), side("y") + + +@NO_RULE_CASE +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_a_key_type_with_no_rule_is_refused_naming_the_column( + type_name: str, operator: Callable[[], Join | SemiJoin] +) -> None: + """Refused by the sync path before rows are matched, with an + ``InputValidationError`` naming the column and its type; also when the stream + is read with no rows (``head()``'s zero-row tables go through the same path).""" + left, right = _no_rule_streams(type_name) + name = type(operator()).__name__ + with pytest.raises( + InputValidationError, match=f"{name} cannot match rows on the tag 'k'" + ): + _ = operator()(left, right).as_table() + no_rows = [ + ArrowTableStream(stream.as_table().slice(0, 0), tag_columns=["n", "k"]) + for stream in (left, right) + ] + with pytest.raises(InputValidationError, match="'k'"): + _ = operator()(*no_rows).as_table() + + +@NO_RULE_CASE +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_a_key_type_with_no_rule_is_refused_on_the_async_path( + type_name: str, operator: Callable[[], Join | SemiJoin] +) -> None: + """The async path, which validation does not precede here, refuses it too.""" + left, right = _no_rule_streams(type_name) + with pytest.raises((InputValidationError, ExceptionGroup)) as caught: + _ = async_rows(operator(), left, right) + error: BaseException = caught.value + while isinstance(error, BaseExceptionGroup) and len(error.exceptions) == 1: + error = error.exceptions[0] + assert isinstance(error, InputValidationError) + assert "'k'" in str(error) + + +@NO_RULE_CASE +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_a_data_column_of_a_type_with_no_rule_passes_through( + type_name: str, operator: Callable[[], Join | SemiJoin] +) -> None: + """Only keys reach Polars: a data column of any type is taken as it is.""" + column = NO_RULE[type_name] + numbers = pa.array([1, 2], pa.int64()) + left = ArrowTableStream( + pa.Table.from_arrays( + [numbers, column, pa.array(["a", "b"])], names=["n", "x", "s"] + ), + tag_columns=["n"], + ) + right = ArrowTableStream( + pa.Table.from_arrays([numbers, pa.array([5, 6], pa.int64())], names=["n", "y"]), + tag_columns=["n"], + ) + table = operator()(left, right).as_table() + assert table.schema.field("x").type == column.type + assert _exact(table.column("x")) == _exact(column) + rows = async_rows(operator(), left, right) + assert [repr(_exact(d.as_table().column("x"))) for _, d in rows] == [ + repr(_exact(column.slice(i, 1))) for i in range(2) + ] + + +# ── the preparation itself ─────────────────────────────────────────────────── + +PREPARED_TYPES: dict[str, Column] = { + **{name: build([0, 1, None, 0]) for name, build in TYPES.items()}, + "dictionary": pa.array(["a", "b", None, "a"]).dictionary_encode(), + "string_view": pa.array(["a", "b", None, "a"], pa.string_view()), + "binary_view": pa.array([b"a", b"b", None, b"a"], pa.binary_view()), + "null": pa.array([None] * 4, pa.null()), + "large_list>": _list_of( + _list_of(_ints([1, 2, None, 1], pa.time64("ns"))) + ), +} + + +@pytest.mark.parametrize("type_name", list(PREPARED_TYPES)) +def test_a_prepared_key_matches_as_its_values_do(type_name: str) -> None: + """Rows 0 and 3 of each column hold one value, row 1 another, row 2 a null. + Polars, given the prepared column, matches exactly the rows whose values are + equal (compared here independently, as exact values), so a preparation that + merged or split values would fail. A sliced column is prepared as its slice, + and the rule and the preparation agree.""" + column = PREPARED_TYPES[type_name] + assert part_without_rule(column.type, structs=True) is None + prepared = polars_ready(column) + assert len(prepared) == len(column) + sliced = polars_ready(column.slice(1, 3)) + assert _exact(sliced) == _exact(prepared.slice(1, 3)) + frame = polars_key_frame(pa.table({"k": column}), ["k"], "row") + assert frame.get_column("row").to_list() == [0, 1, 2, 3] + values = _exact(column) + # A null key never matches in the operators (``Join`` keys on a constant column + # too, ``SemiJoin`` drops null right keys); here only non-null rows are compared. + present = [i for i, value in enumerate(values) if value is not None] + pairs = frame.join(frame, on="k", how="inner", suffix="_other") + matched = { + (int(left), int(right)) + for left, right in zip( + pairs.get_column("row").to_list(), pairs.get_column("row_other").to_list() + ) + if left in present and right in present + } + assert matched == { + (i, j) for i in present for j in present if repr(values[i]) == repr(values[j]) + } + if present: + assert matched >= {(0, 3), (3, 0)} + assert (0, 1) not in matched + + +@pytest.mark.parametrize("type_name", list(NO_RULE)) +def test_the_rule_and_the_preparation_refuse_alike(type_name: str) -> None: + column = NO_RULE[type_name] + assert part_without_rule(column.type, structs=True) is not None + with pytest.raises(TypeError, match="no rule prepares"): + _ = polars_ready(column) + + +def test_a_struct_has_a_rule_for_matching_only() -> None: + """A struct matches field by field; it has no order (``structs=False``).""" + struct_type = pa.struct([("a", pa.date64()), ("b", DEC256)]) + assert part_without_rule(struct_type, structs=True) is None + assert part_without_rule(struct_type, structs=False) == struct_type + assert part_without_rule(pa.large_list(struct_type), structs=False) == struct_type + + +@pytest.mark.parametrize("operator", [Join, SemiJoin]) +def test_a_sliced_input_with_null_list_keys_joins( + operator: Callable[[], Join | SemiJoin], +) -> None: + """A table that is a slice of another, with a null list key: matched as the + unsliced rows would be. (The stream rebuilds a sliced column; a sliced array + given to ``polars_ready`` directly is tested above.)""" + keys = _list_of(_date64([1, 86_400_001, None, 2, 86_400_001])) + whole = pa.Table.from_arrays( + [keys, pa.array([0, 1, 2, 3, 4], pa.int64())], names=["k", "x"] + ) + left = ArrowTableStream(whole.slice(1), tag_columns=["k"]) + right = ArrowTableStream( + pa.Table.from_arrays( + [_list_of(_date64([86_400_001, None])), pa.array([7, 8], pa.int64())], + names=["k", "y"], + ), + tag_columns=["k"], + ) + table = operator()(left, right).as_table() + assert sorted(_exact(table.column("x"))) == [1, 4] + assert _exact(table.column("k")) == [[86_400_001], [86_400_001]]