diff --git a/.zed/rules b/.zed/rules index daef1f173..96ffebf28 100644 --- a/.zed/rules +++ b/.zed/rules @@ -437,8 +437,7 @@ Developer, November 12, 2026 (ITL-981); see `docs/concepts/arrays.md` and (`orcapod.numpy.ndarray`). The leading type text of a value hash is the extension name. - `numpy.ndarray`: one `.npy` file per cell (`numpy.lib.format`, format 3.0, `allow_pickle=False` on write and read; never raise `max_header_size`). Options: - `memory_order`, `byte_order`, `struct_layout`. Where stored arrays must be ordered, order - them by value hash (`storage_sort_key`), never by stored bytes. + `memory_order`, `byte_order`, `struct_layout`. No operator orders stored arrays (ITL-1281). - Library value types are provisional until the library value type audit, after 0.4.0rc1 (developer, November 13, 2026, ITL-1068; moved past 0.4.0rc1 on November 17, 2026): their extension names are listed in `provisional` of `contexts/logical_types.json`, and using @@ -679,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) @@ -990,7 +989,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 @@ -1109,15 +1109,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: @@ -1126,6 +1128,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 @@ -1330,18 +1337,27 @@ data. The rules: number (`take`), so every value is the input's, bit for bit (they used to carry every column through Polars: a `date64` off midnight came back at midnight, a `decimal256` made Polars panic). Keys are prepared in one place, `core/operators/arrow_keys.py` (`polars_ready`: a - logical type as its storage, a dictionary decoded, a temporal value as its integer, `float16` + logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, through lists, fixed-size lists and structs; `part_without_rule` says what may reach Polars). A key whose type has no rule (a map, an interval, a union, a list view) is refused with `InputValidationError` naming the column (`base.require_matchable_key`) on both paths, before rows are matched (never at validation, which would derive every input's zero-row - table on each graph build). `GroupBy` keeps its own copy of the preparation until ITL-1281, which also - moves `MergeJoin` off its round trip. -- MergeJoin requires colliding data columns to have identical Python types; merges into sorted - large_list with source columns reordered to match, where T is the large-normalized input - Arrow type; inputs whose Arrow types still differ after normalization raise - 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 (a + null-typed column read as rows or on the async path is typed large_string, Data's + null convention: ITL-1319). 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: @@ -1411,17 +1427,17 @@ data. The rules: Python's precision (`time64[ns]` within a microsecond, `date64` on one day) are separate groups. A list-valued tag sorts through `(is_null, value)` pairs at every depth (`_sort_key`: Polars puts a null inside a list first). The sort frame only sees prepared columns - (`_polars_ready`: a logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as + (`arrow_keys.polars_ready`: a logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, which Polars cannot read (it panics, which no caller can catch), every list kind, fixed-size lists included, as a large list - over its prepared values). What may reach it is one rule, `_unorderable_part` (an integer, + over its prepared values). What may reach it is one rule, `arrow_keys.part_without_rule(..., structs=False)` (an integer, float, decimal, boolean, string, binary, date, time, timestamp, duration or null, through logical storage and lists of every kind at every depth; no dictionary, since no stream carries one, ITL-1264), checked from the schema at validation and from the table when grouping (the async path skips validation); anything else is refused, never passed through. The output is built from the input's Arrow table: `take()` in the sorted order and list arrays from group offsets (`arrow_utils.aggregated_list_array`, the - array-based sibling of `build_aggregated_table`), so every key and list element is a value + one way an operator builds a list), so every key and list element is a value a member holds, bit for bit (`time64[ns]` keeps its nanoseconds, a float32 signaling NaN its bits; ITL-1248 for `GroupBy`). The hashes read a float's bits, so a group emits, for each float key column (a logical type stored as a float included), its members' value with the smallest bit pattern at the column's own width @@ -1433,8 +1449,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. - The presentation order (`arrow_utils.sort_by_tag_columns`: `as_table(columns={"sort_by_tags": True})`, `head().sort_by_tags()`, the preview) is ascending by the tags, then the system tags, nulls @@ -1451,12 +1467,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 51ff0b3d9..b00961afe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -448,8 +448,7 @@ Developer, November 12, 2026 (ITL-981); see `docs/concepts/arrays.md` and (`orcapod.numpy.ndarray`). The leading type text of a value hash is the extension name. - `numpy.ndarray`: one `.npy` file per cell (`numpy.lib.format`, format 3.0, `allow_pickle=False` on write and read; never raise `max_header_size`). Options: - `memory_order`, `byte_order`, `struct_layout`. Where stored arrays must be ordered, order - them by value hash (`storage_sort_key`), never by stored bytes. + `memory_order`, `byte_order`, `struct_layout`. No operator orders stored arrays (ITL-1281). - Library value types are provisional until the library value type audit, after 0.4.0rc1 (developer, November 13, 2026, ITL-1068; moved past 0.4.0rc1 on November 17, 2026): their extension names are listed in `provisional` of `contexts/logical_types.json`, and using @@ -691,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) @@ -1021,7 +1020,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 @@ -1153,15 +1153,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: @@ -1170,6 +1172,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 @@ -1374,18 +1381,27 @@ data. The rules: number (`take`), so every value is the input's, bit for bit (they used to carry every column through Polars: a `date64` off midnight came back at midnight, a `decimal256` made Polars panic). Keys are prepared in one place, `core/operators/arrow_keys.py` (`polars_ready`: a - logical type as its storage, a dictionary decoded, a temporal value as its integer, `float16` + logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, through lists, fixed-size lists and structs; `part_without_rule` says what may reach Polars). A key whose type has no rule (a map, an interval, a union, a list view) is refused with `InputValidationError` naming the column (`base.require_matchable_key`) on both paths, before rows are matched (never at validation, which would derive every input's zero-row - table on each graph build). `GroupBy` keeps its own copy of the preparation until ITL-1281, which also - moves `MergeJoin` off its round trip. -- MergeJoin requires colliding data columns to have identical Python types; merges into sorted - `large_list` with source columns reordered to match, where `T` is the large-normalized input - Arrow type; inputs whose Arrow types still differ after normalization raise - `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 (a + `null`-typed column read as rows or on the async path is typed `large_string`, `Data`'s + null convention: ITL-1319). 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 @@ -1458,17 +1474,17 @@ data. The rules: Python's precision (`time64[ns]` within a microsecond, `date64` on one day) are separate groups. A list-valued tag sorts through `(is_null, value)` pairs at every depth (`_sort_key`: Polars puts a null inside a list first). The sort frame only sees prepared columns - (`_polars_ready`: a logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as + (`arrow_keys.polars_ready`: a logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, which Polars cannot read (it panics, which no caller can catch), every list kind, fixed-size lists included, as a large list - over its prepared values). What may reach it is one rule, `_unorderable_part` (an integer, + over its prepared values). What may reach it is one rule, `arrow_keys.part_without_rule(..., structs=False)` (an integer, float, decimal, boolean, string, binary, date, time, timestamp, duration or null, through logical storage and lists of every kind at every depth; no dictionary, since no stream carries one, ITL-1264), checked from the schema at validation and from the table when grouping (the async path skips validation); anything else is refused, never passed through. The output is built from the input's Arrow table: `take()` in the sorted order and list arrays from group offsets (`arrow_utils.aggregated_list_array`, the - array-based sibling of `build_aggregated_table`), so every key and list element is a value + one way an operator builds a list), so every key and list element is a value a member holds, bit for bit (`time64[ns]` keeps its nanoseconds, a float32 signaling NaN its bits; ITL-1248 for `GroupBy`). The hashes read a float's bits, so a group emits, for each float key column (a logical type stored as a float included), its members' value with the smallest bit pattern at the column's own width @@ -1480,8 +1496,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. - The presentation order (`arrow_utils.sort_by_tag_columns`: `as_table(columns={"sort_by_tags": True})`, `head().sort_by_tags()`, the preview) is ascending by the tags, then the system tags, nulls @@ -1499,12 +1515,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-1023.md b/changelog.d/ITL-1023.md index a866eb1ab..c7e64cf66 100644 --- a/changelog.d/ITL-1023.md +++ b/changelog.d/ITL-1023.md @@ -121,7 +121,7 @@ the other input has it as a plain tag or not at all; a data-only column of that name in the other input is refused. 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 before; inputs without data-tags merge exactly as before. + list, as for inputs without data-tags (in argument order since ITL-1281). ### Changed diff --git a/changelog.d/ITL-1281.md b/changelog.d/ITL-1281.md new file mode 100644 index 000000000..72f08297d --- /dev/null +++ b/changelog.d/ITL-1281.md @@ -0,0 +1,34 @@ +### 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 hashes differ whenever `a` and + `b` are different sources, and so do the stored paths of everything downstream; their + pipeline hashes differ when the inputs' pipeline hashes do (two inputs of one schema have + one pipeline hash, so the ordered pair is the same either way). 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) + +### Changed + +- **`storage_sort_key` is removed** from the NumPy array and torch tensor logical types, at + the developer's request: its one caller was `MergeJoin`'s sort, which is gone. (ITL-1281) + +### 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. Not covered: a data column of + the Arrow `null` type (or a list of it) keeps that type in the result's table, but read as + rows or on the async path it follows `Data`'s null convention and is typed + `large_string` (ITL-1319, as before this change for `Batch`). (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 501a24f58..93c6c8b07 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -203,7 +203,7 @@ your own classes and logical types (`Path`, `UUID`, arrays) are refused. | Filters, `DropNulls`, `SemiJoin`, `Pick`, `Index` | Keep the data-tag. | | `AddTags` / `add_tags` | Keeps every data-tag; the new tags, constants, are plain tags. A new tag named like any column, a data-tag included, is refused. | | `Batch` | Keeps every tag, list-valued, as for plain tags: `x` becomes the same list in both roles and stays a data-tag. Its source info is one token per member, like any data column: nothing is merged. | -| `MergeJoin` | Follows `Join`. A data-tag in both inputs: **one** scalar data-tag column `x`, not a two-element list (the join equated the values), with one merged token as its source info, the same fold as `Join`'s (below). A data-tag in one input, and a plain tag or no column of that name in the other: `x` stays a data-tag with its own source info. A data-only column `x` in the other input is refused. A key that is `T` in one input and `T \| None` in the other is `T` in both roles. Every other colliding data column is merged into a sorted list, as before. | +| `MergeJoin` | Follows `Join`. A data-tag in both inputs: **one** scalar data-tag column `x`, not a two-element list (the join equated the values), with one merged token as its source info, the same fold as `Join`'s (below). A data-tag in one input, and a plain tag or no column of that name in the other: `x` stays a data-tag with its own source info. A data-only column `x` in the other input is refused. A key that is `T` in one input and `T \| None` in the other is `T` in both roles. Every other colliding data column is merged into a list in argument order: the first input's value, then the second's (ITL-1281). | ```python units = op.sources.DictSource( @@ -216,8 +216,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( @@ -232,7 +233,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..9cc4376b1 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 (for the ordered operators, see the table of orders that + count below); - 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 74cd7f1a2..05a2072aa 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,15 @@ 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. (A data column of the Arrow `null` type keeps that type +in the result's table; read as rows, or on the async path, it is typed `large_string`, as +every row reads a `null` column: ITL-1319.) ```python from orcapod.sources import DictSource @@ -143,24 +149,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 @@ -881,6 +898,9 @@ silent widening; convert explicitly. where the sync path returns an empty stream with typed columns the async path emits nothing. An operator node that received no rows still reads back the sync path's columns and Arrow types: its operator applied to its inputs' zero-row tables (ITL-858, ITL-912). + A second limit: a data column of the Arrow `null` type (or a list of it) is typed + `large_string` in a row, so the async path, which carries rows, types it so too + (ITL-1319). ```python import pyarrow as pa 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/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/docs/dev/scripts/itl_1295/compare_sort_fallback.py b/docs/dev/scripts/itl_1295/compare_sort_fallback.py index 9aeca4bbc..a6eadf167 100644 --- a/docs/dev/scripts/itl_1295/compare_sort_fallback.py +++ b/docs/dev/scripts/itl_1295/compare_sort_fallback.py @@ -292,7 +292,14 @@ def audit() -> None: results: Counter[str] = Counter() for type_name, values in audit_types().items(): for label, table, keys in audit_tables(values): - new = arrow_utils._tag_order_by_polars(table, keys).to_pylist() # pyright: ignore[reportPrivateUsage] + try: + new = arrow_utils._tag_order_by_polars(table, keys).to_pylist() # pyright: ignore[reportPrivateUsage] + except TypeError: + # Since ITL-1281 the key preparation has no rule for a dictionary (no + # stream carries one, ITL-1264): the sort refuses such a tag. + results["refused (no rule)"] += 1 + print(f"{type_name:22} {label:40} refused (no rule)") + continue outcome = compare(table, keys, new) results[outcome["result"]] += 1 line = f"{type_name:22} {label:40} {outcome['result']}" diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 6db505a7d..fc802d168 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -331,7 +331,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 (`: