From 77c74193684d390a705f0310ba316010c8cc80b3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 14:13:36 -0800 Subject: [PATCH 1/7] fix(merge_join, batch): build lists from Arrow arrays; MergeJoin is ordered (ITL-1281) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/arrow_keys.py | 9 +- src/orcapod/core/operators/batch.py | 107 ++++--- src/orcapod/core/operators/group_by.py | 257 +-------------- src/orcapod/core/operators/merge_join.py | 386 +++++++++-------------- 4 files changed, 227 insertions(+), 532 deletions(-) diff --git a/src/orcapod/core/operators/arrow_keys.py b/src/orcapod/core/operators/arrow_keys.py index 0313d4a0b..8328f8b1a 100644 --- a/src/orcapod/core/operators/arrow_keys.py +++ b/src/orcapod/core/operators/arrow_keys.py @@ -22,8 +22,9 @@ 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``). +``Join``, ``SemiJoin``, ``MergeJoin`` (through ``Join``'s inner join) and ``GroupBy`` +use this module; ``GroupBy``'s rule refuses structs (``structs=False``: a struct has +no decided order). """ from __future__ import annotations @@ -43,7 +44,7 @@ pa = LazyModule("pyarrow") -def _is_list_kind(arrow_type: "pa.DataType") -> bool: +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) @@ -119,7 +120,7 @@ def part_without_rule( The first type found that has no rule, or ``None``. """ plain = value_type(arrow_type) - if _is_list_kind(plain): + if is_list_kind(plain): lists = cast( "pa.LargeListType[Any] | pa.ListType[Any] | pa.FixedSizeListType[Any, Any]", plain, diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 87938641e..599543d93 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Any, ClassVar, TYPE_CHECKING +from typing import Any, ClassVar, TYPE_CHECKING, cast from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -15,11 +15,11 @@ from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import polars as pl + import numpy as np import pyarrow as pa else: + np = LazyModule("numpy") pa = LazyModule("pyarrow") - pl = LazyModule("polars") from orcapod.types import Schema @@ -68,6 +68,29 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: """ return None + def _batch_sizes(self, row_count: int) -> list[int]: + """Return the number of members of each batch, in row order. + + Batches are consecutive rows: ``batch_size`` rows each (``0``: every row + in one batch), a last batch with fewer rows kept unless + ``drop_partial_batch``. + + Args: + row_count: The number of input rows. + + Returns: + One size per batch; their sum is the number of rows kept. + """ + if row_count == 0: + return [] + if self.batch_size == 0: + return [] if self.drop_partial_batch else [row_count] + full, rest = divmod(row_count, self.batch_size) + sizes = [self.batch_size] * full + if rest and not self.drop_partial_batch: + sizes.append(rest) + return sizes + def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """Group rows into fixed-size batches, list-wrapping their values. @@ -77,6 +100,11 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: columns are folded to a scalar instead -- record identity hashes them directly, so they must not become lists. + The lists are built from the input's Arrow arrays (the members are + consecutive rows, so each list is a slice; ITL-1281): every value is the + input's, bit for bit, for every Arrow type, and every list of a row is + parallel by member, in the input's row order. + Args: stream: The upstream stream. @@ -87,46 +115,43 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_columns, _ = stream.keys() - system_tag_columns = tuple( - c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) + sizes = self._batch_sizes(table.num_rows) + offsets = cast( + "pa.Int64Array", + pa.array( + np.concatenate([[0], np.cumsum(sizes, dtype=np.int64)]), pa.int64() + ), ) - member_columns = tuple( - c for c in table.column_names if c not in system_tag_columns - ) - - data_list = table.to_pylist() - - batches: list[list[dict[str, Any]]] = [] - next_batch: list[dict[str, Any]] = [] - - for entry in data_list: - next_batch.append(entry) - if self.batch_size > 0 and len(next_batch) >= self.batch_size: - batches.append(next_batch) - next_batch = [] - - if next_batch and not self.drop_partial_batch: - batches.append(next_batch) - - batched_data = [ - { - **{c: [m[c] for m in members] for c in member_columns}, - **{ - c: arrow_utils.fold_system_tag_values( - [m[c] for m in members], label=BATCH_FOLD_LABEL + kept = table.slice(0, int(offsets[-1].as_py())) + bounds = cast(list[int], offsets.to_pylist()) + type_converter = stream.data_context.type_converter + + fields: list[pa.Field[Any]] = [] + arrays: list[pa.Array[Any]] = [] + for field in table.schema: + column = kept.column(field.name) + if field.name.startswith(constants.SYSTEM_TAG_PREFIX): + # Text values, folded per batch; text loses nothing in Python. + values = cast(list[Any], column.to_pylist()) + fields.append(field) + arrays.append( + pa.array( + [ + arrow_utils.fold_system_tag_values( + values[start:end], label=BATCH_FOLD_LABEL + ) + for start, end in zip(bounds[:-1], bounds[1:]) + ], + field.type, ) - for c in system_tag_columns - }, - } - for members in batches - ] - - batched_table = arrow_utils.build_aggregated_table( - batched_data, - table.schema, - member_columns, - stream.data_context.type_converter, - ) + ) + continue + list_type = arrow_utils.aggregated_list_type( + field.type, type_converter, column=field.name + ) + fields.append(pa.field(field.name, list_type, nullable=False)) + arrays.append(arrow_utils.aggregated_list_array(column, offsets, list_type)) + batched_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) n_char = self.orcapod_config.hashing.system_tag_n_char batched_table = arrow_utils.append_to_system_tags( diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index 18f3b847e..38bd390a5 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -5,6 +5,13 @@ from collections.abc import Collection, Mapping, Sequence, Set from typing import Any, ClassVar, TYPE_CHECKING, cast, get_origin +from orcapod.core.operators.arrow_keys import ( + is_list_kind, + part_without_rule, + polars_ready, + value_type, + values_of, +) from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -34,240 +41,6 @@ # for bit. Only the row numbers and the group sizes come back from Polars. -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, - a dictionary's values, at the top level.""" - 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_orderable_scalar(arrow_type: "pa.DataType") -> bool: - """Return whether ``GroupBy`` has an order for a scalar of this (storage) type. - - Every integer, float, decimal, boolean, string, binary, date, time, timestamp - and duration type, and the null type: what ``_polars_ready`` prepares. - """ - 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 _unorderable_part(arrow_type: "pa.DataType") -> "pa.DataType | None": - """Return the part of a tag's type ``GroupBy`` has no order for, or ``None``. - - The one rule for what may key a group or order its members, used by the - validation (from the schema) and by the grouping itself (from the table), so - nothing reaches Polars that ``_polars_ready`` does not prepare: Polars panics on - some types (``decimal256``), and a panic is not an error a caller can catch. A - list, large list or fixed-size list is ordered element by element, through - logical storage and dictionary values at every depth. A struct or a map (a user - class, a ``dict[K, V]``) has no decided order (developer, November 19, 2026), and - neither has any type not named in ``_is_orderable_scalar`` (an interval, a - union, a list view). - - Args: - arrow_type: The Arrow type of a tag column. - - Returns: - The first type found that has no order, or ``None``. - """ - value_type = _value_type(arrow_type) - if _is_list_kind(value_type): - lists = cast( - "pa.LargeListType[Any] | pa.ListType[Any] | pa.FixedSizeListType[Any, Any]", - value_type, - ) - return _unorderable_part(lists.value_type) - return None if _is_orderable_scalar(value_type) else value_type - - -def _without_dictionary(array: "pa.Array[Any]") -> "pa.Array[Any]": - """Decode a dictionary-encoded column to its values; any other column as it is. - - The one place ``GroupBy`` handles a dictionary-encoded tag, a float key's - included: the values each member's index points at, bits as stored. (A stream may - stop carrying dictionary-encoded tags, ITL-1264; then this goes.) - - Args: - array: A column of the input table, or its storage. - - Returns: - The decoded array. - """ - if isinstance(array, pa.DictionaryArray): - return array.dictionary_decode() - return array - - -def _storage(column: "pa.ChunkedArray[Any]") -> "pa.Array[Any]": - """Return a column as one array: a logical type as its storage, decoded. - - Args: - column: A column of the input table. - - Returns: - The column's values as stored. - """ - return _values_of(column.combine_chunks()) - - -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 validation reads its type. - - Args: - array: A column of the input table, 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 column 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 or ordering column in a form Polars reads, ordered and equal alike. - - Only the sort frame sees it; the output takes every value from the input. Every - type ``_unorderable_part`` accepts is prepared here, and no other type reaches - it (the caller refuses it first): - - * a logical type is its storage and a dictionary its values, alternately until - neither applies (``_values_of``, as ``_value_type`` reads the type); - * a date, time, timestamp or duration is its integer (the column's unit and zone - are its type, so the integers order and compare as the values do), so no - conversion of Polars' own can change it; - * 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 limbs (Polars panics on it); - * a list, large list or fixed-size list becomes a large list over its prepared - values (``_sort_key`` orders a list element by element). - - Args: - array: A column of the input table, or the values of one. - - Returns: - The prepared array. - - Raises: - TypeError: For a type ``_unorderable_part`` refuses; never reached through - ``GroupBy``, which refuses the column first. - """ - 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) - return pa.LargeListArray.from_arrays( - cast("pa.Int64Array", lists.offsets.cast(pa.int64())), - _polars_ready(lists.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_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 order. - 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_orderable_scalar(arrow_type): - return array - raise TypeError(f"GroupBy has no order for {arrow_type}") - - def _sort_key(name: str, dtype: object) -> "pl.Expr": """Return the sort key of one frame column: nulls last at every depth. @@ -306,7 +79,7 @@ def _float_bits(array: "pa.Array[Any]") -> "pa.Array[Any] | None": read through its storage or its values. Args: - array: A key column's values as stored (``_storage``). + array: A key column's values as stored (``arrow_keys.values_of``). Returns: The unsigned integers of the column's own width, or ``None``. @@ -323,7 +96,7 @@ def _refuse_unorderable_tags( """Refuse a user tag ``GroupBy`` cannot key a group or order members by. A key must be a scalar value groups are ordered by, and every non-key tag orders - the members, so a type with no order (``_unorderable_part``: a struct or a map, + the members, so a type with no order (``arrow_keys.part_without_rule``: a struct or a map, such as a user class or a ``dict``, an interval, a union) can be neither (developer, November 19, 2026: refuse rather than decide an order). A key that is a list of any kind is refused too. The refusal depends on the schema only, @@ -337,14 +110,14 @@ def _refuse_unorderable_tags( InputValidationError: Naming the first such tag and its type. """ for name, arrow_type in tag_types.items(): - if name in by and _is_list_kind(_value_type(arrow_type)): + if name in by and is_list_kind(value_type(arrow_type)): raise InputValidationError( f"GroupBy: {[name]} are list-valued tag columns and cannot be " + f"grouping keys. Column types: {{{name!r}: {arrow_type}}}. A " + "list-valued tag usually means the stream came from `Batch`; " + "group before batching rather than after." ) - part = _unorderable_part(arrow_type) + part = part_without_rule(arrow_type, structs=False) if part is None: continue if name in by: @@ -610,7 +383,7 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: InputValidationError: If any name in ``by`` is not a tag column, or names a list-valued tag column; or a name in ``member_order`` is not a tag column; or a key is a list of any kind, or a user tag's - type has no order (``_unorderable_part``: a struct, a map, an + type has no order (``arrow_keys.part_without_rule``: a struct, a map, an interval...); checked here when the stream knows its Arrow types without rows, otherwise when it is grouped. """ @@ -677,7 +450,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: Raises: InputValidationError: If a key is a list of any kind, or a user tag's - type has no order (``_unorderable_part``). + type has no order (``arrow_keys.part_without_rule``). """ table = stream.as_table(columns={"source": True, "system_tags": True}) tag_columns, _ = stream.keys() @@ -754,9 +527,9 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: for name, c in zip( [*key_names, *order_names], [*self.by, *sort_columns], strict=True ): - frame_columns[name] = _polars_ready(table.column(c).combine_chunks()) + frame_columns[name] = polars_ready(table.column(c).combine_chunks()) # The bits of each float key, to emit the member value with the smallest. - key_storage = {c: _storage(table.column(c)) for c in self.by} + key_storage = {c: values_of(table.column(c).combine_chunks()) for c in self.by} bit_names: dict[str, str] = {} for i, c in enumerate(self.by): bits = _float_bits(key_storage[c]) diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 2c1031bab..f5acafc45 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -1,13 +1,14 @@ -from collections.abc import Callable -from typing import Any, ClassVar, TYPE_CHECKING +from typing import Any, ClassVar, TYPE_CHECKING, cast from orcapod.core.operators.base import ( BinaryOperator, + require_matchable_key, require_shared_arrow_type, require_tag_data_roles_agree, ) from orcapod.core.operators.join import ( _MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join + _inner_join, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join Join, ) from orcapod.core.operators.key_nullability import ( @@ -28,11 +29,11 @@ from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import polars as pl + import numpy as np import pyarrow as pa else: + np = LazyModule("numpy") pa = LazyModule("pyarrow") - pl = LazyModule("polars") def _output_types( @@ -67,80 +68,56 @@ def _output_types( return resolved -def _identity_key(value: Any) -> Any: - """Order stored values as themselves (the default MergeJoin ordering).""" - return value +def _merged_list( + first: "pa.ChunkedArray[Any]", second: "pa.ChunkedArray[Any]", list_type: Any +) -> "pa.Array[Any]": + """Return the two-element lists of one merged column, built from the inputs' arrays. - -def _storage_sort_key( - type_converter: Any, arrow_type: "pa.DataType" -) -> Callable[[Any], Any]: - """Return the ordering key MergeJoin uses for a column's stored values. - - The array logical type defines ``storage_sort_key`` (the value digest of the - stored array). A list of such values, at any depth (an array column after - ``GroupBy`` or ``Batch``), is ordered by the tuple of its elements' keys, with - ``None`` first. Every other type is ordered by its stored value as before. - General struct ordering is ITL-839. - """ - if isinstance(arrow_type, pa.ExtensionType): - lt = type_converter.get_logical_type_by_arrow_extension_name( - arrow_type.extension_name - ) - key = _logical_sort_key(lt) - if key is not None: - return key - return _identity_key - - -def _logical_sort_key(logical_type: Any) -> Callable[[Any], Any] | None: - """Return a logical type's own ordering key for stored values, if it has one. + Row ``i`` is ``[first[i], second[i]]``: the first argument's value, then the + second's, compared with nothing (ITL-1281). The values are taken from the + joined arrays (``take``) and the lists built from offsets + (``arrow_utils.aggregated_list_array``), so every value is the input's, bit + for bit, for every Arrow type, a struct and a null included. Args: - logical_type: A logical type, or ``None``. + first: The column of the first argument, one value per joined row. + second: The same column of the second argument. + list_type: The merged column's type, from ``aggregated_list_type``. Returns: - The type's ``storage_sort_key``; for a list logical type whose elements - have a key, a key ordering lists by their elements' keys; otherwise - ``None``. + The list array, one two-element list per joined row. """ - key = getattr(logical_type, "storage_sort_key", None) - if callable(key): - return key - element = getattr(logical_type, "element_logical_type", None) - element_key = _logical_sort_key(element) if element is not None else None - if element_key is None: - return None - - def list_key(storage_value: Any) -> tuple[Any, ...]: - """Return the ordering key of one stored list value. - - A null list sorts before every non-null list. Non-null lists compare by - the tuple of their elements' keys, element by element in list order, so - a list that is a prefix of another sorts first. - - Args: - storage_value: The stored list, or ``None`` for a null list. - - Returns: - ``(0,)`` for a null list, otherwise ``(1, element keys...)``. - """ - if storage_value is None: - return (0,) - return (1, tuple(element_key(v) for v in storage_value)) - - return list_key + count = len(first) + values = pa.chunked_array( + [*first.chunks, *second.chunks], type=first.type + ).combine_chunks() + # Row i holds value i of the first column, then value i of the second. + order = np.empty(2 * count, dtype=np.int64) + order[0::2] = np.arange(count, dtype=np.int64) + order[1::2] = np.arange(count, 2 * count, dtype=np.int64) + offsets = pa.array(np.arange(0, 2 * count + 1, 2, dtype=np.int64), pa.int64()) + return arrow_utils.aggregated_list_array( + values.take(pa.array(order, pa.int64())), + cast("pa.Int64Array", offsets), + list_type, + ) class MergeJoin(BinaryOperator): """ Binary operator that joins two streams, merging colliding data columns - into sorted lists. - - For data columns that exist in both streams: - - Values are combined into a list and sorted independently per column. - - Corresponding source columns are reordered to match the sort order of - their data column. + into two-element lists in argument order. + + MergeJoin is ordered, not commutative (developer, November 19, 2026, + ITL-1281): ``MergeJoin()(a, b)`` and ``MergeJoin()(b, a)`` are two + operations with two identities (``argument_symmetry`` is a tuple). For a + data column that exists in both streams, each output row holds the list + ``[value of the first argument, value of the second]``. Nothing is sorted + and no values are compared, so every list of a row is parallel by origin + row: element ``i`` of every merged column and of its source-info list comes + from input ``i``, whose system-tag columns end in ``:{i}``. The lists are + built from the inputs' Arrow arrays, so every value is the input's, bit for + bit, whatever its type (a struct, a logical type and a null included). For non-colliding columns, values are kept as scalars (same as regular Join). @@ -164,9 +141,6 @@ class MergeJoin(BinaryOperator): such a disagreement, because streams expose only Python schemas; it is detected in ``binary_static_process`` before the join. - MergeJoin is commutative: MergeJoin(A, B) produces the same result as - MergeJoin(B, A), achieved by sorting merged values and system tag values. - Data-tags (ITL-1194) follow ``Join``, with ``Join``'s helpers. A tag ``x`` that is a data-tag in both inputs is a join key, so its two values are equal: the output has ONE scalar data-tag column ``x``, not a two-element list, and its @@ -176,7 +150,7 @@ class MergeJoin(BinaryOperator): of one input named like a data-only column of the other is refused (the tag and data role check). A shared key that is ``T`` in one input and ``T | None`` in the other is ``T`` in both roles (ITL-829). Every other colliding data column is - merged into a sorted list, as for plain inputs. + merged into a list in argument order, as for plain inputs. """ # Data-tags (ITL-1023) are handled (ITL-1194). @@ -187,7 +161,8 @@ def kernel_id(self) -> tuple[str, ...]: return (f"{self.__class__.__name__}",) def is_commutative(self) -> bool: - return True + """MergeJoin is ordered: its lists hold the first argument's value first.""" + return False def validate_binary_inputs( self, left_stream: StreamProtocol, right_stream: StreamProtocol @@ -232,23 +207,17 @@ def binary_output_schema( ) -> tuple[Schema, Schema]: columns_config = ColumnConfig.handle_config(columns, all_info=all_info) - # MergeJoin is commutative, so its column order must not depend on - # operand order: tag and data columns are listed by first appearance - # across the inputs in canonical ``pipeline_hash`` order. This is the - # single definition of the order; ``binary_static_process`` reads it - # back from here. - # + # Tag and data columns are listed by first appearance across the inputs + # in argument order (MergeJoin is ordered). This is the single definition + # of the order; ``binary_static_process`` reads it back from here. self._require_tag_data_roles_agree(left_stream, right_stream) # Always get input schemas WITHOUT system tags for the base computation. # System tags are computed separately because the join renames them. - (first_stream, _), (second_stream, _) = self._canonical_order( - left_stream, right_stream - ) - left_tag_schema, _ = first_stream.output_schema() - right_tag_schema, _ = second_stream.output_schema() + left_tag_schema, _ = left_stream.output_schema() + right_tag_schema, _ = right_stream.output_schema() left_data_schema, right_data_schema, merged = self._input_data_schemas( - first_stream, second_stream + left_stream, right_stream ) # Tag schema: union of both tag schemas. A shared tag key that differs in @@ -363,17 +332,14 @@ def _require_tag_data_roles_agree( except InputValidationError as exc: raise InputValidationError(f"MergeJoin: {exc}") from exc - def _canonical_order( - self, left_stream: StreamProtocol, right_stream: StreamProtocol - ) -> list[tuple[StreamProtocol, int]]: - """ - Determine canonical ordering of the two input streams by stable-sorting - on pipeline_hash. Returns list of (stream, original_index) tuples in - canonical order. + def _system_tag_suffix(self, stream: StreamProtocol, position: int) -> str: + """Return what an input's system-tag column names gain: ``{pipeline_hash}:{position}``. + + ``position`` is the input's argument index (0 for the first, 1 for the + second): MergeJoin is ordered, so its inputs are never reordered. """ - streams_with_idx = [(left_stream, 0), (right_stream, 1)] - # Python's sorted is stable, so equal pipeline_hashes preserve input order - return sorted(streams_with_idx, key=lambda s: s[0].pipeline_hash().to_hex()) + n_char = self.orcapod_config.hashing.system_tag_n_char + return f"{stream.pipeline_hash().to_hex(n_char)}:{position}" def _predict_system_tag_schema( self, left_stream: StreamProtocol, right_stream: StreamProtocol @@ -381,22 +347,16 @@ def _predict_system_tag_schema( """Predict the system tag columns that the join would produce. Each input stream's existing system tag columns get renamed by - appending ::{pipeline_hash}:{canonical_position}. This method - computes those output column names without performing the join. + appending ``::{pipeline_hash}:{argument index}``. This method computes + those output column names without performing the join. """ - n_char = self.orcapod_config.hashing.system_tag_n_char - canonical = self._canonical_order(left_stream, right_stream) - system_tag_fields: dict[str, type] = {} - for stream, orig_idx in canonical: - canon_pos = canonical.index((stream, orig_idx)) + for position, stream in enumerate((left_stream, right_stream)): + suffix = self._system_tag_suffix(stream, position) stream_tag_schema, _ = stream.output_schema(columns={"system_tags": True}) for col_name, col_type in stream_tag_schema.items(): if col_name.startswith(constants.SYSTEM_TAG_PREFIX): - new_name = ( - f"{col_name}{constants.BLOCK_SEPARATOR}" - f"{stream.pipeline_hash().to_hex(n_char)}:{canon_pos}" - ) + new_name = f"{col_name}{constants.BLOCK_SEPARATOR}{suffix}" system_tag_fields[new_name] = col_type return Schema(system_tag_fields) @@ -405,45 +365,43 @@ def binary_static_process( ) -> StreamProtocol: """Inner-join two streams on their shared tags, merging colliding data columns. - A data column present in both streams becomes a sorted two-element - list per row, with its source-info column reordered to match. System - tag columns are renamed with each stream's pipeline hash and canonical - position. A zero-row input yields a zero-row result with the same - column types as a non-empty one. + A data column present in both streams becomes a two-element list per + row, ``[left value, right value]``, and its source-info column the list + of the two tokens in the same order. Polars only decides which rows + match, from the prepared key columns and row numbers (``Join``'s + ``_inner_join``, ITL-1284); every output value is taken from the input + tables, and the lists are built from their arrays (ITL-1281). System tag + columns are renamed with each stream's pipeline hash and argument + index. A zero-row input yields a zero-row result with the same column + types as a non-empty one. Args: - left_stream: The left input stream. - right_stream: The right input stream. + left_stream: The left (first) input stream. + right_stream: The right (second) input stream. Returns: The joined stream, with tag columns first. + + Raises: + InputValidationError: If a column the two inputs share has two Arrow + types, or a shared tag key has a type with no rule for matching. """ self._require_tag_data_roles_agree(left_stream, right_stream) - n_char = self.orcapod_config.hashing.system_tag_n_char - - # Determine canonical ordering for system tag positions - canonical = self._canonical_order(left_stream, right_stream) - - # Get tables with source + system_tags, append system tag blocks - tables = {} - for stream, orig_idx in canonical: - canon_pos = canonical.index((stream, orig_idx)) - table = stream.as_table(columns={"source": True, "system_tags": True}) - table = arrow_utils.append_to_system_tags( - table, f"{stream.pipeline_hash().to_hex(n_char)}:{canon_pos}" - ) - tables[orig_idx] = table - # Join in canonical order, so "left" and "right" below are the - # canonically first and second inputs and the physical columns come - # out the same for MergeJoin(a, b) and MergeJoin(b, a). - (first_stream, first_idx), (second_stream, second_idx) = canonical - left_table = tables[first_idx] - right_table = tables[second_idx] + # Tables with source info and system tags, each input's system-tag + # column names extended with its pipeline hash and argument index. + left_table = arrow_utils.append_to_system_tags( + left_stream.as_table(columns={"source": True, "system_tags": True}), + self._system_tag_suffix(left_stream, 0), + ) + right_table = arrow_utils.append_to_system_tags( + right_stream.as_table(columns={"source": True, "system_tags": True}), + self._system_tag_suffix(right_stream, 1), + ) # Determine shared tag keys for inner join - left_tag_keys, left_data_keys = first_stream.keys() - right_tag_keys, right_data_keys = second_stream.keys() + left_tag_keys, left_data_keys = left_stream.keys() + right_tag_keys, right_data_keys = right_stream.keys() shared_tag_keys = set(left_tag_keys) & set(right_tag_keys) # A data-tag of both inputs is a join key: the join keeps one column, @@ -451,9 +409,9 @@ def binary_static_process( # second input's token is set aside under a temporary name until then. merged = Join._merged_data_tags( # pyright: ignore[reportPrivateUsage] # Join's one rule left_tag_keys, - stream_data_tags(first_stream), + stream_data_tags(left_stream), right_tag_keys, - stream_data_tags(second_stream), + stream_data_tags(right_stream), ) right_source = { f"{constants.SOURCE_PREFIX}{name}": f"{_MERGED_SOURCE_PREFIX}{name}" @@ -468,22 +426,20 @@ def binary_static_process( # Find colliding data columns (a merged data-tag column is not one) colliding_keys = (set(left_data_keys) & set(right_data_keys)) - merged - # Snapshot the inputs' Arrow types BEFORE the Polars round-trip, which - # stores strings, binaries and lists in their large layouts, drops - # fixed_size_binary and may strip extension metadata. Every output - # column is typed from these, never from what Arrow infers for the - # Python values. Inputs whose types differ beyond layout are rejected - # here, before the join (require_shared_arrow_type). + # Every output column is typed from the inputs' Arrow types. Inputs + # whose types differ beyond layout are rejected here, before the join + # (require_shared_arrow_type), and so is a key Polars cannot be given. left_types = {f.name: f.type for f in left_table.schema} right_types = {f.name: f.type for f in right_table.schema} output_types = _output_types(left_types, right_types) - - # Capture nullable flags from input schemas BEFORE Polars conversion. - # Polars' join discards nullable info (defaults all to True); we derive - # the output schema from the inputs instead of from data null counts. - # Only capture tag and data columns — system tag and source columns - # are internally created with Arrow's all-nullable default; those fall - # through to null-count inference below. + for key in sorted(shared_tag_keys): + require_matchable_key("MergeJoin", key, output_types[key]) + + # The joined table is built from arrays with no field flags, so the + # flags are taken from the inputs. Only tag and data columns are + # captured: system tag and source columns are internally created with + # Arrow's all-nullable default; those fall through to null-count + # inference below. captured_cols = ( set(left_tag_keys) | set(left_data_keys) @@ -515,34 +471,26 @@ def binary_static_process( if source_col in output_nullable: output_nullable[source_col] = False - # Perform inner join via Polars on shared tag keys - # Use a common key trick to ensure cartesian product if no shared tags + # Inner join on the shared tag keys. A constant key makes the join a + # cartesian product when the inputs share no tag; int8 explicitly, so a + # zero-row table doesn't produce a null-typed column (same as Join). COMMON_JOIN_KEY = "_common" - # COMMON_JOIN_KEY is a temporary column that gets dropped after the join output_nullable.pop(COMMON_JOIN_KEY, None) - # Use int8 explicitly so a zero-row table doesn't produce a null-typed - # column that Polars rejects as a join key (same as Join). left_table = left_table.add_column( 0, COMMON_JOIN_KEY, pa.array([0] * len(left_table), type=pa.int8()) ) right_table = right_table.add_column( 0, COMMON_JOIN_KEY, pa.array([0] * len(right_table), type=pa.int8()) ) + join_keys = sorted(shared_tag_keys | {COMMON_JOIN_KEY}) - join_keys = list(shared_tag_keys | {COMMON_JOIN_KEY}) - - # Track which columns Polars will auto-suffix with _right - # (right-table columns that collide with left, excluding join keys) + # The right-table columns the join suffixes with ``_right``: those the + # left table also has, other than the keys. left_col_set = set(left_table.column_names) - {COMMON_JOIN_KEY} right_col_set = set(right_table.column_names) - {COMMON_JOIN_KEY} - join_key_set = set(join_keys) - {COMMON_JOIN_KEY} - polars_suffixed_bases = (right_col_set & left_col_set) - join_key_set + suffixed_bases = (right_col_set & left_col_set) - set(join_keys) - joined = ( - pl.DataFrame(left_table) - .join(pl.DataFrame(right_table), on=join_keys, how="inner") - .to_arrow() - ) + joined = _inner_join(left_table, right_table, join_keys) joined = joined.drop(COMMON_JOIN_KEY) for left_name, right_name in right_source.items(): joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule @@ -553,93 +501,41 @@ def binary_static_process( # merged column's extension type from the correct registry. tc = left_stream.data_context.type_converter - # Process colliding data columns: merge into sorted lists - for col in colliding_keys: - left_col_name = col - right_col_name = f"{col}_right" - - left_source_col = f"{constants.SOURCE_PREFIX}{col}" - right_source_col = f"{left_source_col}_right" - - if right_col_name not in joined.column_names: - continue - - left_vals = joined.column(left_col_name).to_pylist() - right_vals = joined.column(right_col_name).to_pylist() - - # Also handle corresponding source columns - has_source = ( - left_source_col in joined.column_names - and right_source_col in joined.column_names - ) - if has_source: - left_sources = joined.column(left_source_col).to_pylist() - right_sources = joined.column(right_source_col).to_pylist() - - # A logical type whose stored values are not orderable as Python values - # (struct storage comes back as dicts) supplies its own ordering key. - sort_key = _storage_sort_key(tc, output_types[col]) - - merged_vals = [] - merged_sources = [] if has_source else None - for i in range(len(left_vals)): - lv, rv = left_vals[i], right_vals[i] - if has_source: - ls, rs = left_sources[i], right_sources[i] - # Sort by data value, carry source along - pairs = sorted( - zip([lv, rv], [ls, rs]), key=lambda p: sort_key(p[0]) - ) - merged_vals.append([p[0] for p in pairs]) - merged_sources.append([p[1] for p in pairs]) - else: - merged_vals.append(sorted([lv, rv], key=sort_key)) - - # Replace the left column with merged list, drop right column - col_idx = joined.column_names.index(left_col_name) - joined = joined.drop(left_col_name) - joined = joined.drop(right_col_name) - - list_type = arrow_utils.aggregated_list_type( - output_types[col], tc, column=col - ) - joined = joined.add_column( - col_idx, left_col_name, arrow_utils.list_array(merged_vals, list_type) - ) - output_types[col] = list_type - - if has_source: - source_idx = joined.column_names.index(left_source_col) - joined = joined.drop(left_source_col) - joined = joined.drop(right_source_col) - source_list_type = arrow_utils.aggregated_list_type( - output_types[left_source_col], tc, column=left_source_col + # Merge each colliding data column, and its source-info column, into + # lists in argument order: [left value, right value]. + for col in sorted(colliding_keys): + source_col = f"{constants.SOURCE_PREFIX}{col}" + pairs = [(col, output_types[col])] + if ( + source_col in joined.column_names + and f"{source_col}_right" in joined.column_names + ): + pairs.append((source_col, output_types[source_col])) + for name, element_type in pairs: + list_type = arrow_utils.aggregated_list_type( + element_type, tc, column=name ) - joined = joined.add_column( - source_idx, - left_source_col, - arrow_utils.list_array(merged_sources or [], source_list_type), + merged_list = _merged_list( + joined.column(name), joined.column(f"{name}_right"), list_type ) - output_types[left_source_col] = source_list_type - - # Handle remaining Polars-generated _right suffixed columns - # (only from columns we know Polars auto-suffixed, not original names) - for base_name in polars_suffixed_bases: + index = joined.column_names.index(name) + joined = joined.drop_columns([name, f"{name}_right"]) + joined = joined.add_column(index, name, merged_list) + output_types[name] = list_type + + # Any other right column the join suffixed: kept under its own name when + # the left one is gone, dropped when the left one is still there. + for base_name in suffixed_bases: suffixed_name = f"{base_name}_right" if suffixed_name not in joined.column_names: continue # Already handled during colliding column processing if base_name not in joined.column_names: - # Left version was removed, rename right to original idx = joined.column_names.index(suffixed_name) col_data = joined.column(suffixed_name) - joined = joined.drop(suffixed_name) + joined = joined.drop_columns([suffixed_name]) joined = joined.add_column(idx, base_name, col_data) else: - # Both versions exist, drop the right one - joined = joined.drop(suffixed_name) - - # Sort system tag values for same-pipeline-hash streams to ensure commutativity - joined = arrow_utils.sort_system_tag_values(joined) + joined = joined.drop_columns([suffixed_name]) # Lay the columns out in the order ``binary_output_schema`` defines: # tags, then data, then the hidden columns. ``ArrowTableStream`` reads @@ -655,10 +551,10 @@ def binary_static_process( # Reconstruct the schema: every column takes the type decided above # from the inputs (the large-normalized input type for pass-through - # columns, undoing Polars' other changes such as fixed_size_binary to - # large_binary; the list type built above for merged columns), and + # columns; the list type built above for merged columns), and # nullability comes from the captured input flags, falling back to - # null-count inference for system tag and source-info columns. + # null-count inference for system tag and source-info columns. The + # values are the inputs': the cast changes layouts only. result_schema = pa.schema( [ pa.field( From d6c9b9685146142aa0ec91182aef8e88ea3d5c4d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 14:14:52 -0800 Subject: [PATCH 2/7] test(golden): the 21 approved MergeJoin entries move with its ordered identity (ITL-1281) Co-Authored-By: Claude Opus 5.5 --- .../itl_1281/golden_diff_against_main.py | 68 +++++++++++++++++++ src/orcapod/contexts/data/v1.json | 14 ++-- .../golden/data/v1/pipeline-01.json | 18 ----- .../golden/data/v1/pipeline-02.json | 18 +++++ 4 files changed, 93 insertions(+), 25 deletions(-) create mode 100644 docs/dev/scripts/itl_1281/golden_diff_against_main.py diff --git a/docs/dev/scripts/itl_1281/golden_diff_against_main.py b/docs/dev/scripts/itl_1281/golden_diff_against_main.py new file mode 100644 index 000000000..2d72c8549 --- /dev/null +++ b/docs/dev/scripts/itl_1281/golden_diff_against_main.py @@ -0,0 +1,68 @@ +"""Compare every golden entry with origin/main: only the approved MergeJoin entries differ.""" + +import json +import subprocess +import pathlib + +root = pathlib.Path("tests/test_hashing/golden/data/v1") +files = sorted(p.relative_to(root).as_posix() for p in root.rglob("*.json")) +main_files = subprocess.run( + ["git", "ls-tree", "-r", "--name-only", "origin/main", str(root) + "/"], + capture_output=True, + text=True, +).stdout.split() +assert files == sorted(pathlib.Path(f).relative_to(root).as_posix() for f in main_files) + + +def load(rev, f): + if rev is None: + return json.loads((root / f).read_text()) + return json.loads( + subprocess.run( + ["git", "show", f"{rev}:{root}/{f}"], + capture_output=True, + text=True, + check=True, + ).stdout + ) + + +def group(f): + return pathlib.Path(f).name.split("-")[0].removesuffix(".json") + + +old, new = {}, {} +for f in files: + for k, v in load("origin/main", f).items(): + old[f"{group(f)}:{k}"] = v + for k, v in load(None, f).items(): + new[f"{group(f)}:{k}"] = v + + +def approved(k): + return k.startswith("pipeline:merge_join.") or k.startswith( + "pipeline:join_key_nullability.merge_join." + ) + + +removed = sorted(set(old) - set(new)) +added = sorted(set(new) - set(old)) +common = set(old) & set(new) +changed = sorted(k for k in common if old[k] != new[k]) +print( + f"golden files: {len(files)} (same names as main); entries on main: {len(old)}; on the branch: {len(new)}" +) +print( + f"value moved: {len(changed)}; name gone: {len(removed)}; name new: {len(added)}; byte-identical: {len(common) - len(changed)}" +) +assert all(approved(k) for k in changed + removed + added) +assert len(changed) + len(removed) + len(added) == 21 +print( + "all 21 differences are approved MergeJoin entries; every other entry is identical to main" +) +for k in changed: + print("MOVED", k, json.dumps(old[k]), "->", json.dumps(new[k])) +for k in removed: + print("GONE", k, json.dumps(old[k])) +for k in added: + print("NEW", k, json.dumps(new[k])) diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index f440559de..379644945 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -230,27 +230,27 @@ "folder": "v1", "history": [ { - "date": "2026-11-18", + "date": "2026-11-20", "release": null, "added": { "arrow-01.json": "c66fa55619178f2631d04232555cd58059813e97e9ecd2b9de9e63699e60c964", "datagram-01.json": "598d4a2851819d76ba674e189222e61733ca1861ca82a59e990a8ee5e1b0a7b3", - "pipeline-01.json": "538958d92057f903d72d5c9e9b35fad23f40078638f4f2291865a536fb643035", + "pipeline-01.json": "b00ff9f50154b16f4af0a938d938b768e4ee3695ea96cc54527f713be9359956", "schema-01.json": "79aa2a068e0724891cf43ee528ce8f569e65f08864faa5e34773bfc69ac9576e", "semantic-01.json": "973a97cd3d74f558910b5854dce773fe5aa38a4df96be88ef10e5e6504ffe73d", "torch-01.json": "af2e8b68d66dffaa37e1d0ad75acd42f595d65b9fae00ddcde81bf9e13a265c8" }, "previous": null, - "digest": "9f6e545f710e6c8c36ff546477ddedd251871f1a154588e823145aafa6802442" + "digest": "c38e192faa862305c53d319230c2fe7e11313a4ab00161afc9a62412a1abd354" }, { - "date": "2026-11-18", + "date": "2026-11-20", "release": null, "added": { - "pipeline-02.json": "7584d28939fb31907e9b078f91e0d6605222c31b170eb70bd6e4e4254342358f" + "pipeline-02.json": "63a55854ded5cd5e21cee548108f2105fe0c2f36f438c0e93b7ca148e5e59e50" }, - "previous": "9f6e545f710e6c8c36ff546477ddedd251871f1a154588e823145aafa6802442", - "digest": "7be3c4e8659a3bca78bd54a04a444323db181a9ca2a3285cd7ba5ad4a76a305c" + "previous": "c38e192faa862305c53d319230c2fe7e11313a4ab00161afc9a62412a1abd354", + "digest": "d293b993d0b1e3bbc81e2f81d26e4b5e88d345e3bc25e0c1b331b422870acd89" } ], "provisional": { diff --git a/tests/test_hashing/golden/data/v1/pipeline-01.json b/tests/test_hashing/golden/data/v1/pipeline-01.json index 3ea1a2963..65c0af191 100644 --- a/tests/test_hashing/golden/data/v1/pipeline-01.json +++ b/tests/test_hashing/golden/data/v1/pipeline-01.json @@ -327,24 +327,8 @@ "_tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1", "_tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1" ], - "join_key_nullability.merge_join.content_hash": "semantic_v1:3558c668a6c823d64f5a18c265acf0b38ce8142b4e91e3256ae2e6d64c206a68", - "join_key_nullability.merge_join.pipeline_hash": "semantic_v1:9eb3978aba7a8acc270d9b177156027493a279c294013cec7b08c9e359139d6d", - "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_record_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:0": "row_0", - "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1": "row_0", - "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_source_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:0": "golden_plain_key", - "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1": "golden_nullable_key", "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}].data_hash": "arrow_v1:0000025019693a2d1d578c8af9aaae0e3dab43933bbf1196b4e42a4c3a83c80a1f61ef", - "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_record_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:0": "row_2", - "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1": "row_2", - "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_source_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:0": "golden_plain_key", - "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1": "golden_nullable_key", "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}].data_hash": "arrow_v1:0000022166408838e16c8aac02628c1ab78d2e6ab30d5751d26b5a603cfaeab2d65df6", - "join_key_nullability.merge_join.system_tag_columns": [ - "_tag_source_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:0", - "_tag_record_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:0", - "_tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1", - "_tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:1" - ], "join_key_nullability.semi_join_left_nullable.content_hash": "semantic_v1:78ec7d0b87b6e758692337725de8ecb40ae0d4a3c2fa66c906cb3ed1b9aa6267", "join_key_nullability.semi_join_left_nullable.pipeline_hash": "semantic_v1:427d4a07cdf3dd5e74d5a808a915ef74852ef592880c5a35d32bfdcbdfe92008", "join_key_nullability.semi_join_left_nullable.row[{\"subject\":\"s1\"}]._tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87": "row_0", @@ -450,8 +434,6 @@ "_tag_source_id::ac699f6aae66ff1745c42c76a3cb6cf59ba8588efc02d66e4f23de4be09ac373", "_tag_record_id::ac699f6aae66ff1745c42c76a3cb6cf59ba8588efc02d66e4f23de4be09ac373" ], - "merge_join.content_hash": "semantic_v1:afa3176e91b541aac96c4b50b4948f94d96ca7505305cd42c8c8f1167934db47", - "merge_join.pipeline_hash": "semantic_v1:be7df9479834c360b9d90feebf81ab862382a945d76e443c1bf8b65ea704b387", "merge_join.row[{\"subject\":\"s1\"}]._tag_record_id::a1db704c27d87a21807be6313bd1ed34dfb58236ec9f902a19c10c9ce7d46f6b::a1db704c27d87a21807be6313bd1ed34dfb58236ec9f902a19c10c9ce7d46f6b:1": "row_0", "merge_join.row[{\"subject\":\"s1\"}]._tag_record_id::ac699f6aae66ff1745c42c76a3cb6cf59ba8588efc02d66e4f23de4be09ac373::291aa68096a29e11f917b6276a9932f6874aac880928e17ed9050701d91e4934:0": "row_0", "merge_join.row[{\"subject\":\"s1\"}]._tag_source_id::a1db704c27d87a21807be6313bd1ed34dfb58236ec9f902a19c10c9ce7d46f6b::a1db704c27d87a21807be6313bd1ed34dfb58236ec9f902a19c10c9ce7d46f6b:1": "reweigh", diff --git a/tests/test_hashing/golden/data/v1/pipeline-02.json b/tests/test_hashing/golden/data/v1/pipeline-02.json index 2686426f0..8fe3a03aa 100644 --- a/tests/test_hashing/golden/data/v1/pipeline-02.json +++ b/tests/test_hashing/golden/data/v1/pipeline-02.json @@ -210,8 +210,26 @@ "golden_job/_result/golden_adjust/a2fa1ad227c2c0b24315bf0bfca5b3f5473e1f044a6d48cfcf3b78977510a560/v0/python.function.v1/rev1/rdb_v1", "golden_job/golden_adjust/a2fa1ad227c2c0b24315bf0bfca5b3f5473e1f044a6d48cfcf3b78977510a560/v0/python.function.v1/schema:f8f3638bf17df15345b70be956e0779e01c9905db088daa02dfec441d7de441d/pdb_v1" ], + "join_key_nullability.merge_join.content_hash": "semantic_v1:ca01105efb1de0b081ec687fe7f4037a99d482dbb484291390ba81e4ee9e8349", + "join_key_nullability.merge_join.pipeline_hash": "semantic_v1:45985a1174c1a3ecedfbe4621be2a18b89b130bac8c6c709dbd9aa649ea95ec7", + "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_record_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:1": "row_0", + "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:0": "row_0", + "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_source_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:1": "golden_plain_key", + "join_key_nullability.merge_join.row[{\"subject\":\"s1\"}]._tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:0": "golden_nullable_key", + "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_record_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:1": "row_2", + "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:0": "row_2", + "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_source_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:1": "golden_plain_key", + "join_key_nullability.merge_join.row[{\"subject\":\"s3\"}]._tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:0": "golden_nullable_key", + "join_key_nullability.merge_join.system_tag_columns": [ + "_tag_source_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:0", + "_tag_record_id::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87::fddb365c4147114d8cfc5dcbd611e037b0f7f2729238cd29ade9a66578acad87:0", + "_tag_source_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:1", + "_tag_record_id::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e::d8f6f3824cdd5ed5f1795c5a050b727f3e05354c78d68a1aaff4056a9b66771e:1" + ], "join_pod.pod.content_hash": "semantic_v1:6ada754d8fc4292450d3fb8813f05878b8aabbd52da3615519c80c7418bc0b4e", "join_pod.pod.pipeline_hash": "semantic_v1:f8f3638bf17df15345b70be956e0779e01c9905db088daa02dfec441d7de441d", + "merge_join.content_hash": "semantic_v1:ae8410f9b8cb0940988ec66d428c05984b92c2f78c28e0dcc75d5cd1fa073e2e", + "merge_join.pipeline_hash": "semantic_v1:5f20d36ecb37199b4abde20444a5b857610d89df8d6dad3af3fad3d0848a0f3f", "pod.content_hash": "semantic_v1:9b6de7be825efc4495abaa60baf14e0bc5dbd034f68751b95546308e1266a93a", "pod.pipeline_hash": "semantic_v1:a7f19352f4abe281d50ffdd8d5574b04ea494f5e9da8daef30e189c3fc0ac693", "pod_default_version.decorator.uri": [ From 572f1c61d01a5d8cb36f9fa1d9ea111a8e9c920f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 14:34:12 -0800 Subject: [PATCH 3/7] fix(merge_join, batch): ordered MergeJoin; lists in argument order and from Arrow; tests, docs, rules (ITL-1281) MergeJoin is ordered (developer decision, 2026-11-19): its identity holds its inputs as a tuple, system-tag positions are argument indices, and every merged list is [first argument's value, second argument's value] with its source info in the same order. Nothing is sorted. Batch builds its lists as slices of the input's arrays. GroupBy imports the key preparation from arrow_keys. The Python-value list builders (build_aggregated_table, list_array) are removed. Resolves ITL-1241, ITL-1243 and ITL-839 (structs merge). Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 56 +- CLAUDE.md | 56 +- changelog.d/ITL-1281.md | 24 + docs/concepts/arrays.md | 4 +- docs/concepts/data-tags.md | 7 +- docs/concepts/identity.md | 7 +- docs/concepts/operators.md | 43 +- docs/dev/design_issues/ITL-1241-MJ4.md | 15 + docs/dev/design_issues/ITL-1243-MJ5.md | 14 + docs/dev/design_issues/ITL-1281-BA1.md | 18 + docs/dev/design_issues/ITL-1281-MJ3.md | 27 + docs/dev/design_issues/ITL-839-MJ6.md | 13 + docs/reference/hashing.md | 26 +- docs/tutorial/03-operators.md | 9 +- src/orcapod/core/operators/batch.py | 3 +- src/orcapod/core/operators/merge_join.py | 16 +- src/orcapod/utils/arrow_utils.py | 106 +--- tests/test_arrays/test_array_operators.py | 14 +- tests/test_arrays/test_array_value_format.py | 31 +- tests/test_core/data_tags/test_merge_join.py | 25 +- .../operators/test_async_sync_equivalence.py | 63 +++ .../test_core/operators/test_batch_values.py | 222 ++++++++ .../operators/test_group_by_arrow_values.py | 19 +- .../operators/test_join_tag_order.py | 19 +- tests/test_core/operators/test_merge_join.py | 389 ++++++------- .../operators/test_merge_join_arrow_types.py | 101 ++-- .../operators/test_merge_join_values.py | 526 ++++++++++++++++++ .../test_core/operators/test_several_items.py | 101 ++-- tests/test_core/order_rules.py | 6 +- tests/test_core/test_order_invariance.py | 12 +- .../test_hashing/test_wrong_hash_findings.py | 33 +- tests/test_torch/test_tensor_operators.py | 21 +- .../test_utils/test_arrow_utils_list_types.py | 25 +- 33 files changed, 1494 insertions(+), 557 deletions(-) create mode 100644 changelog.d/ITL-1281.md create mode 100644 docs/dev/design_issues/ITL-1241-MJ4.md create mode 100644 docs/dev/design_issues/ITL-1243-MJ5.md create mode 100644 docs/dev/design_issues/ITL-1281-BA1.md create mode 100644 docs/dev/design_issues/ITL-1281-MJ3.md create mode 100644 docs/dev/design_issues/ITL-839-MJ6.md create mode 100644 tests/test_core/operators/test_batch_values.py create mode 100644 tests/test_core/operators/test_merge_join_values.py diff --git a/.zed/rules b/.zed/rules index 3facf8e88..94b4dd28c 100644 --- a/.zed/rules +++ b/.zed/rules @@ -678,7 +678,7 @@ src/orcapod/ operators/ base.py — UnaryOperator, BinaryOperator, NonZeroInputOperator join.py — Join (N-ary inner join, commutative) - merge_join.py — MergeJoin (binary, colliding cols → sorted list[T]) + merge_join.py — MergeJoin (binary, ordered; colliding cols → [first, second]) semijoin.py — SemiJoin (binary, non-commutative) batch.py — Batch (group rows by count, types become list[T]) group_by.py — GroupBy (many→one reduction keyed on tag values) @@ -971,7 +971,8 @@ generation of hashing; rows of the current data context are the current entries. 1. Name-preserving — single-stream ops. Column name/value pass through unchanged. 2. Name-extending — multi-input ops. System tag column name gets ::{pipeline_hash}:{canonical_position} appended. Commutative operators sort by - pipeline_hash and sort system tag values per row. + pipeline_hash and sort system tag values per row. MergeJoin is ordered (ITL-1281): the + position is the argument index and nothing is sorted. 3. Reducing — many→one ops (Batch, GroupBy). Data columns become list[T]; Batch makes every user tag list[T] and keeps it a tag, while GroupBy keeps its scalar keys and drops every other user tag (ITL-1070). No tag ever moves to the data group. Source-info columns become @@ -1075,15 +1076,17 @@ data. The rules: (arrow_utils.normalize_to_large_types: string to large_string, binary to large_binary, list 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 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). + keep_null=True; only Data maps null to large_string, the function's default). + PolarsFilter is the one operator that still round-trips its columns through Polars; it + casts them back to the normalized input types (arrow_utils.restore_column_types and + restore_schema_nullability). Every other operator takes its values from the input's Arrow + arrays (take, a slice, list offsets; Join, SemiJoin, MergeJoin and GroupBy give + Polars only prepared keys and row numbers), so its values are the input's, bit for bit. This holds for every operator, also one that passes its rows through unchanged (select, map, a no-op filter, Join, SemiJoin), on a plain stream as inside a job: its result is an ArrowTableStream (ITL-1122). - List columns built by Batch, GroupBy and MergeJoin are typed by - arrow_utils.aggregated_list_type (directly or through build_aggregated_table): + arrow_utils.aggregated_list_type: large_list, or for a logical T the logical list type from the type converter (it raises, naming the column, if the converter has none; never strip the element to its storage type). Source-info list columns are large_list of the incoming source-info type: @@ -1092,6 +1095,11 @@ data. The rules: large_list>, ITL-849). An already list-valued data column likewise becomes a list of its incoming list type; never flatten it. Zero-row and non-empty results have the same types. +- Lists built by an operator are parallel by origin row (developer, November 19, 2026, + ITL-1281): element i of every list of an output row (each data and tag list and its + source-info list) comes from the same input row. A member order is decided once per output + row (Batch: the input's row order; GroupBy: its member order; MergeJoin: argument + order) and every list follows it; never sort one list column on its own values. - When two inputs give the same column different Arrow types, normalize both: equal proceeds, anything else raises InputValidationError naming the column and both types — no widening, promotion or picking a side. The rule is arrow_utils.shared_arrow_type, which takes only the @@ -1241,12 +1249,19 @@ data. The rules: 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 - InputValidationError. Non-empty struct columns cannot be merged yet (ITL-839). + table on each graph build). `MergeJoin` matches through the same inner join + (`join._inner_join`), and `GroupBy` imports the same preparation (ITL-1281), its rule + refusing structs (`part_without_rule(..., structs=False)`). +- MergeJoin is ordered, not commutative (developer, November 19, 2026, ITL-1281): + MergeJoin()(a, b) and MergeJoin()(b, a) are two operations with two identities + (argument_symmetry is a tuple), and each input's system-tag columns end in its argument + index. A colliding data column becomes large_list holding [first argument's value, + second argument's value] on every row, and its source-info column the two tokens in the same + order; nothing is sorted and no values are compared, so any value merges (a struct, a logical + type, a null). The lists are built from the joined Arrow arrays + (arrow_utils.aggregated_list_array), so every value is the input's, bit for bit. Colliding + columns must have identical Python types; inputs whose Arrow types still differ after + normalization raise InputValidationError. T is the large-normalized input Arrow type. - Operators predict output schema (including system tag names) without computation. Verify a prediction against unary_static_process(stream).output_schema(...), NOT against process(...) (circular — it delegates back to the pod) and NOT against as_table() (legitimately differs: @@ -1339,8 +1354,8 @@ data. The rules: interval, a union, a list view) is refused (`InputValidationError`, `_refuse_unorderable_tags`), as a key and as a non-key tag (which orders the members): a struct has no decided order (developer, November 19, 2026), so drop it before grouping. A - key that is a list of any kind (a fixed-size list included) is refused as list-valued. `Batch` and `MergeJoin` still rebuild their lists from Python - (ITL-1281). The stance on `0.0`/`-0.0` and NaN for the whole library (match by value, as + key that is a list of any kind (a fixed-size list included) is refused as list-valued. `Batch` and `MergeJoin` build their lists from Arrow + arrays too (ITL-1281). The stance on `0.0`/`-0.0` and NaN for the whole library (match by value, as Polars does; show the smallest bit pattern; rewrite nothing) is ITL-1251. - Data source-info values may be str, None, or list[...], nested to any depth; Arrow/Python types are derived from the value, with None mapping to large_string. That rule has one @@ -1349,12 +1364,13 @@ data. The rules: columns, so a type the stream already has is never re-inferred. A many→one operator must emit a list for EVERY row of a list-valued column — mixing in a bare None makes per-row as_table() schemas diverge and pa.concat_tables fail on the barrier path. -- Aggregating operators (Batch, GroupBy) must build list-valued columns via - arrow_utils.build_aggregated_table, never pa.list_(field.type). The helper types every list - column with aggregated_list_type: large_list of the large-normalized element, or, because - Arrow cannot embed an extension type inside a list value field, the logical list type +- Operators that build lists (Batch, GroupBy, MergeJoin) build every list-valued column + with arrow_utils.aggregated_list_array (member values in member order, lists from offsets), + never from Python values and never pa.list_(field.type). Its type comes from + aggregated_list_type: large_list of the large-normalized element, or, because Arrow + cannot embed an extension type inside a list value field, the logical list type (list[] from ListLogicalType) for a logical element such as a pod annotated - -> Path; it builds that list over the element's storage and wraps it. + -> Path; the list is built over the element's storage and wrapped. - Never build an identity or hash input from a type's raw __module__, or from repr/str/inspect.formatannotation of a type, without going through utils/canonical_type_names.py (canonical_module_name, canonical_type_name, diff --git a/CLAUDE.md b/CLAUDE.md index 3bcd9644a..164382d75 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -690,7 +690,7 @@ src/orcapod/ │ └── operators/ │ ├── base.py # UnaryOperator, BinaryOperator, NonZeroInputOperator │ ├── join.py # Join (N-ary inner join, commutative) -│ ├── merge_join.py # MergeJoin (binary, colliding cols → sorted list[T]) +│ ├── merge_join.py # MergeJoin (binary, ordered; colliding cols → [first, second]) │ ├── semijoin.py # SemiJoin (binary, non-commutative) │ ├── batch.py # Batch (group rows by count, types become list[T]) │ ├── group_by.py # GroupBy (many→one reduction keyed on tag values) @@ -1002,7 +1002,8 @@ current data context are the current entries. through unchanged. 2. **Name-extending** — multi-input ops (join, merge join). Each input's system tag column name gets `::{pipeline_hash}:{canonical_position}` appended. Commutative operators - canonically order inputs by `pipeline_hash` and sort system tag values per row. + canonically order inputs by `pipeline_hash` and sort system tag values per row. `MergeJoin` + is ordered (ITL-1281): the position is the argument index and nothing is sorted. 3. **Reducing** — many→one ops (`Batch`, `GroupBy`). Data columns become `list[T]`; `Batch` makes every user tag `list[T]` and keeps it a tag, while `GroupBy` keeps its scalar keys and drops every other user tag (ITL-1070). No tag ever moves to the data group. Source-info @@ -1119,15 +1120,17 @@ data. The rules: (`arrow_utils.normalize_to_large_types`: `string` to `large_string`, `binary` to `large_binary`, `list` 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 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). + `keep_null=True`; only `Data` maps `null` to `large_string`, the function's default). + `PolarsFilter` is the one operator that still round-trips its columns through Polars; it + casts them back to the normalized input types (`arrow_utils.restore_column_types` and + `restore_schema_nullability`). Every other operator takes its values from the input's Arrow + arrays (`take`, a slice, list offsets; `Join`, `SemiJoin`, `MergeJoin` and `GroupBy` give + Polars only prepared keys and row numbers), so its values are the input's, bit for bit. This holds for every operator, also one that passes its rows through unchanged (select, map, a no-op filter, `Join`, `SemiJoin`), on a plain stream as inside a job: its result is an `ArrowTableStream` (ITL-1122). - List columns built by `Batch`, `GroupBy` and `MergeJoin` are typed by - `arrow_utils.aggregated_list_type` (directly or through `build_aggregated_table`): + `arrow_utils.aggregated_list_type`: `large_list`, or for a logical `T` the logical list type from the type converter (it raises, naming the column, if the converter has none; never strip the element to its storage type). Source-info list columns are `large_list` of the incoming source-info type: @@ -1136,6 +1139,11 @@ data. The rules: `large_list>`, ITL-849). An already list-valued data column likewise becomes a list of its incoming list type; never flatten it. Zero-row and non-empty results have the same types. +- Lists built by an operator are parallel by origin row (developer, November 19, 2026, + ITL-1281): element `i` of every list of an output row (each data and tag list and its + source-info list) comes from the same input row. A member order is decided once per output + row (`Batch`: the input's row order; `GroupBy`: its member order; `MergeJoin`: argument + order) and every list follows it; never sort one list column on its own values. - When two inputs give the same column different Arrow types, normalize both: equal proceeds, anything else raises `InputValidationError` naming the column and both types — no widening, promotion or picking a side. The rule is `arrow_utils.shared_arrow_type`, which takes only the @@ -1285,12 +1293,19 @@ data. The rules: 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 - `InputValidationError`. Non-empty struct columns cannot be merged yet (ITL-839). + table on each graph build). `MergeJoin` matches through the same inner join + (`join._inner_join`), and `GroupBy` imports the same preparation (ITL-1281), its rule + refusing structs (`part_without_rule(..., structs=False)`). +- `MergeJoin` is ordered, not commutative (developer, November 19, 2026, ITL-1281): + `MergeJoin()(a, b)` and `MergeJoin()(b, a)` are two operations with two identities + (`argument_symmetry` is a tuple), and each input's system-tag columns end in its argument + index. A colliding data column becomes `large_list` holding `[first argument's value, + second argument's value]` on every row, and its source-info column the two tokens in the same + order; nothing is sorted and no values are compared, so any value merges (a struct, a logical + type, a null). The lists are built from the joined Arrow arrays + (`arrow_utils.aggregated_list_array`), so every value is the input's, bit for bit. Colliding + columns must have identical Python types; inputs whose Arrow types still differ after + normalization raise `InputValidationError`. `T` is the large-normalized input Arrow type. - Operators predict their output schema (including system tag column names) without performing the actual computation. Verify a prediction against `unary_static_process(stream).output_schema(...)`, **not** against `process(...)` (which @@ -1386,8 +1401,8 @@ data. The rules: interval, a union, a list view) is refused (`InputValidationError`, `_refuse_unorderable_tags`), as a key and as a non-key tag (which orders the members): a struct has no decided order (developer, November 19, 2026), so drop it before grouping. A - key that is a list of any kind (a fixed-size list included) is refused as list-valued. `Batch` and `MergeJoin` still rebuild their lists from Python - (ITL-1281). The stance on `0.0`/`-0.0` and NaN for the whole library (match by value, as + key that is a list of any kind (a fixed-size list included) is refused as list-valued. `Batch` and `MergeJoin` build their lists from Arrow + arrays too (ITL-1281). The stance on `0.0`/`-0.0` and NaN for the whole library (match by value, as Polars does; show the smallest bit pattern; rewrite nothing) is ITL-1251. - `Data` source-info values may be `str`, `None`, or `list[...]`, nested to any depth; the Arrow and Python types are derived from the value, with `None` mapping to `large_string`. @@ -1397,12 +1412,13 @@ data. The rules: many→one operator must emit a list for **every** row of a list-valued column — mixing a bare `None` into some rows makes per-row `as_table()` schemas diverge and `pa.concat_tables` fail on the barrier path. -- Aggregating operators (`Batch`, `GroupBy`) must build list-valued columns via - `arrow_utils.build_aggregated_table`, never `pa.list_(field.type)`. The helper types every list - column with `aggregated_list_type`: `large_list` of the large-normalized element, or, because - Arrow cannot embed an extension type inside a list value field, the logical list type +- Operators that build lists (`Batch`, `GroupBy`, `MergeJoin`) build every list-valued column + with `arrow_utils.aggregated_list_array` (member values in member order, lists from offsets), + never from Python values and never `pa.list_(field.type)`. Its type comes from + `aggregated_list_type`: `large_list` of the large-normalized element, or, because Arrow + cannot embed an extension type inside a list value field, the logical list type (`list[]` from `ListLogicalType`) for a logical element such as a pod annotated - `-> Path`; it builds that list over the element's storage and wraps it. + `-> Path`; the list is built over the element's storage and wrapped. - Never build an identity or hash input from a type's raw `__module__`, or from `repr`/`str`/`inspect.formatannotation` of a type, without going through `utils/canonical_type_names.py` (`canonical_module_name`, `canonical_type_name`, diff --git a/changelog.d/ITL-1281.md b/changelog.d/ITL-1281.md new file mode 100644 index 000000000..a22611fa0 --- /dev/null +++ b/changelog.d/ITL-1281.md @@ -0,0 +1,24 @@ +### Breaking changes and migration + +- **`MergeJoin` is ordered, not commutative.** `MergeJoin()(a, b)` and `MergeJoin()(b, a)` + are two different steps with two identities: their content and pipeline hashes differ, and + so do the stored paths of everything downstream. A merged column holds, on every row, + `[value of the first argument, value of the second]`, and its source-info list the two + tokens in the same order; before, each merged column was sorted on its own values, so the + lists of one row did not follow the same input. Each input's system-tag columns now end in + its argument index (`:0`, `:1`) rather than its position in pipeline-hash order. Results + stored by a `MergeJoin` before this change are computed again. If your pipeline depended + on sorted lists, sort them in a function pod. (ITL-1281, ITL-1241) + +### Fixed + +- **`MergeJoin` and `Batch` keep every value exactly.** Both built their lists from Python + values: a `time64[ns]` value lost its nanoseconds, a `date64` value off midnight came back + at midnight, a float32 signaling NaN came back quiet, and `MergeJoin` panicked on a + `decimal256` column. The lists are now built from the inputs' Arrow arrays, so every value + is the input's, bit for bit, for every Arrow type; `MergeJoin` gives Polars only the + prepared join keys and row numbers, as `Join` does. `Batch`'s results change only for + inputs holding such values; no `Batch` golden value moves. (ITL-1281) +- **`MergeJoin` merges a colliding column holding nulls or structs.** It raised `TypeError` + for a null among the merged values (ITL-1243) and for struct values (ITL-839), because it + compared them; nothing is compared now. diff --git a/docs/concepts/arrays.md b/docs/concepts/arrays.md index e5a5c4012..0ec84815a 100644 --- a/docs/concepts/arrays.md +++ b/docs/concepts/arrays.md @@ -252,8 +252,8 @@ for tag, data in kept: ``` A stored array costs at least 128 bytes of `.npy` header. The stored bytes are NumPy's and -may differ between NumPy versions; nothing in Orcapod depends on them. Where an operator has -to order arrays (`MergeJoin` sorts the values it merges), it orders them by their value hash. +may differ between NumPy versions; nothing in Orcapod depends on them. No operator orders +arrays by their values: `MergeJoin` keeps its inputs' arrays in argument order. ## How an array is hashed diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index 4966f5959..e129eaa9b 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -195,8 +195,9 @@ print(joined.keys()) # (('unit', 'time'), ('unit', 'time', 'area', 'amp')) ``` -`MergeJoin` merges every other colliding data column into a sorted list, and keeps each -data-tag both inputs share as one column: +`MergeJoin` merges every other colliding data column into a list in argument order (the +first input's value, then the second's), and keeps each data-tag both inputs share as one +column: ```python more = op.sources.DictSource( @@ -211,7 +212,7 @@ print(merged.keys()) for tag, data in sorted(merged.iter_data(), key=lambda row: row[0]["time"]): print(tag["time"], data["time"], data["amp"]) # 10 10 [0.5, 0.75] -# 20 20 [0.125, 0.25] +# 20 20 [0.25, 0.125] ``` ```python diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 8d1d96c32..0cfef9533 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -235,8 +235,9 @@ hashes: the columns of `select_columns`, `drop_columns`, `drop_nulls` and the other selections, the entries of `map_tags`, `map_data` and `map_columns`, the constraints of `polars_filter`, `tag_only_columns`, `tags_as_data`; -- the order of the inputs of an operator that declares itself commutative (`Join`, - `MergeJoin`), and of the inputs of a function pod; +- the order of the inputs of an operator that declares itself commutative (`Join`), and of + the inputs of a function pod (`MergeJoin` and `SemiJoin` are ordered: their argument order + is an input you give); - the path the rows take: the sync and the async run give the same rows. What follows your order is where the columns are placed: `keys()`, `as_table()` and a @@ -273,7 +274,7 @@ The order counts only where it is the point of the argument: |---|---| | `record_id_columns` of every source (by default a database table's primary key) | A record id is the canonical JSON of the key columns in key order, so the key order is part of every record id and of the source's identity. It is the explicit argument that states the order. | | `member_order` of `GroupBy` (ITL-1226; not in a release yet) | The explicit order of the members inside each group's lists, the argument that replaces the input's tag order there. | -| the inputs of an operator whose `argument_symmetry` is a tuple (`SemiJoin`) | The inputs have roles: `SemiJoin(left, right)` keeps the rows of `left`. | +| the inputs of an operator whose `argument_symmetry` is a tuple (`SemiJoin`, `MergeJoin`) | The inputs have roles: `SemiJoin(left, right)` keeps the rows of `left`; `MergeJoin(a, b)` lists `a`'s value first in every merged list (ITL-1281). | | the order of the ROWS given to a source without key columns | Its record ids are the row positions, so a reorder is a change (by decision). Row order, never column order. | | the order of the ROWS given to `Batch` | `Batch` groups consecutive rows: row order, never column order. | | the fields of a user class (`@dataclass`, `orcapod.dataclass`, pydantic) | A class is identified with its fields in declared order: reordering them declares another type. | diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 16ec04a90..9c4e2eeed 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -97,10 +97,10 @@ reconciled this way. A plain tag and a data column never share a name across inputs: if one input has `x` as a plain tag column and another has it as a data column only, `Join` (and `MergeJoin`) raises `InputValidationError` when the graph is built; rename one with `map_tags` or `map_data`. A data-tag is the exception: it is one column in both roles, and `Join` merges a key that is a data-tag on its inputs (or plain on one and a data-tag on another) into a data-tag with one data column (see [Data-tags](data-tags.md)). -Column order follows each operator's argument symmetry: commutative operators (`Join`, -`MergeJoin`) list tag and data columns by first appearance across their inputs in canonical -pipeline-hash order, so `Join()(a, b)` and `Join()(b, a)` have the same columns in the same -order, while ordered operators such as `SemiJoin` keep operand order; either way, address +Column order follows each operator's argument symmetry: a commutative operator (`Join`) +lists tag and data columns by first appearance across its inputs in canonical pipeline-hash +order, so `Join()(a, b)` and `Join()(b, a)` have the same columns in the same order, while +ordered operators such as `SemiJoin` and `MergeJoin` keep operand order; either way, address columns by name rather than by position. ```python @@ -133,9 +133,13 @@ print(joined.as_table().to_pandas()) ### MergeJoin -Binary join that handles colliding data columns by merging their values into sorted -`list[T]`. Both inputs must have the same type for any colliding data columns. MergeJoin -is **commutative** -- the order of the two input streams does not affect the result. +Binary join that handles colliding data columns by merging their values into `list[T]`. +Both inputs must have the same type for any colliding data columns. Each merged list holds +the first input's value, then the second input's: MergeJoin is **ordered, not commutative** +(ITL-1281). Nothing is sorted, so the lists of a row are parallel: element 0 of every merged +column (and of its source-info list) comes from the first input's row, element 1 from the +second's. Any value merges, a struct, a logical type or a null included, and every value is +kept exactly as the input holds it. ```python from orcapod.sources import DictSource @@ -143,24 +147,35 @@ from orcapod.operators import MergeJoin scale_a = DictSource( data=[ - {"subject_id": "mouse_01", "weight": 25.3}, - {"subject_id": "mouse_02", "weight": 22.1}, + {"subject_id": "mouse_01", "weight": 25.3, "length": 8.1}, + {"subject_id": "mouse_02", "weight": 22.1, "length": 7.6}, ], tag_columns=["subject_id"], tag_only_columns=True, ) scale_b = DictSource( data=[ - {"subject_id": "mouse_01", "weight": 24.9}, - {"subject_id": "mouse_02", "weight": 22.6}, + {"subject_id": "mouse_01", "weight": 24.9, "length": 8.4}, + {"subject_id": "mouse_02", "weight": 22.6, "length": 7.2}, ], tag_columns=["subject_id"], tag_only_columns=True, ) +def by_subject(stream): + return sorted(stream, key=lambda row: row[0].as_dict()["subject_id"]) + merged = MergeJoin()(scale_a, scale_b) -for tag, data in merged: +for tag, data in by_subject(merged): print(tag.as_dict(), "->", data.as_dict()) -# {'subject_id': 'mouse_01'} -> {'weight': [24.9, 25.3]} -# {'subject_id': 'mouse_02'} -> {'weight': [22.1, 22.6]} +# {'subject_id': 'mouse_01'} -> {'weight': [25.3, 24.9], 'length': [8.1, 8.4]} +# {'subject_id': 'mouse_02'} -> {'weight': [22.1, 22.6], 'length': [7.6, 7.2]} + +swapped = MergeJoin()(scale_b, scale_a) +for tag, data in by_subject(swapped): + print(tag.as_dict(), "->", data.as_dict()) +# {'subject_id': 'mouse_01'} -> {'weight': [24.9, 25.3], 'length': [8.4, 8.1]} +# {'subject_id': 'mouse_02'} -> {'weight': [22.6, 22.1], 'length': [7.2, 7.6]} +print(merged.content_hash() == swapped.content_hash()) +# False ``` Passing the same two streams to `Join` instead raises `InputValidationError`, because both diff --git a/docs/dev/design_issues/ITL-1241-MJ4.md b/docs/dev/design_issues/ITL-1241-MJ4.md new file mode 100644 index 000000000..a82c1f70e --- /dev/null +++ b/docs/dev/design_issues/ITL-1241-MJ4.md @@ -0,0 +1,15 @@ +## `src/orcapod/core/operators/merge_join.py` — Arrow types + +### MJ4 — `MergeJoin(A, B)` and `MergeJoin(B, A)` gave tied values' source info in argument order +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1241 (related: ITL-1281) + +`MergeJoin` was documented as commutative and sorted each merged list by value. Two equal +values kept argument order, so their source-info list followed the order of the arguments +while both orders had one identity: an operator cache or a function pipeline table could hold +different provenance for one identity. + +**Fix:** resolved by ITL-1281 (MJ3): `MergeJoin` is ordered. `MergeJoin(A, B)` and +`MergeJoin(B, A)` are two operations with two identities, and every list of a row is in +argument order, so no tie exists. diff --git a/docs/dev/design_issues/ITL-1243-MJ5.md b/docs/dev/design_issues/ITL-1243-MJ5.md new file mode 100644 index 000000000..5b23961ea --- /dev/null +++ b/docs/dev/design_issues/ITL-1243-MJ5.md @@ -0,0 +1,14 @@ +## `src/orcapod/core/operators/merge_join.py` — Arrow types + +### MJ5 — `MergeJoin` raised `TypeError` when a colliding data column held a null +**Status:** resolved +**Severity:** high +**Issue:** ITL-1243 (related: ITL-1281) + +`MergeJoin` sorted each row's merged values as Python values, so a null beside a value (or +two nulls) raised `TypeError: '<' not supported between instances of ...`, and a run over +any nullable colliding column holding a null failed. + +**Fix:** resolved by ITL-1281 (MJ3): nothing is compared. A null is merged like any value, +in argument order: the merged column is `large_list`, never null itself, and its element +is null where the input's value is. diff --git a/docs/dev/design_issues/ITL-1281-BA1.md b/docs/dev/design_issues/ITL-1281-BA1.md new file mode 100644 index 000000000..7bc241aa3 --- /dev/null +++ b/docs/dev/design_issues/ITL-1281-BA1.md @@ -0,0 +1,18 @@ +## `src/orcapod/core/operators/batch.py` + +### BA1 — `Batch` changed values by rebuilding its lists from Python +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1281 (related: ITL-1250, ITL-1248) + +`Batch` read its input with `table.to_pylist()` and rebuilt every list column from the +Python values (`arrow_utils.build_aggregated_table`). A `time64[ns]` value lost its +nanoseconds, a `date64` value off midnight came back at midnight, and a float32 signaling +NaN came back quiet. + +**Fix:** a batch is consecutive rows, so each list is a slice of the input's column: the +lists are built from the input's Arrow arrays and offsets +(`arrow_utils.aggregated_list_array`), every value bit for bit, in the input's row order. +Batch sizes, drop modes, system-tag folds and types are unchanged; no golden value moves. +`build_aggregated_table` and `list_array`, the builders from Python values, are gone. Tests: +`tests/test_core/operators/test_batch_values.py`. diff --git a/docs/dev/design_issues/ITL-1281-MJ3.md b/docs/dev/design_issues/ITL-1281-MJ3.md new file mode 100644 index 000000000..34dc632d0 --- /dev/null +++ b/docs/dev/design_issues/ITL-1281-MJ3.md @@ -0,0 +1,27 @@ +## `src/orcapod/core/operators/merge_join.py` — Arrow types + +### MJ3 — `MergeJoin` changed values and misaligned its lists by sorting Python values +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1281 (related: ITL-1241, ITL-1243, ITL-839, ITL-1250, ITL-1284) + +`MergeJoin` carried every column through a Polars join and built each merged column from +Python values (`to_pylist`), sorting each row's two values per column. A value with no exact +Python form changed on the way: a `time64[ns]` value lost its nanoseconds, a `date64` value +off midnight came back at midnight, a float32 signaling NaN came back quiet, and a +`decimal256` column made Polars panic. Each column was sorted on its own values, so with two +colliding columns one row could hold `x = [3, 5]` (from B, A) beside `y = [1.0, 2.0]` (from +A, B): the lists were not parallel by origin row. A null among the values (ITL-1243) or a +struct value (ITL-839) could not be sorted and raised `TypeError`, and tied values kept +argument order (ITL-1241). + +**Fix:** `MergeJoin` is ordered, not commutative (developer, November 19, 2026): its identity +holds its inputs as a tuple, each input's system-tag columns end in its argument index, and a +merged list is `[first argument's value, second argument's value]` with its source-info list +in the same order. Nothing is sorted. Polars only matches prepared keys and row numbers +(`Join`'s `_inner_join`, `arrow_keys`); every output value is taken from the input tables +and the lists are built from their arrays (`arrow_utils.aggregated_list_array`), so every +value is the input's, bit for bit, for every Arrow type. The 21 golden entries of +`pipeline:merge_join` and the `merge_join.*` entries of `pipeline:join_key_nullability` +moved, as approved by the developer. Tests: +`tests/test_core/operators/test_merge_join_values.py`. diff --git a/docs/dev/design_issues/ITL-839-MJ6.md b/docs/dev/design_issues/ITL-839-MJ6.md new file mode 100644 index 000000000..dab41f309 --- /dev/null +++ b/docs/dev/design_issues/ITL-839-MJ6.md @@ -0,0 +1,13 @@ +## `src/orcapod/core/operators/merge_join.py` — Arrow types + +### MJ6 — `MergeJoin` raised `TypeError` when a colliding data column held struct values +**Status:** resolved +**Severity:** high +**Issue:** ITL-839 (related: ITL-1281) + +`MergeJoin` sorted each row's merged values as Python values; a struct value is a `dict`, +which cannot be ordered, so a colliding struct column raised `TypeError`. + +**Fix:** resolved by ITL-1281 (MJ3): nothing is compared, and the lists are built from the +inputs' Arrow arrays, so a struct column (and a list of structs, a user class) merges into +`large_list>` in argument order. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 2b6da1705..58cd60338 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -330,7 +330,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | `schema:` / `instance:` / `node:` path components | `core/nodes/function_node.py:FunctionNodeBase.node_identity_path`, `core/nodes/operator_node.py:OperatorNodeBase.node_identity_path`, `side_effects.py:SideEffectJobNode.attach_databases`, `core/sources/cached_source.py:CachedSource._unversioned_cache_path` | | source-node slot names | `core/nodes/source_node.py:SourceNode.from_stream`, `core/nodes/source_node.py:SourceJobNode.from_stream` | | source system-tag column name (schema digest) | `utils/schema_utils.py:compute_schema_hash` | -| system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._predict_system_tag_schema`, `core/operators/merge_join.py:MergeJoin.binary_static_process`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | +| system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._system_tag_suffix`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | | a saved hash shown as a digest | `core/nodes/function_node.py:_bare_digest` | | source ids (`: