From bea48707f9f23e8d7fcf553e967342d4e136443a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Thu, 19 Nov 2026 15:38:25 -0800 Subject: [PATCH 1/5] fix(arrow_utils): sort list and struct tags on prepared keys; take the rows (ITL-1295) When Arrow cannot sort a table (a list tag, or a struct holding one), sort_by_tag_columns sorted the whole table with Polars: a date64 value came back at midnight and a decimal256 value made Polars panic, in as_table(sort_by_tags=True), head().sort_by_tags() and the notebook preview. Polars now orders only the prepared tag columns (arrow_keys.polars_key_frame) and the row numbers, and the rows are taken from the table. Nulls go last at every depth (arrow_keys.sort_key): a null list element or struct field after the values beside it, as GroupBy orders a list and Arrow a struct; before, Polars put them first. That is the only order that moves (docs/dev/scripts/itl_1295/compare_sort_fallback.py). A tag type with no rule raises TypeError naming the column. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 8 + CLAUDE.md | 8 + changelog.d/ITL-1295.md | 7 + docs/concepts/streams.md | 6 + docs/dev/design_issues/ITL-1295-FN3.md | 21 +- .../scripts/itl_1295/compare_sort_fallback.py | 288 +++++++++++++++ src/orcapod/core/operators/arrow_keys.py | 62 +++- src/orcapod/utils/arrow_utils.py | 57 ++- tests/test_core/alignment/checker.py | 26 +- .../streams/test_sort_by_tags_values.py | 341 ++++++++++++++++++ .../test_function_node_stored_values.py | 11 +- 11 files changed, 795 insertions(+), 40 deletions(-) create mode 100644 docs/dev/scripts/itl_1295/compare_sort_fallback.py create mode 100644 tests/test_core/streams/test_sort_by_tags_values.py diff --git a/.zed/rules b/.zed/rules index ca8eb579e..8bd5351c9 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1336,6 +1336,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(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 9f686af4d..b37e71f4f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1383,6 +1383,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(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..9474a3576 100644 --- a/changelog.d/ITL-1295.md +++ b/changelog.d/ITL-1295.md @@ -10,3 +10,10 @@ `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(sort_by_tags=True)`, `head().sort_by_tags()` and the notebook + preview 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. 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..6eca242a2 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -112,6 +112,12 @@ 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, then by the record +ids. 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 diff --git a/docs/dev/design_issues/ITL-1295-FN3.md b/docs/dev/design_issues/ITL-1295-FN3.md index f3b587107..e144bd054 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(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..109d4db8c --- /dev/null +++ b/docs/dev/scripts/itl_1295/compare_sort_fallback.py @@ -0,0 +1,288 @@ +"""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 values; the order is not compared). +""" + +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 + ) + values_kept = all( + _bits(restored.column(k).combine_chunks()).equals( + _bits(table.column(k).combine_chunks()) + ) + for k in keys + ) + except (KeyboardInterrupt, SystemExit): + raise + except BaseException: + values_kept = False + if not values_kept: + return {"types": types, "result": "main wrong", "same order": old == new} + 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]] = [] + + +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())) + 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()), + "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/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 5c55ff76a..90701a44d 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1939,7 +1939,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 @@ -1961,14 +1963,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..b85ca88fd 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,23 +841,19 @@ 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: @@ -865,7 +861,7 @@ def assert_sorted_by_tags(table: pa.Table, tag_keys: Sequence[str]) -> None: The order of ``as_table(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..c62008f96 --- /dev/null +++ b/tests/test_core/streams/test_sort_by_tags_values.py @@ -0,0 +1,341 @@ +"""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(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 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 + +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]), + ) + + +KINDS = { + "large_list": _list_tag, + "struct": _struct_tag, + "large_list": _list_of_struct_tag, +} +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")] + + +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, ...]) -> ArrowTableSource: + return ArrowTableSource( + table, tag_columns=list(tag_order), tag_only_columns=True, 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("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 +) -> None: + table = _table(tag_name, tag_order) + result = READS[read](_source(table, tag_order)) + _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; reported with ITL-1295 part 2, 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") +def plus_one(x: str) -> str: + """Return ``x`` marked.""" + return x + "+" + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("tag_name", list(TAGS)) +def test_a_job_node_sorted_read_keeps_every_value( + tag_name: str, orchestrator: str +) -> None: + tag_order = ("s", "t", "n") + table = _table(tag_name, tag_order).select(["s", "t", "n", "x"]) + job = PipelineJob(name="sorted", database=InMemoryArrowDatabase()) + with job: + plus_one.pod(_source(table, tag_order), label="node") + job.run( + orchestrator=SyncPipelineOrchestrator() + if orchestrator == "sync" + else AsyncPipelineOrchestrator() + ) + order = _expected(table, 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 = table.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] + + +@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: From 10fb87a8d9609dffc83b01aa95a227b535dcc87c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 14:02:38 -0800 Subject: [PATCH 2/5] test(sort_by_tags): name ITL-1302 in the preview-panic expected failures Co-Authored-By: Claude Opus 5.5 --- tests/test_core/streams/test_sort_by_tags_values.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_core/streams/test_sort_by_tags_values.py b/tests/test_core/streams/test_sort_by_tags_values.py index c62008f96..fc84e0d58 100644 --- a/tests/test_core/streams/test_sort_by_tags_values.py +++ b/tests/test_core/streams/test_sort_by_tags_values.py @@ -215,7 +215,7 @@ def test_a_sorted_read_orders_list_and_struct_tags_and_keeps_every_value( strict=True, reason="The notebook preview renders its table through Polars " + "(StreamView._display_frame), which panics on a decimal256 column whatever the " - + "sort does; reported with ITL-1295 part 2, not this sort.", + + "sort does: ITL-1302, not this sort.", ) From 3c07fec80948b96f4d00f8e47a54e5a3bd00d25f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 14:51:45 -0800 Subject: [PATCH 3/5] docs, test(sort_by_tags): address review: valid as_table spelling, preview crash still open, tie order, roles and layouts (ITL-1295) - as_table(sort_by_tags=True) is not a valid call: write as_table(columns={"sort_by_tags": True}) everywhere. - Changelog: the sort is fixed; the preview still crashes on a decimal256 column it shows (ITL-1302). - streams.md: which reads break tag ties by system tags, and which keep the view's order. - Tests: data-tag and mixed roles; the job matrix has two data columns, three tag orders and two table layouts; a list-of-struct tag without a null element passes as a data-tag; with a null element it is a strict expected failure naming ITL-1144. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 2 +- CLAUDE.md | 2 +- changelog.d/ITL-1295.md | 7 +- docs/concepts/streams.md | 10 +- docs/dev/design_issues/ITL-1295-FN3.md | 2 +- .../dev/scripts/itl_1295/measure_read_path.py | 2 +- .../specs/itl-1271-order-invariance-audit.md | 2 +- .../core/streams/arrow_table_stream.py | 2 +- src/orcapod/utils/arrow_utils.py | 2 +- tests/test_core/alignment/checker.py | 2 +- .../streams/test_sort_by_tags_values.py | 116 +++++++++++++++--- 11 files changed, 118 insertions(+), 31 deletions(-) diff --git a/.zed/rules b/.zed/rules index 8bd5351c9..ac75afd33 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1336,7 +1336,7 @@ 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(sort_by_tags=True)`, +- 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 diff --git a/CLAUDE.md b/CLAUDE.md index b37e71f4f..c6d6d16c3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1383,7 +1383,7 @@ 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(sort_by_tags=True)`, +- 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 diff --git a/changelog.d/ITL-1295.md b/changelog.d/ITL-1295.md index 9474a3576..9b1eda10a 100644 --- a/changelog.d/ITL-1295.md +++ b/changelog.d/ITL-1295.md @@ -11,9 +11,10 @@ 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(sort_by_tags=True)`, `head().sort_by_tags()` and the notebook - preview sorted the whole table with Polars, so a `date64` value showed at midnight and a + 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. A null inside a list or a struct now sorts after the values beside it, + 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 6eca242a2..0e0eba670 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -112,8 +112,12 @@ 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, then by the record -ids. A null goes last, and so does a null inside a list or a struct: a list tag is ordered +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. @@ -243,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 e144bd054..a7b37eaf0 100644 --- a/docs/dev/design_issues/ITL-1295-FN3.md +++ b/docs/dev/design_issues/ITL-1295-FN3.md @@ -30,7 +30,7 @@ compares two checkouts). No hash, entry id, stored path or column moves. Tests: `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(sort_by_tags=True)`, `head().sort_by_tags()`, the notebook preview) fell back to +`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 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-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/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 3b5e5eae3..4df52cad8 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -225,7 +225,7 @@ def _identity_table(self) -> "pa.Table": THIS ORDER IS A HASH INPUT AND MUST NOT CHANGE: it is the ordering that every stream's content hash has been built from since before ITL-1053. It is kept apart from ``as_table``'s sort on purpose; the sort in the body is the code - ``as_table(sort_by_tags=True)`` had on origin/main, unchanged: the tags and + ``as_table(columns={"sort_by_tags": True})`` had on origin/main, unchanged: the tags and system tags in this stream's own priority, a type Arrow cannot order leaving the rows in stream order, and a stream with nothing to sort by raising. """ diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 90701a44d..fa6a2ec09 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1929,7 +1929,7 @@ def with_content_hash_column( 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 + 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 keeps its own ordering (``ArrowTableStream._identity_table``). diff --git a/tests/test_core/alignment/checker.py b/tests/test_core/alignment/checker.py index b85ca88fd..cf1e5bda6 100644 --- a/tests/test_core/alignment/checker.py +++ b/tests/test_core/alignment/checker.py @@ -859,7 +859,7 @@ def _null_last(value: Any) -> tuple[Any, ...]: 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 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 diff --git a/tests/test_core/streams/test_sort_by_tags_values.py b/tests/test_core/streams/test_sort_by_tags_values.py index fc84e0d58..7ed0ab868 100644 --- a/tests/test_core/streams/test_sort_by_tags_values.py +++ b/tests/test_core/streams/test_sort_by_tags_values.py @@ -1,7 +1,7 @@ """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(sort_by_tags=True)``, ``head().sort_by_tags()``, +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, @@ -13,8 +13,9 @@ 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 three data columns (``x``, the row's -name; ``d: date64`` off midnight; ``e: decimal256``). +``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 @@ -31,6 +32,7 @@ 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 @@ -101,10 +103,32 @@ def _list_of_struct_tag(make: Any, values: list[Any]) -> "pa.Array[Any]": ) +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) @@ -112,6 +136,10 @@ def _list_of_struct_tag(make: Any, values: list[Any]) -> "pa.Array[Any]": 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]: @@ -176,9 +204,21 @@ def _expected(table: pa.Table, tag_order: tuple[str, ...]) -> list[int]: ) -def _source(table: pa.Table, tag_order: tuple[str, ...]) -> ArrowTableSource: +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=True, source_id="sorted" + table, + tag_columns=list(tag_order), + tag_only_columns=tag_only, + source_id="sorted", ) @@ -197,14 +237,15 @@ def _assert_rows(result: pa.Table, table: pa.Table, order: list[int]) -> None: } +@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 + 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)) + result = READS[read](_source(table, tag_order, role)) _assert_rows(result, table, _expected(table, tag_order)) @@ -284,36 +325,77 @@ def test_nulls_inside_a_list_order_last() -> None: ] -@function_pod(output_keys="y") -def plus_one(x: str) -> str: - """Return ``x`` marked.""" - return x + "+" +@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, orchestrator: str + tag_name: str, + tag_order: tuple[str, ...], + role: str, + layout: str, + orchestrator: str, + request: pytest.FixtureRequest, ) -> None: - tag_order = ("s", "t", "n") - table = _table(tag_name, tag_order).select(["s", "t", "n", "x"]) + """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", + ) + ) + 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: - plus_one.pod(_source(table, tag_order), label="node") + marked.pod(_source(table, tag_order, role), label="node") job.run( orchestrator=SyncPipelineOrchestrator() if orchestrator == "sync" else AsyncPipelineOrchestrator() ) - order = _expected(table, tag_order) + 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 = table.column(name).combine_chunks().take(pa.array(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( From 8fd075957d20bfc682749d86d1f8e4090c4b3480 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 17:55:12 -0800 Subject: [PATCH 4/5] docs(dev): the sort-fallback measurement compares every column, not only the keys (ITL-1295) Co-Authored-By: Claude Opus 5.5 --- .../scripts/itl_1295/compare_sort_fallback.py | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/docs/dev/scripts/itl_1295/compare_sort_fallback.py b/docs/dev/scripts/itl_1295/compare_sort_fallback.py index b1d445076..c5aeda2bd 100644 --- a/docs/dev/scripts/itl_1295/compare_sort_fallback.py +++ b/docs/dev/scripts/itl_1295/compare_sort_fallback.py @@ -17,7 +17,12 @@ 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 values; the order is not compared). +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 @@ -110,18 +115,27 @@ def compare(table: pa.Table, keys: list[str], new: list[Any]) -> dict[str, Any]: restored = arrow_utils.restore_schema_nullability( pl.DataFrame(table).to_arrow(), table.schema ) - values_kept = all( - _bits(restored.column(k).combine_chunks()).equals( - _bits(table.column(k).combine_chunks()) + # 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()) ) - for k in keys - ) + ] except (KeyboardInterrupt, SystemExit): raise except BaseException: - values_kept = False - if not values_kept: - return {"types": types, "result": "main wrong", "same order": old == new} + 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() @@ -146,6 +160,11 @@ def compare(table: pa.Table, keys: list[str], new: list[Any]) -> dict[str, Any]: # ── 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: @@ -153,7 +172,9 @@ def pytest_configure(config: Any) -> None: def wrapped(table: pa.Table, keys: list[str]) -> Any: new = original(table, keys) - _CALLS.append(compare(table, keys, new.to_pylist())) + _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] From 9a0003373aff9a94b7e9b31b8db592c76f87f057 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 17:58:54 -0800 Subject: [PATCH 5/5] docs(dev): no backslash escapes in the measurement script's docstring (ITL-1295) Co-Authored-By: Claude Opus 5.5 --- docs/dev/scripts/itl_1295/compare_sort_fallback.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/scripts/itl_1295/compare_sort_fallback.py b/docs/dev/scripts/itl_1295/compare_sort_fallback.py index c5aeda2bd..9aeca4bbc 100644 --- a/docs/dev/scripts/itl_1295/compare_sort_fallback.py +++ b/docs/dev/scripts/itl_1295/compare_sort_fallback.py @@ -22,7 +22,7 @@ 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). +``grep -rlE "sort_by_tags|[.]head[(]|_repr_html_|preview" tests`` (``test_*.py`` files). """ from __future__ import annotations