diff --git a/.zed/rules b/.zed/rules index 5b6fdb8ab..d25939d96 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1246,8 +1246,7 @@ data. The rules: dropped tags still order the members, so the data lists are as before. Their values are not carried: a step that needs them makes the column data before grouping (at the source, or DerivedSource(tags_as_data=...)). A list-valued tag of the input (a list-typed source tag) - can still order members, so the member sort key (_null_last_key) is - recursive and sorts nulls last at every depth. A grouped stream grouped again on a coarser + can still order members, element by element, nulls last at every depth. A grouped stream grouped again on a coarser key orders its members by the first grouping's keys outside the coarser key, then by record id. An opt-in mode that keeps non-key tags is ITL-1071. - GroupBy never depends on how its input's columns are arranged (developer, November 17, 2026, ITL-1226). Members are ordered by the non-key tags in name order (each ascending, @@ -1261,23 +1260,42 @@ data. The rules: record ids, folds, source-info tokens and hashes; only the output's column order follows the input, as presentation. `TagBy`'s identity is its sorted names, and its new tags are placed in name order. -- `GroupBy` groups keys as the joins match them, except null (developer, November 17, 2026, - ITL-1234): all rows with a null key form one group, and so do all rows with a NaN key (the - grouping key holds every NaN as one object, `_grouping_key`); `0.0` equals `-0.0`. A NaN key - sorts after every number and before null, as in the member order (`_null_last_key`, which - also sorts a NaN tag after every number). The hashes read a float's bits, so a group emits, - for each float key column, its members' value with the smallest bit pattern at the column's - own width, float16, float32 or float64 (`_emitted_key_row`: `0.0` over `-0.0`, a positive NaN - over a negative one; a signaling NaN has smaller bits than the canonical quiet NaN, so it - wins), taken from the input's Arrow column, never through Python (a float32 signaling NaN - comes back quiet from Python): always a value a member holds, never the first row's, never - chosen by `member_order`. Bits are read only for a group whose key is zero or NaN. A logical - type stored as a float, or a dictionary-encoded float, is a float key, read through its - storage or its values (`_float_storage`). Every - other key is rebuilt from its Python value, as before: equal Python values that differ in - Arrow (`time64[ns]` within a microsecond) are one group with one rebuilt key; grouping by - the exact value is ITL-1250. 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. +- `GroupBy` groups keys by their Arrow value, as the joins match them, except null (developer, + November 17, 2026, ITL-1234; November 19, 2026, ITL-1250): all rows with a null key form one + group, and so do all rows with a NaN key; `0.0` equals `-0.0`. It decides which rows group + and in what order with Polars, never through Python values: one stable sort of a frame of + the keys (name order), the member-order tags, the record-id and source-id columns + (`nulls_last`; Polars ties `0.0` with `-0.0` and every NaN, and puts NaN after every number + and before null), group boundaries by Polars' equality (`rle_id`). Keys that differ below + 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 dictionary decoded in one place, + `_without_dictionary`, 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, + float, decimal, boolean, string, binary, date, time, timestamp, duration or null, through + logical storage, dictionary values and lists of every kind at every depth), 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 + 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, or a dictionary over floats, + included), its members' value with the smallest bit pattern at the column's own width + (`0.0` over `-0.0`, a positive NaN over a negative one; a signaling NaN has smaller bits + than the canonical quiet NaN, so it wins): never the first row's, never chosen by + `member_order`. Every other key is the group's first member's (equal values are identical). + Only the system-tag and key source-info folds read Python values, which are text. A user tag + whose type has no order (a struct or a map, such as a user class or a `dict[K, V]`, an + 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 + 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 definition, arrow_utils.source_info_arrow_type, and applies only to tokens supplied as diff --git a/CLAUDE.md b/CLAUDE.md index a2514f2cb..4521206e1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1293,8 +1293,7 @@ data. The rules: dropped tags still order the members, so the data lists are as before. Their values are not carried: a step that needs them makes the column data before grouping (at the source, or `DerivedSource(tags_as_data=...)`). A list-valued tag of the input (a list-typed source tag) - can still order members, so the member sort key (`_null_last_key`) is - recursive and sorts nulls last at every depth. A grouped stream grouped again on a coarser key + can still order members, element by element, nulls last at every depth. A grouped stream grouped again on a coarser key orders its members by the first grouping's keys outside the coarser key, then by record id. An opt-in mode that keeps non-key tags is ITL-1071. - GroupBy never depends on how its input's columns are arranged (developer, November 17, 2026, ITL-1226). Members are ordered by the non-key tags in name order (each ascending, @@ -1308,23 +1307,42 @@ data. The rules: record ids, folds, source-info tokens and hashes; only the output's column order follows the input, as presentation. `TagBy`'s identity is its sorted names, and its new tags are placed in name order. -- `GroupBy` groups keys as the joins match them, except null (developer, November 17, 2026, - ITL-1234): all rows with a null key form one group, and so do all rows with a NaN key (the - grouping key holds every NaN as one object, `_grouping_key`); `0.0` equals `-0.0`. A NaN key - sorts after every number and before null, as in the member order (`_null_last_key`, which - also sorts a NaN tag after every number). The hashes read a float's bits, so a group emits, - for each float key column, its members' value with the smallest bit pattern at the column's - own width, float16, float32 or float64 (`_emitted_key_row`: `0.0` over `-0.0`, a positive NaN - over a negative one; a signaling NaN has smaller bits than the canonical quiet NaN, so it - wins), taken from the input's Arrow column, never through Python (a float32 signaling NaN - comes back quiet from Python): always a value a member holds, never the first row's, never - chosen by `member_order`. Bits are read only for a group whose key is zero or NaN. A logical - type stored as a float, or a dictionary-encoded float, is a float key, read through its - storage or its values (`_float_storage`). Every - other key is rebuilt from its Python value, as before: equal Python values that differ in - Arrow (`time64[ns]` within a microsecond) are one group with one rebuilt key; grouping by - the exact value is ITL-1250. 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. +- `GroupBy` groups keys by their Arrow value, as the joins match them, except null (developer, + November 17, 2026, ITL-1234; November 19, 2026, ITL-1250): all rows with a null key form one + group, and so do all rows with a NaN key; `0.0` equals `-0.0`. It decides which rows group + and in what order with Polars, never through Python values: one stable sort of a frame of + the keys (name order), the member-order tags, the record-id and source-id columns + (`nulls_last`; Polars ties `0.0` with `-0.0` and every NaN, and puts NaN after every number + and before null), group boundaries by Polars' equality (`rle_id`). Keys that differ below + 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 dictionary decoded in one place, + `_without_dictionary`, 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, + float, decimal, boolean, string, binary, date, time, timestamp, duration or null, through + logical storage, dictionary values and lists of every kind at every depth), 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 + 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, or a dictionary over floats, + included), its members' value with the smallest bit pattern at the column's own width + (`0.0` over `-0.0`, a positive NaN over a negative one; a signaling NaN has smaller bits + than the canonical quiet NaN, so it wins): never the first row's, never chosen by + `member_order`. Every other key is the group's first member's (equal values are identical). + Only the system-tag and key source-info folds read Python values, which are text. A user tag + whose type has no order (a struct or a map, such as a user class or a `dict[K, V]`, an + 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 + 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`. That rule has one definition, `arrow_utils.source_info_arrow_type`, and applies only to diff --git a/changelog.d/ITL-1250.md b/changelog.d/ITL-1250.md new file mode 100644 index 000000000..1971de82d --- /dev/null +++ b/changelog.d/ITL-1250.md @@ -0,0 +1,21 @@ +### Breaking changes and migration + +- **`GroupBy` refuses a tag whose type has no order** (a struct or a map, such as a user + class or a `dict[K, V]`, an interval, a union), as a key and as a non-key tag, with + `InputValidationError`: every non-key tag orders a group's members. Before, such a tag + raised a bare `TypeError` while grouping (except when no group had two members), or an + error from Polars. Drop the tag before grouping (`select_tag_columns`); `GroupBy` drops a + non-key tag anyway. A fixed-size-list key is refused as list-valued, as any list key is. + (ITL-1250) + +### Fixed + +- **`GroupBy` groups, orders and emits by Arrow value, never by Python value.** It decides + which rows form a group and in what order with Polars, and builds its output from the + input's Arrow columns. Keys that differ only below what Python keeps are now separate + groups (`time64[ns]` values of 1 ns and 2 ns were one group emitting 0 ns; two `date64` + values on one day were one group at midnight), and members are ordered by such tags + exactly. The data lists hold the members' values bit for bit: before, a `time64[ns]` value + lost its nanoseconds, a `date64` value its time of day, and a float32 signaling NaN came + back quiet (ITL-1248). Results change only for inputs holding such values; no golden + value moves. `GroupBy` is also 5 to 8 times faster on 1e6 rows. (ITL-1250) diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 1f96c98eb..31387ef9f 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -316,9 +316,12 @@ cache keys: - **Groups** are emitted sorted by their keys, taken in name order. The order of the names in `by` is not part of the operator: `GroupBy(by=["a", "b"])` and `GroupBy(by=["b", "a"])` are one operator. -- **Keys** group as the joins match them, except for null: rows with equal keys form one - group, all rows with a null key form one group, and so do all rows with a NaN key (NaN - equals NaN here; `0.0` equals `-0.0`). A NaN key sorts after every number and before null. +- **Keys** group by their Arrow value, as the joins match them, except for null: rows with + equal keys form one group, all rows with a null key form one group, and so do all rows + with a NaN key (NaN equals NaN here; `0.0` equals `-0.0`). A NaN key sorts after every + number and before null. `GroupBy` compares and orders values with Polars, never as Python + values, so keys that differ only below what Python keeps are two groups: `time64[ns]` + values of 1 ns and 2 ns, or two `date64` values on one day. When the members of a group hold a float key with different bits (`0.0` and `-0.0`, or NaN with another sign or payload), the group emits the one with the smallest bit pattern at the column's own width (`float16`, `float32` or `float64`; a logical type stored as a @@ -327,6 +330,10 @@ cache keys: NaN has smaller bits than the canonical quiet NaN, so when a member holds one, it is the key emitted. The emitted key is always a value a member holds, bit for bit, and neither the order of the rows nor `member_order` decides it. +- **Values are kept exactly.** Every emitted key and every element of a data list is taken + from the input's Arrow columns, so a list holds its members' values bit for bit: a + `time64[ns]` value keeps its nanoseconds, a `date64` value its time of day, a float its + bits (a signaling NaN stays signaling). - **No arrangement of the input's columns changes the result.** The order of its tags, the order of its data columns and the layout of its table leave every value, record id and hash of the output unchanged. The output lists its columns as the input does (the keys in @@ -369,6 +376,14 @@ Every name in `by` must be a **scalar tag column** of the input. `GroupBy` raise the last usually means the stream came from `Batch`, so group *before* batching rather than after. +A tag whose type has no order can be neither a key nor a non-key tag of the input, because +every non-key tag orders the members: a struct or a map (a user class, a `dict[K, V]`), an +interval, a union. `GroupBy` raises `InputValidationError` for it, from the schema alone. A +key that is a list of any kind, a fixed-size list included, is refused as list-valued. Since +`GroupBy` drops a non-key tag anyway, drop it before grouping, with `select_tag_columns` +naming the tags to keep. A list-valued non-key tag orders the members element by element, +nulls last at every depth. + Streams also expose this as a fluent method. A single column may be given as a string, as for every operator that takes column names (a string is one name, never its characters): diff --git a/docs/dev/plans/itl-1250-groupby-polars.md b/docs/dev/plans/itl-1250-groupby-polars.md new file mode 100644 index 000000000..4d4243a9d --- /dev/null +++ b/docs/dev/plans/itl-1250-groupby-polars.md @@ -0,0 +1,176 @@ +# ITL-1250: GroupBy groups through Polars, builds from Arrow (plan) + +Branch `eywalker/itl-1250-groupby-compares-keys-as-python-values`, from `origin/main` at +`a026d31f`. Status: approved by the coordinator on 2026-11-19 with the decisions at the end; +implemented. + +Every number below was measured before the change, on `main`, against a prototype of the +design that replaced `GroupBy.unary_static_process` in the measuring process (the prototype +became the implementation and is not kept). The scripts in `docs/dev/scripts/itl_1250/` +measure the checkout they run in: `measure_keys.py` ((a), GroupBy against Polars), +`measure_data_values.py` (the data lists against the input), `timing.py` ((d), run on each +checkout) and `measure_batch_merge_join.py` ((f)). +Library versions: Polars 1.41.2 (locked; `pyproject.toml` allows `>=1.36.0`), PyArrow +23.0.1, pandas 2.2.3. + +## Design + +1. **Which rows group, in what order: one Polars sort.** A frame with synthetic column + names (no user name can collide) holds the row number, the keys (`by`, in name order), + the member-order tags (`member_order`, then the other non-key tags in name order), the + record-id columns, then the source-id columns. One stable sort, + `nulls_last=True, maintain_order=True`, gives the group order and the member order at + once. Group boundaries are `pl.struct(keys).rle_id()`: Polars' own equality. +2. **Polars needs help with a few types**, prepared in Arrow, in the sort frame only: + - an extension type becomes its storage; a dictionary is decoded (only until PR 455 + merges, which refuses dictionary tags); + - `float16` is cast to `float32` (exact for order and equality; the emitted bits are + read from the original column). Polars 1.41 has `Float16`, but the floor 1.36 may not; + - `decimal256` (Polars panics: "operator does not support primitive `Int256`") becomes + four 64-bit limbs (top limb signed), which order and compare as the values do; + - nulls inside a list sort FIRST in Polars, against the rule (nulls last at every + depth): a list-valued tag is sorted through a recursive key, `struct(is_null, value)` + at every depth. Measured equal to main's order on every list case (below). +3. **The output is built from the original Arrow table**: `take()` in the sorted row order, + then list arrays from group offsets (`LargeListArray.from_arrays` with the exact + `aggregated_list_type`, or its storage then wrapped for a logical element). No data + value passes through Python or Polars, so no `restore_column_types` is needed: nothing + comes back from Polars but row numbers and group sizes. I would add that builder beside + `build_aggregated_table` in `arrow_utils` (it takes arrays, not Python rows); `Batch` + and `MergeJoin` could move to it later (see (f)). +4. **The emitted key**: a float key (float storage, logical type over a float) takes, + per group, the member with the smallest bit pattern (the unsigned view of the original + storage, `arg_min` per group in Polars); a null key through a null index. Every other + key takes the group's first member: equal under Polars equality means identical + values for those types. +5. **Folds**: system tags and a data-tag key's source info fold as today + (`fold_system_tag_values`, `group_v1`), over the sorted strings; strings lose nothing + in Python. +6. Validation, identity, config, `unary_output_schema`, the data-tag handling (ITL-1017, + ITL-1070) and the async path (barrier, through `static_process`) are unchanged. + +## (a) Grouping per key type: main (Python dict) against Polars + +`measure_keys.py`: partitions of the row numbers. + +| Key type | main | Polars | | +|---|---|---|---| +| int8/16/32/64, uint8/16/32/64 (min, max, 0, null) | | | same | +| float16/32/64: NaN, -NaN, payload NaN, signaling NaN, -0.0, 0.0, 1.0, null | all NaN one group; 0.0 = -0.0 | same | same | +| bool, large_string (incl. `é` and `é`: two groups), large_binary, fixed_size_binary(4), date32, null type | | | same | +| **date64** 0 ms, 1 ms, 1 day, 1 day + 1 ms | 2 groups (`datetime.date`) | 4 groups | **DIFFER** | +| time32[s], time32[ms], time64[us] | | | same | +| **time64[ns]** 1, 2, 1000, 1001 ns | 2 groups (`datetime.time`, us) | 4 groups | **DIFFER** | +| timestamp[s/ms/us/ns], tz None / UTC / America/New_York | | | same (ns: pandas `Timestamp` keeps ns) | +| duration[s/ms/us/ns] | | | same (ns: pandas `Timedelta`) | +| decimal128(38,10): 1.0000000001, 1.0000000002, 1, 1.0000000000 | | | same | +| decimal256(76,40) | 4 groups | Polars panics | same after the limb encoding | +| logical Path (large_string), logical UUID (fixed_size_binary(16)) | | | same | +| struct key (a user class tag), `dict[K, V]` tag (`large_list>`), Arrow map | bare `TypeError: unhashable type` at run time | Polars groups them | see decision 1 | + +Equal decimals at different scales cannot be in one column: the scale is part of the +type. A list-valued key is refused at validation, as today. + +## (b) Member order: main (`sorted` + `_null_last_key`) against a Polars sort + +`measure_order.py`, a tie shows through a descending second column. + +| Ordering tag | Result | +|---|---| +| int64 with nulls; float64 NaN variants, -0.0, 0.0, ±inf, null; float32 -0.0/0.0/NaN; large_string with non-ASCII (UTF-8 byte order = code point order); large_binary; bool | same: Polars ties -0.0 with 0.0 and every NaN with every NaN, puts NaN after +inf and before null | +| large_list, large_list, large_list>, large_list, nulls at every depth | DIFFER with a plain Polars sort (nulls inside a list first); **same** with the recursive `struct(is_null, value)` key | +| time64[ns], date64 (values below Python's precision) | main ties them and falls to the next column; Polars orders them exactly: the rule (order by the tag's value) is Polars' | +| struct (a user class tag), `dict[K, V]` tag | main: bare `TypeError` when a group has two members; Polars sorts structs field by field in declared order: see decision 2 | + +## (c) Pinned values that move + +- `generate_golden_hashes.py --check` with the prototype installed: "golden values of + semantic, schema, arrow, datagram, pipeline, torch match". **No golden entry moves.** +- Every test file that names `GroupBy` or `group_by(` (52 files, 15,626 tests) plus + `tests/test_hashing/golden/`, with the prototype: 1 failure, + `tests/test_core/operators/test_group_by_nan_keys.py::test_a_time64_ns_key_is_rebuilt_from_its_python_value`, + the PR 441 pin of the ITL-1250 merge (1 ns and 2 ns as one group emitting 0 ns). It + becomes the test of the fix: two groups, keys 1 ns and 2 ns. +- The 8 other test files with a 64-hex literal: 291 passed. +- What moves outside the pins: any input whose keys, ordering tags or data values differ + below Python's precision (time64[ns], date64 off midnight, float32 signaling NaN in + data). No test or golden value holds one. + +## (d) Timing (one process at a time; source built before timing) + +| Rows | Groups | main | prototype | main peak RSS | prototype peak RSS | +|---|---|---|---|---|---| +| 1e5 | 10 | 0.38 s | 0.07 s | 272 MB | 252 MB | +| 1e5 | 1e3 | 0.36 s | 0.07 s | 277 MB | 253 MB | +| 1e5 | 1e5 (63,249 distinct) | 0.92 s | 0.23 s | 375 MB | 279 MB | +| 1e6 | 10 | 5.51 s | 0.69 s | 1.15 GB | 683 MB | +| 1e6 | 1e3 | 4.37 s | 0.70 s | 1.15 GB | 682 MB | +| 1e6 | 1e5 | 4.88 s | 1.07 s | 1.38 GB | 731 MB | + +Most of what remains is the per-group SHA-256 folds of the system tags, as before. + +## Data values in the lists (beyond the keys) + +`measure_data_values.py`: main rebuilds the DATA lists from Python too, so it changes +data values, not only keys: + +| Data column | main | prototype | +|---|---|---| +| time64[ns] 1, 1001 ns | 0, 1000 (truncated) | 1, 1001 | +| date64 1 ms, 1 day + 1 ms | 0, 1 day (midnight) | exact | +| large_list | truncated | exact | +| float32 signaling NaN (ITL-1248) | quieted (0x7f800001 to 0x7fc00001) | bits kept | +| timestamp[ns], duration[ns], float16 / float64 NaN payloads, -0.0, decimal256 | exact | exact | + +So this resolves ITL-1248 for `GroupBy`. + +## (e) Interactions + +- **PR 455** (refuses dictionary tags) edits the dictionary branches of `group_by.py` that + this rewrite replaces: a textual conflict. Proposal: 455 merges first and I drop the + dictionary handling. If this PR is ready first, I keep a decode in the sort frame (the + dictionary tests of `test_group_by_nan_keys.py` pass with the prototype) and say so. +- **PR 453** changes `test_group_by_member_order.py` (content hashes of raw streams), other + lines than mine; no golden overlap with this PR (no value moves here). +- **PR 456** (float rule in hashing): independent. The emitted key is still the + smallest-bit member; under 456 the zero and NaN variants may hash alike, which only makes + that choice invisible to hashes. +- **PR 457, 451**: CLAUDE.md and `docs/concepts/operators.md` text only; a merge, no + semantic overlap. **PR 450 / ITL-1279**: this PR moves no golden value, so it does not + depend on the provisional group. +- **ITL-1017** (data-tag key's source info folds to one token), **ITL-1070** (non-key + tags dropped, data-tags kept as data): kept; their tests pass with the prototype. +- **ITL-1071** (opt-in keep non-key tags): the sort frame already orders by them, so it + stays simple to add. +- **ITL-1248**: resolved for `GroupBy`; `Batch` and `MergeJoin` remain (f). + +## (f) Batch and MergeJoin (report only) + +`measure_batch_merge_join.py`: both build their lists from Python values (`Batch`: +`table.to_pylist()` then `build_aggregated_table`; `MergeJoin`: `to_pylist()` of the two +colliding columns, sorted by Python value) and lose the same values: time64[ns] 1, 1001 ns +become 0, 1000; date64 truncates to midnight; a float32 signaling NaN is quieted. +`MergeJoin` also orders a merged pair by Python value, so two values that differ below a +microsecond tie. Neither is changed here. + +## Decisions for the coordinator + +Answered on 2026-11-19: 1 refuse; 2 refuse too (an order by fields would be a new rule nobody +decided; it can be allowed later, since GroupBy goes into the provisional group); 3 no +design-issue entry (the Linear issue is the record), and ITL-1281 filed for `Batch` and +`MergeJoin`; 4 go first, with the dictionary decode in one small place +(`_without_dictionary`). + +1. **Struct-bearing keys** (a user class tag, a `dict[K, V]` tag, an Arrow map): main + raises a bare `TypeError` at run time. Proposal: refuse at validation with an + `InputValidationError` naming the column (as a list key is refused today), rather than + start grouping by them. +2. **Struct-bearing ordering tags** (a non-key user-class or dict tag): main raises a bare + `TypeError` whenever a group has two members. Proposal: order them, by their fields in + declared order, nulls last at every depth (the same recursive key the lists need; a + structural class's field order is part of its identity). Alternative: refuse at + validation. +3. **Logging**: no design-issue entry matches ITL-1250. Add `docs/dev/design_issues/ITL-1250-GB.md` + (status `in progress`, then `resolved`)? And open a Linear issue (plus an entry) for the + `Batch` / `MergeJoin` data loss in (f)? +4. **Order with PR 455**: wait for it, or go first with a temporary decode. diff --git a/docs/dev/scripts/itl_1250/measure_batch_merge_join.py b/docs/dev/scripts/itl_1250/measure_batch_merge_join.py new file mode 100644 index 000000000..2a32bed89 --- /dev/null +++ b/docs/dev/scripts/itl_1250/measure_batch_merge_join.py @@ -0,0 +1,64 @@ +"""ITL-1250 (f), ITL-1281: do Batch and MergeJoin lose data values through Python? + +Each case puts two values of one Arrow type into one list, by ``Batch`` (both rows in +one batch) and by ``MergeJoin`` (one row on each side, same key), and prints the input +and the list, read exactly: temporal values as integers, floats as bit patterns. +""" + +from __future__ import annotations + +from typing import Any, TypeAlias, cast + +import pyarrow as pa + +from orcapod.core.operators import Batch, MergeJoin +from orcapod.core.streams import ArrowTableStream + +Column: TypeAlias = "pa.Array[Any]" + + +def _exact(array: Column) -> list[Any]: + if pa.types.is_floating(array.type): + width = cast(int, array.type.bit_width) + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + return [None if b is None else hex(b) for b in array.view(unsigned).to_pylist()] + return array.cast(pa.int64()).to_pylist() + + +def _list_values(table: pa.Table) -> Column: + lists = cast("pa.LargeListArray[Any]", table.column("v").combine_chunks()) + return lists.values + + +CASES: dict[str, Column] = { + "time64[ns]": pa.array([1, 1001], pa.int64()).cast(pa.time64("ns")), + "date64": pa.array([1, 86_400_001], pa.int64()).cast(pa.date64()), + "float32 sNaN,-NaN": pa.array([0x7F800001, 0xFFC00000], pa.uint32()).view( + pa.float32() + ), +} + + +def main() -> None: + for name, values in CASES.items(): + rows = pa.Table.from_arrays( + [pa.array([0, 1], pa.int64()), values], names=["r", "v"] + ) + batched = Batch(batch_size=2)( + ArrowTableStream(rows, tag_columns=["r"]) + ).as_table() + key = pa.array([1], pa.int64()) + left = pa.Table.from_arrays([key, values.slice(0, 1)], names=["k", "v"]) + right = pa.Table.from_arrays([key, values.slice(1, 1)], names=["k", "v"]) + merged = MergeJoin()( + ArrowTableStream(left, tag_columns=["k"]), + ArrowTableStream(right, tag_columns=["k"]), + ).as_table() + print( + f"{name}: input {_exact(values)} Batch {_exact(_list_values(batched))}" + + f" MergeJoin {_exact(_list_values(merged))}" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1250/measure_data_values.py b/docs/dev/scripts/itl_1250/measure_data_values.py new file mode 100644 index 000000000..9ecb7db8e --- /dev/null +++ b/docs/dev/scripts/itl_1250/measure_data_values.py @@ -0,0 +1,100 @@ +"""ITL-1250: are the data values inside GroupBy's lists the input's, bit for bit? + +Run in a checkout: on ``main`` at ``a026d31f`` the time64[ns], date64 and float32 +signaling-NaN cases print CHANGED; with ITL-1250 every case prints ``same``. Each case +groups two rows into one group and compares the data list with the input column, +read exactly (temporal values as integers, floats as bit patterns). +""" + +from __future__ import annotations + +import decimal +from typing import Any, TypeAlias, cast + +import pyarrow as pa + +from orcapod.core.operators import GroupBy +from orcapod.core.streams import ArrowTableStream + +Column: TypeAlias = "pa.Array[Any]" + + +def _exact(array: Column) -> list[Any]: + """The values read exactly: unsigned bits for a float, integers for a temporal.""" + if pa.types.is_floating(array.type): + width = cast(int, array.type.bit_width) + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + return [None if b is None else hex(b) for b in array.view(unsigned).to_pylist()] + if pa.types.is_temporal(array.type): + return array.cast(pa.int64()).to_pylist() + if pa.types.is_large_list(array.type): + lists = cast("pa.LargeListArray[Any]", array) + values = _exact(lists.values) + offsets = cast(list[int], lists.offsets.to_pylist()) + return [values[offsets[i] : offsets[i + 1]] for i in range(len(lists))] + return [None if v is None else str(v) for v in array.to_pylist()] + + +def _bits(values: list[int], unsigned: pa.DataType, floating: pa.DataType) -> Column: + return pa.array(values, unsigned).view(floating) + + +def cases() -> list[tuple[str, Column]]: + tiny = decimal.Decimal("1." + "0" * 39 + "1") + return [ + ( + "time64[ns] 1 ns, 1001 ns", + pa.array([1, 1001], pa.int64()).cast(pa.time64("ns")), + ), + ( + "date64 1 ms, 1 day + 1 ms", + pa.array([1, 86_400_001], pa.int64()).cast(pa.date64()), + ), + ( + "timestamp[ns] 1, 1001", + pa.array([1, 1001], pa.int64()).cast(pa.timestamp("ns")), + ), + ( + "duration[ns] 1, 1001", + pa.array([1, 1001], pa.int64()).cast(pa.duration("ns")), + ), + ( + "float32 signaling NaN, -NaN", + _bits([0x7F800001, 0xFFC00000], pa.uint32(), pa.float32()), + ), + ( + "float16 signaling NaN, -0", + _bits([0x7C01, 0x8000], pa.uint16(), pa.float16()), + ), + ( + "float64 payload NaN, -0", + _bits([0x7FF8000000000001, 0x8000000000000000], pa.uint64(), pa.float64()), + ), + ( + "decimal256(76,40)", + pa.array([tiny, decimal.Decimal(-3)], pa.decimal256(76, 40)), + ), + ( + "large_list", + pa.array([[1, 2], [1001]], pa.large_list(pa.int64())).cast( + pa.large_list(pa.time64("ns")) + ), + ), + ] + + +def main() -> None: + for name, values in cases(): + table = pa.Table.from_arrays( + [pa.array([1, 1], pa.int64()), pa.array([0, 1], pa.int64()), values], + names=["g", "r", "v"], + ) + out = GroupBy("g")(ArrowTableStream(table, tag_columns=["g", "r"])).as_table() + grouped = cast("pa.LargeListArray[Any]", out.column("v").combine_chunks()) + before, after = _exact(values), _exact(grouped.values) + verdict = "same" if before == after else "CHANGED" + print(f"{name}\n input: {before}\n grouped: {after} {verdict}") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1250/measure_keys.py b/docs/dev/scripts/itl_1250/measure_keys.py new file mode 100644 index 000000000..219146df1 --- /dev/null +++ b/docs/dev/scripts/itl_1250/measure_keys.py @@ -0,0 +1,203 @@ +"""ITL-1250 (a): GroupBy against Polars group_by, per key type, in the current checkout. + +For each Arrow key type, a table of rows with a key ``k`` and a data column ``v`` (the +row number) is grouped by ``GroupBy`` and by ``polars.DataFrame.group_by`` on the key's +storage (``float16`` as ``float32``). The partition (the sets of ``v``) of each is +printed. On ``main`` at ``a026d31f``, ``time64[ns]`` and ``date64`` off midnight DIFFER +(main merges keys that are one Python value); with ITL-1250 every type Polars reads is +the same. Polars cannot read ``decimal256`` (it panics), which the script reports. +""" + +from __future__ import annotations + +import decimal +import uuid +from pathlib import Path +from typing import Any, TypeAlias, cast + +import polars as pl +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.core.operators import GroupBy +from orcapod.core.streams import ArrowTableStream + +Column: TypeAlias = "pa.Array[Any]" +Partition: TypeAlias = "list[list[int]]" +CTX = get_default_context() + +NAN = {16: 0x7E00, 32: 0x7FC00000, 64: 0x7FF8000000000000} +NEG_NAN = {16: 0xFE00, 32: 0xFFC00000, 64: 0xFFF8000000000000} +PAYLOAD_NAN = {16: 0x7E01, 32: 0x7FC00001, 64: 0x7FF8000000000001} +SIGNALING_NAN = {16: 0x7C01, 32: 0x7F800001, 64: 0x7FF0000000000001} +NEG_ZERO = {16: 0x8000, 32: 0x80000000, 64: 0x8000000000000000} +ONE = {16: 0x3C00, 32: 0x3F800000, 64: 0x3FF0000000000000} + + +def _floats(width: int, bits: list[int | None]) -> Column: + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + floating = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()}[width] + return pa.array(bits, unsigned).view(floating) + + +def _ints(values: list[int | None], arrow_type: pa.DataType) -> Column: + return pa.array(values, pa.int64()).cast(arrow_type) + + +def _logical(python_type: type, storage: list[Any]) -> Column: + arrow_type = cast( + pa.BaseExtensionType, CTX.type_converter.python_type_to_arrow_type(python_type) + ) + return pa.ExtensionArray.from_storage( + arrow_type, pa.array(storage, arrow_type.storage_type) + ) + + +def cases() -> list[tuple[str, Column]]: + out: list[tuple[str, Column]] = [] + for bits in (8, 16, 32, 64): + for signed in (True, False): + arrow_type = getattr(pa, f"{'int' if signed else 'uint'}{bits}")() + low = -(2 ** (bits - 1)) if signed else 0 + high = 2 ** (bits - 1) - 1 if signed else 2**bits - 1 + out.append( + ( + str(arrow_type), + pa.array([low, high, low, 0, None, high, None], arrow_type), + ) + ) + for w in (16, 32, 64): + bits_list: list[int | None] = [ + NAN[w], + NEG_NAN[w], + PAYLOAD_NAN[w], + SIGNALING_NAN[w], + NEG_ZERO[w], + 0, + ONE[w], + None, + ONE[w], + ] + out.append( + ( + f"float{w} (nan, -nan, payload, signaling, -0, 0, 1, null, 1)", + _floats(w, bits_list), + ) + ) + out.append(("bool", pa.array([True, False, True, None, None], pa.bool_()))) + out.append( + ( + "large_string", + pa.array(["a", "é", "", "a", None, "é", "é"], pa.large_string()), + ) + ) + out.append( + ("large_binary", pa.array([b"a", b"\x00", b"", b"a", None], pa.large_binary())) + ) + out.append( + ( + "fixed_size_binary(4)", + pa.array([b"abcd", b"abce", b"abcd", None], pa.binary(4)), + ) + ) + out.append(("date32", pa.array([0, 1, 0, None], pa.int32()).cast(pa.date32()))) + out.append( + ( + "date64 (0 ms, 1 ms, 1 day, 1 day + 1 ms)", + _ints([0, 1, 86_400_000, 86_400_001, None], pa.date64()), + ) + ) + out.append( + ("time32[s]", pa.array([0, 1, 1, None], pa.int32()).cast(pa.time32("s"))) + ) + out.append( + ("time32[ms]", pa.array([0, 1, 1, None], pa.int32()).cast(pa.time32("ms"))) + ) + out.append(("time64[us]", _ints([0, 1, 1, None], pa.time64("us")))) + out.append( + ( + "time64[ns] (1, 2, 1000, 1001 ns)", + _ints([1, 2, 1000, 1001, None], pa.time64("ns")), + ) + ) + for unit in ("s", "ms", "us", "ns"): + out.append( + (f"timestamp[{unit}]", _ints([0, 1, 1000, 1001, None], pa.timestamp(unit))) + ) + out.append( + ( + f"timestamp[{unit}, UTC]", + _ints([0, 1, 1000, 1001, None], pa.timestamp(unit, "UTC")), + ) + ) + out.append( + ( + f"timestamp[{unit}, America/New_York]", + _ints([0, 1, 1000, 1001, None], pa.timestamp(unit, "America/New_York")), + ) + ) + out.append( + (f"duration[{unit}]", _ints([0, 1, 1000, 1001, None], pa.duration(unit))) + ) + d = decimal.Decimal + out.append( + ( + "decimal128(38,10)", + pa.array( + [d("1.0000000001"), d("1.0000000002"), d("1"), d("1.0000000000"), None], + pa.decimal128(38, 10), + ), + ) + ) + out.append( + ( + "decimal256(76,40)", + pa.array( + [d("1." + "0" * 39 + "1"), d("1." + "0" * 39 + "2"), d("1"), None], + pa.decimal256(76, 40), + ), + ) + ) + out.append(("null", pa.array([None, None, None], pa.null()))) + out.append(("logical Path", _logical(Path, ["a", "b", "a", None]))) + u1, u2 = uuid.UUID(int=1).bytes, uuid.UUID(int=2).bytes + out.append(("logical UUID", _logical(uuid.UUID, [u1, u2, u1, None]))) + return out + + +def partition_group_by(key: Column) -> Partition: + table = pa.Table.from_arrays( + [key, pa.array(range(len(key)), pa.int64())], names=["k", "v"] + ) + out = GroupBy("k")(ArrowTableStream(table, tag_columns=["k"])).as_table() + return sorted(sorted(vs) for vs in cast(Partition, out.column("v").to_pylist())) + + +def partition_polars(key: Column) -> Partition: + storage = key.storage if isinstance(key, pa.ExtensionArray) else key + if pa.types.is_float16(storage.type): + storage = storage.cast(pa.float32()) + table = pa.Table.from_arrays( + [storage, pa.array(range(len(key)), pa.int64())], names=["k", "v"] + ) + frame = cast(pl.DataFrame, pl.from_arrow(table)) + grouped = frame.group_by("k").agg(pl.col("v")) + return sorted(sorted(vs) for vs in cast(Partition, grouped["v"].to_list())) + + +def main() -> None: + for name, key in cases(): + results: list[str] = [] + for grouping in (partition_group_by, partition_polars): + try: + results.append(str(grouping(key))) + except BaseException as error: # noqa: BLE001 # Polars panics on decimal256 + results.append(f"ERROR {type(error).__name__}: {str(error)[:100]}") + verdict = "same" if results[0] == results[1] else "DIFFER" + print( + f"{verdict:6} {name}\n GroupBy: {results[0]}\n Polars: {results[1]}" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1250/timing.py b/docs/dev/scripts/itl_1250/timing.py new file mode 100644 index 000000000..b47ab7ffb --- /dev/null +++ b/docs/dev/scripts/itl_1250/timing.py @@ -0,0 +1,48 @@ +"""ITL-1250 (d): the time of one GroupBy, in the current checkout. + +usage: uv run python docs/dev/scripts/itl_1250/timing.py + +A source with tags g (the key, ``groups`` distinct values) and t (a non-key tag that +orders the members), data v (float64) and w (large_string); record ids by position. +Times ``GroupBy("g")(source).as_table()`` once, after building the source. Run it on +two checkouts (``main`` and this branch) to compare, one process at a time. +""" + +from __future__ import annotations + +import sys +import time + +import numpy as np +import pyarrow as pa + +import orcapod as op +from orcapod.core.operators import GroupBy + + +def main() -> None: + rows, groups = int(float(sys.argv[1])), int(float(sys.argv[2])) + rng = np.random.default_rng(0) + table = pa.Table.from_arrays( + [ + pa.array(rng.integers(0, groups, rows), pa.int64()), + pa.array(rng.permutation(rows), pa.int64()), + pa.array(rng.random(rows), pa.float64()), + pa.array([f"w{i}" for i in range(rows)], pa.large_string()), + ], + names=["g", "t", "v", "w"], + ) + source = op.sources.ArrowTableSource( + table, tag_columns=["g", "t"], tag_only_columns=True, source_id="s" + ) + _ = source.as_table() + start = time.perf_counter() + out = GroupBy("g")(source).as_table() + elapsed = time.perf_counter() - start + print( + f"rows={rows:.0e} groups={groups:.0e} out={out.num_rows} seconds={elapsed:.2f}" + ) + + +if __name__ == "__main__": + main() diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index 46ac3dbd4..18f3b847e 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -2,13 +2,13 @@ from __future__ import annotations -import math -from collections.abc import Collection, Sequence, Set +from collections.abc import Collection, Mapping, Sequence, Set from typing import Any, ClassVar, TYPE_CHECKING, cast, get_origin from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import typed_zero_row_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants @@ -18,131 +18,350 @@ from orcapod.utils.schema_utils import column_names if TYPE_CHECKING: + import numpy as np + import polars as pl import pyarrow as pa else: + np = LazyModule("numpy") + pl = LazyModule("polars") pa = LazyModule("pyarrow") -def _null_last_key(value: Any) -> tuple[Any, ...]: - """Build an order key that sorts NaN after every number and nulls last, at any depth. +# GroupBy decides which rows form a group, and in what order, with Polars, and builds +# its output from the input's Arrow arrays (ITL-1250): no value passes through Python, +# so two keys are one group only when Polars finds them equal (all NaN equal, 0.0 equal +# to -0.0, ITL-1234 and ITL-1251), and every emitted value is one a member holds, bit +# for bit. Only the row numbers and the group sizes come back from Polars. - The leading integer keeps a NaN and a null comparable against a real value of - any type. A NaN never compares with ``<``, so without its own place a sort that - meets one keeps the input's row order; here every NaN ties every other NaN and - the next sort column (the record id) breaks the tie (ITL-1226), as Arrow and - Polars order a NaN. A list is keyed element by element, so a list-valued tag - that holds a NaN or a null (a list-typed tag column of a source) still compares. + +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: - value: A tag or system-tag value: a scalar, ``None``, or a list of - these nested to any depth. + arrow_type: The Arrow type of a tag column. Returns: - A tuple that orders values ascending, NaN after every number and nulls - after everything. + The first type found that has no order, or ``None``. """ - if value is None: - return (2,) - if isinstance(value, float) and math.isnan(value): - return (1,) - if isinstance(value, list): - return (0, tuple(_null_last_key(v) for v in value)) - return (0, value) + 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.) -# The grouping form of a NaN key value: one shared object, so every row whose key -# is NaN falls into one group (ITL-1234), as the joins match a NaN key -# (``match_keys``). ``0.0`` and ``-0.0`` already fall into one group: they are equal. -_NAN_KEY = object() + 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 _grouping_key(key: tuple[Any, ...]) -> tuple[Any, ...]: - """Return a group key in the form that groups rows: every NaN as one value. + +def _storage(column: "pa.ChunkedArray[Any]") -> "pa.Array[Any]": + """Return a column as one array: a logical type as its storage, decoded. Args: - key: The values of the ``by`` columns of one row, in the order of ``by``. + column: A column of the input table. Returns: - The key with each NaN replaced by one shared object. + The column's values as stored. """ - return tuple( - _NAN_KEY if isinstance(value, float) and math.isnan(value) else value - for value in key - ) + 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 _float_storage(arrow_type: "pa.DataType") -> "pa.DataType | None": - """Return the float type a column is stored as, or ``None`` when it is not a float. +def _decimal256_limbs(array: "pa.Array[Any]") -> "pa.Array[Any]": + """Return a decimal256 column as a struct of four 64-bit limbs. - A logical (extension) type over float storage, such as a temperature stored as - ``float64``, is stored as that float, and a dictionary-encoded column as the - float type of its values. + 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: - arrow_type: The Arrow type of a key column. + array: A ``decimal256`` array. Returns: - The ``float16``, ``float32`` or ``float64`` type of the column's storage, or - ``None``. + A struct array with the limbs, null where ``array`` is null. """ - storage = ( - arrow_type.storage_type - if isinstance(arrow_type, pa.ExtensionType) - else arrow_type + 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=" int: - """Return the input row whose value of one key column a group emits. - - The members of a group hold equal key values, but equal floats may differ in - their bits: ``0.0`` and ``-0.0``, and NaN with another sign or payload (equal - floats of any other value have the same bits). The hashes of the emitted row - read the bits, so for a zero or NaN key the group emits the member value with - the smallest bit pattern at the column's own width (ITL-1234), chosen per key - column. That is ``0.0`` over ``-0.0``, a positive NaN over a negative one, and - the NaN with the smallest payload; a signaling NaN has smaller bits than the - canonical quiet NaN, so it is the one emitted when a member holds it. A group - whose members agree emits their value. Neither the row order nor - ``member_order`` decides it, and the caller takes the value from the Arrow - column, so its bits are kept exactly. + + +def _polars_ready(array: "pa.Array[Any]") -> "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: - column: A key column of the input table. - indices: The rows of one group, at least one, all with equal keys. + array: A column of the input table, or the values of one. Returns: - The row, one of ``indices``, whose value the group emits for this column. + The prepared array. + + Raises: + TypeError: For a type ``_unorderable_part`` refuses; never reached through + ``GroupBy``, which refuses the column first. """ - first = indices[0] - storage_type = _float_storage(column.type) - if len(indices) == 1 or storage_type is None: - return first - # Only a zero or NaN key can differ in bits among equal values, so the first - # member's value decides whether the group is gathered at all. - scalar = column[first] - if isinstance(scalar, pa.ExtensionScalar): - # A null extension scalar has no storage scalar. - storage = scalar.value - value = None if storage is None else cast(float | None, storage.as_py()) - else: - value = cast(float | None, scalar.as_py()) - if value is None or (value != 0.0 and not math.isnan(value)): - return first - members = column.take(pa.array(indices, pa.int64())).combine_chunks() - if isinstance(members, pa.ExtensionArray): - members = members.storage - if isinstance(members, pa.DictionaryArray): - # The values each member's index points at, bits as stored. - members = members.dictionary_decode() - # The unsigned integer of the float's width, to read its bits; no value of the - # group is null, since a null key equals no float. - unsigned = {16: pa.uint16, 32: pa.uint32, 64: pa.uint64}[storage_type.bit_width]() - bits = cast(list[int], members.view(unsigned).to_pylist()) - return indices[min(range(len(indices)), key=bits.__getitem__)] + 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. + + The sort puts a null scalar last (``nulls_last``), but Polars puts a null INSIDE + a list first, so a list is sorted through ``(is_null, value)`` pairs at every + depth, element by element: a shorter list first when it is a prefix, a NaN after + every number and before null, as for a scalar (ITL-1226). Polars ties ``0.0`` with + ``-0.0`` and every NaN with every NaN. + + Args: + name: The column's name in the sort frame. + dtype: Its Polars type. + + Returns: + The expression to sort by. + """ + + # ``object``: a Polars data type is an instance or a class (``PolarsDataType``, + # which Polars keeps private). + def null_last(expr: "pl.Expr", inner: object) -> "pl.Expr": + if isinstance(inner, pl.List): + value = expr.list.eval(null_last(pl.element(), inner.inner)) + else: + value = expr + return pl.struct(expr.is_null().alias("null"), value.alias("value")) + + if isinstance(dtype, pl.List): + return null_last(pl.col(name), dtype) + return pl.col(name) + + +def _float_bits(array: "pa.Array[Any]") -> "pa.Array[Any] | None": + """Return a float key's bit patterns, or ``None`` when the key is not a float. + + A logical type stored as a float, or a dictionary over floats, is a float key, + read through its storage or its values. + + Args: + array: A key column's values as stored (``_storage``). + + Returns: + The unsigned integers of the column's own width, or ``None``. + """ + if not pa.types.is_floating(array.type): + return None + unsigned = {16: pa.uint16, 32: pa.uint32, 64: pa.uint64}[array.type.bit_width]() + return array.view(unsigned) + + +def _refuse_unorderable_tags( + by: Collection[str], tag_types: Mapping[str, "pa.DataType"] +) -> None: + """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, + 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, + never on whether two members happen to tie. + + Args: + by: The group keys. + tag_types: The Arrow type of each user tag of the input. + + Raises: + 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)): + 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) + if part is None: + continue + if name in by: + raise InputValidationError( + f"GroupBy: the key {name!r} has type {arrow_type}, and GroupBy has no " + + f"order for {part} (a struct or a map, such as a user class or a " + + "dict, or another type without an order): a group key must be a " + + "scalar value with an order. Group by other tags." + ) + raise InputValidationError( + f"GroupBy: the tag {name!r} has type {arrow_type}, and GroupBy has no " + + f"order for {part} (a struct or a map, such as a user class or a dict, " + + "or another type without an order): GroupBy orders a group's members " + + "by every tag that is not a key. GroupBy drops that tag anyway: drop it " + + "before grouping, with stream.select_tag_columns([...]) naming the " + + "tags to keep." + ) GROUP_BY_FOLD_LABEL = "group_v1" @@ -275,7 +494,12 @@ class GroupBy(UnaryOperator): Rows with equal keys form one group, as the joins match keys, except that all rows with a null key form one group too. So do all rows with a NaN key, and ``0.0`` equals ``-0.0`` (ITL-1234). A NaN key sorts after every number and - before null. A float key that the members hold with different bits is + before null. Keys are compared and ordered as Arrow values, with Polars, never + as Python values (ITL-1250): ``time64[ns]`` keys of 1 ns and 2 ns are two + groups. Every emitted key and every list element is taken from the input's + Arrow columns, so the lists hold the members' values bit for bit. A tag whose + type has no order (a struct or a map, such as a user class or a ``dict``, an + interval) can be neither a key nor a non-key tag of the input. A float key that the members hold with different bits is emitted, per key column, as the one with the smallest bit pattern at the column's own width (``0.0`` over ``-0.0``, a positive NaN over a negative one, a signaling NaN over the canonical quiet NaN), taken from the input's @@ -385,7 +609,10 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: Raises: 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. + 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 + interval...); checked here when the stream knows its Arrow types + without rows, otherwise when it is grouped. """ tag_columns, data_columns = stream.keys() missing = [c for c in self.by if c not in tag_columns] @@ -396,10 +623,7 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: f"(Data columns cannot be grouping keys: {list(data_columns)})" ) - # A list-valued tag -- what `Batch` produces -- is unhashable, so it - # cannot key a group. Check the schema rather than hashing a value so - # the error names the operator and column instead of surfacing a bare - # `TypeError: unhashable type: 'list'` from the grouping loop. + # A list-valued tag -- what `Batch` produces -- cannot key a group. tag_types, _ = stream.output_schema() non_scalar = { c: tag_types.get(c) for c in self.by if get_origin(tag_types.get(c)) is list @@ -412,6 +636,16 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: "group before batching rather than after." ) + # Every tag needs an order (a fixed-size list key is list-valued too), from + # the Arrow types, when the stream knows them without rows; a stream that + # does not (a function pod's) is checked when it is grouped. + zero_rows = typed_zero_row_table(stream) + if zero_rows is not None: + _refuse_unorderable_tags( + self.by, + {c: zero_rows.schema.field(c).type for c in tag_columns}, + ) + # The members are ordered by tags only, never by a data value. for name in self.member_order or (): if name in tag_columns: @@ -440,9 +674,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: Returns: A stream with one row per distinct group-key tuple, whose tag columns are the group keys, scalar, in the input's tag order. + + Raises: + InputValidationError: If a key is a list of any kind, or a user tag's + type has no order (``_unorderable_part``). """ table = stream.as_table(columns={"source": True, "system_tags": True}) tag_columns, _ = stream.keys() + # The async path reaches here without ``validate_unary_input``. + _refuse_unorderable_tags( + self.by, {c: table.schema.field(c).type for c in tag_columns} + ) system_tag_columns = tuple( c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) @@ -499,97 +741,115 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: sorted(c for c in system_tag_columns if c.startswith(prefix)) ) - # Every NaN key is one value here (ITL-1234), so the rows whose key is NaN - # form one group, as the joins match them. - rows = table.to_pylist() - groups: dict[tuple[Any, ...], list[int]] = {} - for index, row in enumerate(rows): - key = _grouping_key(tuple(row[c] for c in self.by)) - groups.setdefault(key, []).append(index) - # For each group, the row whose value each key column emits. - keyed_groups: list[tuple[tuple[int, ...], list[dict[str, Any]]]] = [ - ( - tuple(_emitted_key_row(table.column(c), indices) for c in self.by), - [rows[i] for i in indices], - ) - for indices in groups.values() - ] - - grouped_rows: list[dict[str, Any]] = [] - # Emit groups in key order rather than first-appearance order, so a - # reordered input produces a byte-identical output table. The keys are in - # name order (``by`` is sorted); a NaN key sorts after every number and - # before null, as a member's tag does. - key_rows: list[tuple[int, ...]] = [] - for group_key_rows, members in sorted( - keyed_groups, - key=lambda km: tuple( - _null_last_key(rows[r][c]) for r, c in zip(km[0], self.by) - ), + # Polars decides which rows form a group and in what order, in one stable + # sort; the output is built from the input's Arrow arrays (ITL-1250). The + # sort frame has synthetic names, so no user column name can collide: the + # row number, the keys in name order (``by`` is sorted), then the columns + # that order the members. + frame_columns: dict[str, pa.Array[Any]] = { + "row": pa.array(np.arange(table.num_rows, dtype=np.int64), pa.int64()) + } + key_names = [f"key{i}" for i in range(len(self.by))] + order_names = [f"order{i}" for i in range(len(sort_columns))] + for name, c in zip( + [*key_names, *order_names], [*self.by, *sort_columns], strict=True ): - key_rows.append(group_key_rows) - key = tuple(rows[r][c] for r, c in zip(group_key_rows, self.by)) - if sort_columns: - members.sort( - key=lambda r: tuple(_null_last_key(r[c]) for c in sort_columns) + 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} + bit_names: dict[str, str] = {} + for i, c in enumerate(self.by): + bits = _float_bits(key_storage[c]) + if bits is not None: + bit_names[c] = f"bits{i}" + frame_columns[f"bits{i}"] = bits + + frame = cast( + "pl.DataFrame", + pl.from_arrow( + pa.Table.from_arrays( + list(frame_columns.values()), names=list(frame_columns) ) - - grouped_rows.append( - { - **dict(zip(self.by, key)), - **{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=GROUP_BY_FOLD_LABEL - ) - for c in key_source_columns - }, - **{ - c: arrow_utils.fold_system_tag_values( - [m[c] for m in members], label=GROUP_BY_FOLD_LABEL - ) - for c in system_tag_columns - }, - } - ) - - # The schema handed over must not name the dropped columns: the builder - # emits every column of it, and would bring them back as nulls. - grouped_table = arrow_utils.build_aggregated_table( - grouped_rows, - table.drop_columns(list(dropped_columns)).schema, - member_columns, - stream.data_context.type_converter, + ), + ) + # Keys first, so the groups come out in key order: a NaN key after every + # number and before null, null last (``nulls_last``); rows that tie on every + # column keep the input's order. + frame = frame.sort( + [_sort_key(name, frame.schema[name]) for name in key_names + order_names], + nulls_last=True, + maintain_order=True, + ) + # Group boundaries by Polars' own equality: every NaN equals every NaN and + # 0.0 equals -0.0, as the joins match keys (ITL-1234, ITL-1251). + frame = frame.with_columns(pl.struct(key_names).rle_id().alias("group")) + groups = frame.group_by("group", maintain_order=True).agg( + pl.len().alias("size"), + pl.col("row").first().alias("first"), + # A float key: the member value with the smallest bit pattern at the + # column's own width (ITL-1234), never one chosen by the row order or by + # ``member_order``; a null key through a null index. + *( + pl.when(pl.col(bits).is_null().all()) + .then(None) + .otherwise(pl.col("row").sort_by(bits).first()) + .alias(bits) + for bits in bit_names.values() + ), + ) + order = frame["row"].to_arrow() + offsets = cast( + "pa.Int64Array", + pa.array( + np.concatenate([[0], np.cumsum(groups["size"].to_numpy())]), + pa.int64(), + ), ) - # A float key column (a float, a logical type stored as one, or a dictionary - # over floats) holds the chosen member's value as the input's Arrow column - # has it, never through Python: a conversion can change a float's bits (a - # float32 signaling NaN comes back quiet). Every other key keeps the value rebuilt from Python, - # as before: its members may differ in Arrow although equal in Python (two - # time64[ns] values within one microsecond read as one ``datetime.time``), - # and taking one member's would make the key depend on the row order. - # Grouping such keys by their exact value is ITL-1250. - for position, c in enumerate(self.by): - if _float_storage(table.column(c).type) is None: - continue - # A null key is taken through a null index, so it is a null at the top - # level whichever member came first: a dictionary column can hold a null - # as a null index or as an index to a null entry, and only the first is - # a null to a reader of validity (``DropNulls``). - chosen = pa.array( + def emitted(c: str) -> pa.Array[Any]: + # Every member of a group holds the same key value except a float's + # bits, so a non-float key is the first member's. + rows = groups[bit_names.get(c, "first")].to_arrow().cast(pa.int64()) + return table.column(c).take(rows).combine_chunks() + + def folded(c: str) -> pa.Array[Any]: + # The members' text values in member order, folded per group; text loses + # nothing in Python. + values = cast(list[Any], table.column(c).take(order).to_pylist()) + bounds = cast(list[int], offsets.to_pylist()) + return pa.array( [ - None if rows[r[position]][c] is None else r[position] - for r in key_rows + arrow_utils.fold_system_tag_values( + values[start:end], label=GROUP_BY_FOLD_LABEL + ) + for start, end in zip(bounds[:-1], bounds[1:]) ], - pa.int64(), - ) - grouped_table = grouped_table.set_column( - grouped_table.schema.get_field_index(c), - grouped_table.schema.field(c), - table.column(c).take(chosen), + table.schema.field(c).type, ) + # Every stream has a data context; StreamProtocol does not declare it. + type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] + fields: list[pa.Field[Any]] = [] + arrays: list[pa.Array[Any]] = [] + # The input's columns in its order, without the dropped tags: a key and a + # folded column keep their field, a member column becomes a list. + for field in table.drop_columns(list(dropped_columns)).schema: + c = field.name + if c in member_columns: + list_type = arrow_utils.aggregated_list_type( + field.type, type_converter, column=c + ) + fields.append(pa.field(c, list_type, nullable=False)) + arrays.append( + arrow_utils.aggregated_list_array( + table.column(c).take(order), offsets, list_type + ) + ) + else: + fields.append(field) + arrays.append(emitted(c) if c in self.by else folded(c)) + grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + n_char = self.orcapod_config.hashing.system_tag_n_char grouped_table = arrow_utils.append_to_system_tags( grouped_table, stream.pipeline_hash().to_hex(n_char) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c138f6dde..5c55ff76a 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1570,6 +1570,43 @@ def build_aggregated_table( return table +def aggregated_list_array( + values: "pa.Array[Any] | pa.ChunkedArray[Any]", + offsets: "pa.Int64Array", + list_type: pa.DataType, +) -> pa.Array[Any]: + """Build a list column of exactly ``list_type`` from member values and offsets. + + The array-based sibling of ``build_aggregated_table``: the members of row ``i`` + are ``values[offsets[i]:offsets[i + 1]]``, so the values are never read as Python + values and keep every bit (a ``time64[ns]`` value its nanoseconds, a ``date64`` + its time of day, a float32 signaling NaN its bits; ITL-1250, ITL-1248). The + caller puts the values in member order (``take``) and gives ``list_type`` from + ``aggregated_list_type``; for a logical element the list is built over the + element's storage and wrapped, as ``build_aggregated_table`` does. + + Args: + values: Every member's value, group after group, in the input column's type. + offsets: ``int64`` offsets, one more than the number of rows, from 0 to + ``len(values)``. + list_type: The column's type, from ``aggregated_list_type``. + + Returns: + The list array, one row per group, never null at the top level. + """ + if isinstance(values, pa.ChunkedArray): + values = values.combine_chunks() + if isinstance(list_type, pa.BaseExtensionType): + storage_values = ( + values.storage if isinstance(values, pa.ExtensionArray) else values + ) + storage = pa.LargeListArray.from_arrays( + offsets, storage_values, type=list_type.storage_type + ) + return pa.ExtensionArray.from_storage(list_type, storage) + return pa.LargeListArray.from_arrays(offsets, values, type=list_type) + + def _parse_system_tag_column( col_name: str, ) -> tuple[str, str, str] | None: diff --git a/tests/test_core/operators/test_group_by_arrow_values.py b/tests/test_core/operators/test_group_by_arrow_values.py new file mode 100644 index 000000000..7dc747de7 --- /dev/null +++ b/tests/test_core/operators/test_group_by_arrow_values.py @@ -0,0 +1,752 @@ +"""GroupBy groups, orders and emits by Arrow value, never by Python value (ITL-1250). + +``GroupBy`` used to convert its input to Python rows: two keys that became one Python +value were one group (``time64[ns]`` 1 ns and 2 ns are both a ``datetime.time`` of 0 us), +and the data lists were rebuilt from Python, so a value with no exact Python form changed +(``time64[ns]`` truncated to microseconds, ``date64`` moved to midnight, a float32 +signaling NaN quieted, ITL-1248). It now decides which rows group and in what order with +Polars, and builds its output from the input's Arrow arrays. + +Every comparison here reads values exactly: temporal values as their integers, floats as +their bit patterns, decimals as text, recursively through lists. +""" + +from __future__ import annotations + +import decimal +import itertools +import json +from pathlib import Path +from typing import Any, TypeAlias, cast + +import polars as pl +import pyarrow as pa +import pytest + +import orcapod as op +from orcapod.core.operators import GroupBy +from orcapod.core.operators.group_by import ( + GROUP_BY_FOLD_LABEL, + _polars_ready, # pyright: ignore[reportPrivateUsage] # the test is about these + _sort_key, # pyright: ignore[reportPrivateUsage] + _unorderable_part, # pyright: ignore[reportPrivateUsage] +) +from orcapod.contexts import get_default_context +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError +from orcapod.pipeline import ( + AsyncPipelineOrchestrator, + PipelineJob, + SyncPipelineOrchestrator, +) +from orcapod.core.streams.base import StreamBase +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import constants +from orcapod.utils import arrow_utils + +from .several_items import async_rows + +NS = pa.time64("ns") +Column: TypeAlias = "pa.Array[Any]" + + +def _table(columns: dict[str, Column]) -> pa.Table: + return pa.Table.from_arrays(list(columns.values()), names=list(columns)) + + +D = decimal.Decimal +# decimal256 values that differ in the 40th decimal place: no decimal128 holds them. +DEC = pa.decimal256(76, 40) + + +def _dec(units: int, tiny: int = 0) -> D: + """``units`` with ``tiny`` in the 40 decimal places, the sign of ``units``, exactly. + + Built from text: Python's default decimal context keeps 28 digits, so arithmetic + would round ``1 + 1e-40`` to ``1``. + """ + return D(f"{'-' if units < 0 else ''}{abs(units)}.{tiny:040d}") + + +def _ints(values: list[int | None], arrow_type: pa.DataType) -> Column: + """``values`` as integers cast to ``arrow_type`` (a temporal type).""" + return pa.array(values, pa.int64()).cast(arrow_type) + + +def _floats(bits: list[int | None], width: int) -> Column: + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + floating = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()}[width] + return pa.array(bits, unsigned).view(floating) + + +def _exact(column: Column | pa.ChunkedArray[Any]) -> Any: + """The values of ``array`` read exactly: what a Python round trip would lose is kept. + + Temporal values are their integers, floats their bit patterns, decimals their text, + lists recursively, with nulls as ``None``. + """ + array: Column = ( + column.combine_chunks() if isinstance(column, pa.ChunkedArray) else column + ) + if isinstance(array, pa.ExtensionArray): + array = array.storage + arrow_type = array.type + if pa.types.is_large_list(arrow_type) or pa.types.is_list(arrow_type): + lists = cast("pa.LargeListArray[Any] | pa.ListArray[Any]", array) + values = _exact(lists.values) + offsets = lists.offsets.to_pylist() + return [ + values[offsets[i] : offsets[i + 1]] if array[i].is_valid else None + for i in range(len(array)) + ] + if pa.types.is_floating(arrow_type): + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + return array.view(unsigned[arrow_type.bit_width]).to_pylist() + if pa.types.is_temporal(arrow_type): + return array.cast(pa.int64()).to_pylist() + if pa.types.is_decimal(arrow_type): + return [None if v is None else str(v) for v in array.to_pylist()] + return array.to_pylist() + + +def _source( + columns: dict[str, Column], + tags: list[str], + *, + plain: list[str] | None = None, +) -> StreamBase: + """A source over ``columns``; ``tags`` are tags, ``plain`` the plain ones (default all). + + Record ids are the ``rid`` column, so a reordered input keeps every record id. + """ + return op.sources.ArrowTableSource( + _table(columns), + tag_columns=tags, + tag_only_columns=True if plain is None else plain, + source_id="s", + record_id_columns="rid", + ) + + +def _permuted(columns: dict[str, Column], order: tuple[int, ...]) -> dict[str, Column]: + indices = pa.array(order, pa.int64()) + return {name: column.take(indices) for name, column in columns.items()} + + +def _fingerprint(stream: StreamProtocol) -> dict[str, Any]: + """Every column read exactly, the row hashes and the stream's hashes.""" + table = stream.as_table(all_info=True) + return { + "columns": {name: _exact(table.column(name)) for name in table.column_names}, + "row_hashes": [ + (tag.content_hash().to_string(), data.content_hash().to_string()) + for tag, data in stream.iter_data() + ], + "content_hash": stream.content_hash().to_string(), + "pipeline_hash": stream.pipeline_hash().to_string(), + } + + +# ── keys that differ below Python's precision ─────────────────────────────── + +# Five rows, four distinct keys: rows 1 and 4 share a key. On main the first two keys +# of each type were one group, and so were the last two. +KEY_CASES = { + "time64_ns": _ints([1, 2, 1000, 1001, 2], NS), + "date64_off_midnight": _ints([1, 2, 86_400_000, 86_400_001, 2], pa.date64()), + "timestamp_ns": _ints([1, 2, 1000, 1001, 2], pa.timestamp("ns")), + "duration_ns": _ints([1, 2, 1000, 1001, 2], pa.duration("ns")), + "decimal256": pa.array( + [_dec(1, 1), _dec(1, 2), _dec(2), _dec(2, 1), _dec(1, 2)], DEC + ), +} + + +@pytest.mark.parametrize("plain", [True, False], ids=["plain_key", "data_tag_key"]) +@pytest.mark.parametrize("name", list(KEY_CASES)) +def test_keys_that_differ_below_python_precision_are_separate_groups( + name: str, plain: bool +) -> None: + """Four distinct Arrow keys are four groups, each emitting its own key, in every order.""" + key = KEY_CASES[name] + columns: dict[str, Column] = { + "k": key, + "t": pa.array([5, 4, 3, 2, 1], pa.int64()), + "rid": pa.array(["r0", "r1", "r2", "r3", "r4"], pa.large_string()), + "v": pa.array([0, 1, 2, 3, 4], pa.int64()), + } + seen: dict[str, Any] = {} + for order in itertools.permutations(range(5)): + source = _source( + _permuted(columns, order), ["k", "t"], plain=None if plain else ["t"] + ) + grouped = source.group_by("k") + table = grouped.as_table() + assert _exact(table.column("k")) == _exact(key.take(pa.array([0, 1, 2, 3]))) + # Rows 1 and 4 share a key; they are ordered by ``t`` (4 before 1). + assert table.column("v").to_pylist() == [[0], [4, 1], [2], [3]] + fingerprint = _fingerprint(grouped) + if not seen: + seen = fingerprint + assert fingerprint == seen + + +@pytest.mark.parametrize("by", [["a", "b"], ["b", "a"]], ids=["a_b", "b_a"]) +@pytest.mark.parametrize("roles", ["plain", "data_tags", "mixed"]) +def test_two_exact_keys_group_by_both_values_in_every_row_order( + by: list[str], roles: str +) -> None: + """Two keys, each differing only below a microsecond or below a day, in any by order.""" + columns: dict[str, Column] = { + "a": _ints([1, 2, 1, 2, 1], NS), + "b": _ints( + [86_400_001, 86_400_001, 86_400_002, 86_400_001, 86_400_001], pa.date64() + ), + "t": pa.array([0, 1, 2, 3, 4], pa.int64()), + "rid": pa.array(["r0", "r1", "r2", "r3", "r4"], pa.large_string()), + "v": pa.array([0, 1, 2, 3, 4], pa.int64()), + "w": _ints([10, 11, 12, 13, 14], NS), + } + plain = {"plain": None, "data_tags": ["t"], "mixed": ["a", "t"]}[roles] + seen: dict[str, Any] = {} + for order in itertools.permutations(range(5)): + grouped = _source( + _permuted(columns, order), ["a", "b", "t"], plain=plain + ).group_by(by) + table = grouped.as_table() + # Groups in key order, keys in name order: (1, +1), (1, +2), (2, +1). + assert _exact(table.column("a")) == [1, 1, 2] + assert _exact(table.column("b")) == [86_400_001, 86_400_002, 86_400_001] + assert table.column("v").to_pylist() == [[0, 4], [2], [1, 3]] + assert _exact(table.column("w")) == [[10, 14], [12], [11, 13]] + fingerprint = _fingerprint(grouped) + if not seen: + seen = fingerprint + assert fingerprint == seen + + +# ── data values are kept bit for bit ──────────────────────────────────────── + +# Two groups (g = 1, 2); ``t`` orders the members. Every data column holds values that a +# Python round trip changes. +DATA_COLUMNS: dict[str, Column] = { + "g": pa.array([1, 2, 1, 2, 1], pa.int64()), + "t": pa.array([3, 1, 2, 0, 1], pa.int64()), + "rid": pa.array(["r0", "r1", "r2", "r3", "r4"], pa.large_string()), + "d_time": _ints([1, 1001, 2, None, 999_999_999], NS), + "d_date": _ints([1, 86_400_001, None, 86_399_999, 2], pa.date64()), + # signaling NaN, -NaN, payload NaN, -0.0, null + "d_f32": _floats([0x7F800001, 0xFFC00000, 0x7FC00001, 0x80000000, None], 32), + "d_f16": _floats([0x7C01, 0xFE00, 0x7E01, 0x8000, None], 16), + "d_list": pa.array( + [[1, None], [], None, [1001], [2, 3]], pa.large_list(pa.int64()) + ).cast(pa.large_list(NS)), + "d_dec": pa.array([_dec(1, 1), None, _dec(-3), _dec(2, 1), _dec(0, 1)], DEC), +} +DATA_NAMES = ["d_time", "d_date", "d_f32", "d_f16", "d_list", "d_dec"] +# Members of g=1: rows 4 (t=1), 2 (t=2), 0 (t=3); of g=2: rows 3 (t=0), 1 (t=1). +MEMBERS = [[4, 2, 0], [3, 1]] + + +def _expected_lists(name: str) -> list[Any]: + column = DATA_COLUMNS[name] + return [_exact(column.take(pa.array(m, pa.int64()))) for m in MEMBERS] + + +@pytest.mark.parametrize("roles", ["plain", "data_tags", "mixed"]) +def test_data_lists_hold_the_input_values_bit_for_bit(roles: str) -> None: + """Every data list equals the input's values in member order, read exactly.""" + plain = {"plain": None, "data_tags": [], "mixed": ["t"]}[roles] + for order in itertools.permutations(range(5)): + source = _source(_permuted(DATA_COLUMNS, order), ["g", "t"], plain=plain) + table = source.group_by("g").as_table() + for name in DATA_NAMES: + assert _exact(table.column(name)) == _expected_lists(name), name + if roles != "plain" and roles != "mixed": + # A data-tag non-key keeps its data column, as a list in member order. + assert table.column("t").to_pylist() == [[1, 2, 3], [0, 1]] + + +def _group_rows_exact(rows: list[Any]) -> dict[int, dict[str, Any]]: + """Each async or sync row's data, read exactly, by its key ``g``.""" + out: dict[int, dict[str, Any]] = {} + for tag, data in rows: + [g] = tag.as_table().column("g").to_pylist() + table = data.as_table() + out[g] = {name: _exact(table.column(name))[0] for name in DATA_NAMES} + return out + + +def test_data_lists_are_bit_exact_on_the_async_path() -> None: + source = _source(DATA_COLUMNS, ["g", "t"], plain=["t"]) + expected = { + g: {name: _expected_lists(name)[i] for name in DATA_NAMES} + for i, g in enumerate([1, 2]) + } + assert _group_rows_exact(async_rows(GroupBy("g"), source)) == expected + assert _group_rows_exact(list(GroupBy("g")(source).iter_data())) == expected + + +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_data_lists_are_bit_exact_in_a_job(orchestrator: Any) -> None: + job = PipelineJob(name="exact_values", database=InMemoryArrowDatabase()) + with job: + _ = _source(DATA_COLUMNS, ["g", "t"], plain=["t"]).group_by( + "g", label="grouped" + ) + job.run(orchestrator=orchestrator()) + table = job.nodes["grouped"].as_table() + assert table.column("g").to_pylist() == [1, 2] + for name in DATA_NAMES: + assert _exact(table.column(name)) == _expected_lists(name), name + + +# ── member order by exact value ───────────────────────────────────────────── + + +@pytest.mark.parametrize("member_order", [None, ["t"], ["t", "u"]]) +def test_members_are_ordered_by_the_exact_value_of_a_tag( + member_order: list[str] | None, +) -> None: + """A time64[ns] tag orders members by nanoseconds, not by the record id.""" + columns: dict[str, Column] = { + "g": pa.array([1, 1, 1, 1], pa.int64()), + "t": _ints([2, 1, 1001, 1000], NS), + "u": pa.array([0, 0, 0, 0], pa.int64()), + # Record ids against the order of t (v1, v0, v3, v2): a tie on t below a + # microsecond would order v0 before v1 and v2 before v3. + "rid": pa.array(["r2", "r3", "r0", "r1"], pa.large_string()), + "v": pa.array([0, 1, 2, 3], pa.int64()), + } + for order in itertools.permutations(range(4)): + source = _source(_permuted(columns, order), ["g", "t", "u"]) + grouped = source.group_by("g", member_order=member_order) + assert grouped.as_table().column("v").to_pylist() == [[1, 0, 3, 2]] + + +def test_members_are_ordered_by_a_decimal256_tag() -> None: + columns: dict[str, Column] = { + "g": pa.array([1, 1, 1, 1], pa.int64()), + "t": pa.array([_dec(-1, 1), _dec(1, 1), _dec(1), None], DEC), + "rid": pa.array(["r0", "r1", "r2", "r3"], pa.large_string()), + "v": pa.array([0, 1, 2, 3], pa.int64()), + } + for order in itertools.permutations(range(4)): + grouped = _source(_permuted(columns, order), ["g", "t"]).group_by("g") + assert grouped.as_table().column("v").to_pylist() == [[0, 2, 1, 3]] + + +def test_a_list_valued_tag_orders_by_exact_elements_with_nulls_last_at_every_depth() -> ( + None +): + """Lists compare element by element; a null sorts last in a list and at the top.""" + tags = pa.array( + [[1, None], [2], None, [None], [], [1], [1, 2]], pa.large_list(pa.int64()) + ).cast(pa.large_list(NS)) + columns: dict[str, Column] = { + "g": pa.array([1] * 7, pa.int64()), + "t": tags, + "rid": pa.array([f"r{i}" for i in range(7)], pa.large_string()), + "v": pa.array(range(7), pa.int64()), + } + # [] < [1] < [1, 2] < [1, null] < [2] < [null] < null; on main [1] and [2] tied. + expected = [[4, 5, 6, 0, 1, 3, 2]] + for order in itertools.islice(itertools.permutations(range(7)), 0, 5040, 97): + grouped = _source(_permuted(columns, order), ["g", "t"]).group_by("g") + assert grouped.as_table().column("v").to_pylist() == expected + + +# ── zero rows ─────────────────────────────────────────────────────────────── + + +def test_zero_rows_give_the_types_of_the_rows() -> None: + table = _table({name: DATA_COLUMNS[name] for name in ["g", "t", *DATA_NAMES]}) + full = GroupBy("g")(ArrowTableStream(table, tag_columns=["g", "t"])).as_table() + empty = GroupBy("g")( + ArrowTableStream(table.slice(0, 0), tag_columns=["g", "t"]) + ).as_table() + assert empty.num_rows == 0 + assert empty.schema == full.schema + + +# ── struct-bearing tags are refused ───────────────────────────────────────── + +STRUCT = pa.array( + [{"x": 1, "y": "a"}, {"x": 1, "y": "a"}, {"x": 2, "y": None}], + pa.struct([("x", pa.int64()), ("y", pa.large_string())]), +) +# A ``dict[str, int]`` tag is stored as a list of key/value structs. +DICT_SHAPED = pa.array( + [[{"key": "a", "value": 1}], [{"key": "a", "value": 1}], []], + pa.large_list(pa.struct([("key", pa.large_string()), ("value", pa.int64())])), +) +MAP = pa.array( + [[("a", 1)], [("a", 1)], [("b", 2)]], pa.map_(pa.large_string(), pa.int64()) +) +STRUCT_TAGS = {"struct": STRUCT, "dict_shaped": DICT_SHAPED, "map": MAP} + + +def _struct_stream(tag: Column) -> ArrowTableStream: + table = _table( + { + "g": pa.array([1, 1, 2], pa.int64()), + "s": tag, + "v": pa.array([0, 1, 2], pa.int64()), + "w": pa.array([3, 4, 5], pa.int64()), + } + ) + return ArrowTableStream(table, tag_columns=["g", "s"]) + + +@pytest.mark.parametrize("name", list(STRUCT_TAGS)) +def test_a_struct_bearing_key_is_refused(name: str) -> None: + stream = _struct_stream(STRUCT_TAGS[name]) + with pytest.raises(InputValidationError, match=r"'s'.*struct|struct.*'s'"): + _ = GroupBy("s")(stream) + with pytest.raises(InputValidationError, match=r"'s'"): + _ = GroupBy(["g", "s"])(stream) + + +@pytest.mark.parametrize("name", list(STRUCT_TAGS)) +def test_a_struct_bearing_ordering_tag_is_refused(name: str) -> None: + """A non-key tag orders the members, and a struct has no decided order.""" + stream = _struct_stream(STRUCT_TAGS[name]) + with pytest.raises(InputValidationError, match="select_tag_columns"): + _ = GroupBy("g")(stream) + # The async path refuses it too: it runs the operator without ``process``. + with pytest.raises(InputValidationError, match="select_tag_columns"): + _ = async_rows(GroupBy("g"), stream) + + +def test_dropping_the_struct_tag_first_groups() -> None: + stream = _struct_stream(STRUCT).select_tag_columns(["g"]) + assert GroupBy("g")(stream).as_table().column("v").to_pylist() == [[0, 1], [2]] + + +# ── every list kind orders element by element; nothing unprepared reaches Polars ── +# +# Polars panics on a decimal256 (an error no caller can catch), so every tag reaches +# its sort only through one preparation, through lists, large lists and fixed-size +# lists at every depth (CodeRabbit, PR 458). Each case has two ordering tags: ``t1`` +# of the type under test and ``t2``, which breaks the tie between rows 0 and 4. + + +def _fixed(values: list[Any], element: pa.DataType, size: int) -> Column: + return pa.array(values, pa.list_(element, size)) + + +LIST_KIND_CASES: dict[str, tuple[Column, list[int], list[int]]] = { + # [1, 5] < [1, null] < [1 + 1e-40, 2] (rows 0 and 4) < null + "fixed_size_list": ( + _fixed( + [[_dec(1, 1), _dec(2)], [_dec(1), None], None, [_dec(1), _dec(5)]] + + [[_dec(1, 1), _dec(2)]], + DEC, + 2, + ), + [3, 1, 4, 0, 2], + [3, 1, 4, 2, 0], + ), + # [-0.5] < [2.0] (rows 0 and 4) < [null] < null + "fixed_size_list": ( + pa.FixedSizeListArray.from_arrays( + _floats([0x4000, None, 0xB800, 0, 0x4000], 16), + 1, + mask=pa.array([False, False, False, True, False]), + ), + [2, 4, 0, 1, 3], + [2, 4, 1, 3, 0], + ), + # nanoseconds two levels down: [[1], [1]] < [[1], [null]] < [[2], [1]] < [null, [0]] + "fixed_size_list>": ( + _fixed( + [[[2], [1]], [[1], [None]], [[1], [1]], [None, [0]], [[2], [1]]], + pa.list_(pa.int64(), 1), + 2, + ).cast(pa.list_(pa.list_(NS, 1), 2)), + [2, 1, 4, 0, 3], + [2, 1, 4, 3, 0], + ), + # [] < [[1], [1]] < [[2]] (rows 0 and 4) < [null] + "large_list>": ( + pa.array( + [[[_dec(2)]], [], [[_dec(1)], [_dec(1)]], [None], [[_dec(2)]]], + pa.large_list(pa.list_(DEC, 1)), + ), + [1, 2, 4, 0, 3], + [1, 2, 4, 3, 0], + ), +} + + +def _list_kind_columns(t1: Column) -> dict[str, Column]: + return { + "g": pa.array([1] * 5, pa.int64()), + "t1": t1, + "t2": pa.array([1, 0, 0, 0, 0], pa.int64()), + "rid": pa.array([f"r{i}" for i in range(5)], pa.large_string()), + "v": pa.array(range(5), pa.int64()), + "w": _ints([10, 11, 12, 13, 14], NS), + } + + +@pytest.mark.parametrize("name", list(LIST_KIND_CASES)) +def test_every_list_kind_orders_members_element_by_element(name: str) -> None: + t1, by_name, t2_first = LIST_KIND_CASES[name] + columns = _list_kind_columns(t1) + for order in itertools.permutations(range(5)): + source = _source(_permuted(columns, order), ["g", "t1", "t2"]) + for member_order, expected in ((None, by_name), (["t2"], t2_first)): + grouped = source.group_by("g", member_order=member_order) + table = grouped.as_table() + assert table.column("v").to_pylist() == [expected], member_order + assert _exact(table.column("w")) == [[10 + i for i in expected]] + + +@pytest.mark.parametrize("name", list(LIST_KIND_CASES)) +def test_every_list_kind_orders_members_the_same_sync_and_async(name: str) -> None: + t1, by_name, _ = LIST_KIND_CASES[name] + source = _source(_list_kind_columns(t1), ["g", "t1", "t2"]) + for rows in ( + async_rows(GroupBy("g"), source), + list(GroupBy("g")(source).iter_data()), + ): + [(_, data)] = rows + assert data.as_table().column("v").to_pylist() == [by_name] + + +def test_a_fixed_size_list_key_is_refused_as_list_valued() -> None: + columns = _list_kind_columns(LIST_KIND_CASES["fixed_size_list"][0]) + source = _source(columns, ["g", "t1", "t2"]) + with pytest.raises(InputValidationError, match="list-valued"): + _ = source.group_by(["g", "t1"]) + with pytest.raises(InputValidationError, match="list-valued"): + _ = async_rows(GroupBy(["t1", "g"]), source) + + +# Tag types GroupBy has no order for, beyond a struct or a map at the top level. +UNORDERABLE_TAGS: dict[str, Column] = { + "month_day_nano_interval": pa.array( + # (months, days, nanoseconds): one month against 31 days has no order. + [(1, 0, 0), (0, 31, 0), None], + pa.month_day_nano_interval(), + ), + "dense_union": pa.UnionArray.from_dense( + pa.array([0, 1, 0], pa.int8()), + pa.array([0, 0, 1], pa.int32()), + [pa.array([1, 2], pa.int64()), pa.array(["a"], pa.large_string())], + ), + "large_list_view": pa.array([[1], [2], None], pa.large_list_view(pa.int64())), + "large_list": pa.array( + [[[("a", 1)]], [[("b", 2)]], []], + pa.large_list(pa.map_(pa.large_string(), pa.int64())), + ), + "fixed_size_list": pa.FixedSizeListArray.from_arrays( + pa.StructArray.from_arrays([pa.array([1, 2, 3], pa.int64())], names=["x"]), + 1, + ), +} + + +def _unorderable_stream(tag: Column) -> ArrowTableStream: + table = _table( + { + "g": pa.array([1, 1, 2], pa.int64()), + "u": pa.array([0, 1, 2], pa.int64()), + "s": tag, + "v": pa.array([0, 1, 2], pa.int64()), + "w": pa.array([3, 4, 5], pa.int64()), + } + ) + return ArrowTableStream(table, tag_columns=["g", "u", "s"]) + + +@pytest.mark.parametrize("name", list(UNORDERABLE_TAGS)) +def test_a_tag_without_an_order_is_refused_in_every_role(name: str) -> None: + """Refused as an ordering tag and as a key, on the sync and the async path.""" + stream = _unorderable_stream(UNORDERABLE_TAGS[name]) + for by in (["g"], ["u", "g"]): + with pytest.raises(InputValidationError, match="select_tag_columns"): + _ = GroupBy(by)(stream) + with pytest.raises(InputValidationError, match="select_tag_columns"): + _ = async_rows(GroupBy(by), stream) + for by in (["s"], ["g", "s"]): + with pytest.raises(InputValidationError, match=r"'s'"): + _ = GroupBy(by)(stream) + with pytest.raises(InputValidationError, match=r"'s'"): + _ = async_rows(GroupBy(by), stream) + kept = stream.select_tag_columns(["g", "u"]) + assert GroupBy("g")(kept).as_table().column("v").to_pylist() == [[0, 1], [2]] + + +# ── every list follows one member order: the lists are parallel by origin row ── + + +@pytest.mark.parametrize("roles", ["plain", "data_tags", "mixed"]) +def test_every_list_and_fold_follows_one_member_order(roles: str) -> None: + """Element i of every data list, every source-info list and the folded record id + belong to one origin row, in every row order (developer, November 19, 2026). + + The data columns are anti-correlated (``a`` rises where ``b`` falls), so a list + sorted by its own values would come out in another order than its neighbours. + """ + columns: dict[str, Column] = { + "g": pa.array([1, 2, 1, 1, 2, 1], pa.int64()), + "t": pa.array([3, 0, 1, 2, 1, 0], pa.int64()), + "u": pa.array([0, 1, 1, 0, 0, 1], pa.int64()), + "rid": pa.array([f"r{i}" for i in range(6)], pa.large_string()), + "a": pa.array([10, 11, 12, 13, 14, 15], pa.int64()), + "b": pa.array([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], pa.float64()), + "c": _ints([600, 500, 400, 300, 200, 100], NS), + } + row_of_a = {10 + i: f"r{i}" for i in range(6)} + plain = {"plain": None, "data_tags": [], "mixed": ["u"]}[roles] + for order in itertools.permutations(range(6)): + source = _source(_permuted(columns, order), ["g", "t", "u"], plain=plain) + for member_order in (None, ["u"]): + table = source.group_by("g", member_order=member_order).as_table( + all_info=True + ) + [record_column] = [ + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) + ] + exact_c = _exact(table.column("c")) + for index, row in enumerate(table.to_pylist()): + rows = [row_of_a[a] for a in row["a"]] + # Every data list holds the values of those rows, in that order + # (``c`` read from Arrow: as Python it would lose its nanoseconds). + assert row["b"] == [5.0 - int(r[1:]) for r in rows] + assert exact_c[index] == [600 - 100 * int(r[1:]) for r in rows] + # Every source-info list names the same rows, in the same order. + for name in ("a", "b", "c"): + tokens = row[f"{constants.SOURCE_PREFIX}{name}"] + assert [json.loads(t.split("::")[1])["rid"] for t in tokens] == rows + # The folded record id is the fold of the same rows, in that order. + assert row[record_column] == arrow_utils.fold_system_tag_values( + [json.dumps({"rid": r}, separators=(",", ":")) for r in rows], + label=GROUP_BY_FOLD_LABEL, + ) + + +# ── validation and preparation agree on every type ────────────────────────── +# +# CodeRabbit, PR 458: a dictionary over a logical type passed validation but its +# preparation unwrapped the logical type before decoding the dictionary, then met it +# again and raised. Both now read a type through logical storage and dictionary values +# alternately, until neither applies. + +PATH_TYPE = cast( + pa.BaseExtensionType, + get_default_context().type_converter.python_type_to_arrow_type(Path), +) + + +def _paths(values: list[str | None]) -> Column: + return pa.ExtensionArray.from_storage( + PATH_TYPE, pa.array(values, PATH_TYPE.storage_type) + ) + + +def _dictionary(values: Column, indices: list[int | None]) -> Column: + return pa.DictionaryArray.from_arrays(pa.array(indices, pa.int32()), values) + + +def test_a_dictionary_over_a_logical_type_orders_and_keys() -> None: + """A dictionary-encoded Path tag orders the members and keys the groups.""" + columns: dict[str, Column] = { + "g": pa.array([1, 1, 1, 2], pa.int64()), + "t1": _dictionary(_paths(["/b", "/a"]), [0, 1, None, 1]), + "t2": pa.array([0, 0, 0, 1], pa.int64()), + "rid": pa.array([f"r{i}" for i in range(4)], pa.large_string()), + "v": pa.array(range(4), pa.int64()), + } + table = _table(columns) + stream = ArrowTableStream(table, tag_columns=["g", "t1", "t2"]) + # "/a" before "/b", null last; for every key path, sync and async. + for rows in ( + list(GroupBy("g")(stream).iter_data()), + async_rows(GroupBy("g"), stream), + ): + lists = sorted( + cast(list[int], data.as_table().column("v").to_pylist()[0]) + for _, data in rows + ) + assert lists == [[1, 0, 2], [3]] + for rows in ( + list(GroupBy(["t1", "t2"])(stream).iter_data()), + async_rows(GroupBy(["t2", "t1"]), stream), + ): + assert len(rows) == 4 + + +AGREEMENT_TYPES: dict[str, Column] = { + "int8": pa.array([1, None, -1], pa.int8()), + "uint64": pa.array([0, None, 2**64 - 1], pa.uint64()), + "float16": _floats([0x3C00, None, 0x7C01], 16), + "float64": pa.array([1.0, None, float("nan")], pa.float64()), + "bool": pa.array([True, None, False]), + "decimal128": pa.array([D(1), None, D(-1)], pa.decimal128(10, 2)), + "decimal256": pa.array([_dec(1, 1), None, _dec(-1)], DEC), + "large_string": pa.array(["b", None, "a"], pa.large_string()), + "string_view": pa.array(["b", None, "a"], pa.string_view()), + "binary_view": pa.array([b"b", None, b"a"], pa.binary_view()), + "fixed_size_binary": pa.array([b"ab", None, b"ba"], pa.binary(2)), + "date64": _ints([1, None, 86_400_001], pa.date64()), + "time32[s]": pa.array([1, None, 2], pa.int32()).cast(pa.time32("s")), + "time64[ns]": _ints([1, None, 2], NS), + "timestamp[ns, tz]": _ints([1, None, 2], pa.timestamp("ns", "UTC")), + "duration[s]": _ints([1, None, 2], pa.duration("s")), + "null": pa.array([None, None, None], pa.null()), + "logical Path": _paths(["/b", None, "/a"]), + "dictionary": _dictionary( + pa.array(["b", "a"], pa.large_string()), [0, None, 1] + ), + "dictionary": _dictionary(_paths(["/b", "/a"]), [0, None, 1]), + "large_list>": pa.LargeListArray.from_arrays( + pa.array([0, 1, 1, 2], pa.int64()), + _dictionary(_paths(["/b", "/a"]), [0, 1]), + ), + "fixed_size_list": _fixed([[_dec(1)], None, [_dec(2)]], DEC, 1), + "large_list>": pa.LargeListArray.from_arrays( + pa.array([0, 1, 1, 2], pa.int64()), + pa.FixedSizeListArray.from_arrays(_floats([0x3C00, 0x4000], 16), 1), + ), + # Without an order: + "struct": pa.StructArray.from_arrays( + [pa.array([1, 2, 3], pa.int64())], names=["x"] + ), + "map": pa.array([[("a", 1)], None, []], pa.map_(pa.large_string(), pa.int64())), + "interval": pa.array([(1, 0, 0), None, (0, 31, 0)], pa.month_day_nano_interval()), + "dense_union": UNORDERABLE_TAGS["dense_union"], + "large_list_view": pa.array([[1], None, [2]], pa.large_list_view(pa.int64())), + "large_list": pa.array( + [[{"x": 1}], None, []], pa.large_list(pa.struct([("x", pa.int64())])) + ), + "dictionary": _dictionary( + pa.StructArray.from_arrays([pa.array([1, 2], pa.int64())], names=["x"]), + [0, None, 1], + ), +} +ORDERABLE = 23 + + +@pytest.mark.parametrize("name", list(AGREEMENT_TYPES)) +def test_validation_and_preparation_agree_on_every_type(name: str) -> None: + """A type validation accepts is prepared and read by Polars; any other is refused + by both, never passed through.""" + array = AGREEMENT_TYPES[name] + accepted = _unorderable_part(array.type) is None + assert accepted == (list(AGREEMENT_TYPES).index(name) < ORDERABLE) + if accepted: + prepared = _polars_ready(array) + frame = pl.from_arrow(pa.Table.from_arrays([prepared], names=["x"])) + assert isinstance(frame, pl.DataFrame) + _ = frame.sort(_sort_key("x", frame.schema["x"]), nulls_last=True) + else: + with pytest.raises(TypeError, match="no order"): + _ = _polars_ready(array) diff --git a/tests/test_core/operators/test_group_by_nan_keys.py b/tests/test_core/operators/test_group_by_nan_keys.py index aa3ed4152..b951ee65a 100644 --- a/tests/test_core/operators/test_group_by_nan_keys.py +++ b/tests/test_core/operators/test_group_by_nan_keys.py @@ -17,7 +17,7 @@ import itertools import json import struct -from typing import Any, cast +from typing import Any import pyarrow as pa import pytest @@ -414,13 +414,13 @@ def test_a_float_backed_logical_key_groups_the_same_sync_and_async() -> None: assert fingerprint == seen[0], orchestrator.__name__ -def test_a_time64_ns_key_is_rebuilt_from_its_python_value() -> None: - """Pins today's grouping of a key that is not a float, whatever the row order. +def test_a_time64_ns_key_groups_by_its_exact_value() -> None: + """1 ns and 2 ns are two groups, each emitting its own key, whatever the row order. - ``GroupBy`` compares keys as Python values, and a ``time64[ns]`` value reads as a - ``datetime.time`` of microseconds: 1 ns and 2 ns form one group, which emits - the Python value rebuilt (0 ns), as on ``main``. Grouping by the exact value is - ITL-1250. Only a float key is taken from the Arrow column. + ``GroupBy`` compared keys as Python values, and a ``time64[ns]`` value reads as a + ``datetime.time`` of microseconds: 1 ns and 2 ns were one group, which emitted the + Python value rebuilt (0 ns). It now groups by the Arrow value (ITL-1250), and every + key is taken from the input's Arrow column, not only a float key. """ for values in ([1, 2], [2, 1]): table = pa.table( @@ -430,9 +430,8 @@ def test_a_time64_ns_key_is_rebuilt_from_its_python_value() -> None: table, tag_columns=["k"], tag_only_columns=True, source_id="s" ) out = source.group_by("k").as_table() - assert out.column("k").cast(pa.int64()).to_pylist() == [0] - members = cast(list[list[int]], out.column("v").to_pylist()) - assert sorted(members[0]) == sorted(values) + assert out.column("k").cast(pa.int64()).to_pylist() == [1, 2] + assert out.column("v").to_pylist() == [[1], [2]] # ── a dictionary-encoded float key ──────────────────────────────────────────