diff --git a/.zed/rules b/.zed/rules index 5571ece3d..daef1f173 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1436,6 +1436,14 @@ data. The rules: 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. +- The presentation order (`arrow_utils.sort_by_tag_columns`: `as_table(columns={"sort_by_tags": True})`, + `head().sort_by_tags()`, the preview) is ascending by the tags, then the system tags, nulls + last at every depth: a null list element or struct field after the values beside it, as + `GroupBy` orders a list and Arrow a struct (ITL-1295). Arrow sorts when it can; for a list + tag (or a struct holding one) Polars orders the prepared keys only + (`arrow_keys.polars_key_frame`, `arrow_keys.sort_key`) and the rows are taken from the + table, so no value passes through Polars. A tag type with no rule (a map, an interval, a + union, a list view) raises `TypeError` naming the column. - 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 e6171fd63..51ff0b3d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1483,6 +1483,14 @@ data. The rules: 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. +- The presentation order (`arrow_utils.sort_by_tag_columns`: `as_table(columns={"sort_by_tags": True})`, + `head().sort_by_tags()`, the preview) is ascending by the tags, then the system tags, nulls + last at every depth: a null list element or struct field after the values beside it, as + `GroupBy` orders a list and Arrow a struct (ITL-1295). Arrow sorts when it can; for a list + tag (or a struct holding one) Polars orders the prepared keys only + (`arrow_keys.polars_key_frame`, `arrow_keys.sort_key`) and the rows are taken from the + table, so no value passes through Polars. A tag type with no rule (a map, an interval, a + union, a list view) raises `TypeError` naming the column. - `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-1295.md b/changelog.d/ITL-1295.md index 84938674d..9b1eda10a 100644 --- a/changelog.d/ITL-1295.md +++ b/changelog.d/ITL-1295.md @@ -10,3 +10,11 @@ `decimal256` tag, the second run crashing the process. Now only the bookkeeping columns pass through Polars, and every value is taken from the stored tables. No hash, entry id or stored table changes. (ITL-1295) +- **A read sorted by tags shows every value as it is.** When a tag is a list (or a struct + holding one), `as_table(columns={"sort_by_tags": True})` and `head().sort_by_tags()` + sorted the whole table with Polars, so a `date64` value showed at midnight and a + `decimal256` value crashed the process. Now only the tags are compared and every value is + the stream's own. The notebook preview orders its rows the same way, but it still renders + them through Polars, so a `decimal256` column it shows still crashes it (ITL-1302). A null inside a list or a struct now sorts after the values beside it, + as a null tag sorts last (it used to sort first), so rows with such tags can appear in + another order. (ITL-1295) diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 7487ae670..0e0eba670 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -112,6 +112,16 @@ only what is readily available, never compute, poll or deliver a row (they read code (a function, a predicate, a side effect) and never write to a database. `run()` computes (see "Computing a stream outside a job" below). +Tag order is ascending by the tag columns, in the stream's tag order. Rows with equal tags +are ordered by their system tags (their source ids and record ids) by a read that has them: +`as_table(columns={"sort_by_tags": True})`, `head(n, columns={"sort_by_tags": True})` and +the preview. `head().sort_by_tags()` and a view's `sort_by_tags()` have no system tags, so +they keep such rows in the order the view holds them (see "Computing a stream outside a job" below). +A null goes last, and so does a null inside a list or a struct: a list tag is ordered +element by element (a shorter list first when it is the start of a longer one), a struct +field by field. Sorting moves whole rows and never changes a value: every value shown is +the stream's own, whatever its Arrow type. + With no rows to show, a head still has the columns and Arrow types the rows would have. To learn them it applies each operator to empty (zero-row) tables, which processes no data: a chain of N operators applies up to N operators to empty tables (about 60 ms for 20). A filter @@ -237,7 +247,7 @@ What each kind of object shows: sorting included, and applies it to the rows it has before taking the first `n`. The default does not sort, as `as_table()` does not, so `head()` shows rows in the order the stream holds them. The notebook preview asks for the sorted head, so it shows the same rows -whatever order they were computed in. With `sort_by_tags=True`, or `all_info=True`, rows are +whatever order they were computed in. With `columns={"sort_by_tags": True}`, or `all_info=True`, rows are sorted by tag first (nulls last; rows with equal tags are ordered by their system tags): ```python diff --git a/docs/dev/design_issues/ITL-1295-FN3.md b/docs/dev/design_issues/ITL-1295-FN3.md index f3b587107..a7b37eaf0 100644 --- a/docs/dev/design_issues/ITL-1295-FN3.md +++ b/docs/dev/design_issues/ITL-1295-FN3.md @@ -27,8 +27,19 @@ also names takes `_right`), and the rows of a cross-session ephemeral miss are r the pipeline table. For every type Polars held exactly the result is what it was: columns, order, names, types, nullability, rows (`docs/dev/scripts/itl_1295/dump_reads.py` compares two checkouts). No hash, entry id, stored path or column moves. Tests: -`tests/test_pipeline/test_function_node_stored_values.py`. Remaining: the sort fallback of -`arrow_utils.sort_by_tag_columns` (list and struct tags, `as_table(sort_by_tags=True)`, -`head().sort_by_tags()`) still sorts through Polars; it needs the key preparation of -`core/operators/arrow_keys.py` (ITL-1284) and is the second part of ITL-1295 (strict -expected failures name it). +`tests/test_pipeline/test_function_node_stored_values.py`. + +**Fix (part 2):** the sort every presentation uses (`arrow_utils.sort_by_tag_columns`: +`as_table(columns={"sort_by_tags": True})`, `head().sort_by_tags()`, the notebook preview) fell back to +sorting the whole table with Polars when Arrow could not sort it (a list tag, or a struct +holding one), with the same losses. Now Polars orders only the prepared tag columns and row +numbers (`arrow_keys.polars_key_frame`, `arrow_keys.sort_key`) and the rows are taken from +the table. Nulls go last at every depth: a null list element or struct field after the +values beside it, as `GroupBy` orders a list and as Arrow orders a struct (so a struct tag +orders the same with or without a list tag beside it); before, Polars put them first. That +is the only order that moves (`docs/dev/scripts/itl_1295/compare_sort_fallback.py` +compares main's order with the new one). A tag type with no rule (a map, an interval, a +union, a list view) raises `TypeError` naming the column instead of a Polars error. Tests: +`tests/test_core/streams/test_sort_by_tags_values.py`. Not fixed here: the notebook +preview renders its rows through Polars, which panics on a `decimal256` column whatever +the sort (strict expected failures in that file). diff --git a/docs/dev/scripts/itl_1295/compare_sort_fallback.py b/docs/dev/scripts/itl_1295/compare_sort_fallback.py new file mode 100644 index 000000000..9aeca4bbc --- /dev/null +++ b/docs/dev/scripts/itl_1295/compare_sort_fallback.py @@ -0,0 +1,311 @@ +"""ITL-1295 part 2: the sort fallback's row order, before (main) and after (this branch). + +usage: + uv run python docs/dev/scripts/itl_1295/compare_sort_fallback.py audit + uv run pytest -p compare_sort_fallback (with this folder on PYTHONPATH; + writes ``COMPARE_SORT_FALLBACK_OUT``, default ``sort_fallback_calls.json``) + +``sort_by_tag_columns`` falls back to Polars when Arrow cannot sort (a list or a struct +tag). Before, Polars sorted the whole table (``old_order`` below, the code of main at +3d3dec21, given a row-number column); now it orders prepared keys and the rows are +taken (``arrow_utils._tag_order_by_polars``). Both are computed on the same table: + +* as a pytest plugin, on every call the tests make (``_tag_order_by_polars`` wrapped); +* ``audit``: tables of three tag columns (the type under test in a list and in a + struct, ``int64``, ``large_string``), in two tag orders, for every audit type. + +Per call: ``same`` (one permutation), ``moved`` (rows ordered differently: listed with +the reason found: a null inside a list or struct; for a table Arrow sorts itself, +whether the new order is Arrow's), ``main raised`` (Polars refused or panicked) +or ``main wrong`` (main's sort ran but changed a value in ANY column of the table, a +key or not: the changed columns are listed; the order is not compared). Each call also +records the test file that made it. + +The plugin run selects every test file that sorts, heads or previews: +``grep -rlE "sort_by_tags|[.]head[(]|_repr_html_|preview" tests`` (``test_*.py`` files). +""" + +from __future__ import annotations + +import decimal +import json +import os +import struct +import sys +from collections import Counter +from typing import Any, cast + +import numpy as np +import polars as pl +import pyarrow as pa + +from orcapod.utils import arrow_utils + +_ROW = "__compare_row" + + +def old_order(table: pa.Table, keys: list[str]) -> list[Any]: + """Main's fallback (3d3dec21) with a row-number column: the order it gave.""" + numbered = table.append_column( + _ROW, pa.array(np.arange(table.num_rows), pa.int64()) + ) + sorted_table = ( + pl.DataFrame(numbered) + .sort(by=keys, descending=False, nulls_last=True, maintain_order=True) + .to_arrow() + ) + return sorted_table.column(_ROW).to_pylist() + + +def _null_inside(value: Any) -> bool: + """Whether a list element or a struct field, at any depth, is null.""" + if isinstance(value, list): + return any(v is None or _null_inside(v) for v in value) + if isinstance(value, dict): + return any(v is None or _null_inside(v) for v in value.values()) + return False + + +def arrow_order(table: pa.Table, keys: list[str]) -> list[Any] | None: + """Arrow's own order (a struct of scalars), or ``None`` where Arrow cannot sort.""" + numbered = table.append_column( + _ROW, pa.array(np.arange(table.num_rows), pa.int64()) + ) + try: + ordered = numbered.sort_by([(k, "ascending") for k in keys]) + except (pa.ArrowNotImplementedError, pa.ArrowTypeError): + return None + return ordered.column(_ROW).to_pylist() + + +def _bits(array: "pa.Array[Any]") -> "pa.Array[Any]": + """An array with every float viewed as its bits, so a NaN equals itself.""" + if pa.types.is_floating(array.type): + width = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[ + array.type.bit_width + ] + return array.view(width) + if isinstance(array, (pa.ListArray, pa.LargeListArray)): + return pa.LargeListArray.from_arrays( + cast("pa.Int64Array", array.offsets.cast(pa.int64())), + _bits(array.values), + mask=array.is_null(), + ) + if isinstance(array, pa.StructArray): + return pa.StructArray.from_arrays( + [_bits(array.field(i)) for i in range(array.type.num_fields)], + names=[f.name for f in array.type], + mask=array.is_null(), + ) + if isinstance(array, pa.DictionaryArray): + return array.dictionary_decode() + return array + + +def compare(table: pa.Table, keys: list[str], new: list[Any]) -> dict[str, Any]: + """Classify one call.""" + types = ", ".join(f"{k}: {table.schema.field(k).type}" for k in keys) + try: + old = old_order(table, keys) + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as error: # a Polars panic is a BaseException + return {"types": types, "result": "main raised", "error": type(error).__name__} + try: + restored = arrow_utils.restore_schema_nullability( + pl.DataFrame(table).to_arrow(), table.schema + ) + # Every column, not only the keys: main's sort carried the whole table through + # Polars, so a data column could change while every key stayed equal. + changed = [ + name + for name in table.column_names + if not _bits(restored.column(name).combine_chunks()).equals( + _bits(table.column(name).combine_chunks()) + ) + ] + except (KeyboardInterrupt, SystemExit): + raise + except BaseException: + changed = list(table.column_names) + if changed: + return { + "types": types, + "result": "main wrong", + "same order": old == new, + "keys changed": any(name in keys for name in changed), + "changed columns": changed, + } + if old == new: + return {"types": types, "result": "same"} + rows = table.select(keys).to_pylist() + moved = [i for i, (a, b) in enumerate(zip(old, new, strict=True)) if a != b] + why = ( + "null inside a list or struct" + if any(_null_inside(rows[old[i]]) or _null_inside(rows[new[i]]) for i in moved) + else "UNEXPLAINED" + ) + arrow = arrow_order(table, keys) + if arrow is not None: + why += "; now Arrow's own order" if arrow == new else "; NOT Arrow's order" + return { + "types": types, + "result": "moved", + "why": why, + "main": [rows[i] for i in old], + "now": [rows[i] for i in new], + } + + +# ── the pytest plugin ───────────────────────────────────────────────────────── + +_CALLS: list[dict[str, Any]] = [] +_TEST: list[str] = [""] + + +def pytest_runtest_setup(item: Any) -> None: + _TEST[0] = item.nodeid + + +def pytest_configure(config: Any) -> None: + original = arrow_utils._tag_order_by_polars # pyright: ignore[reportPrivateUsage] + + def wrapped(table: pa.Table, keys: list[str]) -> Any: + new = original(table, keys) + _CALLS.append( + {**compare(table, keys, new.to_pylist()), "test": _TEST[0].split("::")[0]} + ) + return new + + arrow_utils._tag_order_by_polars = wrapped # pyright: ignore[reportPrivateUsage] + + +def pytest_unconfigure(config: Any) -> None: + out = os.environ.get("COMPARE_SORT_FALLBACK_OUT", "sort_fallback_calls.json") + with open(out, "w") as handle: + json.dump(_CALLS, handle, default=str, indent=1) + print( + f"\nsort fallback calls: {len(_CALLS)}; {dict(Counter(c['result'] for c in _CALLS))}" + ) + + +# ── the audit ───────────────────────────────────────────────────────────────── + + +def _f32(bits: int) -> float: + return struct.unpack(" dict[str, "pa.Array[Any]"]: + """Five values of each audit type, one null, out of order, two equal.""" + day = 86_400_000 + return { + "int64": pa.array([3, 1, None, 2, 1], pa.int64()), + "date64 off midnight": pa.array([day + 5, 3, None, day + 1, 3], pa.date64()), + "date32": pa.array([5, 1, None, 3, 1], pa.date32()), + "time64[ns]": pa.array([5, 1_000_001, None, 1_000_000, 5], pa.time64("ns")), + "timestamp[ns, UTC]": pa.array([5, 1, None, 3, 1], pa.timestamp("ns", "UTC")), + "duration[ns]": pa.array([5, -1, None, 3, -1], pa.duration("ns")), + "decimal128": pa.array( + [ + decimal.Decimal("2.5"), + decimal.Decimal("-1"), + None, + decimal.Decimal("0.1"), + decimal.Decimal("-1"), + ], + pa.decimal128(10, 2), + ), + "decimal256": pa.array( + [ + decimal.Decimal("2.5"), + decimal.Decimal("-1"), + None, + decimal.Decimal("1e30"), + decimal.Decimal("-1"), + ], + pa.decimal256(40, 2), + ), + "float32 (sNaN, -0.0)": pa.array( + [_f32(0x7FA00000), -0.0, None, 0.0, 1.5], pa.float32() + ), + "float64 NaN": pa.array([float("nan"), 2.0, None, -1.0, 2.0], pa.float64()), + "float16": pa.array( + np.array([1.5, -0.0, 0.0, 2.0, 1.5], np.float16), pa.float16() + ), + "large_string (é)": pa.array(["é", "é", None, "b", "é"], pa.large_string()), + "large_binary": pa.array( + [b"\x02", b"\x00", None, b"\x01", b"\x00"], pa.large_binary() + ), + "fixed_size_binary": pa.array([b"bb", b"aa", None, b"ab", b"aa"], pa.binary(2)), + "bool": pa.array([True, False, None, True, False], pa.bool_()), + "uint64 max": pa.array([2**64 - 1, 0, None, 5, 0], pa.uint64()), + # Since ITL-1264 (PR 455) no stream carries a dictionary-encoded column; this + # row measures the sort helper on a table directly, which no stream reaches. + "dictionary": pa.DictionaryArray.from_arrays( + pa.array([0, 1, None, 2, 1], pa.int32()), pa.array(["c", "a", "b"]) + ), + } + + +def _lists(values: "pa.Array[Any]", with_null_inside: bool) -> "pa.Array[Any]": + """Lists over ``values``: per row, its value then the next row's; the last row null. + + Without nulls inside, a null value is replaced by the first row's (never null). + """ + count = len(values) + order = [[i, (i + 1) % count] for i in range(count)] + if not with_null_inside: + order = [[i if values[i].is_valid else 0 for i in pair] for pair in order] + flat = pa.array([i for pair in order for i in pair], pa.int64()) + offsets = pa.array(np.arange(count + 1) * 2, pa.int64()) + mask = pa.array([False] * (count - 1) + [True], pa.bool_()) + return pa.LargeListArray.from_arrays(offsets, values.take(flat), mask=mask) # pyright: ignore[reportArgumentType] + + +def audit_tables(values: "pa.Array[Any]") -> list[tuple[str, pa.Table, list[str]]]: + """Tables with three tags (list or struct of the type, int64, large_string).""" + count = len(values) + other_int = pa.array([1, 1, 0, 1, 1][:count], pa.int64()) + other_str = pa.array(["b", "a", "a", "b", "a"][:count], pa.large_string()) + data = pa.array(np.arange(count), pa.int64()) + tables = [] + for name, tag in ( + ("list, nulls inside", _lists(values, True)), + ("list, no null inside", _lists(values, False)), + ("struct", pa.StructArray.from_arrays([values, other_int], names=["v", "i"])), + ( + "list of struct", + pa.LargeListArray.from_arrays( + pa.array(np.arange(count + 1), pa.int64()), # pyright: ignore[reportArgumentType] + pa.StructArray.from_arrays([values, other_int], names=["v", "i"]), + ), + ), + ): + table = pa.table({"t": tag, "n": other_int, "s": other_str, "x": data}) + for keys in (["t", "n", "s"], ["s", "t", "n"], ["n", "s", "t"]): + tables.append((f"{name}, keys {keys}", table, keys)) + return tables + + +def audit() -> None: + results: Counter[str] = Counter() + for type_name, values in audit_types().items(): + for label, table, keys in audit_tables(values): + new = arrow_utils._tag_order_by_polars(table, keys).to_pylist() # pyright: ignore[reportPrivateUsage] + outcome = compare(table, keys, new) + results[outcome["result"]] += 1 + line = f"{type_name:22} {label:40} {outcome['result']}" + if outcome["result"] == "moved": + line += f" ({outcome['why']})" + if outcome["result"] == "main raised": + line += f" ({outcome['error']})" + print(line) + print(dict(results)) + + +if __name__ == "__main__": + if sys.argv[1:] == ["audit"]: + audit() + else: + print(__doc__) diff --git a/docs/dev/scripts/itl_1295/measure_read_path.py b/docs/dev/scripts/itl_1295/measure_read_path.py index 0ced9b75f..2d313701b 100644 --- a/docs/dev/scripts/itl_1295/measure_read_path.py +++ b/docs/dev/scripts/itl_1295/measure_read_path.py @@ -14,7 +14,7 @@ summary's computed / reused counts, and ``k`` as presented; * ``load_only``: another new job, ``run(load_only=True)``; * ``in_memory``: the same graph without a job (``FunctionPodStream``), no database; -* ``head_sorted``: ``as_table(sort_by_tags=True)`` of the source (``sort_by_tag_columns`` +* ``head_sorted``: ``as_table(columns={"sort_by_tags": True})`` of the source (``sort_by_tag_columns`` falls back to Polars for types Arrow cannot sort). Each value is compared with the input exactly (temporal values as integers, floats as diff --git a/docs/dev/specs/itl-1246-data-tag-identity-order.md b/docs/dev/specs/itl-1246-data-tag-identity-order.md index b346f576f..644e9f416 100644 --- a/docs/dev/specs/itl-1246-data-tag-identity-order.md +++ b/docs/dev/specs/itl-1246-data-tag-identity-order.md @@ -254,7 +254,7 @@ Recursively sorting list tags, as `sort_by_tag_columns` does with Polars, would that pin. **F4. The presentation sort follows tag column order.** `arrow_utils.sort_by_tag_columns` -backs `as_table(sort_by_tags=True)`, `head()`, the preview and `StreamView.sort_by_tags`. +backs `as_table(columns={"sort_by_tags": True})`, `head()`, the preview and `StreamView.sort_by_tags`. It orders rows by the tags in tag order, then the system tags in column order. Which rows `head(n)` shows and their order therefore depend on tag order. It is not a hash. Recommended: name order (the same canonical rule) in a separate issue, or an explicit diff --git a/docs/dev/specs/itl-1271-order-invariance-audit.md b/docs/dev/specs/itl-1271-order-invariance-audit.md index b5589f2f4..633abaa2b 100644 --- a/docs/dev/specs/itl-1271-order-invariance-audit.md +++ b/docs/dev/specs/itl-1271-order-invariance-audit.md @@ -96,7 +96,7 @@ argument order and input order: | the same | layout | ITL-1249 | | `AddTags` column placement | keyword order | ITL-1269 (landed in PR 457: new tags placed in name order) | | `DerivedSource(tags_as_data=...)` column placement of the new data columns | mapping order | **fixed here**: copies in the order of their new names (no hash moves) | -| rows `head(n)` / `as_table(sort_by_tags=True)` / preview show | tag order; for joins and pods also layout | ITL-1270 (and ITL-1249 for layout) | +| rows `head(n)` / `as_table(columns={"sort_by_tags": True})` / preview show | tag order; for joins and pods also layout | ITL-1270 (and ITL-1249 for layout) | | stored column order of `pdb_v1` and `odb_v1` | tag order and layout | presentation: a Delta store written by two tag orders reads back by name (checked: two runs, one path, all rows) | | saved job file: a bound source's `tag_columns`, a `Join` node's input order | as declared | presentation: the file records the declaration; a load rebuilds the same hashes | diff --git a/src/orcapod/core/operators/arrow_keys.py b/src/orcapod/core/operators/arrow_keys.py index 0313d4a0b..5370b582d 100644 --- a/src/orcapod/core/operators/arrow_keys.py +++ b/src/orcapod/core/operators/arrow_keys.py @@ -22,8 +22,10 @@ Every other type (a map, an interval, a union, a list view, ...) has no rule: ``part_without_rule`` names it, and the caller refuses the column, naming it. -``Join`` and ``SemiJoin`` use this module. ``GroupBy`` keeps its own copy until -ITL-1281 makes it import this one (its rule refuses structs: ``structs=False``). +``Join`` and ``SemiJoin`` use this module, and so does the order every presentation +uses (``arrow_utils.sort_by_tag_columns``, when Arrow cannot sort: a list or struct +tag), which orders by ``sort_key``. ``GroupBy`` keeps its own copy until ITL-1281 +makes it import this one (its rule refuses structs: ``structs=False``). """ from __future__ import annotations @@ -306,3 +308,59 @@ def polars_key_frame( return cast( "pl.DataFrame", pl.from_arrow(pa.Table.from_arrays(arrays, names=names)) ) + + +def _null_last(expr: "pl.Expr", dtype: object) -> "pl.Expr": + """Return a list element or struct field as an ``(is_null, value)`` pair: null last.""" + return pl.struct( + expr.is_null().alias("null"), _nulls_inside_last(expr, dtype).alias("value") + ) + + +def _nulls_inside_last(expr: "pl.Expr", dtype: object) -> "pl.Expr": + """Return ``expr`` with every null inside it ordered after the values beside it. + + The elements of a list and the fields of a struct, at every depth, become + ``(is_null, value)`` pairs. A null list or struct stays null: the sort's + ``nulls_last`` (or the pair it is in) puts it last. + + Args: + expr: A prepared column, or a part of one. + dtype: Its Polars type. + + Returns: + The expression to order by. + """ + if isinstance(dtype, pl.List): + return expr.list.eval(_null_last(pl.element(), dtype.inner)) + if isinstance(dtype, pl.Struct): + return pl.when(expr.is_not_null()).then( + pl.struct( + _null_last(expr.struct.field(field.name), field.dtype).alias(field.name) + for field in dtype.fields + ) + ) + return expr + + +def sort_key(name: str, dtype: object) -> "pl.Expr": + """Return the expression a prepared key column is ordered by: nulls last, at every depth. + + Sorted with ``nulls_last``, a null value orders last. Polars puts a null INSIDE a + list or a struct first, so every list element and struct field, at every depth, is + ordered through an ``(is_null, value)`` pair: a null after every value, as Arrow + orders a struct's fields and ``GroupBy`` a list's elements (ITL-1226). A list orders + element by element, a shorter one first when it is a prefix; a struct field by + field. A NaN orders after every number and before null; Polars ties ``0.0`` with + ``-0.0``. + + Args: + name: The column's name in the frame. + dtype: Its Polars type (``frame.schema[name]``). + + Returns: + The expression to sort by. + """ + # ``object``: a Polars data type is an instance or a class (``PolarsDataType``, + # which Polars keeps private). + return _nulls_inside_last(pl.col(name), dtype) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 54b62c80f..460c45cd7 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -2146,8 +2146,8 @@ def canonical_identity_row_order( def sort_by_tag_columns(table: "pa.Table", tag_keys: tuple[str, ...]) -> "pa.Table": """Return ``table`` with its rows in tag order: the sort every presentation uses. - This is the order of ``as_table(sort_by_tags=True)``, ``head`` and the notebook - preview. It is not a hash input: a stream's identity does not depend on row order + This is the order of ``as_table(columns={"sort_by_tags": True})``, ``head`` and the + notebook preview. It is not a hash input: a stream's identity does not depend on row order (``ArrowTableStream._identity_table``: rows ordered by their own hash). The rows are ordered ascending by the tag columns ``tag_keys``, nulls last. Rows with @@ -2156,7 +2156,9 @@ def sort_by_tag_columns(table: "pa.Table", tag_keys: tuple[str, ...]) -> "pa.Tab result does not depend on the order the rows arrived in whenever the table has system tags. A table with neither is returned as it is. A caller that must keep the order of a stream with no regular tag column does not call this for it. A tag type Arrow cannot - order (a list) is ordered with Polars, nulls last. + order (a list, or a struct holding one) is ordered with Polars over the prepared keys + only, nulls last at every depth, inside a list or a struct too, as Arrow orders a + struct (``_tag_order_by_polars``); the rows are taken from ``table``. Whole rows move together: a column added to ``table`` before the sort (a content hash) stays with its row. Column types and nullability are those of ``table``. Sort before @@ -2178,14 +2180,53 @@ def sort_by_tag_columns(table: "pa.Table", tag_keys: tuple[str, ...]) -> "pa.Tab try: return table.sort_by([(key, "ascending") for key in keys]) except (pa.ArrowNotImplementedError, pa.ArrowTypeError): - import polars as pl + return table.take(_tag_order_by_polars(table, keys)) - sorted_table = ( - pl.DataFrame(table) - .sort(by=keys, descending=False, nulls_last=True, maintain_order=True) - .to_arrow() - ) - return restore_schema_nullability(sorted_table, table.schema) + +def _tag_order_by_polars(table: "pa.Table", keys: list[str]) -> "pa.Array[Any]": + """Return the row numbers of ``table`` in tag order, ordered with Polars. + + For a tag Arrow cannot order (a list, or a struct holding one). Polars sees only the key + columns, prepared (``arrow_keys.polars_key_frame``: a ``date64`` as its integer, a + ``decimal256`` as its limbs, ...), and the row numbers; the caller takes the rows + from ``table``, so every value is the table's own (ITL-1295). The order is + ``arrow_keys.sort_key``: ascending, nulls last, inside a list or a struct too; rows + equal on every key keep their order. + + Args: + table: The table to order. + keys: The columns to order by, in priority. + + Returns: + The row numbers, as an ``int64`` array. + + Raises: + TypeError: When a key's type holds a part with no order (a map, an interval, a + union, a list view), naming the column. + """ + from orcapod.core.operators import arrow_keys + + for key in keys: + arrow_type = table.schema.field(key).type + part = arrow_keys.part_without_rule(arrow_type, structs=True) + if part is not None: + raise TypeError( + f"cannot order rows by the tag {key!r}: its type {arrow_type} holds " + + f"{part}, which has no order (a map, an interval, a union or a list " + + "view has none)" + ) + names = [f"key{index}" for index in range(len(keys))] + # Frame names of the frame's own: no key can clash with the row-number column. + frame = arrow_keys.polars_key_frame( + table.select(keys).rename_columns(names), names, "row" + ) + ordered = frame.sort( + [arrow_keys.sort_key(name, frame.schema[name]) for name in names], + descending=False, + nulls_last=True, + maintain_order=True, + ) + return ordered.get_column("row").to_arrow() if __name__ == "__main__": diff --git a/tests/test_core/alignment/checker.py b/tests/test_core/alignment/checker.py index 9fb1d8b67..cf1e5bda6 100644 --- a/tests/test_core/alignment/checker.py +++ b/tests/test_core/alignment/checker.py @@ -751,7 +751,7 @@ def assert_requested_columns( ] assert not missing, f"no source-info columns {missing}" if require_sorted and (all_info or columns.get("sort_by_tags")): - # List-valued tags (Batch) too: they are sorted with Polars, nulls last. + # List-valued tags (Batch) too: nulls last, inside a list too. assert_sorted_by_tags(table, layout.tag_keys) if (all_info or columns.get("system_tags")) and not layout.no_system_tags: pairs = [ @@ -841,31 +841,27 @@ def rows_table(pairs: Iterable[tuple[Any, Any]]) -> pa.Table: def _null_last(value: Any) -> tuple[Any, ...]: - """A sort key: ascending, a null cell after every value. + """A sort key: ascending, a null after every value, at every depth. - A list cell (``Batch``'s tags, sorted with Polars) is ordered element by element, a - shorter prefix first; inside a list a null element comes before every value, as - Polars orders it (only the null cell itself goes last). + A list cell (``Batch``'s tags) is ordered element by element, a shorter prefix + first, and a struct cell field by field; a null element or field comes after every + value, as a null cell does (ITL-1295: as ``GroupBy`` orders a list, Arrow a struct). """ if value is None: return (1,) - return (0, _in_list(value) if isinstance(value, list) else value) - - -def _in_list(value: list[Any]) -> tuple[Any, ...]: - """The Polars order of a list's elements: a null element before every value.""" - return tuple( - (0,) if v is None else (1, _in_list(v) if isinstance(v, list) else v) - for v in value - ) + if isinstance(value, list): + return (0, tuple(_null_last(v) for v in value)) + if isinstance(value, dict): + return (0, tuple(_null_last(v) for v in value.values())) + return (0, value) def assert_sorted_by_tags(table: pa.Table, tag_keys: Sequence[str]) -> None: """Assert the rows of ``table`` are in the presentation order ``sort_by_tags`` asks. - The order of ``as_table(sort_by_tags=True)`` and ``head`` (#354, + The order of ``as_table(columns={"sort_by_tags": True})`` and ``head`` (#354, ``arrow_utils.sort_by_tag_columns``): ascending by ``tag_keys``, a null cell last (a - list-valued tag is ordered with Polars: element by element, a null element first), + list-valued tag element by element, a null element last too), then by the system tag columns the table has, in column order. Rows equal on all of these keep their input order, which the table does not show, so they may come in any order. """ diff --git a/tests/test_core/streams/test_sort_by_tags_values.py b/tests/test_core/streams/test_sort_by_tags_values.py new file mode 100644 index 000000000..58e0c4fb3 --- /dev/null +++ b/tests/test_core/streams/test_sort_by_tags_values.py @@ -0,0 +1,425 @@ +"""A read sorted by tags keeps every value and orders lists and structs (ITL-1295). + +When a tag is a list (or a struct holding one), Arrow cannot sort the table, and the +sort every presentation uses (``as_table(columns={"sort_by_tags": True})``, ``head().sort_by_tags()``, +the notebook preview) orders it with Polars. It used to carry the whole table through +Polars: a ``date64`` came back at midnight (tags and data alike) and a ``decimal256`` +made Polars panic. Now Polars sees only the prepared tag columns and the row numbers, +and the rows are taken from the table: every value is the table's own, bit for bit. + +The order: ascending by the tags in tag order, nulls last at every depth: a null list +element or struct field after the values beside it (a list element by element, a +shorter list first when it is a prefix; a struct field by field). Arrow sorts a struct +tag of scalars itself, in that order, and the fallback gives a struct the same order. + +Each table has three tags (``t``, the list or struct under test, ``n: int64``, +``s: large_string``) in three tag orders and in three roles (plain tags, data-tags, one +data-tag among plain tags), and three data columns (``x``, the row's name; +``d: date64`` off midnight; ``e: decimal256``). +""" + +from __future__ import annotations + +import decimal +import re +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.semantic_types.nested_none import NestedNoneNotRestorableError + +D = decimal.Decimal +DAY = 86_400_000 + +# Seven rows; every row differs in its tags, so no tie reaches the record ids. +N = [1, 1, 0, 1, 1, 0, 1] +S = ["b", "a", "a", "b", "a", "b", "a"] +X = [f"r{i}" for i in range(7)] +DATA_D = pa.array([DAY * i + 7 for i in range(7)], pa.date64()) +DATA_E = pa.array( + [D(f"1e{30 + i}") + D("0.01") for i in range(7)], pa.decimal256(40, 2) +) + + +def _date64(values: list[int | None]) -> "pa.Array[Any]": + return pa.array(values, pa.date64()) + + +def _decimal256(values: list[Any]) -> "pa.Array[Any]": + return pa.array(values, pa.decimal256(40, 2)) + + +# The elements under test: a < b < c; a list of them has a null inside it and two +# lists share a first element, so the second decides (and a null inside goes last). +ELEMENTS = { + "date64": (_date64, [DAY + 1, DAY + 2, 2 * DAY + 5]), + "decimal256": (_decimal256, [D("-1e35"), D("0.01"), D("1e36")]), +} + + +def _list_tag(make: Any, values: list[Any]) -> "pa.Array[Any]": + a, b, _ = values + # [b, None], [a], [b, a], None, [None], [], [b, a] + return pa.LargeListArray.from_arrays( + pa.array([0, 2, 3, 5, 5, 6, 6, 8], pa.int64()), + make([b, None, a, b, a, None, b, a]), + mask=pa.array([False, False, False, True, False, False, False]), + ) + + +def _struct_tag(make: Any, values: list[Any]) -> "pa.Array[Any]": + a, b, c = values + return pa.StructArray.from_arrays( + [ + make([c, a, None, b, a, b, a]), + pa.array([1, 2, 3, 1, 3, None, 2], pa.int64()), + ], + names=["v", "i"], + mask=pa.array([False, False, False, False, False, False, True]), + ) + + +def _list_of_struct_tag(make: Any, values: list[Any]) -> "pa.Array[Any]": + a, b, _ = values + # [(b, 1), None], [(a, 2)], [(b, 1), (a, None)], None, [None], [], [(b, 1), (a, 2)] + elements = pa.StructArray.from_arrays( + [ + make([b, a, a, b, a, a, b, a]), + pa.array([1, 0, 2, 1, None, 0, 1, 2], pa.int64()), + ], + names=["v", "i"], + mask=pa.array([False, True, False, False, False, True, False, False]), + ) + return pa.LargeListArray.from_arrays( + pa.array([0, 2, 3, 5, 5, 6, 6, 8], pa.int64()), + elements, + mask=pa.array([False, False, False, True, False, False, False]), + ) + + +def _list_of_struct_tag_without_null_element( + make: Any, values: list[Any] +) -> "pa.Array[Any]": + a, b, _ = values + # [(b, 1)], [(a, 2)], [(b, 1), (a, 2)], None, [(a, 0)], [], [(b, 1), (a, 1)]: no + # null struct element (a null list and an empty list only), so the list can be a + # data-tag a function reads (a null element cannot be read back yet, ITL-1144). + elements = pa.StructArray.from_arrays( + [ + make([b, a, b, a, a, b, a]), + pa.array([1, 2, 1, 2, 0, 1, 1], pa.int64()), + ], + names=["v", "i"], + ) + return pa.LargeListArray.from_arrays( + pa.array([0, 1, 2, 4, 4, 5, 5, 7], pa.int64()), + elements, + mask=pa.array([False, False, False, True, False, False, False]), + ) + + +KINDS = { + "large_list": _list_tag, + "struct": _struct_tag, + "large_list": _list_of_struct_tag, + "large_list": _list_of_struct_tag_without_null_element, +} +TAGS = { + f"{kind}<{name}>": (build, make, values) + for name, (make, values) in ELEMENTS.items() + for kind, build in KINDS.items() +} +TAG_ORDERS = [("t", "n", "s"), ("n", "s", "t"), ("s", "t", "n")] +# How the tags are given: plain tags, every tag also a data column (data-tags), or the +# last tag in tag order a data-tag among plain tags. +PLAIN, DATA_TAGS, MIXED = "plain", "data_tags", "mixed" +ROLES = (PLAIN, DATA_TAGS, MIXED) + + +def _exact(array: "pa.Array[Any]") -> list[Any]: + """Values, temporal ones as integers, so a date64 off midnight shows.""" + if pa.types.is_date64(array.type): + return array.view(pa.int64()).to_pylist() + if isinstance(array, pa.LargeListArray): + values = _exact(array.values) + offsets = [int(o) for o in array.offsets.to_numpy()] + nulls = array.is_null().to_pylist() + return [ + None if nulls[i] else values[offsets[i] : offsets[i + 1]] + for i in range(len(array)) + ] + if isinstance(array, pa.StructArray): + fields = [_exact(array.field(i)) for i in range(array.type.num_fields)] + nulls = array.is_null().to_pylist() + return [ + None if nulls[i] else tuple(f[i] for f in fields) for i in range(len(array)) + ] + return array.to_pylist() + + +def _key(value: Any) -> Any: + """The order stated in the module docstring: nulls last at every depth.""" + if value is None: + return (1,) + if isinstance(value, list): + return (0, [_key(v) for v in value]) + if isinstance(value, tuple): + return (0, tuple(_key(v) for v in value)) + return (0, value) + + +def _table(tag_name: str, tag_order: tuple[str, ...]) -> pa.Table: + build, make, values = TAGS[tag_name] + columns = { + "t": build(make, values), + "n": pa.array(N, pa.int64()), + "s": pa.array(S, pa.large_string()), + } + arrays = { + **{name: columns[name] for name in tag_order}, + "x": pa.array(X, pa.large_string()), + "d": DATA_D, + "e": DATA_E, + } + return pa.Table.from_arrays( + list(arrays.values()), + schema=pa.schema( + pa.field(name, array.type, nullable=name != "x") + for name, array in arrays.items() + ), + ) + + +def _expected(table: pa.Table, tag_order: tuple[str, ...]) -> list[int]: + values = {name: _exact(table.column(name).combine_chunks()) for name in tag_order} + return sorted( + range(table.num_rows), + key=lambda row: tuple(_key(values[name][row]) for name in tag_order), + ) + + +def _source( + table: pa.Table, tag_order: tuple[str, ...], role: str = PLAIN +) -> ArrowTableSource: + tag_only: bool | list[str] + if role == PLAIN: + tag_only = True + elif role == DATA_TAGS: + tag_only = [] + else: + tag_only = list(tag_order[:-1]) + return ArrowTableSource( + table, + tag_columns=list(tag_order), + tag_only_columns=tag_only, + source_id="sorted", + ) + + +def _assert_rows(result: pa.Table, table: pa.Table, order: list[int]) -> None: + """``result`` holds ``table``'s rows in ``order``, every value exactly.""" + for name in ("t", "n", "s", "x", "d", "e"): + got = result.column(name).combine_chunks() + want = table.column(name).combine_chunks().take(pa.array(order)) + assert got.type == want.type, name + assert _exact(got) == _exact(want), name + + +READS = { + "as_table": lambda stream: stream.as_table(columns={"sort_by_tags": True}), + "head().sort_by_tags()": lambda stream: stream.head(10).sort_by_tags().as_table(), +} + + +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("read", list(READS)) +@pytest.mark.parametrize("tag_order", TAG_ORDERS, ids=lambda o: "".join(o)) +@pytest.mark.parametrize("tag_name", list(TAGS)) +def test_a_sorted_read_orders_list_and_struct_tags_and_keeps_every_value( + tag_name: str, tag_order: tuple[str, ...], read: str, role: str +) -> None: + table = _table(tag_name, tag_order) + result = READS[read](_source(table, tag_order, role)) + _assert_rows(result, table, _expected(table, tag_order)) + + +# The tags whose decimal256 values the preview shows as they are (it summarises a list +# of structs as text). +PREVIEW_SHOWS_DECIMAL256 = ("large_list", "struct") +PREVIEW_PANICS = pytest.mark.xfail( + strict=True, + reason="The notebook preview renders its table through Polars " + + "(StreamView._display_frame), which panics on a decimal256 column whatever the " + + "sort does: ITL-1302, not this sort.", +) + + +@pytest.mark.parametrize("tag_order", TAG_ORDERS, ids=lambda o: "".join(o)) +@pytest.mark.parametrize( + "tag_name", + [ + pytest.param(name, marks=PREVIEW_PANICS) + if name in PREVIEW_SHOWS_DECIMAL256 + else name + for name in TAGS + ], +) +def test_the_preview_shows_list_and_struct_tags_in_tag_order( + tag_name: str, tag_order: tuple[str, ...] +) -> None: + """The preview's rows (its ``x`` cells); the ``decimal256`` data column is left out.""" + table = _table(tag_name, tag_order).drop_columns(["e"]) + source = _source(table, tag_order) + + def preview() -> str: + try: + return source._repr_html_() + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as error: # a Polars panic is a BaseException + raise AssertionError(f"{type(error).__name__}: {error}") from None + + html = preview() + assert "sorted by tags" in html + shown = re.findall(r"]*>"(r\d)"", html) + assert shown == [X[row] for row in _expected(table, tag_order)] + + +@pytest.mark.parametrize("tag_order", TAG_ORDERS, ids=lambda o: "".join(o)) +@pytest.mark.parametrize("element", list(ELEMENTS)) +def test_a_struct_tag_orders_the_same_beside_a_list_tag( + element: str, tag_order: tuple[str, ...] +) -> None: + """Alone, Arrow sorts a struct tag; beside a list tag, the fallback does: one order.""" + table = _table(f"struct<{element}>", tag_order) + alone = READS["as_table"](_source(table, tag_order)) + with_list = table.append_column( + "l", pa.array([[1]] * table.num_rows, pa.large_list(pa.int64())) + ) + beside = READS["as_table"](_source(with_list, (*tag_order, "l"))) + assert beside.column("x").to_pylist() == alone.column("x").to_pylist() + assert alone.column("x").to_pylist() == [ + X[row] for row in _expected(table, tag_order) + ] + + +def test_nulls_inside_a_list_order_last() -> None: + """``[b, a]`` before ``[b, None]``; ``[None]`` after every list starting with a value.""" + make, (a, b, _) = ELEMENTS["date64"] + table = _table("large_list", ("t", "n", "s")) + result = READS["as_table"](_source(table, ("t", "n", "s"))) + assert _exact(result.column("t").combine_chunks()) == [ + [], + [a], + [b, a], + [b, a], + [b, None], + [None], + None, + ] + + +@function_pod(output_keys=["y", "z"]) +def marked(x: str, w: str) -> tuple[str, str]: + """Return ``x`` and ``w`` marked.""" + return x + "+", w + "-" + + +TAGS_FIRST, DATA_FIRST = "tags_first", "data_first" + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("layout", [TAGS_FIRST, DATA_FIRST]) +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("tag_order", TAG_ORDERS, ids=lambda o: "".join(o)) +@pytest.mark.parametrize("tag_name", list(TAGS)) +def test_a_job_node_sorted_read_keeps_every_value( + tag_name: str, + tag_order: tuple[str, ...], + role: str, + layout: str, + orchestrator: str, + request: pytest.FixtureRequest, +) -> None: + """A function node with two data columns in and two out, read sorted: through the + node and through its stored records, for every tag order, role and table layout, + on the sync and the async orchestrator.""" + t_is_data_tag = role == DATA_TAGS or (role == MIXED and tag_order[-1] == "t") + if tag_name.startswith("large_list<") and t_is_data_tag: + # The function reads a data-tag as data; a None struct element inside the + # list cannot be read back yet: the sync run records those two rows as failed + # (the read misses them), the async run raises. + request.applymarker( + pytest.mark.xfail( + strict=True, + raises=AssertionError + if orchestrator == "sync" + else NestedNoneNotRestorableError, + reason="ITL-1144: NestedNoneNotRestorableError: a None inside a " + + "container cannot be read back yet, so the rows whose list-of-struct " + + "data-tag holds a null element fail in the function; ITL-1308: the " + + "sync run records those rows as failed and continues, the async run " + + "raises", + ) + ) + full = _table(tag_name, tag_order) + data = {"x": full.column("x"), "w": pa.array([f"w{i}" for i in range(7)])} + tags = {name: full.column(name) for name in tag_order} + columns = {**tags, **data} if layout == TAGS_FIRST else {**data, **tags} + # The tags keep their flags; both data columns hold no null. + table = pa.Table.from_arrays( + list(columns.values()), + schema=pa.schema( + full.schema.field(name) if name in tags else pa.field(name, col.type, False) + for name, col in columns.items() + ), + ) + job = PipelineJob(name="sorted", database=InMemoryArrowDatabase()) + with job: + marked.pod(_source(table, tag_order, role), label="node") + job.run( + orchestrator=SyncPipelineOrchestrator() + if orchestrator == "sync" + else AsyncPipelineOrchestrator() + ) + order = _expected(full, tag_order) + for result in ( + job.nodes["node"].as_table(columns={"sort_by_tags": True}), + job.nodes["node"].as_source().as_table(columns={"sort_by_tags": True}), + ): + for name in tag_order: + want = full.column(name).combine_chunks().take(pa.array(order)) + assert _exact(result.column(name).combine_chunks()) == _exact(want), name + assert result.column("y").to_pylist() == [X[row] + "+" for row in order] + assert result.column("z").to_pylist() == [f"w{row}-" for row in order] + + +@pytest.mark.parametrize( + "tag", + [ + pa.array([[("a", 1)], [("b", 2)]], pa.map_(pa.large_string(), pa.int64())), + pa.array([(1, 2, 3), (0, 1, 2)], pa.month_day_nano_interval()), + pa.array([[2], [1]], pa.list_view(pa.int64())), + ], + ids=["map", "interval", "list_view"], +) +def test_a_tag_with_no_order_is_refused_naming_it(tag: "pa.Array[Any]") -> None: + """A raw stream may hold one (a source refuses it); Polars never sees it.""" + stream = ArrowTableStream( + pa.table( + { + "l": pa.array([[1], [0]], pa.large_list(pa.int64())), + "bad": tag, + "x": [1, 2], + } + ), + tag_columns=["l", "bad"], + ) + with pytest.raises(TypeError, match="cannot order rows by the tag 'bad'"): + stream.as_table(columns={"sort_by_tags": True}) diff --git a/tests/test_pipeline/test_function_node_stored_values.py b/tests/test_pipeline/test_function_node_stored_values.py index f6342109c..d741512fb 100644 --- a/tests/test_pipeline/test_function_node_stored_values.py +++ b/tests/test_pipeline/test_function_node_stored_values.py @@ -350,15 +350,7 @@ def test_a_join_of_a_reused_node_finds_the_rows_of_the_first_run( assert rows[0] == rows[1] == [(1, 11, 10), (2, 21, 20)] -# ── the sort fallback: part 2, after PR 459 (arrow_keys) ───────────────────── - -SORT_FALLBACK = pytest.mark.xfail( - strict=True, - reason="ITL-1295 part 2: arrow_utils.sort_by_tag_columns falls back to a Polars " - + "sort for list and struct tags, which carries every column through Polars " - + "(a date64 comes back at midnight, a decimal256 panics); it needs the key " - + "preparation of arrow_keys (PR 459).", -) +# ── a sorted read of stored list tags (the sort fallback, ITL-1295 part 2) ───── def _no_panic(read: Callable[[], Any]) -> Any: @@ -371,7 +363,6 @@ def _no_panic(read: Callable[[], Any]) -> Any: raise AssertionError(f"{type(error).__name__}: {error}") from None -@SORT_FALLBACK @pytest.mark.parametrize("type_name", ["large_list", "large_list"]) @pytest.mark.parametrize("read", ["as_table", "view"]) def test_a_sorted_read_of_a_list_tag_is_exact(type_name: str, read: str) -> None: