From ab21bea894f5282e76cb395255336d95f2534990 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 22:05:57 -0800 Subject: [PATCH 01/18] fix(logical_types): order a set of a scalar-stored logical type canonically (ITL-922) Struct-stored elements (user classes) keep their repr order, pending the developer's decision in ITL-922. Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-922.md | 9 + .../list_logical_type_factory.py | 44 +- .../test_set_of_logical_elements.py | 436 ++++++++++++++++++ 3 files changed, 470 insertions(+), 19 deletions(-) create mode 100644 changelog.d/ITL-922.md create mode 100644 tests/test_logical_types/test_set_of_logical_elements.py diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md new file mode 100644 index 000000000..f7d620345 --- /dev/null +++ b/changelog.d/ITL-922.md @@ -0,0 +1,9 @@ +### Fixed + +- A `set[T]` of a logical type whose storage value is a scalar (text, bytes, a number) is + stored in the same canonical order as a set of a plain type (ITL-922). A NaN, two + elements with one storage value and elements that cannot be ordered are refused with + `CanonicalOrderError`; before, a set of a user-registered logical type stored as a float + and holding a NaN was stored, and hashed, in iteration order. The stored order of sets of + `Path`, `UPath`, `UUID`, `File` and `Directory` is unchanged. A set of a user class (stored + as a struct) is left as it was. diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index accb1f88a..336000797 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -113,7 +113,7 @@ class ListLogicalType(BaseLogicalType): Python type and Arrow extension type are derived, or an ``ArrowElement`` for a set of a plain Arrow type. is_set: If ``True``, uses ``set[T]`` semantics (``storage_to_python`` returns a - ``set``; ``python_to_storage`` sorts storage values for determinism). Defaults to + ``set``; ``python_to_storage`` stores the elements in canonical order). Defaults to ``False`` (``list[T]`` semantics). Attributes: @@ -342,11 +342,15 @@ def python_to_storage( Delegates per-element conversion to ``converter.python_to_storage`` using the element Python type. If ``value`` is ``None``, returns an empty list. - For ``set[T]`` (``is_set=True``), the resulting list is sorted to guarantee - deterministic storage order regardless of Python set iteration order. For a - logical element sorting is attempted naturally; if elements are not comparable - (``TypeError``), falls back to ``repr``-based ordering. A plain Arrow element is - put in the canonical order of ``canonical_order.sort_set_elements``. + For ``set[T]`` (``is_set=True``), the storage values are put in the canonical + order of ``canonical_order.sort_set_elements``, whatever order the set iterates + in: for a plain Arrow element and for a logical element alike (ITL-922). A NaN, + two elements with one storage value and elements that cannot be ordered are + refused. + + The one exception, pending the developer's decision in ITL-922: a logical + element stored as a struct (a user class) has no canonical order yet, so its + set keeps the order it had, by the ``repr`` of the storage values. Args: value: A Python list (or set) of elements of type ``element_python_type``, @@ -358,8 +362,9 @@ def python_to_storage( For set semantics the list is sorted. Raises: - CanonicalOrderError: For a set of a plain Arrow type holding a NaN, elements - that cannot be ordered, or two elements with one storage value. + CanonicalOrderError: For a set holding a NaN, elements that cannot be + ordered, or two elements with one storage value (not for a set of a + struct-stored element, see above). """ if value is None: return [] @@ -371,17 +376,18 @@ def python_to_storage( for item in value ] if self._is_set: - if self._element_logical_type is None: - # A set of a plain Arrow type keeps the canonical order a plain set - # had before it was a native container (ITL-905), so the stored - # elements are unchanged (ITL-611). - from orcapod.semantic_types.canonical_order import sort_set_elements - - return sort_set_elements(elements) - try: - elements = sorted(elements) - except TypeError: - elements = sorted(elements, key=repr) + if pa.types.is_struct(self._storage_type.value_type): + # TODO(ITL-922): pending the developer's decision. A struct (a user + # class's storage) has no canonical order yet, so a set of one keeps + # the order it always had: by the ``repr`` of the storage values. A + # change here moves the stored order, so the row hash, of such sets. + return sorted(elements, key=repr) + # One canonical order for every other set (ITL-905, ITL-611, ITL-922): it + # refuses a NaN, a repeated storage value and values with no order, and + # never falls back to another order. + from orcapod.semantic_types.canonical_order import sort_set_elements + + return sort_set_elements(elements) return elements def storage_to_python( diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py new file mode 100644 index 000000000..fa2cd0454 --- /dev/null +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -0,0 +1,436 @@ +"""The stored order of a ``set[T]`` whose element ``T`` is a logical type (ITL-922). + +A set has no order, so the order it is stored in, and with it the row hash, must come +from its elements' values alone. A set of a logical type whose storage value is a scalar +(text, bytes, a number) is put in the canonical order of +``canonical_order.sort_set_elements``, as a set of a plain Arrow type is: a NaN, two +elements with one storage value and elements that cannot be ordered are refused. + +A set of a logical type stored as a struct (a user class: a dataclass, a structural +class, a pydantic model) is left as it was, ordered by the ``repr`` of the storage +values, pending the developer's decision in ITL-922. The tests at the end pin that order, +so a later change of it is visible. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import uuid +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +import polars as pl +import pyarrow as pa +import pydantic +import pytest +from typing_extensions import override +from upath import UPath + +import orcapod as op +from orcapod.contexts import create_registry, get_default_context +from orcapod.errors import CanonicalOrderError, RowFailuresWarning +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.identifier import version_metadata +from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, +) +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.sources import DictSource + +# ── user-registered logical types ──────────────────────────────────────────── + + +class Reading(float): + """A value of a user-registered logical type stored as a float.""" + + +class LogicalReading(BaseLogicalType): + """A user-registered logical type whose storage is ``double``.""" + + logical_type_name: str = "example.itl922.reading" + python_type: type[Reading] = Reading + _arrow_ext_class = make_arrow_extension_type( + "example.itl922.reading", pa.float64(), version_metadata(1) + ) + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + """Return the reading extension type.""" + return self._arrow_ext_class() + + def get_polars_extension_type(self) -> pl.BaseExtension: + """Return the equivalent Polars type.""" + polars_type = cast( + "Callable[[], pl.BaseExtension]", + make_polars_extension_type( + self.logical_type_name, pa.float64(), version_metadata(1).decode() + ), + ) + return polars_type() + + def python_to_storage( + self, value: Reading, converter: TypeConverterProtocol | None = None + ) -> float: + """Store the reading as a plain float.""" + return float(value) + + def storage_to_python( + self, storage_value: float, converter: TypeConverterProtocol | None = None + ) -> Reading: + """Rebuild a reading from its float.""" + return Reading(storage_value) + + +@dataclasses.dataclass(frozen=True) +class Word: + """A word that is told apart by its spelling but stored in lower case.""" + + text: str + + +class LogicalWord(BaseLogicalType): + """A user-registered logical type that stores two different values as one.""" + + logical_type_name: str = "example.itl922.word" + python_type: type[Word] = Word + _arrow_ext_class = make_arrow_extension_type( + "example.itl922.word", pa.large_string(), version_metadata(1) + ) + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + """Return the word extension type.""" + return self._arrow_ext_class() + + def get_polars_extension_type(self) -> pl.BaseExtension: + """Return the equivalent Polars type.""" + polars_type = cast( + "Callable[[], pl.BaseExtension]", + make_polars_extension_type( + self.logical_type_name, pa.large_string(), version_metadata(1).decode() + ), + ) + return polars_type() + + def python_to_storage( + self, value: Word, converter: TypeConverterProtocol | None = None + ) -> str: + """Store the word in lower case.""" + return value.text.lower() + + def storage_to_python( + self, storage_value: str, converter: TypeConverterProtocol | None = None + ) -> Word: + """Rebuild a word from its stored text.""" + return Word(storage_value) + + +@pytest.fixture +def registered_types(monkeypatch: pytest.MonkeyPatch) -> None: + """Register the two user logical types with an isolated converter.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(LogicalReading()) + converter.register_logical_type(LogicalWord()) + monkeypatch.setattr(get_default_context(), "type_converter", converter) + + +# ── sources with several tag and data columns, in two arrangements ─────────── + +ARRANGEMENTS = ("tags_first", "data_first_reversed") +"""Two layouts of one row: ``site, day, s, n`` and ``n, s, day, site``.""" + + +def _source( + sets: list[set[Any]], element: Any, arrangement: str = "tags_first" +) -> DictSource: + """Return a source of one row per set, with two tag and two data columns. + + Args: + sets: The value of the set column ``s`` of each row. + element: The element type of the set column. + arrangement: One of ``ARRANGEMENTS``: the order of the row's columns and of + the declared tag columns. + + Returns: + The source; its data columns are ``s`` (the set) and ``n`` (an integer). + """ + schema: dict[str, Any] = {"site": str, "day": int, "s": set[element], "n": int} + tags = ["site", "day"] + names = list(schema) + if arrangement == "data_first_reversed": + names.reverse() + tags.reverse() + rows = [ + {"site": f"site{i}", "day": i, "s": value, "n": 10 * i} + for i, value in enumerate(sets) + ] + return DictSource( + data=[{name: row[name] for name in names} for row in rows], + tag_columns=tags, + tag_only_columns=True, + data_schema={name: schema[name] for name in names}, + source_id="itl922", + ) + + +def _stored(source: DictSource) -> dict[str, list[Any]]: + """Return the stored elements of the set column ``s``, by the ``site`` tag.""" + table = source.as_table() + column = table.column("s").combine_chunks() + if isinstance(column, pa.ExtensionArray): + column = column.storage + return dict(zip(table.column("site").to_pylist(), column.to_pylist())) + + +def _row_hashes(source: DictSource) -> dict[str, str]: + """Return each row's data content hash, by the ``site`` tag.""" + return { + cast(str, tag["site"]): data.content_hash().to_string() + for tag, data in source.iter_data() + } + + +# ── a float-stored logical type (the fault of ITL-922) ─────────────────────── + + +@pytest.mark.usefixtures("registered_types") +class TestSetOfFloatStoredLogicalType: + """A set of a logical type stored as a float is in canonical order or refused.""" + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_nan_element_is_refused(self, arrangement: str) -> None: + """A NaN has no order: the set is refused, never stored in iteration order.""" + with pytest.raises(CanonicalOrderError, match="NaN"): + _source( + [{Reading(1.0)}, {Reading("nan"), Reading(1.0), Reading(-2.0)}], + Reading, + arrangement, + ).as_table() + + def test_a_nan_alone_is_refused(self) -> None: + """A one-element set holding a NaN is refused too.""" + with pytest.raises(CanonicalOrderError, match="NaN"): + _source([{Reading("nan")}], Reading).as_table() + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_elements_are_stored_in_numeric_order(self, arrangement: str) -> None: + """The stored order is numeric, whatever order the elements were given in.""" + values = [2.0, -1.5, 10.0, 0.5] + forward = {Reading(v) for v in values} + backward = {Reading(v) for v in reversed(values)} + stored = _stored(_source([forward, backward], Reading, arrangement)) + assert stored == { + "site0": [-1.5, 0.5, 2.0, 10.0], + "site1": [-1.5, 0.5, 2.0, 10.0], + } + + def test_arrangement_changes_no_row_hash(self) -> None: + """The two arrangements of the columns give the same row hashes.""" + sets = [{Reading(2.0), Reading(-1.5)}, {Reading(10.0), Reading(0.5)}] + first, second = (_row_hashes(_source(sets, Reading, a)) for a in ARRANGEMENTS) + assert first == second + assert first["site0"] != first["site1"] + + def test_set_is_read_back_as_given(self) -> None: + """The set a row gives back holds the elements it was given.""" + source = _source([{Reading(2.0), Reading(-1.5)}], Reading) + _, data = next(iter(source.iter_data())) + value = data.as_dict()["s"] + assert value == {Reading(2.0), Reading(-1.5)} + assert all(isinstance(element, Reading) for element in cast(set[Any], value)) + + +@pytest.mark.usefixtures("registered_types") +class TestSetOfTextStoredLogicalType: + """A set of a user-registered logical type stored as text.""" + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_two_elements_with_one_storage_value_are_refused( + self, arrangement: str + ) -> None: + """Two different elements stored as one value would be stored twice.""" + with pytest.raises(CanonicalOrderError, match="duplicate"): + _source( + [{Word("b")}, {Word("A"), Word("a"), Word("c")}], Word, arrangement + ).as_table() + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_elements_are_stored_in_code_point_order(self, arrangement: str) -> None: + """Text storage values are ordered by code point.""" + stored = _stored( + _source( + [{Word("b"), Word("é"), Word("a"), Word("z")}, {Word("c")}], + Word, + arrangement, + ) + ) + assert stored == {"site0": ["a", "b", "z", "é"], "site1": ["c"]} + + +# ── a function that returns such a set, sync and async ─────────────────────── + + +def spread(low: float, high: float) -> tuple[set[Reading], int]: + """Return the readings of one row; one is a NaN when ``high`` is.""" + return {Reading(high), Reading(low), Reading((low + high) / 2)}, 3 + + +def _inputs(rows: list[tuple[float, float]], arrangement: str) -> DictSource: + """Return the input of ``spread``: two tags and the two parameters.""" + names = ["site", "day", "low", "high"] + tags = ["site", "day"] + if arrangement == "data_first_reversed": + names.reverse() + tags.reverse() + full = [ + {"site": f"site{i}", "day": i, "low": low, "high": high} + for i, (low, high) in enumerate(rows) + ] + return DictSource( + data=[{name: row[name] for name in names} for row in full], + tag_columns=tags, + tag_only_columns=True, + source_id="itl922_inputs", + ) + + +def _run(job: op.PipelineJob, mode: str) -> None: + """Run the job on the sync or the async path.""" + if mode == "sync": + job.run() + else: + asyncio.run(job.run_async()) + + +def _job(rows: list[tuple[float, float]], arrangement: str) -> op.PipelineJob: + """Return a job applying ``spread`` to the rows.""" + job = op.PipelineJob(name="itl922", database=op.databases.InMemoryArrowDatabase()) + # The pod is built here, after the fixture registered the element's logical type. + pod = op.function_pod(output_keys=("readings", "count"))(spread).pod + with job: + pod(_inputs(rows, arrangement), label="spread") + return job + + +@pytest.mark.usefixtures("registered_types") +@pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) +class TestFunctionReturningASet: + """A function output ``set[Reading]`` follows the same rule on both paths.""" + + def test_returned_set_is_stored_in_numeric_order( + self, mode: str, arrangement: str + ) -> None: + """The stored output is in numeric order on the sync and the async path.""" + job = _job([(4.0, -2.0), (0.0, 8.0)], arrangement) + _run(job, mode) + table = job.nodes["spread"].as_table() + column = table.column("readings").combine_chunks() + assert isinstance(column, pa.ExtensionArray) + stored = dict(zip(table.column("site").to_pylist(), column.storage.to_pylist())) + assert stored == {"site0": [-2.0, 1.0, 4.0], "site1": [0.0, 4.0, 8.0]} + assert sorted(table.column("count").to_pylist()) == [3, 3] + + def test_returned_nan_is_refused(self, mode: str, arrangement: str) -> None: + """A returned set holding a NaN fails its row; the other row is stored.""" + job = _job([(4.0, -2.0), (0.0, float("nan"))], arrangement) + with pytest.warns(RowFailuresWarning, match="CanonicalOrderError"): + _run(job, mode) + table = job.nodes["spread"].as_table() + assert table.column("site").to_pylist() == ["site0"] + column = table.column("readings").combine_chunks() + assert isinstance(column, pa.ExtensionArray) + assert column.storage.to_pylist() == [[-2.0, 1.0, 4.0]] + + +# ── built-in scalar-stored logical types: the stored order is unchanged ────── + + +class TestBuiltInScalarStoredElements: + """The stored order of a set of a built-in logical type is as it was (ITL-922).""" + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_path_elements(self, arrangement: str) -> None: + """Paths are stored as text, in code point order.""" + paths = {Path("/b"), Path("/a/z"), Path("/é"), Path("/B"), Path("/a")} + stored = _stored(_source([paths, {Path("/x")}], Path, arrangement)) + assert stored == {"site0": ["/B", "/a", "/a/z", "/b", "/é"], "site1": ["/x"]} + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_upath_elements(self, arrangement: str) -> None: + """Universal paths are stored as text, in code point order.""" + paths = {UPath("s3://b/x"), UPath("s3://a/y"), UPath("/local")} + stored = _stored(_source([paths], UPath, arrangement)) + assert stored == {"site0": ["/local", "s3://a/y", "s3://b/x"]} + + @pytest.mark.parametrize("arrangement", ARRANGEMENTS) + def test_uuid_elements(self, arrangement: str) -> None: + """UUIDs are stored as their 16 bytes, in unsigned byte order.""" + numbers = [2**127, 5, 2**64, 255, 256] + ids = {uuid.UUID(int=n) for n in numbers} + stored = _stored(_source([ids], uuid.UUID, arrangement)) + assert stored == {"site0": [uuid.UUID(int=n).bytes for n in sorted(numbers)]} + + def test_file_and_directory_elements(self, tmp_path: Path) -> None: + """Files and directories are stored in the natural order of their storage.""" + for name in ("b.txt", "a.txt", "c.txt"): + (tmp_path / name).write_text(name) + for name in ("y", "x"): + (tmp_path / name).mkdir() + (tmp_path / name / "f").write_text(name) + files = {op.File(tmp_path / name) for name in ("b.txt", "a.txt", "c.txt")} + stored_files = _stored(_source([files], op.File))["site0"] + assert len(stored_files) == 3 + assert stored_files == sorted(stored_files) + directories = {op.Directory(tmp_path / name) for name in ("y", "x")} + stored_directories = _stored(_source([directories], op.Directory))["site0"] + assert len(stored_directories) == 2 + assert stored_directories == sorted(stored_directories) + + +# ── struct-stored elements (user classes): today's order, pinned ───────────── +# +# Pending the developer's decision in ITL-922. A user class is stored as a struct, which +# has no canonical order yet, so its sets keep the order they had: by the ``repr`` of the +# storage values (text order: 10 before 2). These tests pin that order so that a change +# of it, which moves the row hash of every such set, is visible. + + +@dataclasses.dataclass(frozen=True) +class ExactPoint: + """An exact user class.""" + + a: int + b: str + + +@op.dataclass(name="itl922.StructuralPoint", frozen=True) +class StructuralPoint: + """A structural user class.""" + + a: int + b: str + + +class ModelPoint(pydantic.BaseModel): + """A pydantic user class.""" + + model_config = pydantic.ConfigDict(frozen=True) + + a: int + b: str + + +@pytest.mark.parametrize("point", [ExactPoint, StructuralPoint, ModelPoint]) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) +def test_user_class_elements_keep_their_order(point: Any, arrangement: str) -> None: + """A set of a user class is stored in the ``repr`` order of its structs (ITL-922).""" + points = [point(a=2, b="a"), point(a=1, b="b"), point(a=10, b="c")] + stored = _stored(_source([set(points), set(reversed(points))], point, arrangement)) + expected = [{"a": 1, "b": "b"}, {"a": 10, "b": "c"}, {"a": 2, "b": "a"}] + assert stored == {"site0": expected, "site1": expected} From faa29d96f965626d9fdc88e87e7b7d270af84d4c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:20:17 -0800 Subject: [PATCH 02/18] fix(logical_types)!: canonically order stored sets of user-class values (ITL-922) --- .zed/rules | 4 + CLAUDE.md | 4 + changelog.d/ITL-922.md | 18 +- docs/concepts/your-own-data-types.md | 6 + docs/dev/design_issues/ITL-922-DO2.md | 19 ++ docs/reference/hashing.md | 20 +- src/orcapod/core/data_function.py | 5 + .../list_logical_type_factory.py | 25 +-- src/orcapod/semantic_types/canonical_order.py | 83 +++++++- .../test_set_of_logical_elements.py | 181 ++++++++++++++++-- 10 files changed, 305 insertions(+), 60 deletions(-) create mode 100644 docs/dev/design_issues/ITL-922-DO2.md diff --git a/.zed/rules b/.zed/rules index 47691fb2e..0772ab812 100644 --- a/.zed/rules +++ b/.zed/rules @@ -385,6 +385,10 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. +- Native sets use `canonical_order.sort_set_elements` on converted storage values + (ITL-922). Compare structs by declared field order and lists by item order, + recursively. Class comparators have no effect. A NaN at any depth, duplicate storage + values or incomparable values raise `CanonicalOrderError`. The caller adds the column. - `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611): `ListLogicalType` over an `ArrowElement`, extension name `set[]` (`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer, diff --git a/CLAUDE.md b/CLAUDE.md index 29205c0e3..e90f98e1c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -396,6 +396,10 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. +- Native sets use `canonical_order.sort_set_elements` on converted storage values + (ITL-922). Compare structs by declared field order and lists by item order, + recursively. Class comparators have no effect. A NaN at any depth, duplicate storage + values or incomparable values raise `CanonicalOrderError`. The caller adds the column. - `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611): `ListLogicalType` over an `ArrowElement`, extension name `set[]` (`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer, diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index f7d620345..1a64aa9c8 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -1,9 +1,13 @@ +### Breaking changes and migration + +- Rebuilding rows with a `set[T]` of user-class values can change their hashes + (ITL-922). The elements now sort by their stored fields in declared order. + For example, a numeric field with `2` sorts before `10`. Orcapod recomputes + cached results whose input hashes change when the data is rebuilt. + ### Fixed -- A `set[T]` of a logical type whose storage value is a scalar (text, bytes, a number) is - stored in the same canonical order as a set of a plain type (ITL-922). A NaN, two - elements with one storage value and elements that cannot be ordered are refused with - `CanonicalOrderError`; before, a set of a user-registered logical type stored as a float - and holding a NaN was stored, and hashed, in iteration order. The stored order of sets of - `Path`, `UPath`, `UUID`, `File` and `Directory` is unchanged. A set of a user class (stored - as a struct) is left as it was. +- Sets of logical types use canonical storage order for both scalar and struct + storage (ITL-922). The sort descends into nested structs and lists, with + `None` first. A NaN at any depth, incomparable values, or two elements with + equal storage raise `CanonicalOrderError` naming the column. diff --git a/docs/concepts/your-own-data-types.md b/docs/concepts/your-own-data-types.md index 87f903309..7a6bb22de 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -45,6 +45,12 @@ can return. For example, a returned object with `None` in an `int` field raises values deliberately. Pydantic's own validation still applies whenever it constructs a model. +A `set[T]` of user-class instances is stored in declared field order. Orcapod compares +the stored field values, descending into nested classes and lists and placing `None` +first. A class's own comparison methods have no effect on storage order. Unorderable +values, NaNs anywhere in an element, and distinct elements that store the same fields +raise `CanonicalOrderError`. See [canonical set order](../reference/hashing.md#1e-dict-and-set-values-canonical-order). + ## `op.dataclass` in a notebook `op.dataclass` is used like `dataclasses.dataclass` and returns a real dataclass. Define diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md new file mode 100644 index 000000000..39c21a5df --- /dev/null +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -0,0 +1,19 @@ +## `src/orcapod/semantic_types/canonical_order.py` — dict and set values in canonical order + +### DO2 — Sets of logical elements used representation text as a fallback order +**Status:** resolved +**Severity:** medium +**Issue:** ITL-922 + +Struct storage fell back to representation-text order, which put a field with +`10` before `2`. NaNs and distinct instances with equal declared fields could +enter storage. A scalar-stored logical type could also admit NaNs and equal +storage values. + +**Fix:** Apply canonical order to converted storage values. Compare structs in +declared field order and lists in item order, recursing with the scalar rules +at each leaf. Build one sort key per element. The order is independent of any +class comparison method, so the same rule applies to classes rebuilt from +metadata. Reject NaNs at any depth, incomparable values and duplicate storage +values. The conversion boundary supplies the column name. Rebuilding sets of +user classes can change affected row hashes. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index bd752c850..143cfc4bf 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1012,14 +1012,19 @@ orders for equal hashed inputs; reconstructing user-class instances is outside t | `str` | Unicode code point, never locale | | `bytes` | unsigned bytewise | | `date`, `datetime`, `time`, `timedelta` | natural order; datetimes by instant (they are timezone aware after conversion) | +| Struct set element (such as a user class) | field by field in declared order | +| List inside a set element | item by item, with a shorter prefix first | -A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`) has no order +Struct fields and list items follow the same rules recursively, including `None` first. +The stored order depends only on the storage values and field declaration. Python class +comparators such as those generated by `@dataclass(order=True)` do not participate. + +A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`), +including a NaN anywhere inside a set element, has no order and raises `CanonicalOrderError` (a `ValueError`) naming the column, as do keys or elements -that cannot be compared and two keys or elements that convert to the same stored value -(decided November 12, 2026). A -dict or set whose nested unordered containers are all already in this order is stored -byte-for-byte as before this rule existed, -so its hash did not change. +that cannot be compared and two keys or elements that convert to the same stored value. +For user-class sets written with the old representation-text order, rebuilding the data +can change row hashes and cause affected cached results to be recomputed (ITL-922). **Signed zero.** In a table Orcapod builds, `-0.0` hashes as `0.0` wherever it appears: in a plain `float` column and as a dict key or set element alike, as Python compares them @@ -1045,8 +1050,7 @@ canonical JSON text (ITL-942); that order is never stored and never seen. The tw different on purpose (JSON text puts `10` before `2`; storage order is numeric) and neither is defined in terms of the other: changing the hasher's order would move semantic hashes of affected inputs, and changing storage order would move row hashes and what a pod reads back. -`set[T]` of a logical type (`set[Path]`, `set[UUID]`) is ordered by `ListLogicalType`, not -by this rule. +`ListLogicalType` applies the same storage rule to `set[T]` of a logical type. **The set's identity is part of the row hash** (ITL-611). A set of a primitive is stored under its native container type, and the Arrow hasher hashes an extension column's diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 7fd1200b0..1aa0e2bd3 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -29,6 +29,7 @@ ) from orcapod.core.result_cache import ResultCache from orcapod.errors import ( + CanonicalOrderError, NoOutputsDeclaredError, OutputContainerTypeError, OutputTypeError, @@ -1108,6 +1109,8 @@ def _convert_outputs( The one-row table, typed by the declared schema. Raises: + CanonicalOrderError: If an output's unordered container has no canonical + storage order. The converter names the column. OutputTypeError: If an output cannot be converted, for example an integer out of range for its declared width, a ``datetime`` without a time zone or one with a part below one microsecond; it names that output. @@ -1117,6 +1120,8 @@ def _convert_outputs( return converter.python_dicts_to_arrow_table( [output_data], python_schema=output_schema ) + except CanonicalOrderError: + raise except Exception as exc: # Find the output that fails on its own, so the error can name it. for key, value in output_data.items(): diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 336000797..d2abc8b21 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -344,13 +344,8 @@ def python_to_storage( For ``set[T]`` (``is_set=True``), the storage values are put in the canonical order of ``canonical_order.sort_set_elements``, whatever order the set iterates - in: for a plain Arrow element and for a logical element alike (ITL-922). A NaN, - two elements with one storage value and elements that cannot be ordered are - refused. - - The one exception, pending the developer's decision in ITL-922: a logical - element stored as a struct (a user class) has no canonical order yet, so its - set keeps the order it had, by the ``repr`` of the storage values. + in. Struct fields are compared in declared order and list items in sequence, + recursively (ITL-922). Args: value: A Python list (or set) of elements of type ``element_python_type``, @@ -362,9 +357,8 @@ def python_to_storage( For set semantics the list is sorted. Raises: - CanonicalOrderError: For a set holding a NaN, elements that cannot be - ordered, or two elements with one storage value (not for a set of a - struct-stored element, see above). + CanonicalOrderError: For a NaN at any depth, elements that cannot be + ordered, or two elements with one storage value. """ if value is None: return [] @@ -376,18 +370,9 @@ def python_to_storage( for item in value ] if self._is_set: - if pa.types.is_struct(self._storage_type.value_type): - # TODO(ITL-922): pending the developer's decision. A struct (a user - # class's storage) has no canonical order yet, so a set of one keeps - # the order it always had: by the ``repr`` of the storage values. A - # change here moves the stored order, so the row hash, of such sets. - return sorted(elements, key=repr) - # One canonical order for every other set (ITL-905, ITL-611, ITL-922): it - # refuses a NaN, a repeated storage value and values with no order, and - # never falls back to another order. from orcapod.semantic_types.canonical_order import sort_set_elements - return sort_set_elements(elements) + return sort_set_elements(elements, self._storage_type.value_type) return elements def storage_to_python( diff --git a/src/orcapod/semantic_types/canonical_order.py b/src/orcapod/semantic_types/canonical_order.py index 3ac9b7e0a..501a9aea3 100644 --- a/src/orcapod/semantic_types/canonical_order.py +++ b/src/orcapod/semantic_types/canonical_order.py @@ -17,6 +17,8 @@ ``0.0`` store different bytes and hash differently, like any float value. * ``str``: Unicode code point (never locale). ``bytes``: unsigned bytewise. * ``date``, ``datetime`` (by instant), ``time``, ``timedelta``: natural order. +* Structs in sets: lexicographically by the declared storage fields, in field order. +* Lists in sets: lexicographically by their items, with a proper prefix sorting first. Keys or elements that cannot be ordered against each other, and two keys or elements with the same storage value, raise ``CanonicalOrderError``. @@ -33,11 +35,13 @@ from itertools import pairwise from typing import Any, TypeVar, cast, get_args, get_origin +import pyarrow as pa + from orcapod.errors import CanonicalOrderError _T = TypeVar("_T") -# A sort key: ``(0,)`` for None, ``(1, value)`` otherwise. +# A sort key starts with 0 for None or 1 followed by the value or its child ranks. _Rank = tuple[Any, ...] @@ -55,11 +59,69 @@ def _key_rank(key: object) -> _Rank: return (1, key) +def _storage_ranker(storage_type: pa.DataType) -> Callable[[Any], _Rank]: + """Build the rank function for a set element's declared storage type.""" + if isinstance(storage_type, pa.StructType): + fields = tuple( + (field.name, _storage_ranker(field.type)) for field in storage_type + ) + + def rank_struct(value: Any) -> _Rank: + if value is None: + return (0,) + if isinstance(value, dict): + return (1, *(rank(value.get(name)) for name, rank in fields)) + if isinstance(value, tuple) and len(value) == len(fields): + return (1, *(rank(item) for (_, rank), item in zip(fields, value))) + raise CanonicalOrderError("expected a struct storage value") + + return rank_struct + if isinstance( + storage_type, + ( + pa.ListType, + pa.LargeListType, + pa.FixedSizeListType, + pa.ListViewType, + pa.LargeListViewType, + ), + ): + rank_item = _storage_ranker(storage_type.value_type) + + def rank_list(value: Any) -> _Rank: + if value is None: + return (0,) + if isinstance(value, (str, bytes, dict, set, frozenset)): + raise CanonicalOrderError("expected a list storage value") + try: + items = iter(value) + except TypeError as exc: + raise CanonicalOrderError("expected a list storage value") from exc + return (1, *(rank_item(item) for item in items)) + + return rank_list + if isinstance(storage_type, pa.ExtensionType): + return _storage_ranker(storage_type.storage_type) + if pa.types.is_nested(storage_type): + + def rank_unsupported(value: Any) -> _Rank: + if value is None: + return (0,) + raise CanonicalOrderError(f"storage type {storage_type} cannot be ordered") + + return rank_unsupported + return _key_rank + + def _is_nan(value: object) -> bool: """Return whether ``value`` is a NaN of any numeric type. Integers are never NaN and are not converted (a large ``int`` does not fit a float). """ + if isinstance(value, float): + return math.isnan(value) + if type(value) in (int, bool, str, bytes): + return False if isinstance(value, Decimal): return value.is_nan() if isinstance(value, numbers.Real) and not isinstance(value, numbers.Integral): @@ -74,12 +136,12 @@ def _sorted_by_rank(items: list[tuple[_Rank, _T]]) -> list[_T]: CanonicalOrderError: If two ranks cannot be compared or are equal. """ try: - items = sorted(items, key=lambda item: item[0]) + items.sort(key=lambda item: item[0]) + for (previous, _), (current, _) in pairwise(items): + if previous == current: + raise CanonicalOrderError("duplicate key or set element") except TypeError as exc: - raise CanonicalOrderError(f"values cannot be ordered: {exc}") from exc - for (previous, _), (current, payload) in pairwise(items): - if previous == current: - raise CanonicalOrderError(f"duplicate key or set element: {payload!r}") + raise CanonicalOrderError("values cannot be ordered") from exc return [payload for _, payload in items] @@ -99,11 +161,15 @@ def sort_dict_entries(entries: list[dict[str, _T]]) -> list[dict[str, _T]]: return _sorted_by_rank([(_key_rank(entry["key"]), entry) for entry in entries]) -def sort_set_elements(elements: list[_T]) -> list[_T]: +def sort_set_elements( + elements: list[_T], storage_type: pa.DataType | None = None +) -> list[_T]: """Return the storage elements of one set value in canonical order. Args: elements: The converted elements of a set. + storage_type: The declared Arrow element storage type, when available. + It supplies struct field order and list item types. Returns: A new list holding the same elements, sorted. @@ -112,7 +178,8 @@ def sort_set_elements(elements: list[_T]) -> list[_T]: CanonicalOrderError: For a NaN element, elements that cannot be ordered against each other, or two elements with the same storage value. """ - return _sorted_by_rank([(_key_rank(element), element) for element in elements]) + rank = _key_rank if storage_type is None else _storage_ranker(storage_type) + return _sorted_by_rank([(rank(element), element) for element in elements]) def canonical_python_value( diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index fa2cd0454..7ed92fd65 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -6,16 +6,18 @@ ``canonical_order.sort_set_elements``, as a set of a plain Arrow type is: a NaN, two elements with one storage value and elements that cannot be ordered are refused. -A set of a logical type stored as a struct (a user class: a dataclass, a structural -class, a pydantic model) is left as it was, ordered by the ``repr`` of the storage -values, pending the developer's decision in ITL-922. The tests at the end pin that order, -so a later change of it is visible. +Struct storage is compared by declared field order, recursively through lists and +nested structs. """ from __future__ import annotations import asyncio import dataclasses +import json +import os +import subprocess +import sys import uuid from collections.abc import Callable from pathlib import Path @@ -60,7 +62,7 @@ class LogicalReading(BaseLogicalType): @override def get_arrow_extension_type(self) -> pa.ExtensionType: """Return the reading extension type.""" - return self._arrow_ext_class() + return self._arrow_ext_class() # pyright: ignore[reportCallIssue] # factory fixes the extension name and storage type def get_polars_extension_type(self) -> pl.BaseExtension: """Return the equivalent Polars type.""" @@ -104,7 +106,7 @@ class LogicalWord(BaseLogicalType): @override def get_arrow_extension_type(self) -> pa.ExtensionType: """Return the word extension type.""" - return self._arrow_ext_class() + return self._arrow_ext_class() # pyright: ignore[reportCallIssue] # factory fixes the extension name and storage type def get_polars_extension_type(self) -> pl.BaseExtension: """Return the equivalent Polars type.""" @@ -184,7 +186,9 @@ def _stored(source: DictSource) -> dict[str, list[Any]]: column = table.column("s").combine_chunks() if isinstance(column, pa.ExtensionArray): column = column.storage - return dict(zip(table.column("site").to_pylist(), column.to_pylist())) + sites = cast(list[str], table.column("site").to_pylist()) + values = cast(list[list[Any]], column.to_pylist()) + return dict(zip(sites, values)) def _row_hashes(source: DictSource) -> dict[str, str]: @@ -393,12 +397,7 @@ def test_file_and_directory_elements(self, tmp_path: Path) -> None: assert stored_directories == sorted(stored_directories) -# ── struct-stored elements (user classes): today's order, pinned ───────────── -# -# Pending the developer's decision in ITL-922. A user class is stored as a struct, which -# has no canonical order yet, so its sets keep the order they had: by the ``repr`` of the -# storage values (text order: 10 before 2). These tests pin that order so that a change -# of it, which moves the row hash of every such set, is visible. +# ── struct-stored elements ────────────────────────────────────────────────── @dataclasses.dataclass(frozen=True) @@ -428,9 +427,157 @@ class ModelPoint(pydantic.BaseModel): @pytest.mark.parametrize("point", [ExactPoint, StructuralPoint, ModelPoint]) @pytest.mark.parametrize("arrangement", ARRANGEMENTS) -def test_user_class_elements_keep_their_order(point: Any, arrangement: str) -> None: - """A set of a user class is stored in the ``repr`` order of its structs (ITL-922).""" - points = [point(a=2, b="a"), point(a=1, b="b"), point(a=10, b="c")] +def test_user_class_elements_are_stored_in_field_order( + point: Any, arrangement: str +) -> None: + """A set of a user class is stored in numeric and then text order.""" + points = [ + point(a=2, b="z"), + point(a=-10, b="b"), + point(a=10, b="c"), + point(a=2, b="a"), + ] stored = _stored(_source([set(points), set(reversed(points))], point, arrangement)) - expected = [{"a": 1, "b": "b"}, {"a": 10, "b": "c"}, {"a": 2, "b": "a"}] + expected = [ + {"a": -10, "b": "b"}, + {"a": 2, "b": "a"}, + {"a": 2, "b": "z"}, + {"a": 10, "b": "c"}, + ] assert stored == {"site0": expected, "site1": expected} + + +@dataclasses.dataclass(frozen=True) +class PointSubclass(ExactPoint): + """A distinct value that stores only the base class's fields.""" + + extra: int + + +@dataclasses.dataclass(frozen=True) +class Measurement: + """A nested struct with an optional numeric field and a sequence.""" + + z: float | None + a: list[float | None] + + @override + def __hash__(self) -> int: + """Hash the sequence's items so a measurement can belong to a set.""" + return hash((self.z, tuple(self.a))) + + +@dataclasses.dataclass(frozen=True) +class Sample: + """A class whose fields are declared out of alphabetical order.""" + + z: Measurement + a: str + + def __lt__(self, other: Sample) -> bool: + """Fail if storage ever asks the user class to compare instances.""" + raise AssertionError("the user comparator must not run") + + +def _samples(*, integral_values: bool = True) -> set[Sample]: + """Return input values that exercise every level of the sort key.""" + whole = int if integral_values else float + return { + Sample(Measurement(whole(10), []), "a"), + Sample(Measurement(2.5, [whole(10)]), "a"), + Sample(Measurement(2.5, [whole(2)]), "z"), + Sample(Measurement(2.5, [whole(2)]), "b"), + Sample(Measurement(2.5, [None]), "z"), + Sample(Measurement(2.5, []), "z"), + Sample(Measurement(whole(-2), []), "z"), + Sample(Measurement(None, []), "z"), + } + + +_SAMPLE_STORAGE = [ + {"z": {"z": None, "a": []}, "a": "z"}, + {"z": {"z": -2.0, "a": []}, "a": "z"}, + {"z": {"z": 2.5, "a": []}, "a": "z"}, + {"z": {"z": 2.5, "a": [None]}, "a": "z"}, + {"z": {"z": 2.5, "a": [2.0]}, "a": "b"}, + {"z": {"z": 2.5, "a": [2.0]}, "a": "z"}, + {"z": {"z": 2.5, "a": [10.0]}, "a": "a"}, + {"z": {"z": 10.0, "a": []}, "a": "a"}, +] + + +def test_nested_structs_and_lists_sort_by_storage_value() -> None: + """Use declared field order, list order and scalar order, including nulls.""" + assert _stored(_source([_samples()], Sample)) == {"site0": _SAMPLE_STORAGE} + + +def test_subclass_with_equal_stored_fields_is_refused() -> None: + """The declared base's storage is identical for two distinct set elements.""" + points = {ExactPoint(2, "a"), PointSubclass(2, "a", 9)} + assert len(points) == 2 + with pytest.raises(CanonicalOrderError, match=r"Column 's': .*duplicate"): + _source([points], ExactPoint).as_table() + + +def test_incomparable_struct_field_values_are_refused() -> None: + """Report the column when corresponding storage fields cannot be compared.""" + points = {ExactPoint(2, "a"), ExactPoint(cast(Any, "2"), "a")} + with pytest.raises(CanonicalOrderError, match=r"Column 's': .*cannot be ordered"): + _source([points], ExactPoint).as_table() + + +def test_nan_in_nested_list_is_refused() -> None: + """A NaN deep in a single element is refused even when no comparison is needed.""" + values = {Sample(Measurement(1, [2, float("nan")]), "a")} + with pytest.raises(CanonicalOrderError, match=r"Column 's': .*NaN"): + _source([values], Sample).as_table() + + +def _produce_samples(low: float) -> set[Sample]: + """Produce the test set, or a set with a nested NaN for the failing row.""" + if low < 0: + return {Sample(Measurement(1.0, [low, float("nan")]), "a")} + return _samples(integral_values=False) + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +def test_function_returns_canonically_stored_structs(mode: str) -> None: + """Both paths store ordered structs and diagnose a nested NaN by column.""" + job = op.PipelineJob( + name="itl922_struct", database=op.databases.InMemoryArrowDatabase() + ) + pod = op.function_pod(output_keys="samples")(_produce_samples).pod + with job: + pod(_inputs([(0.0, 1.0), (-2.0, 1.0)], "tags_first"), label="produce") + with pytest.warns( + RowFailuresWarning, match=r"CanonicalOrderError.*Column 'samples': .*NaN" + ): + _run(job, mode) + table = job.nodes["produce"].as_table() + assert table.column("site").to_pylist() == ["site0"] + column = table.column("samples").combine_chunks() + assert isinstance(column, pa.ExtensionArray) + assert column.storage.to_pylist() == [_SAMPLE_STORAGE] + + +def test_struct_storage_order_and_hash_are_independent_of_hash_seed() -> None: + """Two interpreters serialize and hash the same class set identically.""" + script = """ +import json +from tests.test_logical_types.test_set_of_logical_elements import Sample, _row_hashes, _samples, _source, _stored + +source = _source([_samples()], Sample) +print(json.dumps([_stored(source), _row_hashes(source)])) +""" + results = [ + json.loads( + subprocess.check_output( + [sys.executable, "-c", script], + env={**os.environ, "PYTHONHASHSEED": seed}, + text=True, + ) + ) + for seed in ("1", "2") + ] + assert results[0] == results[1] + assert results[0][0] == {"site0": _SAMPLE_STORAGE} From 4b5f3758d99efdd74119c5ea5411c8f5a0584819 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:44:25 -0800 Subject: [PATCH 03/18] fix(logical_types): order logical sets after Arrow coercion --- .zed/rules | 10 +- CLAUDE.md | 10 +- changelog.d/ITL-922.md | 8 +- docs/dev/design_issues/ITL-922-DO2.md | 7 +- docs/reference/hashing.md | 10 +- src/orcapod/core/data_function.py | 6 +- src/orcapod/core/function_pod.py | 4 +- src/orcapod/errors.py | 4 + .../list_logical_type_factory.py | 42 ++- src/orcapod/semantic_types/canonical_order.py | 241 ++++++++++++------ .../semantic_types/precomputed_converters.py | 5 +- .../semantic_types/universal_converter.py | 6 +- src/orcapod/utils/arrow_utils.py | 62 +++++ .../function_pod/test_output_conformance.py | 21 ++ .../test_set_of_logical_elements.py | 231 ++++++++++++++++- 15 files changed, 551 insertions(+), 116 deletions(-) diff --git a/.zed/rules b/.zed/rules index 0772ab812..d70ed57d7 100644 --- a/.zed/rules +++ b/.zed/rules @@ -385,10 +385,12 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. -- Native sets use `canonical_order.sort_set_elements` on converted storage values - (ITL-922). Compare structs by declared field order and lists by item order, - recursively. Class comparators have no effect. A NaN at any depth, duplicate storage - values or incomparable values raise `CanonicalOrderError`. The caller adds the column. +- Sets of user-defined logical types use `canonical_order.ordered_set_storage` after + coercion to the declared Arrow type (ITL-922). Compare structs by declared field order + and lists by item order, recursively. Class comparators have no effect. A NaN at any + depth, duplicate storage values or incomparable values raise `CanonicalOrderError`. + The caller adds the column. Path, UPath, UUID, File and Directory sets keep their native + scalar sort. - `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611): `ListLogicalType` over an `ArrowElement`, extension name `set[]` (`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer, diff --git a/CLAUDE.md b/CLAUDE.md index e90f98e1c..2a0a8215c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -396,10 +396,12 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. -- Native sets use `canonical_order.sort_set_elements` on converted storage values - (ITL-922). Compare structs by declared field order and lists by item order, - recursively. Class comparators have no effect. A NaN at any depth, duplicate storage - values or incomparable values raise `CanonicalOrderError`. The caller adds the column. +- Sets of user-defined logical types use `canonical_order.ordered_set_storage` after + coercion to the declared Arrow type (ITL-922). Compare structs by declared field order + and lists by item order, recursively. Class comparators have no effect. A NaN at any + depth, duplicate storage values or incomparable values raise `CanonicalOrderError`. + The caller adds the column. Path, UPath, UUID, File and Directory sets keep their native + scalar sort. - `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611): `ListLogicalType` over an `ArrowElement`, extension name `set[]` (`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer, diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 1a64aa9c8..e8a609404 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -7,7 +7,7 @@ ### Fixed -- Sets of logical types use canonical storage order for both scalar and struct - storage (ITL-922). The sort descends into nested structs and lists, with - `None` first. A NaN at any depth, incomparable values, or two elements with - equal storage raise `CanonicalOrderError` naming the column. +- Sets of user-defined logical types are ordered after Arrow coerces each element + to the declared storage type (ITL-922). The sort descends into nested structs + and lists, with `None` first. A NaN at any depth, incomparable values, or two + elements with equal storage raise `CanonicalOrderError` naming the column. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 39c21a5df..0c2297025 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -10,9 +10,10 @@ Struct storage fell back to representation-text order, which put a field with enter storage. A scalar-stored logical type could also admit NaNs and equal storage values. -**Fix:** Apply canonical order to converted storage values. Compare structs in -declared field order and lists in item order, recursing with the scalar rules -at each leaf. Build one sort key per element. The order is independent of any +**Fix:** Apply canonical order after coercion to the declared Arrow element type. +Sort the struct fields in declared order and use a lexicographic key for each +list field. Check adjacent sorted values for duplicates. The five built-in +scalar-stored types keep their native sort. The order is independent of any class comparison method, so the same rule applies to classes rebuilt from metadata. Reject NaNs at any depth, incomparable values and duplicate storage values. The conversion boundary supplies the column name. Rebuilding sets of diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 143cfc4bf..d32f67e61 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1016,13 +1016,15 @@ orders for equal hashed inputs; reconstructing user-class instances is outside t | List inside a set element | item by item, with a shorter prefix first | Struct fields and list items follow the same rules recursively, including `None` first. -The stored order depends only on the storage values and field declaration. Python class -comparators such as those generated by `@dataclass(order=True)` do not participate. +For a set of user-defined logical values, Orcapod coerces each element to its declared Arrow +type before comparing it. Python class comparators such as those generated by +`@dataclass(order=True)` do not participate. A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`), including a NaN anywhere inside a set element, has no order -and raises `CanonicalOrderError` (a `ValueError`) naming the column, as do keys or elements -that cannot be compared and two keys or elements that convert to the same stored value. +and raises `CanonicalOrderError` (a `ValueError`) naming the column. Primitive containers +and sets of user-defined logical values also reject incomparable values and duplicate +storage keys. Sets of Path, UPath, UUID, File and Directory keep their native scalar sort. For user-class sets written with the old representation-text order, rebuilding the data can change row hashes and cause affected cached results to be recomputed (ITL-922). diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 1aa0e2bd3..d45d478ff 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -29,7 +29,7 @@ ) from orcapod.core.result_cache import ResultCache from orcapod.errors import ( - CanonicalOrderError, + LogicalSetCanonicalOrderError, NoOutputsDeclaredError, OutputContainerTypeError, OutputTypeError, @@ -1109,7 +1109,7 @@ def _convert_outputs( The one-row table, typed by the declared schema. Raises: - CanonicalOrderError: If an output's unordered container has no canonical + LogicalSetCanonicalOrderError: If an output's logical set has no canonical storage order. The converter names the column. OutputTypeError: If an output cannot be converted, for example an integer out of range for its declared width, a ``datetime`` without a time zone @@ -1120,7 +1120,7 @@ def _convert_outputs( return converter.python_dicts_to_arrow_table( [output_data], python_schema=output_schema ) - except CanonicalOrderError: + except LogicalSetCanonicalOrderError: raise except Exception as exc: # Find the output that fails on its own, so the error can name it. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 1d0f7d9ce..d0d063a81 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1576,9 +1576,7 @@ def _table_from_pairs( all_data, python_schema=python_schema ) all_tags_as_tables = arrow_utils.concat_tables_by_name(tag_tables) - all_data_as_tables: pa.Table = pa.Table.from_pylist( - struct_data, schema=data_schema - ) + all_data_as_tables = arrow_utils.table_from_storage(struct_data, data_schema) return arrow_utils.hstack_tables(all_tags_as_tables, all_data_as_tables) def as_table( diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index eda66139c..831cbe443 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -77,6 +77,10 @@ class CanonicalOrderError(ValueError): """ +class LogicalSetCanonicalOrderError(CanonicalOrderError): + """Raised when the Arrow storage of a logical set has no canonical order.""" + + class UnsupportedValueError(ValueError): """A value cannot be stored by the logical type of its column. diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index d2abc8b21..53e93292c 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -139,6 +139,18 @@ class ListLogicalType(BaseLogicalType): binds_python_type: bool = True + # These fixed encoders return sortable strings or bytes. Keep their native + # sort, including the existing behavior for aliases of the same stored value. + _NATIVE_SORT_TYPES = frozenset( + ( + "orcapod.path", + "orcapod.upath", + "orcapod.uuid", + "orcapod.file", + "orcapod.directory", + ) + ) + def __init__( self, element_logical_type: "LogicalTypeProtocol | ArrowElement", @@ -146,6 +158,10 @@ def __init__( is_set: bool = False, ) -> None: self._is_set = is_set + self._uses_native_sort = ( + not isinstance(element_logical_type, ArrowElement) + and element_logical_type.logical_type_name in self._NATIVE_SORT_TYPES + ) self._arrow_ext: pa.ExtensionType | None = None self._polars_ext: pl.BaseExtension | None = None @@ -336,16 +352,15 @@ def index_element(self) -> type: def python_to_storage( self, value: Any, converter: TypeConverterProtocol | None - ) -> list: + ) -> list | pa.Array[Any]: """Convert a Python list or set to its Arrow storage representation. Delegates per-element conversion to ``converter.python_to_storage`` using the element Python type. If ``value`` is ``None``, returns an empty list. - For ``set[T]`` (``is_set=True``), the storage values are put in the canonical - order of ``canonical_order.sort_set_elements``, whatever order the set iterates - in. Struct fields are compared in declared order and list items in sequence, - recursively (ITL-922). + A set of user-registered logical values is ordered after encoding into + Arrow storage. Struct fields are compared in declared order and list + items in sequence, recursively (ITL-922). Args: value: A Python list (or set) of elements of type ``element_python_type``, @@ -353,8 +368,8 @@ def python_to_storage( converter: The active ``TypeConverterProtocol`` for per-element delegation. Returns: - A plain Python list of storage values suitable for Arrow large_list storage. - For set semantics the list is sorted. + A Python list or Arrow array suitable for Arrow large_list storage. + For set semantics the elements are sorted. Raises: CanonicalOrderError: For a NaN at any depth, elements that cannot be @@ -369,11 +384,18 @@ def python_to_storage( converter.python_to_storage(item, self._element_python_type) for item in value ] - if self._is_set: + if not self._is_set: + return elements + if self._uses_native_sort: + return sorted(elements) + if self._element_logical_type is None: from orcapod.semantic_types.canonical_order import sort_set_elements - return sort_set_elements(elements, self._storage_type.value_type) - return elements + return sort_set_elements(elements) + + from orcapod.semantic_types.canonical_order import ordered_set_storage + + return ordered_set_storage(elements, self._storage_type.value_type) def storage_to_python( self, storage_value: Any, converter: TypeConverterProtocol | None diff --git a/src/orcapod/semantic_types/canonical_order.py b/src/orcapod/semantic_types/canonical_order.py index 501a9aea3..884405b61 100644 --- a/src/orcapod/semantic_types/canonical_order.py +++ b/src/orcapod/semantic_types/canonical_order.py @@ -32,16 +32,17 @@ import typing from collections.abc import Callable from decimal import Decimal -from itertools import pairwise +from itertools import islice, pairwise from typing import Any, TypeVar, cast, get_args, get_origin import pyarrow as pa +import pyarrow.compute as pc -from orcapod.errors import CanonicalOrderError +from orcapod.errors import CanonicalOrderError, LogicalSetCanonicalOrderError _T = TypeVar("_T") -# A sort key starts with 0 for None or 1 followed by the value or its child ranks. +# A sort key: ``(0,)`` for None, ``(1, value)`` otherwise. _Rank = tuple[Any, ...] @@ -59,69 +60,11 @@ def _key_rank(key: object) -> _Rank: return (1, key) -def _storage_ranker(storage_type: pa.DataType) -> Callable[[Any], _Rank]: - """Build the rank function for a set element's declared storage type.""" - if isinstance(storage_type, pa.StructType): - fields = tuple( - (field.name, _storage_ranker(field.type)) for field in storage_type - ) - - def rank_struct(value: Any) -> _Rank: - if value is None: - return (0,) - if isinstance(value, dict): - return (1, *(rank(value.get(name)) for name, rank in fields)) - if isinstance(value, tuple) and len(value) == len(fields): - return (1, *(rank(item) for (_, rank), item in zip(fields, value))) - raise CanonicalOrderError("expected a struct storage value") - - return rank_struct - if isinstance( - storage_type, - ( - pa.ListType, - pa.LargeListType, - pa.FixedSizeListType, - pa.ListViewType, - pa.LargeListViewType, - ), - ): - rank_item = _storage_ranker(storage_type.value_type) - - def rank_list(value: Any) -> _Rank: - if value is None: - return (0,) - if isinstance(value, (str, bytes, dict, set, frozenset)): - raise CanonicalOrderError("expected a list storage value") - try: - items = iter(value) - except TypeError as exc: - raise CanonicalOrderError("expected a list storage value") from exc - return (1, *(rank_item(item) for item in items)) - - return rank_list - if isinstance(storage_type, pa.ExtensionType): - return _storage_ranker(storage_type.storage_type) - if pa.types.is_nested(storage_type): - - def rank_unsupported(value: Any) -> _Rank: - if value is None: - return (0,) - raise CanonicalOrderError(f"storage type {storage_type} cannot be ordered") - - return rank_unsupported - return _key_rank - - def _is_nan(value: object) -> bool: """Return whether ``value`` is a NaN of any numeric type. Integers are never NaN and are not converted (a large ``int`` does not fit a float). """ - if isinstance(value, float): - return math.isnan(value) - if type(value) in (int, bool, str, bytes): - return False if isinstance(value, Decimal): return value.is_nan() if isinstance(value, numbers.Real) and not isinstance(value, numbers.Integral): @@ -136,12 +79,12 @@ def _sorted_by_rank(items: list[tuple[_Rank, _T]]) -> list[_T]: CanonicalOrderError: If two ranks cannot be compared or are equal. """ try: - items.sort(key=lambda item: item[0]) - for (previous, _), (current, _) in pairwise(items): - if previous == current: - raise CanonicalOrderError("duplicate key or set element") + items = sorted(items, key=lambda item: item[0]) except TypeError as exc: - raise CanonicalOrderError("values cannot be ordered") from exc + raise CanonicalOrderError(f"values cannot be ordered: {exc}") from exc + for (previous, _), (current, payload) in pairwise(items): + if previous == current: + raise CanonicalOrderError(f"duplicate key or set element: {payload!r}") return [payload for _, payload in items] @@ -161,15 +104,11 @@ def sort_dict_entries(entries: list[dict[str, _T]]) -> list[dict[str, _T]]: return _sorted_by_rank([(_key_rank(entry["key"]), entry) for entry in entries]) -def sort_set_elements( - elements: list[_T], storage_type: pa.DataType | None = None -) -> list[_T]: - """Return the storage elements of one set value in canonical order. +def sort_set_elements(elements: list[_T]) -> list[_T]: + """Return the storage elements of one primitive set in canonical order. Args: elements: The converted elements of a set. - storage_type: The declared Arrow element storage type, when available. - It supplies struct field order and list item types. Returns: A new list holding the same elements, sorted. @@ -178,8 +117,162 @@ def sort_set_elements( CanonicalOrderError: For a NaN element, elements that cannot be ordered against each other, or two elements with the same storage value. """ - rank = _key_rank if storage_type is None else _storage_ranker(storage_type) - return _sorted_by_rank([(rank(element), element) for element in elements]) + return _sorted_by_rank([(_key_rank(element), element) for element in elements]) + + +_LIST_ARRAY_TYPES = ( + pa.ListArray, + pa.LargeListArray, + pa.FixedSizeListArray, + pa.ListViewArray, + pa.LargeListViewArray, +) + + +def _ordinal_column(keys: list[Any]) -> pa.Array[Any]: + """Represent each distinct non-null Python comparison key by its sorted rank.""" + ranks = {key: i for i, key in enumerate(sorted(set(keys) - {None}))} + return pa.array([ranks.get(key) for key in keys], type=pa.int64()) + + +def _list_sort_column( + array: pa.ListArray[Any] + | pa.LargeListArray[Any] + | pa.FixedSizeListArray[Any] + | pa.ListViewArray[Any] + | pa.LargeListViewArray[Any], +) -> pa.Array[Any]: + """Use one lexicographic key per stored list, comparing only its own children.""" + children = _sort_columns(array.flatten()) + # All child columns hold built-in scalars. Tag nulls to put them first, including + # inside nested lists. The tuple comparison gives a proper prefix precedence. + child_keys = zip( + *( + [(value is not None, value) for value in column.to_pylist()] + for column in children + ), + strict=True, + ) + keys = [ + None if length is None else tuple(islice(child_keys, length)) + for length in pc.list_value_length(array).to_pylist() + ] + return _ordinal_column(keys) + + +def _sort_columns(array: pa.Array[Any]) -> list[pa.Array[Any]]: + """Flatten struct comparison keys in field order, preserving parent nulls.""" + if array.null_count == len(array): + # Arrow has no equality kernel for the null type. A constant key gives + # the same ties and also covers unsupported storage whose values are null. + return [pc.is_valid(array)] + if isinstance(array, pa.StructArray): + # flatten() masks the children where a struct is null. The validity key + # distinguishes a null struct from a present struct with all null fields. + columns: list[pa.Array[Any]] = ( + [pc.is_valid(array)] + if array.null_count or not array.type.num_fields + else [] + ) + for child in array.flatten(): + columns.extend(_sort_columns(child)) + return columns + if isinstance(array, _LIST_ARRAY_TYPES): + return [_list_sort_column(array)] + if isinstance(array, pa.ExtensionArray): + return _sort_columns(array.storage) + if isinstance(array, pa.DictionaryArray): + return _sort_columns(array.dictionary_decode()) + + kind = array.type + if pa.types.is_float16(kind): + array = array.cast(pa.float32()) + if pa.types.is_floating(kind): + if pc.any(pc.is_nan(array)).as_py(): + raise LogicalSetCanonicalOrderError( + "a NaN key or set element has no canonical order" + ) + return [array] + if pa.types.is_string_view(kind): + return [array.cast(pa.large_string())] + if pa.types.is_binary_view(kind): + return [array.cast(pa.large_binary())] + if isinstance(kind, (pa.Decimal32Type, pa.Decimal64Type)): + return [array.cast(pa.decimal128(kind.precision, kind.scale))] + if pa.types.is_interval(kind): + # Arrow has no sort/equality kernels for intervals. Its Python scalars + # expose their stored months, days and nanoseconds as a tuple. + return [_ordinal_column(array.to_pylist())] + if pa.types.is_nested(kind): + raise LogicalSetCanonicalOrderError(f"storage type {kind} cannot be ordered") + + # Use physical units for temporal values, including inside list keys, where + # Python date/time objects could otherwise drop sub-day or sub-microsecond bits. + if pa.types.is_date32(kind) or pa.types.is_time32(kind): + return [array.view(pa.int32())] + if pa.types.is_temporal(kind): + return [array.view(pa.int64())] + return [array] + + +def _adjacent_equal(array: pa.Array[Any]) -> pa.BooleanArray: + """Compare neighboring sorted keys, with null equal to null.""" + left, right = array.slice(0, len(array) - 1), array.slice(1) + equal = pc.equal(left, right) + if array.null_count: + both_null = pc.and_(pc.is_null(left), pc.is_null(right)) + equal = pc.or_kleene(equal, both_null) + equal = pc.fill_null(equal, pa.scalar(False)) + return cast(pa.BooleanArray, equal) + + +def ordered_set_storage( + elements: list[Any], storage_type: pa.DataType +) -> pa.Array[Any]: + """Encode a logical set's elements once and return them in canonical order. + + Args: + elements: The converted elements of one logical set. + storage_type: The declared Arrow element storage type. + + Returns: + The exact Arrow storage values, in canonical order. + + Raises: + LogicalSetCanonicalOrderError: For an unorderable value (including NaN), + or two elements with equal storage keys. + """ + try: + array = pa.array(elements, type=storage_type) + columns = _sort_columns(array) + if len(array) < 2: + return array + names = [str(i) for i in range(len(columns))] + indices = pc.sort_indices( + pa.Table.from_arrays(columns, names=names), + sort_keys=[(name, "ascending") for name in names], + null_placement="at_start", + ) + + # Intersect adjacent-equality masks until no possible duplicate remains. + duplicates = None + for column in columns: + equal = _adjacent_equal(column.take(indices)) + duplicates = equal if duplicates is None else pc.and_(duplicates, equal) + if not pc.any(duplicates).as_py(): + try: + return array.take(indices) + except pa.ArrowNotImplementedError: + # View types lack a take kernel, including inside structs. + return pa.concat_arrays( + [ + array.slice(i, 1) + for i in cast(list[int], indices.to_pylist()) + ] + ) + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + raise LogicalSetCanonicalOrderError("duplicate key or set element") def canonical_python_value( diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 3e56bc801..0b05f9fab 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -14,6 +14,7 @@ from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.utils.arrow_utils import table_from_storage class SemanticSchemaConverter: @@ -140,9 +141,9 @@ def python_dicts_to_arrow_table( when the caller needs to enforce specific field types or nullable flags that differ from what was inferred at construction time. """ - return pa.Table.from_pylist( + return table_from_storage( self.python_dicts_to_struct_dicts(data), - schema=arrow_schema or self.arrow_schema, + arrow_schema or self.arrow_schema, ) def arrow_table_to_python_dicts(self, table: pa.Table) -> list[dict[str, Any]]: diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 678270275..24d6508a8 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1296,9 +1296,7 @@ def python_dicts_to_struct_dicts( converted_record[field_name] = converter(record[field_name]) except CanonicalOrderError as exc: # The ordering rule cannot say which column it was in. - raise CanonicalOrderError( - f"Column {field_name!r}: {exc}" - ) from exc + raise type(exc)(f"Column {field_name!r}: {exc}") from exc except UnsupportedValueError as exc: # The value's own type cannot say which column it was in. raise UnsupportedValueError( @@ -1400,7 +1398,7 @@ def python_dicts_to_arrow_table( ) # TODO: add more helpful message here - return pa.Table.from_pylist(struct_dicts, schema=arrow_schema) + return arrow_utils.table_from_storage(struct_dicts, arrow_schema) def arrow_table_to_python_dicts( self, arrow_table: pa.Table diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 57b5115a5..c444a8995 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -37,6 +37,68 @@ def make_empty_table( return pa.Table.from_batches([], schema=arrow_schema) +def table_from_storage( + rows: list[dict[str, Any]], schema: pa.Schema | None +) -> pa.Table: + """Build a table, reusing the encoded elements of top-level logical sets. + + Rows otherwise follow Arrow's ``Table.from_pylist`` conventions. Building a + large-list column from offsets avoids passing each encoded element back + through a Python scalar when Arrow appends a list value. + """ + if schema is None: + return pa.Table.from_pylist(rows) + encoded_columns: dict[int, pa.Array[Any]] = {} + for index, field in enumerate(schema): + kind = field.type + if not isinstance(kind, pa.ExtensionType) or not kind.extension_name.startswith( + "set[" + ): + continue + storage_type = kind.storage_type + if not isinstance(storage_type, pa.LargeListType): + continue + first = next( + (value for row in rows if (value := row.get(field.name)) is not None), + None, + ) + if not isinstance(first, pa.Array) or first.type != storage_type.value_type: + continue + values = [row.get(field.name) for row in rows] + if not all( + value is None + or (isinstance(value, pa.Array) and value.type == storage_type.value_type) + for value in values + ): + continue + arrays: list[pa.Array[Any]] = [] + offsets = [0] + for value in values: + if value is not None: + arrays.append(value) + offsets.append(offsets[-1] + (len(value) if value is not None else 0)) + elements = arrays[0] if len(arrays) == 1 else pa.concat_arrays(arrays) + mask = pa.array([value is None for value in values]) + storage = pa.LargeListArray.from_arrays( + pa.array(offsets, type=pa.int64()), elements, type=storage_type, mask=mask + ) + encoded_columns[index] = pa.ExtensionArray.from_storage(kind, storage) + + if not encoded_columns: + return pa.Table.from_pylist(rows, schema=schema) + other_schema = pa.schema( + field for index, field in enumerate(schema) if index not in encoded_columns + ) + other_columns = iter(pa.Table.from_pylist(rows, schema=other_schema).itercolumns()) + return pa.Table.from_arrays( + [ + encoded_columns[index] if index in encoded_columns else next(other_columns) + for index in range(len(schema)) + ], + schema=schema, + ) + + def schema_select( arrow_schema: "pa.Schema", column_names: Collection[str], diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index 8a2d83621..56a551ca6 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -1245,3 +1245,24 @@ def test_second_run_reuses_the_result_of_another_value( store = InMemoryArrowDatabase() assert self._run(store, (20,), AsyncPipelineOrchestrator) == {"r20": 20} assert self._run(store, (20, 99), second_cls) == {"r20": 20, "r99": 20} + + +@pytest.mark.parametrize( + "annotation, value, container, declared", + [ + (dict[float, int], {float("nan"): 1}, "dict", "dict[float, int]"), + (set[float], {float("nan")}, "set", "set[float]"), + ], +) +def test_primitive_unordered_output_keeps_output_type_error( + annotation: Any, value: Any, container: str, declared: str +) -> None: + """An unordered primitive output retains its public conversion diagnostic.""" + stream = make_pod(annotation, value, name="nan_output").pod(make_source()) + with pytest.raises(errors.OutputTypeError) as raised: + list(stream.iter_data()) + assert str(raised.value) == ( + f"Function 'nan_output' returned {container} for output 'y', " + f"which is declared {declared}: CanonicalOrderError. " + "The output does not conform; convert the value in the function." + ) diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index 7ed92fd65..d95bedbe0 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -20,9 +20,13 @@ import sys import uuid from collections.abc import Callable +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal from pathlib import Path -from typing import Any, cast +from random import Random +from typing import Any, Never, cast +import numpy as np import polars as pl import pyarrow as pa import pydantic @@ -40,6 +44,10 @@ make_arrow_extension_type, make_polars_extension_type, ) +from orcapod.semantic_types.canonical_order import ( + ordered_set_storage, + sort_set_elements, +) from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.sources import DictSource @@ -581,3 +589,224 @@ def test_struct_storage_order_and_hash_are_independent_of_hash_seed() -> None: ] assert results[0] == results[1] assert results[0][0] == {"site0": _SAMPLE_STORAGE} + + +@dataclasses.dataclass(frozen=True) +class StoredDay: + """Datetime inputs to this class lose their time of day on write.""" + + z: date + a: str + + +@dataclasses.dataclass(frozen=True) +class StoredSingle: + """Different Python floats can round to the same float32.""" + + z: np.float32 + a: str + + +@pytest.mark.parametrize( + "element, first, second", + [ + (StoredDay, datetime(2026, 1, 1, 1), datetime(2026, 1, 1, 2)), + (StoredSingle, float(2**24), float(2**24 + 1)), + ], +) +def test_duplicates_after_arrow_coercion_are_refused( + element: Any, first: Any, second: Any +) -> None: + """Refuse values that only become equal once written into the declared type.""" + values = {element(first, "a"), element(second, "a")} + assert len(values) == 2 + with pytest.raises(CanonicalOrderError, match=r"Column 's': .*duplicate"): + _source([values], element).as_table() + + +def test_ties_after_arrow_coercion_use_the_next_field_and_keep_the_hash() -> None: + """Re-encoding the stored float32 values preserves both order and content hash.""" + values = { + StoredSingle(cast(Any, float(2**24)), "z"), + StoredSingle(cast(Any, float(2**24 + 1)), "a"), + } + source = _source([values], StoredSingle) + _, row = next(iter(source.iter_data())) + assert row.update(s=row["s"]).content_hash() == row.content_hash() + assert [item["a"] for item in _stored(source)["site0"]] == ["a", "z"] + + +def test_stored_string_order_ignores_a_subclass_comparator() -> None: + """Compare the stored text in code point order even if the inputs disagree.""" + + comparisons = 0 + + class ReverseText(str): + @override + def __lt__(self, other: str) -> bool: + nonlocal comparisons + comparisons += 1 + return str.__gt__(self, other) + + original = _source( + [{ExactPoint(1, ReverseText(s)) for s in ("a", "z")}], ExactPoint + ) + plain = _source([{ExactPoint(1, s) for s in ("a", "z")}], ExactPoint) + assert _stored(original) == _stored(plain) + assert _row_hashes(original) == _row_hashes(plain) + assert comparisons == 0 + + +def test_builtin_scalar_sets_skip_generic_ordering( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The five built-ins keep the single native sort of their storage values.""" + + def unexpected(*_args: object, **_kwargs: object) -> Never: + pytest.fail("a built-in scalar set entered generic canonical ordering") + + monkeypatch.setattr( + "orcapod.semantic_types.canonical_order.sort_set_elements", unexpected + ) + for name in ("b", "a"): + (tmp_path / name).write_text(name) + (tmp_path / f"{name}-dir").mkdir() + for element, values in ( + (Path, {Path("/b"), Path("/a")}), + (UPath, {UPath("s3://b/x"), UPath("s3://a/y")}), + (uuid.UUID, {uuid.UUID(int=2), uuid.UUID(int=1)}), + (op.File, {op.File(tmp_path / name) for name in ("a", "b")}), + (op.Directory, {op.Directory(tmp_path / name) for name in ("a-dir", "b-dir")}), + ): + stored = _stored(_source([values], element))["site0"] + assert len(stored) == 2 + assert stored == sorted(stored) + + +@pytest.mark.parametrize( + "storage_type, kind", + [ + (pa.bool_(), "bool"), + *((type_(), "signed") for type_ in (pa.int8, pa.int16, pa.int32, pa.int64)), + *( + (type_(), "unsigned") + for type_ in (pa.uint8, pa.uint16, pa.uint32, pa.uint64) + ), + *((type_(), "float") for type_ in (pa.float16, pa.float32, pa.float64)), + *( + (type_(8, 2), "decimal") + for type_ in (pa.decimal32, pa.decimal64, pa.decimal128, pa.decimal256) + ), + *((type_(), "text") for type_ in (pa.string, pa.large_string, pa.string_view)), + *( + (type_(), "binary") + for type_ in (pa.binary, pa.large_binary, pa.binary_view) + ), + (pa.binary(4), "binary"), + (pa.date32(), "date"), + (pa.date64(), "date"), + (pa.time32("ms"), "time"), + (pa.time64("ns"), "time"), + (pa.timestamp("ms"), "timestamp"), + (pa.timestamp("ns", "America/New_York"), "zoned timestamp"), + (pa.duration("us"), "duration"), + (pa.duration("ns"), "duration"), + (pa.null(), "null"), + ], + ids=lambda value: str(value), +) +def test_arrow_scalar_storage_order_matches_primitive_order( + storage_type: pa.DataType, kind: str +) -> None: + """Arrow's sort on each scalar storage kind follows the primitive order.""" + random = Random(922) + numbers = random.sample(range(1, 120), 40) + if kind == "bool": + values = [False, True] + elif kind == "signed": + values = [n - 60 for n in numbers] + elif kind == "unsigned": + values = numbers + elif kind == "float": + # Half-floats need NumPy scalars on the input path. + values = [np.float16((n - 60) / 7) for n in numbers] + values.extend([np.float16(-np.inf), np.float16(np.inf)]) + elif kind == "decimal": + values = [Decimal(n - 60).scaleb(-2) for n in numbers] + elif kind == "text": + values = [random.choice("éÅ𝄞𐀀aZ\x00") + chr(n) for n in numbers] + values.extend(["", "a", "a\x00", "e\u0301", "é"]) + elif kind == "binary": + values = [n.to_bytes(2, "big") + random.randbytes(2) for n in numbers] + values.extend([b"\x00\x00\x00\x00", b"\xff\xff\xff\xff"]) + elif kind == "date": + values = [date(2026, 1, 1) + timedelta(days=n - 60) for n in numbers] + elif kind == "time": + values = [time(n % 24, n % 60, microsecond=n * 1000) for n in numbers] + elif kind == "timestamp" or kind == "zoned timestamp": + start = datetime(2026, 11, 1, 4) + if kind == "zoned timestamp": + start = start.replace(tzinfo=timezone.utc) + # Span a repeated local hour in the zoned Arrow storage. + values = [start + timedelta(minutes=n * 3) for n in numbers] + elif kind == "duration": + values = [timedelta(microseconds=n - 60) for n in numbers] + else: + assert kind == "null" + values = [] + shuffled: list[Any] = [*values, None] + random.shuffle(shuffled) + array = cast("pa.Array[Any]", pa.array(shuffled, type=storage_type)) + stored = array.to_pylist() + expected = sort_set_elements(stored) + assert ordered_set_storage(shuffled, storage_type).to_pylist() == expected + + +def test_arrow_struct_null_is_distinct_from_a_struct_of_nulls() -> None: + """Flattening a struct preserves the validity of the struct itself.""" + shape = pa.struct([("z", pa.struct([("n", pa.int64())])), ("a", pa.string())]) + values = [ + {"z": {"n": 0}, "a": "a"}, + {"z": {"n": None}, "a": "a"}, + {"z": None, "a": "z"}, + None, + ] + assert ordered_set_storage(values, shape).to_pylist() == values[::-1] + + +def test_nested_list_order_preserves_arrow_temporal_precision() -> None: + """List comparison keys use stored nanoseconds even below Python's precision.""" + shape = pa.struct([("z", pa.list_(pa.time64("ns"))), ("a", pa.string())]) + values = [{"z": [3], "a": "a"}, {"z": [2], "a": "z"}] + assert ordered_set_storage(values, shape).equals(pa.array(values[::-1], type=shape)) + + +def test_arrow_set_order_ties_signed_zero_in_nested_lists() -> None: + """Zeros with opposite signs are equal storage keys even inside lists.""" + shape = pa.struct([("z", pa.list_(pa.float64()))]) + with pytest.raises(CanonicalOrderError, match="duplicate"): + ordered_set_storage([{"z": [-0.0]}, {"z": [0.0]}], shape) + + +def test_encoded_struct_set_column_keeps_null_and_empty_rows() -> None: + """Assemble typed set storage directly while keeping row offsets and validity.""" + converter = get_default_context().type_converter + values = [ + None, + {ExactPoint(10, "a"), ExactPoint(2, "z")}, + set(), + {ExactPoint(3, "b")}, + ] + table = converter.python_dicts_to_arrow_table( + [{"s": value, "i": i} for i, value in enumerate(values)], + python_schema={"s": set[ExactPoint] | None, "i": int}, + ) + array = table["s"].combine_chunks() + assert isinstance(array, pa.ExtensionArray) + assert array.storage.to_pylist() == [ + None, + [{"a": 2, "b": "z"}, {"a": 10, "b": "a"}], + [], + [{"a": 3, "b": "b"}], + ] + assert table["i"].to_pylist() == [0, 1, 2, 3] From 216aeeac3cd287df1421e5c14fd988812fab54ee Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:20:10 -0800 Subject: [PATCH 04/18] fix(logical_types): canonicalize nested stored sets and batch column writes --- changelog.d/ITL-922.md | 5 +- docs/api/errors.md | 1 + docs/dev/design_issues/ITL-922-DO2.md | 14 ++- docs/reference/hashing.md | 4 +- .../list_logical_type_factory.py | 52 +++++++- src/orcapod/semantic_types/canonical_order.py | 112 ++++++++++++++---- .../semantic_types/precomputed_converters.py | 8 +- .../semantic_types/universal_converter.py | 107 ++++++++++++++--- src/orcapod/utils/arrow_utils.py | 12 +- .../function_pod/test_output_conformance.py | 15 +++ .../test_set_of_logical_elements.py | 101 ++++++++++++++++ 11 files changed, 369 insertions(+), 62 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index e8a609404..e6c21de86 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -9,5 +9,6 @@ - Sets of user-defined logical types are ordered after Arrow coerces each element to the declared storage type (ITL-922). The sort descends into nested structs - and lists, with `None` first. A NaN at any depth, incomparable values, or two - elements with equal storage raise `CanonicalOrderError` naming the column. + and lists, with `None` first. Nested dict keys and set items are ordered after + coercion too. A NaN at any depth, incomparable values, or two keys or elements + with equal storage raise `CanonicalOrderError` naming the column. diff --git a/docs/api/errors.md b/docs/api/errors.md index 2008bf91b..5277bdbbb 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -17,6 +17,7 @@ These exceptions and warnings report invalid inputs, schemas, or values. ::: orcapod.errors.RecursiveTypeError ::: orcapod.errors.CanonicalOrderError +::: orcapod.errors.LogicalSetCanonicalOrderError ::: orcapod.errors.UnsupportedValueError diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 0c2297025..fc9363bb3 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -12,9 +12,11 @@ storage values. **Fix:** Apply canonical order after coercion to the declared Arrow element type. Sort the struct fields in declared order and use a lexicographic key for each -list field. Check adjacent sorted values for duplicates. The five built-in -scalar-stored types keep their native sort. The order is independent of any -class comparison method, so the same rule applies to classes rebuilt from -metadata. Reject NaNs at any depth, incomparable values and duplicate storage -values. The conversion boundary supplies the column name. Rebuilding sets of -user classes can change affected row hashes. +list field. Sort nested dict keys and set items in their own declared storage +types before comparing the enclosing elements. Check adjacent sorted values +for duplicates within each set. Multi-row table conversion encodes and sorts +each set column in one pass. The five built-in scalar-stored types keep their +native sort for standalone sets. The same order applies to classes rebuilt +from metadata. Reject NaNs at any depth, incomparable values and duplicate +storage values. The conversion boundary supplies the column name. Rebuilding +sets of user classes can change affected row hashes. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index d32f67e61..f7e08fe09 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1018,7 +1018,9 @@ orders for equal hashed inputs; reconstructing user-class instances is outside t Struct fields and list items follow the same rules recursively, including `None` first. For a set of user-defined logical values, Orcapod coerces each element to its declared Arrow type before comparing it. Python class comparators such as those generated by -`@dataclass(order=True)` do not participate. +`@dataclass(order=True)` do not participate. Nested dict keys and set items are also +ordered in their declared storage types. Two keys or items that coerce to the same +stored value are refused before they can collapse on read. A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`), including a NaN anywhere inside a set element, has no order diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 53e93292c..e4d5bf76b 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -62,6 +62,12 @@ make_arrow_extension_type, make_polars_extension_type, ) +from orcapod.semantic_types.canonical_order import ( + _in_logical_set, + _ordered_set_column, + ordered_set_storage, + sort_set_elements, +) if TYPE_CHECKING: from orcapod.logical_types.protocols import ( @@ -162,6 +168,11 @@ def __init__( not isinstance(element_logical_type, ArrowElement) and element_logical_type.logical_type_name in self._NATIVE_SORT_TYPES ) + self._orders_stored_sets = ( + is_set + and not self._uses_native_sort + and not isinstance(element_logical_type, ArrowElement) + ) self._arrow_ext: pa.ExtensionType | None = None self._polars_ext: pl.BaseExtension | None = None @@ -377,6 +388,14 @@ def python_to_storage( """ if value is None: return [] + if self._orders_stored_sets: + token = _in_logical_set.set(True) + try: + elements = self._encode_elements(value, converter) + finally: + _in_logical_set.reset(token) + return ordered_set_storage(elements, self._storage_type.value_type) + if converter is None: elements = list(value) else: @@ -386,16 +405,37 @@ def python_to_storage( ] if not self._is_set: return elements + if _in_logical_set.get(): + return ordered_set_storage(elements, self._storage_type.value_type) if self._uses_native_sort: return sorted(elements) - if self._element_logical_type is None: - from orcapod.semantic_types.canonical_order import sort_set_elements - - return sort_set_elements(elements) - from orcapod.semantic_types.canonical_order import ordered_set_storage + return sort_set_elements(elements) - return ordered_set_storage(elements, self._storage_type.value_type) + def _encode_elements( + self, value: Any, converter: TypeConverterProtocol | None + ) -> list[Any]: + """Convert elements using their declared logical type.""" + if converter is None: + return list(value) + return [ + converter.python_to_storage(item, self._element_python_type) + for item in value + ] + + def _python_sets_to_storage( + self, values: list[Any], converter: TypeConverterProtocol + ) -> pa.LargeListArray[Any]: + """Encode and order a column of sets in one Arrow pass.""" + token = _in_logical_set.set(True) + try: + rows = [ + None if value is None else self._encode_elements(value, converter) + for value in values + ] + finally: + _in_logical_set.reset(token) + return _ordered_set_column(rows, self._storage_type) def storage_to_python( self, storage_value: Any, converter: TypeConverterProtocol | None diff --git a/src/orcapod/semantic_types/canonical_order.py b/src/orcapod/semantic_types/canonical_order.py index 884405b61..a91326b04 100644 --- a/src/orcapod/semantic_types/canonical_order.py +++ b/src/orcapod/semantic_types/canonical_order.py @@ -31,10 +31,12 @@ import types import typing from collections.abc import Callable +from contextvars import ContextVar from decimal import Decimal from itertools import islice, pairwise from typing import Any, TypeVar, cast, get_args, get_origin +import polars as pl import pyarrow as pa import pyarrow.compute as pc @@ -45,6 +47,10 @@ # A sort key: ``(0,)`` for None, ``(1, value)`` otherwise. _Rank = tuple[Any, ...] +# Field converters also serve standalone primitive containers. Only an enclosing +# user-class set requires canonicalizing those fields against their Arrow storage. +_in_logical_set: ContextVar[bool] = ContextVar("_in_logical_set", default=False) + def _key_rank(key: object) -> _Rank: """Return the sort key of one storage key or set element. @@ -144,6 +150,24 @@ def _list_sort_column( ) -> pa.Array[Any]: """Use one lexicographic key per stored list, comparing only its own children.""" children = _sort_columns(array.flatten()) + lengths = pc.list_value_length(array) + if len(children) == 1 and ( + pa.types.is_integer(children[0].type) + or pa.types.is_floating(children[0].type) + or pa.types.is_boolean(children[0].type) + ): + # Dense rank compares list items lexicographically, with null items first + # and equal lists sharing a rank. List validity stays separate from length. + # Rebuild offsets over the flattened children, which omit null parent lists. + offsets = pc.cumulative_sum( + pa.concat_arrays( + [pa.array([0], type=pa.int64()), lengths.cast(pa.int64()).fill_null(0)] + ) + ) + lists = pa.LargeListArray.from_arrays( + cast(pa.Int64Array, offsets), children[0], mask=pc.is_null(array) + ) + return pl.Series(lists).rank("dense").to_arrow() # All child columns hold built-in scalars. Tag nulls to put them first, including # inside nested lists. The tuple comparison gives a proper prefix precedence. child_keys = zip( @@ -155,7 +179,7 @@ def _list_sort_column( ) keys = [ None if length is None else tuple(islice(child_keys, length)) - for length in pc.list_value_length(array).to_pylist() + for length in lengths.to_pylist() ] return _ordinal_column(keys) @@ -245,33 +269,71 @@ def ordered_set_storage( try: array = pa.array(elements, type=storage_type) columns = _sort_columns(array) - if len(array) < 2: - return array - names = [str(i) for i in range(len(columns))] - indices = pc.sort_indices( - pa.Table.from_arrays(columns, names=names), - sort_keys=[(name, "ascending") for name in names], - null_placement="at_start", - ) + return _sort_set_array(array, columns) if len(array) > 1 else array + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + - # Intersect adjacent-equality masks until no possible duplicate remains. - duplicates = None - for column in columns: - equal = _adjacent_equal(column.take(indices)) - duplicates = equal if duplicates is None else pc.and_(duplicates, equal) - if not pc.any(duplicates).as_py(): - try: - return array.take(indices) - except pa.ArrowNotImplementedError: - # View types lack a take kernel, including inside structs. - return pa.concat_arrays( - [ - array.slice(i, 1) - for i in cast(list[int], indices.to_pylist()) - ] - ) +def _ordered_dict_storage( + entries: list[dict[str, Any]], entry_type: pa.DataType +) -> pa.Array[Any]: + """Order typed dict entries by their keys and reject equal stored keys.""" + try: + array = cast(pa.StructArray, pa.array(entries, type=entry_type)) + columns = _sort_columns(array.field("key")) + return _sort_set_array(array, columns) if len(array) > 1 else array except (TypeError, pa.ArrowException) as exc: raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + + +def _ordered_set_column( + rows: list[list[Any] | None], storage_type: pa.LargeListType[Any] +) -> pa.LargeListArray[Any]: + """Encode and sort the elements of a column, keeping each set in its row.""" + try: + storage = cast("pa.LargeListArray[Any]", pa.array(rows, type=storage_type)) + elements = storage.values + if len(elements) == 0: + return storage + columns = _sort_columns(elements) + if pc.max(pc.list_value_length(storage)).as_py() <= 1: + return storage + sorted_elements = _sort_set_array( + elements, [pc.list_parent_indices(storage), *columns] + ) + return pa.LargeListArray.from_arrays( + storage.offsets, + sorted_elements, + type=storage_type, + mask=pc.is_null(storage), + ) + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + + +def _sort_set_array( + array: pa.Array[Any], columns: list[pa.Array[Any]] +) -> pa.Array[Any]: + """Sort stored values by the comparison columns and refuse equal neighbors.""" + names = [str(i) for i in range(len(columns))] + indices = pc.sort_indices( + pa.Table.from_arrays(columns, names=names), + sort_keys=[(name, "ascending") for name in names], + null_placement="at_start", + ) + # Intersect adjacent equality masks until no possible duplicate remains. + duplicates = None + for column in columns: + equal = _adjacent_equal(column.take(indices)) + duplicates = equal if duplicates is None else pc.and_(duplicates, equal) + if not pc.any(duplicates).as_py(): + try: + return array.take(indices) + except pa.ArrowNotImplementedError: + # View types lack a take kernel, including inside structs. + return pa.concat_arrays( + [array.slice(i, 1) for i in cast(list[int], indices.to_pylist())] + ) raise LogicalSetCanonicalOrderError("duplicate key or set element") diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 0b05f9fab..192edb680 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -13,6 +13,7 @@ import pyarrow as pa +from orcapod.errors import LogicalSetCanonicalOrderError from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.utils.arrow_utils import table_from_storage @@ -86,7 +87,12 @@ def python_dicts_to_struct_dicts( converted_record[field_name] = None else: # Convert using the pre-computed converter - converted_record[field_name] = converter(value) + try: + converted_record[field_name] = converter(value) + except LogicalSetCanonicalOrderError as exc: + raise LogicalSetCanonicalOrderError( + f"Column {field_name!r}: {exc}" + ) from exc converted_data.append(converted_record) return converted_data diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 24d6508a8..cfb92d081 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -34,6 +34,9 @@ UnsupportedValueError, ) from orcapod.semantic_types.canonical_order import ( + _in_logical_set, + _ordered_dict_storage, + ordered_set_storage, sort_dict_entries, sort_set_elements, ) @@ -1393,12 +1396,68 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) - struct_dicts = self.python_dicts_to_struct_dicts( - python_dicts, python_schema=python_schema - ) + return self._storage_table(python_dicts, python_schema, arrow_schema) + + def _storage_table( + self, + rows: list[dict[str, Any]], + python_schema: SchemaLike, + arrow_schema: pa.Schema, + ) -> pa.Table: + """Batch logical set columns and convert the remaining cells as usual.""" + if len(rows) <= 1 or self._logical_type_registry is None: + return arrow_utils.table_from_storage( + self.python_dicts_to_struct_dicts(rows, python_schema), arrow_schema + ) - # TODO: add more helpful message here - return arrow_utils.table_from_storage(struct_dicts, arrow_schema) + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + + encoded_columns: dict[int, pa.Array[Any]] = {} + remaining_schema = dict(python_schema) + registry = self._logical_type_registry + for index, field in enumerate(arrow_schema): + field_type = field.type + if not isinstance( + field_type, pa.ExtensionType + ) or not field_type.extension_name.startswith("set["): + continue + annotation = remaining_schema.get(field.name) + nullable = False + if get_origin(annotation) in (typing.Union, types.UnionType): + args = get_args(annotation) + if len(args) == 2 and type(None) in args: + annotation = next(arg for arg in args if arg is not type(None)) + nullable = True + if get_origin(annotation) is not set: + continue + logical_type = registry.get_by_python_type(typing.cast(type, annotation)) + if ( + not isinstance(logical_type, ListLogicalType) + or not logical_type._orders_stored_sets + or not field_type.equals(logical_type.get_arrow_extension_type()) + ): + continue + values = [row.get(field.name) for row in rows] + # A present None for a required type still takes the converter's + # usual error path. A missing cell is handled as a null as before. + if not nullable and any( + value is None and field.name in row + for value, row in zip(values, rows, strict=True) + ): + continue + try: + storage = logical_type._python_sets_to_storage(values, self) + except CanonicalOrderError as exc: + raise type(exc)(f"Column {field.name!r}: {exc}") from exc + except UnsupportedValueError as exc: + raise UnsupportedValueError(f"Column {field.name!r}: {exc}") from exc + encoded_columns[index] = pa.ExtensionArray.from_storage(field_type, storage) + del remaining_schema[field.name] + + struct_dicts = self.python_dicts_to_struct_dicts(rows, remaining_schema) + return arrow_utils.table_from_storage( + struct_dicts, arrow_schema, encoded_columns=encoded_columns + ) def arrow_table_to_python_dicts( self, arrow_table: pa.Table @@ -1905,16 +1964,20 @@ def _convert_datetime(dt: datetime) -> datetime: elif origin is list: element_converter = self.get_python_to_arrow_converter(args[0]) - def convert_list(value: Any) -> list[Any]: + def convert_list(value: Any) -> list[Any] | pa.Array[Any]: """Convert list storage, preserving set order independence on updates.""" if value is None: raise _none_not_admitted(python_type) elements = [element_converter(item) for item in value] # An Arrow schema remembers a plain set only as a list. Python set # inputs still need canonical storage order; actual lists keep theirs. - return ( - sort_set_elements(elements) if isinstance(value, set) else elements - ) + if not isinstance(value, set): + return elements + if _in_logical_set.get(): + return ordered_set_storage( + elements, self.python_type_to_arrow_type(args[0]) + ) + return sort_set_elements(elements) return convert_list @@ -1924,15 +1987,18 @@ def convert_list(value: Any) -> list[Any]: # A dict is order independent: entries are stored in canonical key order # so equal dicts store and hash identically (ITL-905). - def convert_dict(value: Any) -> list[dict[str, Any]]: + def convert_dict(value: Any) -> list[dict[str, Any]] | pa.Array[Any]: if value is None: raise _none_not_admitted(python_type) - return sort_dict_entries( - [ - {"key": key_converter(k), "value": value_converter(v)} - for k, v in value.items() - ] - ) + entries = [ + {"key": key_converter(k), "value": value_converter(v)} + for k, v in value.items() + ] + if _in_logical_set.get(): + storage_type = self.python_type_to_arrow_type(python_type) + assert isinstance(storage_type, pa.LargeListType) + return _ordered_dict_storage(entries, storage_type.value_type) + return sort_dict_entries(entries) return convert_dict @@ -1941,10 +2007,15 @@ def convert_dict(value: Any) -> list[dict[str, Any]]: # order, which depends on PYTHONHASHSEED for str and bytes (ITL-905). element_converter = self.get_python_to_arrow_converter(args[0]) - def convert_set(value: Any) -> list[Any]: + def convert_set(value: Any) -> list[Any] | pa.Array[Any]: if value is None: raise _none_not_admitted(python_type) - return sort_set_elements([element_converter(item) for item in value]) + elements = [element_converter(item) for item in value] + if _in_logical_set.get(): + return ordered_set_storage( + elements, self.python_type_to_arrow_type(args[0]) + ) + return sort_set_elements(elements) return convert_set diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c444a8995..7d9fec828 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -38,18 +38,24 @@ def make_empty_table( def table_from_storage( - rows: list[dict[str, Any]], schema: pa.Schema | None + rows: list[dict[str, Any]], + schema: pa.Schema | None, + *, + encoded_columns: dict[int, pa.Array[Any]] | None = None, ) -> pa.Table: """Build a table, reusing the encoded elements of top-level logical sets. Rows otherwise follow Arrow's ``Table.from_pylist`` conventions. Building a large-list column from offsets avoids passing each encoded element back - through a Python scalar when Arrow appends a list value. + through a Python scalar when Arrow appends a list value. Columns supplied in + ``encoded_columns`` are already assembled and keyed by schema position. """ if schema is None: return pa.Table.from_pylist(rows) - encoded_columns: dict[int, pa.Array[Any]] = {} + encoded_columns = dict(encoded_columns) if encoded_columns else {} for index, field in enumerate(schema): + if index in encoded_columns: + continue kind = field.type if not isinstance(kind, pa.ExtensionType) or not kind.extension_name.startswith( "set[" diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index 56a551ca6..d9a31bef8 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -1266,3 +1266,18 @@ def test_primitive_unordered_output_keeps_output_type_error( f"which is declared {declared}: CanonicalOrderError. " "The output does not conform; convert the value in the function." ) + + +@dataclass(frozen=True, eq=False) +class WithDict: + d: dict[float, int] + + +def test_logical_set_output_reports_nested_dict_nan() -> None: + """Keep the column-qualified canonical order error from a logical set output.""" + + stream = make_pod( + set[WithDict], {WithDict({float("nan"): 1})}, name="nested_nan" + ).pod(make_source()) + with pytest.raises(errors.CanonicalOrderError, match=r"Column 'y': .*NaN"): + list(stream.iter_data()) diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index d95bedbe0..4d78729c0 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -50,6 +50,7 @@ ) from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.sources import DictSource +from orcapod.types import Schema # ── user-registered logical types ──────────────────────────────────────────── @@ -810,3 +811,103 @@ def test_encoded_struct_set_column_keeps_null_and_empty_rows() -> None: [{"a": 3, "b": "b"}], ] assert table["i"].to_pylist() == [0, 1, 2, 3] + + +def test_nested_dict_order_ignores_user_comparators() -> None: + """Canonicalize dict keys from storage before comparing the enclosing set.""" + + class ReverseText(str): + @override + def __lt__(self, other: str) -> bool: + pytest.fail("dict key comparator called") + + @op.dataclass(frozen=True, eq=False) + class WithDict: + d: dict[str, int] + + plain = WithDict({"a": 1, "z": 2}) + custom = WithDict({ReverseText("a"): 1, ReverseText("z"): 2}) + first = _source([{plain}], WithDict) + second = _source([{custom}], WithDict) + assert _stored(first) == _stored(second) + assert _row_hashes(first) == _row_hashes(second) + with pytest.raises(CanonicalOrderError, match=r"Column 's': .*duplicate"): + _source([{plain, custom}], WithDict).as_table() + + +@pytest.mark.parametrize("mapping", [False, True]) +def test_nested_unordered_storage_collision_is_refused(mapping: bool) -> None: + """A set element cannot contain entries that would collapse on read.""" + + @op.dataclass(frozen=True, eq=False) + class DictField: + values: dict[date, int] + + @op.dataclass(frozen=True, eq=False) + class SetField: + values: set[date] + + first, second = datetime(2026, 1, 1, 1), datetime(2026, 1, 1, 2) + element = DictField({first: 1, second: 2}) if mapping else SetField({first, second}) + with pytest.raises(CanonicalOrderError, match=r"Column 's': .*duplicate"): + _source([{element}], type(element)).as_table() + + +def test_precomputed_converter_names_logical_set_column() -> None: + """The precomputed table writer also supplies the failing column.""" + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter + + @op.dataclass(frozen=True, eq=False) + class WithDict: + d: dict[float, int] + + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema: dict[str, Any] = {"bad": set[WithDict]} + converter.ensure_types_registered_for_schemas(Schema(schema)) + writer = SemanticSchemaConverter(converter, python_schema=schema) + with pytest.raises(CanonicalOrderError, match=r"Column 'bad': .*NaN"): + writer.python_dicts_to_arrow_table([{"bad": {WithDict({float("nan"): 1})}}]) + + +def test_numeric_list_keys_skip_python_ranking(monkeypatch: pytest.MonkeyPatch) -> None: + """Rank variable-width nullable numeric list keys without decoding Python values.""" + from orcapod.semantic_types import canonical_order + + def unexpected(_keys: object) -> Never: + pytest.fail("numeric list keys entered Python ranking") + + monkeypatch.setattr(canonical_order, "_ordinal_column", unexpected) + shape = pa.struct([("items", pa.large_list(pa.float64())), ("value", pa.int64())]) + rows = [ + {"items": [0.0, 1.0], "value": 0}, + {"items": [None], "value": 0}, + {"items": None, "value": 0}, + {"items": [-0.0], "value": 2}, + {"items": [], "value": 0}, + {"items": [0.0], "value": 1}, + {"items": [None, -2.0], "value": 0}, + ] + result = ordered_set_storage(rows, shape) + assert result.equals(pa.array([rows[i] for i in (2, 4, 1, 6, 5, 3, 0)], type=shape)) + + +def test_small_logical_sets_share_one_sort(monkeypatch: pytest.MonkeyPatch) -> None: + """Sort all rows of a flat set column in one pass without mixing their values.""" + from orcapod.semantic_types import canonical_order + + sort_indices = canonical_order.pc.sort_indices + sizes: list[int] = [] + + def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: + sizes.append(table.num_rows) + return sort_indices(table, *args, **kwargs) + + monkeypatch.setattr(canonical_order.pc, "sort_indices", record_size) + small = ExactPoint(2, "x") + large = ExactPoint(10, "y") + table = get_default_context().type_converter.python_dicts_to_arrow_table( + [{"s": {small, large}} for _ in range(32)], python_schema={"s": set[ExactPoint]} + ) + assert sizes == [64] + assert table["s"].to_pylist() == [[{"a": 2, "b": "x"}, {"a": 10, "b": "y"}]] * 32 From 8eee15e463f8ede2b925eb0c92bc5be9e42476bb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:34:26 -0800 Subject: [PATCH 05/18] perf(logical_types): batch stored set sorting and rank list keys natively --- changelog.d/ITL-922.md | 2 + docs/dev/design_issues/ITL-922-DO2.md | 4 +- src/orcapod/core/data_function.py | 21 ++--- src/orcapod/core/function_pod.py | 24 ++++-- .../list_logical_type_factory.py | 25 ++++-- src/orcapod/semantic_types/canonical_order.py | 50 +++++++++++- .../semantic_types/precomputed_converters.py | 25 +++++- .../semantic_types/universal_converter.py | 78 ++++++++++++++++--- .../function_pod/test_output_conformance.py | 42 ++++++++++ .../test_set_of_logical_elements.py | 71 +++++++++++++---- 10 files changed, 287 insertions(+), 55 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index e6c21de86..2fd0ab702 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -12,3 +12,5 @@ and lists, with `None` first. Nested dict keys and set items are ordered after coercion too. A NaN at any depth, incomparable values, or two keys or elements with equal storage raise `CanonicalOrderError` naming the column. +- Table conversion orders logical set columns in batches. Text list fields and + short fixed-width integer list keys use native ranking. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index fc9363bb3..d2cea4277 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -15,7 +15,9 @@ Sort the struct fields in declared order and use a lexicographic key for each list field. Sort nested dict keys and set items in their own declared storage types before comparing the enclosing elements. Check adjacent sorted values for duplicates within each set. Multi-row table conversion encodes and sorts -each set column in one pass. The five built-in scalar-stored types keep their +each set column in one pass, including precomputed and function-stream tables. +Function iteration validates each row's stored keys before yielding it. +The five built-in scalar-stored types keep their native sort for standalone sets. The same order applies to classes rebuilt from metadata. Reject NaNs at any depth, incomparable values and duplicate storage values. The conversion boundary supplies the column name. Rebuilding diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index d45d478ff..bb458cc3f 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -46,6 +46,7 @@ check_conformance, normalize_output_numbers, ) +from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.types import ContentHash, DataValue, Schema, SchemaLike from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names @@ -1062,7 +1063,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: ) # Validate storage eagerly, but retain compatible user-class instances. Reading # the table back here would rebind structural objects to the registry's class. - self._convert_outputs(output_data, output_schema) + self._validate_output_storage(output_data, output_schema) normalized = { key: typing.cast( DataValue, normalize_output_numbers(value, output_schema[key]) @@ -1096,18 +1097,15 @@ def _executor_return_options(self) -> dict[str, object] | None: return self._executor.return_container_options(self._return_container) return None - def _convert_outputs( + def _validate_output_storage( self, output_data: dict[str, DataValue], output_schema: Schema - ) -> pa.Table: - """Convert checked outputs to a one-row Arrow table with the declared types. + ) -> None: + """Check that the outputs can be stored with their declared Arrow types. Args: output_data: The parsed outputs, already checked against ``output_schema``. output_schema: The declared output types. - Returns: - The one-row table, typed by the declared schema. - Raises: LogicalSetCanonicalOrderError: If an output's logical set has no canonical storage order. The converter names the column. @@ -1117,9 +1115,12 @@ def _convert_outputs( """ converter = self.data_context.type_converter try: - return converter.python_dicts_to_arrow_table( - [output_data], python_schema=output_schema - ) + if isinstance(converter, UniversalTypeConverter): + converter._validate_output_storage(output_data, output_schema) + else: + converter.python_dicts_to_arrow_table( + [output_data], python_schema=output_schema + ) except LogicalSetCanonicalOrderError: raise except Exception as exc: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index d0d063a81..c3f6667ff 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -53,6 +53,7 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data +from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, @@ -1547,6 +1548,7 @@ def _table_from_pairs( tag_tables: list[pa.Table] = [] all_data = [] data_schema = None + tag_columns = ColumnConfig(system_tags=True) # A data-tag that falls through the pod is one column: it is laid # out from the tags, with its exact Arrow type, never converted from its # Python value (ITL-1023). @@ -1558,9 +1560,11 @@ def _table_from_pairs( data_schema = pa.schema(f for f in data_schema if f.name not in shared) # Tags are passed through untouched: each row's own Arrow table keeps # the input's tag types, a logical type included (ITL-928). - tag_tables.append(tag.as_table(columns={"system_tags": True})) + tag_tables.append(tag.as_table(columns=tag_columns)) row = data.as_dict(all_info=True) - all_data.append({k: v for k, v in row.items() if k not in shared}) + all_data.append( + {k: v for k, v in row.items() if k not in shared} if shared else row + ) # TODO: re-verify the implemetation of this conversion converter = self.data_context.type_converter @@ -1572,11 +1576,19 @@ def _table_from_pairs( # (meta, source info) are typed from their values. python_schema = dict(infer_python_schema_from_pylist_data(all_data)) python_schema.update(self.output_schema()[1]) - struct_data = converter.python_dicts_to_struct_dicts( - all_data, python_schema=python_schema - ) all_tags_as_tables = arrow_utils.concat_tables_by_name(tag_tables) - all_data_as_tables = arrow_utils.table_from_storage(struct_data, data_schema) + assert data_schema is not None + if isinstance(converter, UniversalTypeConverter): + all_data_as_tables = converter._storage_table( + all_data, python_schema, data_schema + ) + else: + struct_data = converter.python_dicts_to_struct_dicts( + all_data, python_schema=python_schema + ) + all_data_as_tables = arrow_utils.table_from_storage( + struct_data, data_schema + ) return arrow_utils.hstack_tables(all_tags_as_tables, all_data_as_tables) def as_table( diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index e4d5bf76b..d79ea3889 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -65,6 +65,7 @@ from orcapod.semantic_types.canonical_order import ( _in_logical_set, _ordered_set_column, + _validate_set_storage, ordered_set_storage, sort_set_elements, ) @@ -389,11 +390,7 @@ def python_to_storage( if value is None: return [] if self._orders_stored_sets: - token = _in_logical_set.set(True) - try: - elements = self._encode_elements(value, converter) - finally: - _in_logical_set.reset(token) + elements = self._encode_set_elements(value, converter) return ordered_set_storage(elements, self._storage_type.value_type) if converter is None: @@ -412,6 +409,24 @@ def python_to_storage( return sort_set_elements(elements) + def _encode_set_elements( + self, value: Any, converter: TypeConverterProtocol | None + ) -> list[Any]: + """Encode elements with storage-based ordering for nested containers.""" + token = _in_logical_set.set(True) + try: + return self._encode_elements(value, converter) + finally: + _in_logical_set.reset(token) + + def _validate_python_set( + self, value: Any, converter: TypeConverterProtocol + ) -> None: + """Validate one set after Arrow coercion so it can be emitted as a Python value.""" + _validate_set_storage( + self._encode_set_elements(value, converter), self._storage_type.value_type + ) + def _encode_elements( self, value: Any, converter: TypeConverterProtocol | None ) -> list[Any]: diff --git a/src/orcapod/semantic_types/canonical_order.py b/src/orcapod/semantic_types/canonical_order.py index a91326b04..17dc17d47 100644 --- a/src/orcapod/semantic_types/canonical_order.py +++ b/src/orcapod/semantic_types/canonical_order.py @@ -150,18 +150,47 @@ def _list_sort_column( ) -> pa.Array[Any]: """Use one lexicographic key per stored list, comparing only its own children.""" children = _sort_columns(array.flatten()) - lengths = pc.list_value_length(array) if len(children) == 1 and ( pa.types.is_integer(children[0].type) or pa.types.is_floating(children[0].type) or pa.types.is_boolean(children[0].type) + or pa.types.is_string(children[0].type) + or pa.types.is_large_string(children[0].type) ): # Dense rank compares list items lexicographically, with null items first # and equal lists sharing a rank. List validity stays separate from length. + if isinstance(array, pa.LargeListArray) and not array.null_count: + offsets = array.offsets + if array.offset or offsets[0].as_py() != 0: + offsets = pc.subtract(offsets, offsets[0]) + child = children[0] + if pa.types.is_integer(child.type) and not child.null_count: + # Rank short, fixed-width keys as scalar fields. This avoids + # comparing and hashing a separate list for every child. + width, remainder = divmod(len(child), len(array)) + if 1 < width <= 4 and not remainder: + lengths_match = pc.equal( + pc.list_value_length(array), pa.scalar(width) + ) + if pc.all(lengths_match).as_py(): + items = child.to_numpy().reshape(-1, width) + return ( + pl.DataFrame( + {f"item_{i}": items[:, i] for i in range(width)} + ) + .to_struct() + .rank("dense") + .to_arrow() + ) + lists = pa.LargeListArray.from_arrays(offsets, children[0]) + return pl.Series(lists).rank("dense").to_arrow() # Rebuild offsets over the flattened children, which omit null parent lists. offsets = pc.cumulative_sum( pa.concat_arrays( - [pa.array([0], type=pa.int64()), lengths.cast(pa.int64()).fill_null(0)] + [ + pa.array([0], type=pa.int64()), + pc.list_value_length(array).cast(pa.int64()).fill_null(0), + ] ) ) lists = pa.LargeListArray.from_arrays( @@ -179,7 +208,7 @@ def _list_sort_column( ) keys = [ None if length is None else tuple(islice(child_keys, length)) - for length in lengths.to_pylist() + for length in pc.list_value_length(array).to_pylist() ] return _ordinal_column(keys) @@ -274,6 +303,21 @@ def ordered_set_storage( raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc +def _validate_set_storage(elements: list[Any], storage_type: pa.DataType) -> None: + """Check an output row's stored keys for collisions without ordering the row.""" + if not elements: + return + try: + array = pa.array(elements, type=storage_type) + columns = _sort_columns(array) + if len(array) > 1: + keys = zip(*(column.to_pylist() for column in columns), strict=True) + if len(set(keys)) != len(array): + raise LogicalSetCanonicalOrderError("duplicate key or set element") + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + + def _ordered_dict_storage( entries: list[dict[str, Any]], entry_type: pa.DataType ) -> pa.Array[Any]: diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 192edb680..6c4327801 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -74,13 +74,19 @@ def python_dicts_to_struct_dicts( """ Convert a list of Python dictionaries to a list of Arrow-compatible struct dictionaries. """ + return self._convert_rows(data, self._python_to_arrow_converters) + + def _convert_rows( + self, data: list[dict[str, Any]], converters: dict[str, Callable[[Any], Any]] + ) -> list[dict[str, Any]]: + """Apply the selected precomputed converters, keeping missing cells null.""" if not data: raise ValueError("Cannot convert empty data list") converted_data = [] for record in data: converted_record = {} - for field_name, converter in self._python_to_arrow_converters.items(): + for field_name, converter in converters.items(): # TODO: test the case of None/missing value value = record.get(field_name) if value is None: @@ -147,9 +153,22 @@ def python_dicts_to_arrow_table( when the caller needs to enforce specific field types or nullable flags that differ from what was inferred at construction time. """ + schema = arrow_schema or self.arrow_schema + encoded_columns = self.universal_converter._encode_set_columns( + data, self.python_schema, schema, allow_explicit_null=True + ) + converters = self._python_to_arrow_converters + if encoded_columns: + encoded_names = {schema.field(index).name for index in encoded_columns} + converters = { + name: converter + for name, converter in converters.items() + if name not in encoded_names + } return table_from_storage( - self.python_dicts_to_struct_dicts(data), - arrow_schema or self.arrow_schema, + self._convert_rows(data, converters), + schema, + encoded_columns=encoded_columns, ) def arrow_table_to_python_dicts(self, table: pa.Table) -> list[dict[str, Any]]: diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index cfb92d081..7335f1047 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1405,15 +1405,74 @@ def _storage_table( arrow_schema: pa.Schema, ) -> pa.Table: """Batch logical set columns and convert the remaining cells as usual.""" + encoded_columns = self._encode_set_columns(rows, python_schema, arrow_schema) + encoded_names = {arrow_schema.field(index).name for index in encoded_columns} + remaining_schema = ( + { + name: annotation + for name, annotation in python_schema.items() + if name not in encoded_names + } + if encoded_columns + else python_schema + ) + struct_dicts = self.python_dicts_to_struct_dicts(rows, remaining_schema) + return arrow_utils.table_from_storage( + struct_dicts, arrow_schema, encoded_columns=encoded_columns + ) + + def _validate_output_storage( + self, row: dict[str, Any], python_schema: SchemaLike + ) -> None: + """Validate a function's output row before exposing its Python values.""" + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + + validated = set() + for name, annotation in python_schema.items(): + value = row.get(name) + if not isinstance(value, set): + continue + if get_origin(annotation) in (typing.Union, types.UnionType): + args = get_args(annotation) + if len(args) == 2 and type(None) in args: + annotation = next(arg for arg in args if arg is not type(None)) + logical_type = self.get_logical_type(typing.cast(type, annotation)) + if ( + not isinstance(logical_type, ListLogicalType) + or not logical_type._orders_stored_sets + ): + continue + try: + logical_type._validate_python_set(value, self) + except CanonicalOrderError as exc: + raise type(exc)(f"Column {name!r}: {exc}") from exc + validated.add(name) + + if not validated: + self.python_dicts_to_arrow_table([row], python_schema=python_schema) + elif len(validated) != len(python_schema): + remaining = { + name: annotation + for name, annotation in python_schema.items() + if name not in validated + } + self.python_dicts_to_arrow_table([row], python_schema=remaining) + + def _encode_set_columns( + self, + rows: list[dict[str, Any]], + python_schema: SchemaLike, + arrow_schema: pa.Schema, + *, + allow_explicit_null: bool = False, + ) -> dict[int, pa.Array[Any]]: + """Encode each canonical set column in one pass, by Arrow field index.""" if len(rows) <= 1 or self._logical_type_registry is None: - return arrow_utils.table_from_storage( - self.python_dicts_to_struct_dicts(rows, python_schema), arrow_schema - ) + return {} from orcapod.logical_types.list_logical_type_factory import ListLogicalType encoded_columns: dict[int, pa.Array[Any]] = {} - remaining_schema = dict(python_schema) registry = self._logical_type_registry for index, field in enumerate(arrow_schema): field_type = field.type @@ -1421,8 +1480,8 @@ def _storage_table( field_type, pa.ExtensionType ) or not field_type.extension_name.startswith("set["): continue - annotation = remaining_schema.get(field.name) - nullable = False + annotation = python_schema.get(field.name) + nullable = allow_explicit_null if get_origin(annotation) in (typing.Union, types.UnionType): args = get_args(annotation) if len(args) == 2 and type(None) in args: @@ -1452,12 +1511,7 @@ def _storage_table( except UnsupportedValueError as exc: raise UnsupportedValueError(f"Column {field.name!r}: {exc}") from exc encoded_columns[index] = pa.ExtensionArray.from_storage(field_type, storage) - del remaining_schema[field.name] - - struct_dicts = self.python_dicts_to_struct_dicts(rows, remaining_schema) - return arrow_utils.table_from_storage( - struct_dicts, arrow_schema, encoded_columns=encoded_columns - ) + return encoded_columns def arrow_table_to_python_dicts( self, arrow_table: pa.Table diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index d9a31bef8..c39cf905e 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -32,6 +32,8 @@ from typing import Any, Literal, NamedTuple, cast import numpy as np +import pyarrow as pa +import pyarrow.compute as pc import pytest from pydantic import BaseModel @@ -1281,3 +1283,43 @@ def test_logical_set_output_reports_nested_dict_nan() -> None: ).pod(make_source()) with pytest.raises(errors.CanonicalOrderError, match=r"Column 'y': .*NaN"): list(stream.iter_data()) + + +@dataclass(frozen=True) +class SetOutputPoint: + value: int + + +def test_function_table_sorts_logical_sets_by_column( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Table assembly orders the populated stream in one column-wide pass.""" + stream = make_pod( + set[SetOutputPoint], {SetOutputPoint(10), SetOutputPoint(2)}, name="points" + ).pod(make_source(tuple(range(32)))) + sort_indices = pc.sort_indices + sizes: list[int] = [] + + def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: + sizes.append(table.num_rows) + return sort_indices(table, *args, **kwargs) + + monkeypatch.setattr(pc, "sort_indices", record_size) + assert len(list(stream.iter_data())) == 32 + table = stream.as_table() + assert sizes == [64] + assert table["y"].to_pylist() == [[{"value": 2}, {"value": 10}]] * 32 + + +@dataclass(frozen=True, eq=False) +class SetOutputFloat: + value: float + + +def test_function_iteration_refuses_equal_logical_set_storage() -> None: + """A row-only consumer still sees a column-qualified duplicate error.""" + stream = make_pod( + set[SetOutputFloat], {SetOutputFloat(-0.0), SetOutputFloat(0.0)}, name="points" + ).pod(make_source()) + with pytest.raises(errors.CanonicalOrderError, match=r"Column 'y': .*duplicate"): + next(stream.iter_data()) diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index 4d78729c0..d4d800107 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -29,6 +29,7 @@ import numpy as np import polars as pl import pyarrow as pa +import pyarrow.compute as pc import pydantic import pytest from typing_extensions import override @@ -870,44 +871,84 @@ class WithDict: writer.python_dicts_to_arrow_table([{"bad": {WithDict({float("nan"): 1})}}]) -def test_numeric_list_keys_skip_python_ranking(monkeypatch: pytest.MonkeyPatch) -> None: - """Rank variable-width nullable numeric list keys without decoding Python values.""" +@pytest.mark.parametrize( + ("item_type", "low", "high"), + [(pa.float64(), -2.0, 1.0), (pa.large_string(), "A", "火")], +) +def test_list_keys_skip_python_ranking( + monkeypatch: pytest.MonkeyPatch, item_type: pa.DataType, low: Any, high: Any +) -> None: + """Rank variable-width nullable list keys without decoding Python values.""" from orcapod.semantic_types import canonical_order def unexpected(_keys: object) -> Never: - pytest.fail("numeric list keys entered Python ranking") + pytest.fail("scalar list keys entered Python ranking") monkeypatch.setattr(canonical_order, "_ordinal_column", unexpected) - shape = pa.struct([("items", pa.large_list(pa.float64())), ("value", pa.int64())]) + shape = pa.struct([("items", pa.large_list(item_type)), ("value", pa.int64())]) + tied = -0.0 if pa.types.is_floating(item_type) else low + first = 0.0 if pa.types.is_floating(item_type) else low rows = [ - {"items": [0.0, 1.0], "value": 0}, + {"items": [first, high], "value": 0}, {"items": [None], "value": 0}, {"items": None, "value": 0}, - {"items": [-0.0], "value": 2}, + {"items": [tied], "value": 2}, {"items": [], "value": 0}, - {"items": [0.0], "value": 1}, - {"items": [None, -2.0], "value": 0}, + {"items": [first], "value": 1}, + {"items": [None, low], "value": 0}, ] result = ordered_set_storage(rows, shape) assert result.equals(pa.array([rows[i] for i in (2, 4, 1, 6, 5, 3, 0)], type=shape)) -def test_small_logical_sets_share_one_sort(monkeypatch: pytest.MonkeyPatch) -> None: +@pytest.mark.parametrize("precomputed", [False, True]) +def test_small_logical_sets_share_one_sort( + monkeypatch: pytest.MonkeyPatch, precomputed: bool +) -> None: """Sort all rows of a flat set column in one pass without mixing their values.""" - from orcapod.semantic_types import canonical_order + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter - sort_indices = canonical_order.pc.sort_indices + sort_indices = pc.sort_indices sizes: list[int] = [] def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: sizes.append(table.num_rows) return sort_indices(table, *args, **kwargs) - monkeypatch.setattr(canonical_order.pc, "sort_indices", record_size) + monkeypatch.setattr(pc, "sort_indices", record_size) small = ExactPoint(2, "x") large = ExactPoint(10, "y") - table = get_default_context().type_converter.python_dicts_to_arrow_table( - [{"s": {small, large}} for _ in range(32)], python_schema={"s": set[ExactPoint]} - ) + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema: dict[str, Any] = {"s": set[ExactPoint]} + rows = [{"s": {small, large}} for _ in range(32)] + converter.ensure_types_registered_for_schemas(Schema(schema)) + if precomputed: + writer = SemanticSchemaConverter(converter, python_schema=schema) + table = writer.python_dicts_to_arrow_table(rows) + else: + table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) assert sizes == [64] assert table["s"].to_pylist() == [[{"a": 2, "b": "x"}, {"a": 10, "b": "y"}]] * 32 + + +def test_fixed_width_integer_list_keys_rank_columns( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Project uniform integer lists into native scalar columns before ranking.""" + rank = pl.Series.rank + ranked_types: list[pl.DataType] = [] + + def record_type(series: pl.Series, *args: Any, **kwargs: Any) -> pl.Series: + ranked_types.append(series.dtype) + return rank(series, *args, **kwargs) + + monkeypatch.setattr(pl.Series, "rank", record_type) + shape = pa.large_list(pa.large_list(pa.int64())) + rows = [[[0, -7], [5, 0]], [[0, -7]], [[-5, 500]], [[0, -8]]] + result = ordered_set_storage(rows, shape) + assert result.equals(pa.array([rows[i] for i in (2, 3, 1, 0)], type=shape)) + assert ranked_types == [ + pl.Struct({"item_0": pl.Int64, "item_1": pl.Int64}), + pl.List(pl.UInt32), + ] From c9daaa5b85ef11aa5ca6a3b85d72b1b3e89ae810 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:05:21 -0800 Subject: [PATCH 06/18] perf(logical_types): batch canonical ordering for struct sets --- .zed/rules | 6 +- CLAUDE.md | 6 +- changelog.d/ITL-922.md | 9 +- docs/dev/design_issues/ITL-922-DO2.md | 12 +- docs/reference/hashing.md | 9 +- .../list_logical_type_factory.py | 173 ++++++--- .../logical_types/user_class_logical_type.py | 7 +- src/orcapod/semantic_types/canonical_order.py | 328 +++++++++++++----- .../semantic_types/universal_converter.py | 27 +- src/orcapod/utils/arrow_utils.py | 2 +- .../test_set_of_logical_elements.py | 138 +++++++- 11 files changed, 526 insertions(+), 191 deletions(-) diff --git a/.zed/rules b/.zed/rules index d70ed57d7..243cec0ea 100644 --- a/.zed/rules +++ b/.zed/rules @@ -385,12 +385,12 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. -- Sets of user-defined logical types use `canonical_order.ordered_set_storage` after +- Sets of struct-stored logical types use `canonical_order.ordered_set_storage` after coercion to the declared Arrow type (ITL-922). Compare structs by declared field order and lists by item order, recursively. Class comparators have no effect. A NaN at any depth, duplicate storage values or incomparable values raise `CanonicalOrderError`. - The caller adds the column. Path, UPath, UUID, File and Directory sets keep their native - scalar sort. + Other logical sets keep their native sort. Sets of user-defined scalar-stored types + also reject NaNs and duplicate storage values after coercion. The caller adds the column. - `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611): `ListLogicalType` over an `ArrowElement`, extension name `set[]` (`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer, diff --git a/CLAUDE.md b/CLAUDE.md index 2a0a8215c..c22946dfc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -396,12 +396,12 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. -- Sets of user-defined logical types use `canonical_order.ordered_set_storage` after +- Sets of struct-stored logical types use `canonical_order.ordered_set_storage` after coercion to the declared Arrow type (ITL-922). Compare structs by declared field order and lists by item order, recursively. Class comparators have no effect. A NaN at any depth, duplicate storage values or incomparable values raise `CanonicalOrderError`. - The caller adds the column. Path, UPath, UUID, File and Directory sets keep their native - scalar sort. + Other logical sets keep their native sort. Sets of user-defined scalar-stored types + also reject NaNs and duplicate storage values after coercion. The caller adds the column. - `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611): `ListLogicalType` over an `ArrowElement`, extension name `set[]` (`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer, diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 2fd0ab702..405e783a9 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -7,10 +7,13 @@ ### Fixed -- Sets of user-defined logical types are ordered after Arrow coerces each element +- Sets of struct-stored logical types are ordered after Arrow coerces each element to the declared storage type (ITL-922). The sort descends into nested structs and lists, with `None` first. Nested dict keys and set items are ordered after coercion too. A NaN at any depth, incomparable values, or two keys or elements with equal storage raise `CanonicalOrderError` naming the column. -- Table conversion orders logical set columns in batches. Text list fields and - short fixed-width integer list keys use native ranking. +- Sets of user-defined scalar-stored types keep their native sort and reject + NaNs or duplicate storage values after Arrow coercion. +- Table conversion batches struct-set columns and lists of struct sets. + Nested dictionary keys, set items, and list comparison keys use Arrow + or Polars kernels. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index d2cea4277..3383b33e7 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -10,15 +10,15 @@ Struct storage fell back to representation-text order, which put a field with enter storage. A scalar-stored logical type could also admit NaNs and equal storage values. -**Fix:** Apply canonical order after coercion to the declared Arrow element type. +**Fix:** Apply canonical order to struct-stored elements after Arrow coercion. Sort the struct fields in declared order and use a lexicographic key for each list field. Sort nested dict keys and set items in their own declared storage types before comparing the enclosing elements. Check adjacent sorted values for duplicates within each set. Multi-row table conversion encodes and sorts each set column in one pass, including precomputed and function-stream tables. Function iteration validates each row's stored keys before yielding it. -The five built-in scalar-stored types keep their -native sort for standalone sets. The same order applies to classes rebuilt -from metadata. Reject NaNs at any depth, incomparable values and duplicate -storage values. The conversion boundary supplies the column name. Rebuilding -sets of user classes can change affected row hashes. +Sets of other logical types keep their native sort. For user-defined scalar +storage, one Arrow pass per table column rejects NaNs and duplicate stored +values. The same ordering rules apply to classes rebuilt from metadata. +The conversion boundary supplies the column name. Rebuilding sets of user +classes can change affected row hashes. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index f7e08fe09..836016331 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1016,7 +1016,7 @@ orders for equal hashed inputs; reconstructing user-class instances is outside t | List inside a set element | item by item, with a shorter prefix first | Struct fields and list items follow the same rules recursively, including `None` first. -For a set of user-defined logical values, Orcapod coerces each element to its declared Arrow +For a set of struct-stored logical values, Orcapod coerces each element to its declared Arrow type before comparing it. Python class comparators such as those generated by `@dataclass(order=True)` do not participate. Nested dict keys and set items are also ordered in their declared storage types. Two keys or items that coerce to the same @@ -1024,9 +1024,10 @@ stored value are refused before they can collapse on read. A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`), including a NaN anywhere inside a set element, has no order -and raises `CanonicalOrderError` (a `ValueError`) naming the column. Primitive containers -and sets of user-defined logical values also reject incomparable values and duplicate -storage keys. Sets of Path, UPath, UUID, File and Directory keep their native scalar sort. +and raises `CanonicalOrderError` (a `ValueError`) naming the column for primitive containers +and struct-stored sets. Those containers also reject incomparable values and duplicate +storage keys. Sets of scalar-stored logical types keep their native sort. For user-defined +scalar types, Arrow validation also rejects NaNs and duplicate storage values. For user-class sets written with the old representation-text order, rebuilding the data can change row hashes and cause affected cached results to be recomputed (ITL-922). diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index d79ea3889..046b6c56b 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -63,7 +63,9 @@ make_polars_extension_type, ) from orcapod.semantic_types.canonical_order import ( + _StorageNormalizer, _in_logical_set, + _nested_unordered_order, _ordered_set_column, _validate_set_storage, ordered_set_storage, @@ -146,15 +148,20 @@ class ListLogicalType(BaseLogicalType): binds_python_type: bool = True - # These fixed encoders return sortable strings or bytes. Keep their native - # sort, including the existing behavior for aliases of the same stored value. - _NATIVE_SORT_TYPES = frozenset( + # Built-in encoders keep their existing native sort and storage semantics. + _BUILTIN_ELEMENTS = frozenset( ( "orcapod.path", "orcapod.upath", "orcapod.uuid", "orcapod.file", "orcapod.directory", + "orcapod.numpy.ndarray", + "orcapod.pandas.dataframe", + "orcapod.pandas.series", + "orcapod.polars.dataframe", + "orcapod.polars.series", + "orcapod.torch.tensor", ) ) @@ -165,15 +172,9 @@ def __init__( is_set: bool = False, ) -> None: self._is_set = is_set - self._uses_native_sort = ( - not isinstance(element_logical_type, ArrowElement) - and element_logical_type.logical_type_name in self._NATIVE_SORT_TYPES - ) - self._orders_stored_sets = ( - is_set - and not self._uses_native_sort - and not isinstance(element_logical_type, ArrowElement) - ) + self._orders_stored_sets = False + self._batches_sets = False + self._batched_element: ListLogicalType | None = None self._arrow_ext: pa.ExtensionType | None = None self._polars_ext: pl.BaseExtension | None = None @@ -240,6 +241,21 @@ def _container_metadata(element_metadata: bytes) -> bytes: # Derive storage type: large_list of the element's storage type (not extension type). element_storage = element_ext_type.storage_type self._storage_type = pa.large_list(element_storage) + self._orders_stored_sets = is_set and pa.types.is_struct(element_storage) + self._batches_sets = is_set and ( + self._orders_stored_sets + or ( + not isinstance(element_logical_type, ListLogicalType) + and element_ext_name not in self._BUILTIN_ELEMENTS + ) + ) + if ( + not is_set + and isinstance(element_logical_type, ListLogicalType) + and element_logical_type._batches_sets + ): + self._batched_element = element_logical_type + self._batches_sets = True # Compose the extension name from the category and element extension name. self._logical_type_name = f"{category}[{element_ext_name}]" @@ -389,30 +405,52 @@ def python_to_storage( """ if value is None: return [] - if self._orders_stored_sets: - elements = self._encode_set_elements(value, converter) - return ordered_set_storage(elements, self._storage_type.value_type) + if self._batches_sets and not _in_logical_set.get(): + if self._batched_element is not None: + if converter is None: + return list(value) + return self._batched_element._python_values_to_storage( + list(value), converter, nested=True + ) + if self._orders_stored_sets: + elements = self._encode_struct_set(value, converter) + return ordered_set_storage( + elements, + self._storage_type.value_type, + normalize=self._normalizer(converter), + ) + elements = self._native_sort(self._encode_elements(value, converter)) + return _validate_set_storage(elements, self._storage_type.value_type) - if converter is None: - elements = list(value) - else: - elements = [ - converter.python_to_storage(item, self._element_python_type) - for item in value - ] - if not self._is_set: - return elements - if _in_logical_set.get(): - return ordered_set_storage(elements, self._storage_type.value_type) - if self._uses_native_sort: + elements = self._encode_elements(value, converter) + if self._is_set: + if _in_logical_set.get(): + return elements + if self._element_logical_type is None: + return sort_set_elements(elements) + return self._native_sort(elements) + return elements + + @staticmethod + def _native_sort(elements: list[Any]) -> list[Any]: + """Keep the original logical set order for non-struct elements.""" + try: return sorted(elements) - - return sort_set_elements(elements) - - def _encode_set_elements( + except TypeError: + return sorted(elements, key=repr) + + def _normalizer( + self, converter: TypeConverterProtocol | None + ) -> _StorageNormalizer | None: + """Resolve only fields whose declared containers are unordered.""" + if converter is None or self._element_logical_type is None: + return None + return _nested_unordered_order(self._element_logical_type, converter) + + def _encode_struct_set( self, value: Any, converter: TypeConverterProtocol | None ) -> list[Any]: - """Encode elements with storage-based ordering for nested containers.""" + """Encode a struct set, deferring nested ordering until Arrow coercion.""" token = _in_logical_set.set(True) try: return self._encode_elements(value, converter) @@ -422,10 +460,14 @@ def _encode_set_elements( def _validate_python_set( self, value: Any, converter: TypeConverterProtocol ) -> None: - """Validate one set after Arrow coercion so it can be emitted as a Python value.""" - _validate_set_storage( - self._encode_set_elements(value, converter), self._storage_type.value_type - ) + """Validate a struct set before it is emitted as a Python value.""" + if value: + _validate_set_storage( + self._encode_struct_set(value, converter), + self._storage_type.value_type, + normalize=self._normalizer(converter), + struct_elements=True, + ) def _encode_elements( self, value: Any, converter: TypeConverterProtocol | None @@ -438,19 +480,54 @@ def _encode_elements( for item in value ] - def _python_sets_to_storage( - self, values: list[Any], converter: TypeConverterProtocol + def _python_values_to_storage( + self, + values: list[Any], + converter: TypeConverterProtocol, + *, + nested: bool = False, ) -> pa.LargeListArray[Any]: - """Encode and order a column of sets in one Arrow pass.""" - token = _in_logical_set.set(True) - try: - rows = [ - None if value is None else self._encode_elements(value, converter) - for value in values - ] - finally: - _in_logical_set.reset(token) - return _ordered_set_column(rows, self._storage_type) + """Encode all sets at this nesting level in one Arrow pass.""" + if nested and any(value is None for value in values): + # The ordinary converter rejects null elements of these declared + # lists before calling their registered storage encoder. + converter.python_to_storage(None, self.python_type) + if self._batched_element is not None: + offsets = [0] + items: list[Any] = [] + for value in values: + if value is not None: + items.extend(value) + offsets.append(len(items)) + return pa.LargeListArray.from_arrays( + pa.array(offsets, type=pa.int64()), + self._batched_element._python_values_to_storage( + items, converter, nested=True + ), + type=self._storage_type, + mask=pa.array([value is None for value in values], type=pa.bool_()), + ) + + if self._orders_stored_sets: + token = _in_logical_set.set(True) + try: + rows = [ + None if value is None else self._encode_elements(value, converter) + for value in values + ] + finally: + _in_logical_set.reset(token) + return _ordered_set_column( + rows, self._storage_type, normalize=self._normalizer(converter) + ) + + rows = [ + None + if value is None + else self._native_sort(self._encode_elements(value, converter)) + for value in values + ] + return _ordered_set_column(rows, self._storage_type, order=False) def storage_to_python( self, storage_value: Any, converter: TypeConverterProtocol | None diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 7f9578b3b..6addac401 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -114,7 +114,7 @@ def __init__( self._logical_name = logical_name self._python_type = python_type self._storage_type = storage_type - self._field_annotations = field_annotations + self._field_annotations = tuple(field_annotations) self._identity_record = identity_record metadata: dict[str, Any] = {"category": self.category} @@ -144,6 +144,11 @@ def identity_record(self) -> dict[str, Any] | None: """The identity record, or ``None`` for a logical type built without one.""" return self._identity_record + @property + def field_annotations(self) -> tuple[tuple[str, Any], ...]: + """The declared annotations of stored fields, in storage order.""" + return self._field_annotations + @property def storage_type(self) -> pa.StructType: """The Arrow struct type of the stored fields.""" diff --git a/src/orcapod/semantic_types/canonical_order.py b/src/orcapod/semantic_types/canonical_order.py index 17dc17d47..55993edd9 100644 --- a/src/orcapod/semantic_types/canonical_order.py +++ b/src/orcapod/semantic_types/canonical_order.py @@ -30,11 +30,11 @@ import numbers import types import typing -from collections.abc import Callable +from collections.abc import Callable, Sequence from contextvars import ContextVar from decimal import Decimal -from itertools import islice, pairwise -from typing import Any, TypeVar, cast, get_args, get_origin +from itertools import pairwise +from typing import TYPE_CHECKING, Any, TypeVar, cast, get_args, get_origin import polars as pl import pyarrow as pa @@ -42,7 +42,14 @@ from orcapod.errors import CanonicalOrderError, LogicalSetCanonicalOrderError +if TYPE_CHECKING: + from orcapod.logical_types.protocols import ( + LogicalTypeProtocol, + TypeConverterProtocol, + ) + _T = TypeVar("_T") +_StorageNormalizer = Callable[["pa.Array[Any]"], "pa.Array[Any]"] # A sort key: ``(0,)`` for None, ``(1, value)`` otherwise. _Rank = tuple[Any, ...] @@ -150,67 +157,73 @@ def _list_sort_column( ) -> pa.Array[Any]: """Use one lexicographic key per stored list, comparing only its own children.""" children = _sort_columns(array.flatten()) - if len(children) == 1 and ( - pa.types.is_integer(children[0].type) - or pa.types.is_floating(children[0].type) - or pa.types.is_boolean(children[0].type) - or pa.types.is_string(children[0].type) - or pa.types.is_large_string(children[0].type) - ): - # Dense rank compares list items lexicographically, with null items first - # and equal lists sharing a rank. List validity stays separate from length. - if isinstance(array, pa.LargeListArray) and not array.null_count: - offsets = array.offsets - if array.offset or offsets[0].as_py() != 0: - offsets = pc.subtract(offsets, offsets[0]) - child = children[0] - if pa.types.is_integer(child.type) and not child.null_count: - # Rank short, fixed-width keys as scalar fields. This avoids - # comparing and hashing a separate list for every child. - width, remainder = divmod(len(child), len(array)) - if 1 < width <= 4 and not remainder: - lengths_match = pc.equal( - pc.list_value_length(array), pa.scalar(width) + # Polars ranks lists of native scalar keys. Use Arrow dense ranks for + # child types whose representation Polars cannot rank inside a list. + children = [ + child + if ( + pa.types.is_integer(child.type) + or pa.types.is_floating(child.type) + or pa.types.is_boolean(child.type) + or pa.types.is_string(child.type) + or pa.types.is_large_string(child.type) + or pa.types.is_binary(child.type) + or pa.types.is_large_binary(child.type) + ) + else pc.rank(child, tiebreaker="dense", null_placement="at_start") + for child in children + ] + if len(children) == 1: + child = children[0] + else: + # A list of struct-key ranks preserves the original lexicographic + # order. Rank the columns before putting them inside a list. + child = ( + pl.DataFrame(pa.table({str(i): col for i, col in enumerate(children)})) + .to_struct() + .rank("dense") + .to_arrow() + ) + if isinstance(array, pa.LargeListArray) and not array.null_count: + offsets = array.offsets + if array.offset or offsets[0].as_py() != 0: + offsets = pc.subtract(offsets, offsets[0]) + if ( + len(children) == 1 + and pa.types.is_integer(child.type) + and not child.null_count + ): + # Rank short, fixed-width keys as scalar fields instead of lists. + width, remainder = divmod(len(child), len(array)) + if 1 < width <= 4 and not remainder: + lengths_match = pc.equal(pc.list_value_length(array), pa.scalar(width)) + if pc.all(lengths_match).as_py(): + items = child.to_numpy().reshape(-1, width) + return ( + pl.DataFrame({f"item_{i}": items[:, i] for i in range(width)}) + .to_struct() + .rank("dense") + .to_arrow() ) - if pc.all(lengths_match).as_py(): - items = child.to_numpy().reshape(-1, width) - return ( - pl.DataFrame( - {f"item_{i}": items[:, i] for i in range(width)} - ) - .to_struct() - .rank("dense") - .to_arrow() - ) - lists = pa.LargeListArray.from_arrays(offsets, children[0]) - return pl.Series(lists).rank("dense").to_arrow() - # Rebuild offsets over the flattened children, which omit null parent lists. - offsets = pc.cumulative_sum( - pa.concat_arrays( - [ - pa.array([0], type=pa.int64()), - pc.list_value_length(array).cast(pa.int64()).fill_null(0), - ] - ) + return ( + pl.Series(pa.LargeListArray.from_arrays(offsets, child)) + .rank("dense") + .to_arrow() ) - lists = pa.LargeListArray.from_arrays( - cast(pa.Int64Array, offsets), children[0], mask=pc.is_null(array) + + # Rebuild offsets over the flattened children, which omit null parent lists. + offsets = pc.cumulative_sum( + pa.concat_arrays( + [ + pa.array([0], type=pa.int64()), + pc.list_value_length(array).cast(pa.int64()).fill_null(0), + ] ) - return pl.Series(lists).rank("dense").to_arrow() - # All child columns hold built-in scalars. Tag nulls to put them first, including - # inside nested lists. The tuple comparison gives a proper prefix precedence. - child_keys = zip( - *( - [(value is not None, value) for value in column.to_pylist()] - for column in children - ), - strict=True, ) - keys = [ - None if length is None else tuple(islice(child_keys, length)) - for length in pc.list_value_length(array).to_pylist() - ] - return _ordinal_column(keys) + lists = pa.LargeListArray.from_arrays( + cast(pa.Int64Array, offsets), child, mask=pc.is_null(array) + ) + return pl.Series(lists).rank("dense").to_arrow() def _sort_columns(array: pa.Array[Any]) -> list[pa.Array[Any]]: @@ -280,13 +293,17 @@ def _adjacent_equal(array: pa.Array[Any]) -> pa.BooleanArray: def ordered_set_storage( - elements: list[Any], storage_type: pa.DataType + elements: list[Any], + storage_type: pa.DataType, + *, + normalize: _StorageNormalizer | None = None, ) -> pa.Array[Any]: """Encode a logical set's elements once and return them in canonical order. Args: elements: The converted elements of one logical set. storage_type: The declared Arrow element storage type. + normalize: Orders nested unordered fields once their values are encoded. Returns: The exact Arrow storage values, in canonical order. @@ -297,64 +314,183 @@ def ordered_set_storage( """ try: array = pa.array(elements, type=storage_type) + if normalize is not None: + array = normalize(array) columns = _sort_columns(array) return _sort_set_array(array, columns) if len(array) > 1 else array except (TypeError, pa.ArrowException) as exc: raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc -def _validate_set_storage(elements: list[Any], storage_type: pa.DataType) -> None: - """Check an output row's stored keys for collisions without ordering the row.""" - if not elements: - return +def _validate_set_storage( + elements: list[Any], + storage_type: pa.DataType, + *, + normalize: _StorageNormalizer | None = None, + struct_elements: bool = False, +) -> pa.Array[Any]: + """Validate the stored keys of one set without changing its order.""" try: array = pa.array(elements, type=storage_type) - columns = _sort_columns(array) - if len(array) > 1: - keys = zip(*(column.to_pylist() for column in columns), strict=True) - if len(set(keys)) != len(array): + keys = _sort_columns(normalize(array) if normalize is not None else array) + if struct_elements and len(array) > 1: + # Eager function output validates one row before it can be yielded. + # Hashing its flat keys avoids setting up a second Arrow table per row. + tuples = zip(*(key.to_pylist() for key in keys), strict=True) + if len(set(tuples)) != len(array): raise LogicalSetCanonicalOrderError("duplicate key or set element") + elif not struct_elements: + _require_distinct(keys) + return array except (TypeError, pa.ArrowException) as exc: raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc -def _ordered_dict_storage( - entries: list[dict[str, Any]], entry_type: pa.DataType -) -> pa.Array[Any]: - """Order typed dict entries by their keys and reject equal stored keys.""" - try: - array = cast(pa.StructArray, pa.array(entries, type=entry_type)) - columns = _sort_columns(array.field("key")) - return _sort_set_array(array, columns) if len(array) > 1 else array - except (TypeError, pa.ArrowException) as exc: - raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc +def _require_distinct(columns: list[pa.Array[Any]]) -> None: + """Check stored equality, with nulls and both signs of zero comparing equal.""" + if len(columns[0]) <= 1: + return + # Arrow grouping distinguishes IEEE zero bit patterns. Normalize only the + # comparison key so storage keeps the original sign. + keys = [ + pc.if_else( + pc.equal(column, pa.scalar(0.0, type=column.type)), + pa.scalar(0.0, type=column.type), + column, + ) + if pa.types.is_floating(column.type) + else column + for column in columns + ] + names = [str(i) for i in range(len(keys))] + table = pa.Table.from_arrays(keys, names=names) + if ( + table.group_by(names, use_threads=False).aggregate([]).num_rows + != table.num_rows + ): + raise LogicalSetCanonicalOrderError("duplicate key or set element") + + +def _list_with_values( + storage: pa.LargeListArray[Any], values: pa.Array[Any] +) -> pa.LargeListArray[Any]: + """Rebuild list storage with the same offsets, type and validity.""" + return pa.LargeListArray.from_arrays( + storage.offsets, values, type=storage.type, mask=pc.is_null(storage) + ) def _ordered_set_column( - rows: list[list[Any] | None], storage_type: pa.LargeListType[Any] + rows: list[list[Any] | None], + storage_type: pa.LargeListType[Any], + *, + normalize: _StorageNormalizer | None = None, + order: bool = True, ) -> pa.LargeListArray[Any]: - """Encode and sort the elements of a column, keeping each set in its row.""" + """Encode a column of sets, keeping each set in its row.""" try: storage = cast("pa.LargeListArray[Any]", pa.array(rows, type=storage_type)) - elements = storage.values - if len(elements) == 0: - return storage - columns = _sort_columns(elements) - if pc.max(pc.list_value_length(storage)).as_py() <= 1: - return storage - sorted_elements = _sort_set_array( - elements, [pc.list_parent_indices(storage), *columns] - ) - return pa.LargeListArray.from_arrays( - storage.offsets, - sorted_elements, - type=storage_type, - mask=pc.is_null(storage), - ) + if normalize is not None: + storage = _list_with_values(storage, normalize(storage.values)) + if order: + return _order_unordered_lists(storage) + if len(storage.values): + columns = _sort_columns(storage.values) + if pc.max(pc.list_value_length(storage)).as_py() > 1: + _require_distinct([pc.list_parent_indices(storage), *columns]) + return storage except (TypeError, pa.ArrowException) as exc: raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc +def _order_unordered_lists( + storage: pa.LargeListArray[Any], *, dict_keys: bool = False +) -> pa.LargeListArray[Any]: + """Sort and check dict keys or set items in one pass across their parents.""" + elements = storage.values + if not len(elements): + return storage + keys = cast(pa.StructArray, elements).field("key") if dict_keys else elements + columns = _sort_columns(keys) + if pc.max(pc.list_value_length(storage)).as_py() <= 1: + return storage + return _list_with_values( + storage, _sort_set_array(elements, [pc.list_parent_indices(storage), *columns]) + ) + + +def _nested_unordered_order( + logical_type: LogicalTypeProtocol, converter: TypeConverterProtocol +) -> _StorageNormalizer | None: + """Resolve the unordered fields of a struct from its declared Python annotations.""" + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType + + def struct_order( + kind: pa.StructType, fields: Sequence[tuple[str, Any]] + ) -> _StorageNormalizer | None: + operations = { + i: operation + for i, (name, annotation) in enumerate(fields) + if (operation := resolve(kind.field(name).type, annotation)) is not None + } + if not operations: + return None + + def normalize_struct(array: pa.Array[Any]) -> pa.StructArray: + struct = cast(pa.StructArray, array) + children = [struct.field(i) for i in range(kind.num_fields)] + for i, operation in operations.items(): + children[i] = operation(children[i]) + return pa.StructArray.from_arrays( + children, fields=list(kind), mask=pc.is_null(struct) + ) + + return normalize_struct + + def resolve(kind: pa.DataType, annotation: Any) -> _StorageNormalizer | None: + if not isinstance(kind, (pa.LargeListType, pa.StructType)): + return None + origin = get_origin(annotation) + args = get_args(annotation) + if origin in (typing.Union, types.UnionType): + return resolve(kind, next(arg for arg in args if arg is not type(None))) + if isinstance(kind, pa.StructType): + if origin is tuple: + return struct_order( + kind, [(f"f{i}", arg) for i, arg in enumerate(args)] + ) + child_type = converter.get_logical_type_for_python_type(annotation) + if isinstance(child_type, UserClassLogicalType): + return struct_order(kind, child_type.field_annotations) + return None + if origin not in (list, tuple, dict, set) or not args: + return None + if origin is dict: + entry_type = cast(pa.StructType, kind.value_type) + normalize_items = struct_order( + entry_type, [("key", args[0]), ("value", args[1])] + ) + else: + normalize_items = resolve(kind.value_type, args[0]) + unordered = origin in (dict, set) + if not unordered and normalize_items is None: + return None + + def normalize_list(array: pa.Array[Any]) -> pa.LargeListArray[Any]: + storage = cast("pa.LargeListArray[Any]", array) + if normalize_items is not None: + storage = _list_with_values(storage, normalize_items(storage.values)) + if unordered: + storage = _order_unordered_lists(storage, dict_keys=origin is dict) + return storage + + return normalize_list + + if isinstance(logical_type, UserClassLogicalType): + return struct_order(logical_type.storage_type, logical_type.field_annotations) + return None + + def _sort_set_array( array: pa.Array[Any], columns: list[pa.Array[Any]] ) -> pa.Array[Any]: diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 7335f1047..cf68eb098 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -35,7 +35,6 @@ ) from orcapod.semantic_types.canonical_order import ( _in_logical_set, - _ordered_dict_storage, ordered_set_storage, sort_dict_entries, sort_set_elements, @@ -1478,7 +1477,7 @@ def _encode_set_columns( field_type = field.type if not isinstance( field_type, pa.ExtensionType - ) or not field_type.extension_name.startswith("set["): + ) or not field_type.extension_name.startswith(("set[", "list[")): continue annotation = python_schema.get(field.name) nullable = allow_explicit_null @@ -1487,12 +1486,12 @@ def _encode_set_columns( if len(args) == 2 and type(None) in args: annotation = next(arg for arg in args if arg is not type(None)) nullable = True - if get_origin(annotation) is not set: + if get_origin(annotation) not in (set, list): continue logical_type = registry.get_by_python_type(typing.cast(type, annotation)) if ( not isinstance(logical_type, ListLogicalType) - or not logical_type._orders_stored_sets + or not logical_type._batches_sets or not field_type.equals(logical_type.get_arrow_extension_type()) ): continue @@ -1505,7 +1504,7 @@ def _encode_set_columns( ): continue try: - storage = logical_type._python_sets_to_storage(values, self) + storage = logical_type._python_values_to_storage(values, self) except CanonicalOrderError as exc: raise type(exc)(f"Column {field.name!r}: {exc}") from exc except UnsupportedValueError as exc: @@ -2041,18 +2040,14 @@ def convert_list(value: Any) -> list[Any] | pa.Array[Any]: # A dict is order independent: entries are stored in canonical key order # so equal dicts store and hash identically (ITL-905). - def convert_dict(value: Any) -> list[dict[str, Any]] | pa.Array[Any]: + def convert_dict(value: Any) -> list[dict[str, Any]]: if value is None: raise _none_not_admitted(python_type) entries = [ {"key": key_converter(k), "value": value_converter(v)} for k, v in value.items() ] - if _in_logical_set.get(): - storage_type = self.python_type_to_arrow_type(python_type) - assert isinstance(storage_type, pa.LargeListType) - return _ordered_dict_storage(entries, storage_type.value_type) - return sort_dict_entries(entries) + return entries if _in_logical_set.get() else sort_dict_entries(entries) return convert_dict @@ -2061,15 +2056,13 @@ def convert_dict(value: Any) -> list[dict[str, Any]] | pa.Array[Any]: # order, which depends on PYTHONHASHSEED for str and bytes (ITL-905). element_converter = self.get_python_to_arrow_converter(args[0]) - def convert_set(value: Any) -> list[Any] | pa.Array[Any]: + def convert_set(value: Any) -> list[Any]: if value is None: raise _none_not_admitted(python_type) elements = [element_converter(item) for item in value] - if _in_logical_set.get(): - return ordered_set_storage( - elements, self.python_type_to_arrow_type(args[0]) - ) - return sort_set_elements(elements) + return ( + elements if _in_logical_set.get() else sort_set_elements(elements) + ) return convert_set diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 7d9fec828..3da4bfea7 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -58,7 +58,7 @@ def table_from_storage( continue kind = field.type if not isinstance(kind, pa.ExtensionType) or not kind.extension_name.startswith( - "set[" + ("set[", "list[") ): continue storage_type = kind.storage_type diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index d4d800107..0d7b3c6f9 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -1,13 +1,8 @@ """The stored order of a ``set[T]`` whose element ``T`` is a logical type (ITL-922). -A set has no order, so the order it is stored in, and with it the row hash, must come -from its elements' values alone. A set of a logical type whose storage value is a scalar -(text, bytes, a number) is put in the canonical order of -``canonical_order.sort_set_elements``, as a set of a plain Arrow type is: a NaN, two -elements with one storage value and elements that cannot be ordered are refused. - Struct storage is compared by declared field order, recursively through lists and -nested structs. +nested structs. Scalar-stored logical sets retain their native comparison. For +user-defined scalar types, a NaN or two elements with one storage value are refused. """ from __future__ import annotations @@ -873,7 +868,16 @@ class WithDict: @pytest.mark.parametrize( ("item_type", "low", "high"), - [(pa.float64(), -2.0, 1.0), (pa.large_string(), "A", "火")], + [ + (pa.float64(), -2.0, 1.0), + (pa.large_string(), "A", "火"), + (pa.large_binary(), b"A", b"\xff"), + ( + pa.struct([("n", pa.int64()), ("s", pa.large_string())]), + {"n": 2, "s": "z"}, + {"n": 10, "s": "a"}, + ), + ], ) def test_list_keys_skip_python_ranking( monkeypatch: pytest.MonkeyPatch, item_type: pa.DataType, low: Any, high: Any @@ -882,7 +886,7 @@ def test_list_keys_skip_python_ranking( from orcapod.semantic_types import canonical_order def unexpected(_keys: object) -> Never: - pytest.fail("scalar list keys entered Python ranking") + pytest.fail("list keys entered Python ranking") monkeypatch.setattr(canonical_order, "_ordinal_column", unexpected) shape = pa.struct([("items", pa.large_list(item_type)), ("value", pa.int64())]) @@ -952,3 +956,119 @@ def record_type(series: pl.Series, *args: Any, **kwargs: Any) -> pl.Series: pl.Struct({"item_0": pl.Int64, "item_1": pl.Int64}), pl.List(pl.UInt32), ] + + +def test_nested_dicts_share_one_sort(monkeypatch: pytest.MonkeyPatch) -> None: + """Order all dict fields in one pass, keeping entries with their parent.""" + + @op.dataclass(frozen=True, eq=False) + class Mapping: + items: dict[str, int] + + sort_indices = pc.sort_indices + sizes: list[int] = [] + + def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: + sizes.append(table.num_rows) + return sort_indices(table, *args, **kwargs) + + monkeypatch.setattr(pc, "sort_indices", record_size) + stored = _stored(_source([{Mapping({"z": 2, "a": i}) for i in range(8)}], Mapping)) + assert sizes == [16, 8] + assert stored["site0"] == [ + {"items": [{"key": "a", "value": i}, {"key": "z", "value": 2}]} + for i in range(8) + ] + + +def test_list_of_struct_sets_shares_one_sort(monkeypatch: pytest.MonkeyPatch) -> None: + """Batch the sets in a list, preserving the list order and empty sets.""" + sort_indices = pc.sort_indices + sizes: list[int] = [] + + def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: + sizes.append(table.num_rows) + return sort_indices(table, *args, **kwargs) + + monkeypatch.setattr(pc, "sort_indices", record_size) + converter = get_default_context().type_converter + schema = {"s": list[set[ExactPoint]]} + converter.ensure_types_registered_for_schemas(Schema(schema)) + data = [ + { + "s": [{ExactPoint(i + 10, "z"), ExactPoint(i + 2, "a")} for i in range(8)] + + [set()] + } + ] + result = converter.python_dicts_to_arrow_table(data, python_schema=schema) + assert sizes == [16] + assert result["s"].to_pylist() == [ + [[{"a": i + 2, "b": "a"}, {"a": i + 10, "b": "z"}] for i in range(8)] + [[]] + ] + + +@pytest.mark.usefixtures("registered_types") +def test_non_struct_sets_and_containers_skip_storage_ordering( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Keep native order for primitive containers and scalar logical sets.""" + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("a non-struct set entered storage ordering") + + monkeypatch.setattr(pc, "sort_indices", unexpected) + converter = get_default_context().type_converter + schema: dict[str, Any] = { + "text": str, + "dict": dict[str, int], + "list": list[bytes], + "set": set[int], + "builtin": list[set[Path]], + "custom": list[set[Reading]], + } + converter.ensure_types_registered_for_schemas(Schema(schema)) + row = { + "text": "value", + "dict": {"z": 2, "a": 1}, + "list": [b"z", b"a"], + "set": {2, 1}, + "builtin": [{Path("/z"), Path("/a")}], + "custom": [{Reading(2), Reading(-1)}], + } + expected = { + "text": "value", + "dict": [{"key": "a", "value": 1}, {"key": "z", "value": 2}], + "list": [b"z", b"a"], + "set": [1, 2], + "builtin": [["/a", "/z"]], + "custom": [[-1.0, 2.0]], + } + for count in (1, 2): + table = converter.python_dicts_to_arrow_table( + [row] * count, python_schema=schema + ) + assert table.to_pylist() == [expected] * count + + +@pytest.mark.usefixtures("registered_types") +def test_scalar_logical_sets_validate_once_per_column( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Check for duplicates across a column without mixing set rows.""" + from orcapod.semantic_types import canonical_order + + require_distinct = canonical_order._require_distinct + sizes: list[int] = [] + + def record_size(columns: list[pa.Array[Any]]) -> None: + sizes.append(len(columns[0])) + require_distinct(columns) + + monkeypatch.setattr(canonical_order, "_require_distinct", record_size) + converter = get_default_context().type_converter + schema = {"s": set[Word]} + converter.ensure_types_registered_for_schemas(Schema(schema)) + rows = [{"s": {Word("z"), Word("A")}} for _ in range(8)] + table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + assert table["s"].to_pylist() == [["a", "z"]] * 8 + assert sizes == [16] From e91dedb1a0b1ed3b98c3139999558df9a47aea21 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:41:21 -0800 Subject: [PATCH 07/18] perf(logical_types): isolate and batch struct-set storage --- .zed/rules | 2 +- CLAUDE.md | 2 +- changelog.d/ITL-922.md | 6 +- docs/dev/design_issues/ITL-922-DO2.md | 5 +- src/orcapod/core/data_function.py | 37 +- src/orcapod/core/function_pod.py | 11 +- .../list_logical_type_factory.py | 263 +++---- src/orcapod/semantic_types/canonical_order.py | 410 +---------- .../semantic_types/logical_set_storage.py | 680 ++++++++++++++++++ .../semantic_types/precomputed_converters.py | 49 +- .../semantic_types/universal_converter.py | 222 ++++-- .../function_pod/test_output_conformance.py | 43 ++ .../test_set_of_logical_elements.py | 130 +++- 13 files changed, 1166 insertions(+), 694 deletions(-) create mode 100644 src/orcapod/semantic_types/logical_set_storage.py diff --git a/.zed/rules b/.zed/rules index 243cec0ea..a6753882a 100644 --- a/.zed/rules +++ b/.zed/rules @@ -385,7 +385,7 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. -- Sets of struct-stored logical types use `canonical_order.ordered_set_storage` after +- Sets of struct-stored logical types use `logical_set_storage` after coercion to the declared Arrow type (ITL-922). Compare structs by declared field order and lists by item order, recursively. Class comparators have no effect. A NaN at any depth, duplicate storage values or incomparable values raise `CanonicalOrderError`. diff --git a/CLAUDE.md b/CLAUDE.md index c22946dfc..6bf659e15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -396,7 +396,7 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension identifier is the container kind plus the element's identifier; the type hash treats them like any generic alias (origin and arguments). A change to how they are stored or hashed is a data context (global hash version) change, not a logical type change. -- Sets of struct-stored logical types use `canonical_order.ordered_set_storage` after +- Sets of struct-stored logical types use `logical_set_storage` after coercion to the declared Arrow type (ITL-922). Compare structs by declared field order and lists by item order, recursively. Class comparators have no effect. A NaN at any depth, duplicate storage values or incomparable values raise `CanonicalOrderError`. diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 405e783a9..fc22a53bb 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -14,6 +14,6 @@ with equal storage raise `CanonicalOrderError` naming the column. - Sets of user-defined scalar-stored types keep their native sort and reject NaNs or duplicate storage values after Arrow coercion. -- Table conversion batches struct-set columns and lists of struct sets. - Nested dictionary keys, set items, and list comparison keys use Arrow - or Polars kernels. +- Table conversion batches struct sets in columns, including sets nested in + lists and user classes. Nested dictionary keys, set items, and list comparison + keys use Arrow or Polars kernels. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 3383b33e7..a5ca4060c 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -15,8 +15,9 @@ Sort the struct fields in declared order and use a lexicographic key for each list field. Sort nested dict keys and set items in their own declared storage types before comparing the enclosing elements. Check adjacent sorted values for duplicates within each set. Multi-row table conversion encodes and sorts -each set column in one pass, including precomputed and function-stream tables. -Function iteration validates each row's stored keys before yielding it. +each set column in one pass, including sets nested in lists and user classes. +Function iteration checks the coerced storage keys for NaNs and duplicates +without sorting the row. Sets of other logical types keep their native sort. For user-defined scalar storage, one Arrow pass per table column rejects NaNs and duplicate stored values. The same ordering rules apply to classes rebuilt from metadata. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index bb458cc3f..e00c241c8 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -42,6 +42,7 @@ PythonFunctionReturnCheckProtocol, ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.semantic_types.output_conformance import ( check_conformance, normalize_output_numbers, @@ -766,6 +767,9 @@ def output_source_info( return {column: f"{source}::{result_id}::{column}" for column in columns} +_OutputTableConverter = Callable[[list[dict[str, Any]], SchemaLike], pa.Table | None] + + class PythonDataFunction(DataFunctionBase[PythonFunctionExecutorProtocol]): @property def data_function_type_id(self) -> str: @@ -846,6 +850,9 @@ def __init__( self._function_name = function_name # (output key, conversion) pairs already reported with ValueConversionWarning. self._reported_conversions: set[tuple[str, str]] = set() + self._output_table_converter: ( + tuple[TypeConverterProtocol, _OutputTableConverter] | None + ) = None super().__init__( label=label, @@ -1063,7 +1070,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: ) # Validate storage eagerly, but retain compatible user-class instances. Reading # the table back here would rebind structural objects to the registry's class. - self._validate_output_storage(output_data, output_schema) + self._convert_outputs(output_data, output_schema) normalized = { key: typing.cast( DataValue, normalize_output_numbers(value, output_schema[key]) @@ -1097,10 +1104,20 @@ def _executor_return_options(self) -> dict[str, object] | None: return self._executor.return_container_options(self._return_container) return None - def _validate_output_storage( + def _resolve_output_table_converter( + self, converter: TypeConverterProtocol + ) -> _OutputTableConverter: + """Keep native output conversion unless the schema has a struct set.""" + if isinstance(converter, UniversalTypeConverter): + validate = converter._eager_set_output_validator(self.output_data_schema) + if validate is not None: + return validate + return converter.python_dicts_to_arrow_table + + def _convert_outputs( self, output_data: dict[str, DataValue], output_schema: Schema ) -> None: - """Check that the outputs can be stored with their declared Arrow types. + """Check that outputs can be stored with their declared Arrow types. Args: output_data: The parsed outputs, already checked against ``output_schema``. @@ -1110,17 +1127,15 @@ def _validate_output_storage( LogicalSetCanonicalOrderError: If an output's logical set has no canonical storage order. The converter names the column. OutputTypeError: If an output cannot be converted, for example an integer - out of range for its declared width, a ``datetime`` without a time zone - or one with a part below one microsecond; it names that output. + out of range for its declared width or a datetime without a time zone. """ converter = self.data_context.type_converter try: - if isinstance(converter, UniversalTypeConverter): - converter._validate_output_storage(output_data, output_schema) - else: - converter.python_dicts_to_arrow_table( - [output_data], python_schema=output_schema - ) + cached = self._output_table_converter + if cached is None or cached[0] is not converter: + cached = (converter, self._resolve_output_table_converter(converter)) + self._output_table_converter = cached + cached[1]([output_data], output_schema) except LogicalSetCanonicalOrderError: raise except Exception as exc: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index c3f6667ff..8d59da61b 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1548,7 +1548,6 @@ def _table_from_pairs( tag_tables: list[pa.Table] = [] all_data = [] data_schema = None - tag_columns = ColumnConfig(system_tags=True) # A data-tag that falls through the pod is one column: it is laid # out from the tags, with its exact Arrow type, never converted from its # Python value (ITL-1023). @@ -1560,11 +1559,9 @@ def _table_from_pairs( data_schema = pa.schema(f for f in data_schema if f.name not in shared) # Tags are passed through untouched: each row's own Arrow table keeps # the input's tag types, a logical type included (ITL-928). - tag_tables.append(tag.as_table(columns=tag_columns)) + tag_tables.append(tag.as_table(columns={"system_tags": True})) row = data.as_dict(all_info=True) - all_data.append( - {k: v for k, v in row.items() if k not in shared} if shared else row - ) + all_data.append({k: v for k, v in row.items() if k not in shared}) # TODO: re-verify the implemetation of this conversion converter = self.data_context.type_converter @@ -1586,9 +1583,7 @@ def _table_from_pairs( struct_data = converter.python_dicts_to_struct_dicts( all_data, python_schema=python_schema ) - all_data_as_tables = arrow_utils.table_from_storage( - struct_data, data_schema - ) + all_data_as_tables = pa.Table.from_pylist(struct_data, schema=data_schema) return arrow_utils.hstack_tables(all_tags_as_tables, all_data_as_tables) def as_table( diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 046b6c56b..722d1f331 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -52,7 +52,7 @@ import json import logging from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast import polars as pl import pyarrow as pa @@ -62,15 +62,6 @@ make_arrow_extension_type, make_polars_extension_type, ) -from orcapod.semantic_types.canonical_order import ( - _StorageNormalizer, - _in_logical_set, - _nested_unordered_order, - _ordered_set_column, - _validate_set_storage, - ordered_set_storage, - sort_set_elements, -) if TYPE_CHECKING: from orcapod.logical_types.protocols import ( @@ -122,7 +113,7 @@ class ListLogicalType(BaseLogicalType): Python type and Arrow extension type are derived, or an ``ArrowElement`` for a set of a plain Arrow type. is_set: If ``True``, uses ``set[T]`` semantics (``storage_to_python`` returns a - ``set``; ``python_to_storage`` stores the elements in canonical order). Defaults to + ``set``; ``python_to_storage`` sorts storage values for determinism). Defaults to ``False`` (``list[T]`` semantics). Attributes: @@ -165,6 +156,28 @@ class ListLogicalType(BaseLogicalType): ) ) + _orders_stored_sets = False + _validates_scalar_sets = False + + def __new__( + cls, + element_logical_type: LogicalTypeProtocol | ArrowElement, + *, + is_set: bool = False, + ) -> ListLogicalType: + """Choose the storage encoder once, when the logical set is registered.""" + if ( + cls is ListLogicalType + and is_set + and not isinstance(element_logical_type, (ArrowElement, ListLogicalType)) + ): + element = element_logical_type.get_arrow_extension_type() + if pa.types.is_struct(element.storage_type): + return object.__new__(_StructSetLogicalType) + if element.extension_name not in cls._BUILTIN_ELEMENTS: + return object.__new__(_ScalarSetLogicalType) + return super().__new__(cls) + def __init__( self, element_logical_type: "LogicalTypeProtocol | ArrowElement", @@ -172,9 +185,6 @@ def __init__( is_set: bool = False, ) -> None: self._is_set = is_set - self._orders_stored_sets = False - self._batches_sets = False - self._batched_element: ListLogicalType | None = None self._arrow_ext: pa.ExtensionType | None = None self._polars_ext: pl.BaseExtension | None = None @@ -241,21 +251,6 @@ def _container_metadata(element_metadata: bytes) -> bytes: # Derive storage type: large_list of the element's storage type (not extension type). element_storage = element_ext_type.storage_type self._storage_type = pa.large_list(element_storage) - self._orders_stored_sets = is_set and pa.types.is_struct(element_storage) - self._batches_sets = is_set and ( - self._orders_stored_sets - or ( - not isinstance(element_logical_type, ListLogicalType) - and element_ext_name not in self._BUILTIN_ELEMENTS - ) - ) - if ( - not is_set - and isinstance(element_logical_type, ListLogicalType) - and element_logical_type._batches_sets - ): - self._batched_element = element_logical_type - self._batches_sets = True # Compose the extension name from the category and element extension name. self._logical_type_name = f"{category}[{element_ext_name}]" @@ -380,15 +375,17 @@ def index_element(self) -> type: def python_to_storage( self, value: Any, converter: TypeConverterProtocol | None - ) -> list | pa.Array[Any]: + ) -> list: """Convert a Python list or set to its Arrow storage representation. Delegates per-element conversion to ``converter.python_to_storage`` using the element Python type. If ``value`` is ``None``, returns an empty list. - A set of user-registered logical values is ordered after encoding into - Arrow storage. Struct fields are compared in declared order and list - items in sequence, recursively (ITL-922). + For ``set[T]`` (``is_set=True``), the resulting list is sorted to guarantee + deterministic storage order regardless of Python set iteration order. For a + logical element sorting is attempted naturally; if elements are not comparable + (``TypeError``), falls back to ``repr``-based ordering. A plain Arrow element is + put in the canonical order of ``canonical_order.sort_set_elements``. Args: value: A Python list (or set) of elements of type ``element_python_type``, @@ -396,138 +393,35 @@ def python_to_storage( converter: The active ``TypeConverterProtocol`` for per-element delegation. Returns: - A Python list or Arrow array suitable for Arrow large_list storage. - For set semantics the elements are sorted. + A plain Python list of storage values suitable for Arrow large_list storage. + For set semantics the list is sorted. Raises: - CanonicalOrderError: For a NaN at any depth, elements that cannot be - ordered, or two elements with one storage value. + CanonicalOrderError: For a set of a plain Arrow type holding a NaN, elements + that cannot be ordered, or two elements with one storage value. """ if value is None: return [] - if self._batches_sets and not _in_logical_set.get(): - if self._batched_element is not None: - if converter is None: - return list(value) - return self._batched_element._python_values_to_storage( - list(value), converter, nested=True - ) - if self._orders_stored_sets: - elements = self._encode_struct_set(value, converter) - return ordered_set_storage( - elements, - self._storage_type.value_type, - normalize=self._normalizer(converter), - ) - elements = self._native_sort(self._encode_elements(value, converter)) - return _validate_set_storage(elements, self._storage_type.value_type) - - elements = self._encode_elements(value, converter) + if converter is None: + elements = list(value) + else: + elements = [ + converter.python_to_storage(item, self._element_python_type) + for item in value + ] if self._is_set: - if _in_logical_set.get(): - return elements if self._element_logical_type is None: - return sort_set_elements(elements) - return self._native_sort(elements) - return elements + # A set of a plain Arrow type keeps the canonical order a plain set + # had before it was a native container (ITL-905), so the stored + # elements are unchanged (ITL-611). + from orcapod.semantic_types.canonical_order import sort_set_elements - @staticmethod - def _native_sort(elements: list[Any]) -> list[Any]: - """Keep the original logical set order for non-struct elements.""" - try: - return sorted(elements) - except TypeError: - return sorted(elements, key=repr) - - def _normalizer( - self, converter: TypeConverterProtocol | None - ) -> _StorageNormalizer | None: - """Resolve only fields whose declared containers are unordered.""" - if converter is None or self._element_logical_type is None: - return None - return _nested_unordered_order(self._element_logical_type, converter) - - def _encode_struct_set( - self, value: Any, converter: TypeConverterProtocol | None - ) -> list[Any]: - """Encode a struct set, deferring nested ordering until Arrow coercion.""" - token = _in_logical_set.set(True) - try: - return self._encode_elements(value, converter) - finally: - _in_logical_set.reset(token) - - def _validate_python_set( - self, value: Any, converter: TypeConverterProtocol - ) -> None: - """Validate a struct set before it is emitted as a Python value.""" - if value: - _validate_set_storage( - self._encode_struct_set(value, converter), - self._storage_type.value_type, - normalize=self._normalizer(converter), - struct_elements=True, - ) - - def _encode_elements( - self, value: Any, converter: TypeConverterProtocol | None - ) -> list[Any]: - """Convert elements using their declared logical type.""" - if converter is None: - return list(value) - return [ - converter.python_to_storage(item, self._element_python_type) - for item in value - ] - - def _python_values_to_storage( - self, - values: list[Any], - converter: TypeConverterProtocol, - *, - nested: bool = False, - ) -> pa.LargeListArray[Any]: - """Encode all sets at this nesting level in one Arrow pass.""" - if nested and any(value is None for value in values): - # The ordinary converter rejects null elements of these declared - # lists before calling their registered storage encoder. - converter.python_to_storage(None, self.python_type) - if self._batched_element is not None: - offsets = [0] - items: list[Any] = [] - for value in values: - if value is not None: - items.extend(value) - offsets.append(len(items)) - return pa.LargeListArray.from_arrays( - pa.array(offsets, type=pa.int64()), - self._batched_element._python_values_to_storage( - items, converter, nested=True - ), - type=self._storage_type, - mask=pa.array([value is None for value in values], type=pa.bool_()), - ) - - if self._orders_stored_sets: - token = _in_logical_set.set(True) + return sort_set_elements(elements) try: - rows = [ - None if value is None else self._encode_elements(value, converter) - for value in values - ] - finally: - _in_logical_set.reset(token) - return _ordered_set_column( - rows, self._storage_type, normalize=self._normalizer(converter) - ) - - rows = [ - None - if value is None - else self._native_sort(self._encode_elements(value, converter)) - for value in values - ] - return _ordered_set_column(rows, self._storage_type, order=False) + elements = sorted(elements) + except TypeError: + elements = sorted(elements, key=repr) + return elements def storage_to_python( self, storage_value: Any, converter: TypeConverterProtocol | None @@ -559,6 +453,63 @@ def storage_to_python( return set(elements) if self._is_set else elements +class _ValidatedSetLogicalType(ListLogicalType): + """A logical set whose storage must be checked after Arrow conversion.""" + + def python_to_storage( + self, value: Any, converter: TypeConverterProtocol | None + ) -> Any: + """Convert and validate one set for callers outside the table writer.""" + from functools import partial + + from orcapod.semantic_types.logical_set_storage import ( + _validate_scalar_column, + ordered_set_storage, + storage_plan, + ) + from orcapod.semantic_types.universal_converter import UniversalTypeConverter + + if value is None: + return [] + if isinstance(converter, UniversalTypeConverter): + plan = converter._set_storage_plan(self.python_type, self._storage_type) + elif converter is not None: + plan = storage_plan( + self.python_type, + self._storage_type, + converter, + lambda annotation: partial( + converter.python_to_storage, annotation=annotation + ), + ) + elif self._orders_stored_sets: + return ordered_set_storage(list(value), self._storage_type.value_type) + else: + storage = cast( + "pa.LargeListArray[Any]", + pa.array( + [super().python_to_storage(value, None)], type=self._storage_type + ), + ) + return _validate_scalar_column(storage).values + storage = cast( + "pa.LargeListArray[Any]", plan.encode_column([value], self._storage_type) + ) + return storage.values + + +class _StructSetLogicalType(_ValidatedSetLogicalType): + """A set ordered by its struct elements' declared Arrow storage.""" + + _orders_stored_sets = True + + +class _ScalarSetLogicalType(_ValidatedSetLogicalType): + """A custom scalar set with native ordering and storage validation.""" + + _validates_scalar_sets = True + + class ListLogicalTypeFactory: """Stateless factory that reconstructs ``ListLogicalType`` instances from Arrow metadata. diff --git a/src/orcapod/semantic_types/canonical_order.py b/src/orcapod/semantic_types/canonical_order.py index 55993edd9..3ac9b7e0a 100644 --- a/src/orcapod/semantic_types/canonical_order.py +++ b/src/orcapod/semantic_types/canonical_order.py @@ -17,8 +17,6 @@ ``0.0`` store different bytes and hash differently, like any float value. * ``str``: Unicode code point (never locale). ``bytes``: unsigned bytewise. * ``date``, ``datetime`` (by instant), ``time``, ``timedelta``: natural order. -* Structs in sets: lexicographically by the declared storage fields, in field order. -* Lists in sets: lexicographically by their items, with a proper prefix sorting first. Keys or elements that cannot be ordered against each other, and two keys or elements with the same storage value, raise ``CanonicalOrderError``. @@ -30,34 +28,18 @@ import numbers import types import typing -from collections.abc import Callable, Sequence -from contextvars import ContextVar +from collections.abc import Callable from decimal import Decimal from itertools import pairwise -from typing import TYPE_CHECKING, Any, TypeVar, cast, get_args, get_origin +from typing import Any, TypeVar, cast, get_args, get_origin -import polars as pl -import pyarrow as pa -import pyarrow.compute as pc - -from orcapod.errors import CanonicalOrderError, LogicalSetCanonicalOrderError - -if TYPE_CHECKING: - from orcapod.logical_types.protocols import ( - LogicalTypeProtocol, - TypeConverterProtocol, - ) +from orcapod.errors import CanonicalOrderError _T = TypeVar("_T") -_StorageNormalizer = Callable[["pa.Array[Any]"], "pa.Array[Any]"] # A sort key: ``(0,)`` for None, ``(1, value)`` otherwise. _Rank = tuple[Any, ...] -# Field converters also serve standalone primitive containers. Only an enclosing -# user-class set requires canonicalizing those fields against their Arrow storage. -_in_logical_set: ContextVar[bool] = ContextVar("_in_logical_set", default=False) - def _key_rank(key: object) -> _Rank: """Return the sort key of one storage key or set element. @@ -118,7 +100,7 @@ def sort_dict_entries(entries: list[dict[str, _T]]) -> list[dict[str, _T]]: def sort_set_elements(elements: list[_T]) -> list[_T]: - """Return the storage elements of one primitive set in canonical order. + """Return the storage elements of one set value in canonical order. Args: elements: The converted elements of a set. @@ -133,390 +115,6 @@ def sort_set_elements(elements: list[_T]) -> list[_T]: return _sorted_by_rank([(_key_rank(element), element) for element in elements]) -_LIST_ARRAY_TYPES = ( - pa.ListArray, - pa.LargeListArray, - pa.FixedSizeListArray, - pa.ListViewArray, - pa.LargeListViewArray, -) - - -def _ordinal_column(keys: list[Any]) -> pa.Array[Any]: - """Represent each distinct non-null Python comparison key by its sorted rank.""" - ranks = {key: i for i, key in enumerate(sorted(set(keys) - {None}))} - return pa.array([ranks.get(key) for key in keys], type=pa.int64()) - - -def _list_sort_column( - array: pa.ListArray[Any] - | pa.LargeListArray[Any] - | pa.FixedSizeListArray[Any] - | pa.ListViewArray[Any] - | pa.LargeListViewArray[Any], -) -> pa.Array[Any]: - """Use one lexicographic key per stored list, comparing only its own children.""" - children = _sort_columns(array.flatten()) - # Polars ranks lists of native scalar keys. Use Arrow dense ranks for - # child types whose representation Polars cannot rank inside a list. - children = [ - child - if ( - pa.types.is_integer(child.type) - or pa.types.is_floating(child.type) - or pa.types.is_boolean(child.type) - or pa.types.is_string(child.type) - or pa.types.is_large_string(child.type) - or pa.types.is_binary(child.type) - or pa.types.is_large_binary(child.type) - ) - else pc.rank(child, tiebreaker="dense", null_placement="at_start") - for child in children - ] - if len(children) == 1: - child = children[0] - else: - # A list of struct-key ranks preserves the original lexicographic - # order. Rank the columns before putting them inside a list. - child = ( - pl.DataFrame(pa.table({str(i): col for i, col in enumerate(children)})) - .to_struct() - .rank("dense") - .to_arrow() - ) - if isinstance(array, pa.LargeListArray) and not array.null_count: - offsets = array.offsets - if array.offset or offsets[0].as_py() != 0: - offsets = pc.subtract(offsets, offsets[0]) - if ( - len(children) == 1 - and pa.types.is_integer(child.type) - and not child.null_count - ): - # Rank short, fixed-width keys as scalar fields instead of lists. - width, remainder = divmod(len(child), len(array)) - if 1 < width <= 4 and not remainder: - lengths_match = pc.equal(pc.list_value_length(array), pa.scalar(width)) - if pc.all(lengths_match).as_py(): - items = child.to_numpy().reshape(-1, width) - return ( - pl.DataFrame({f"item_{i}": items[:, i] for i in range(width)}) - .to_struct() - .rank("dense") - .to_arrow() - ) - return ( - pl.Series(pa.LargeListArray.from_arrays(offsets, child)) - .rank("dense") - .to_arrow() - ) - - # Rebuild offsets over the flattened children, which omit null parent lists. - offsets = pc.cumulative_sum( - pa.concat_arrays( - [ - pa.array([0], type=pa.int64()), - pc.list_value_length(array).cast(pa.int64()).fill_null(0), - ] - ) - ) - lists = pa.LargeListArray.from_arrays( - cast(pa.Int64Array, offsets), child, mask=pc.is_null(array) - ) - return pl.Series(lists).rank("dense").to_arrow() - - -def _sort_columns(array: pa.Array[Any]) -> list[pa.Array[Any]]: - """Flatten struct comparison keys in field order, preserving parent nulls.""" - if array.null_count == len(array): - # Arrow has no equality kernel for the null type. A constant key gives - # the same ties and also covers unsupported storage whose values are null. - return [pc.is_valid(array)] - if isinstance(array, pa.StructArray): - # flatten() masks the children where a struct is null. The validity key - # distinguishes a null struct from a present struct with all null fields. - columns: list[pa.Array[Any]] = ( - [pc.is_valid(array)] - if array.null_count or not array.type.num_fields - else [] - ) - for child in array.flatten(): - columns.extend(_sort_columns(child)) - return columns - if isinstance(array, _LIST_ARRAY_TYPES): - return [_list_sort_column(array)] - if isinstance(array, pa.ExtensionArray): - return _sort_columns(array.storage) - if isinstance(array, pa.DictionaryArray): - return _sort_columns(array.dictionary_decode()) - - kind = array.type - if pa.types.is_float16(kind): - array = array.cast(pa.float32()) - if pa.types.is_floating(kind): - if pc.any(pc.is_nan(array)).as_py(): - raise LogicalSetCanonicalOrderError( - "a NaN key or set element has no canonical order" - ) - return [array] - if pa.types.is_string_view(kind): - return [array.cast(pa.large_string())] - if pa.types.is_binary_view(kind): - return [array.cast(pa.large_binary())] - if isinstance(kind, (pa.Decimal32Type, pa.Decimal64Type)): - return [array.cast(pa.decimal128(kind.precision, kind.scale))] - if pa.types.is_interval(kind): - # Arrow has no sort/equality kernels for intervals. Its Python scalars - # expose their stored months, days and nanoseconds as a tuple. - return [_ordinal_column(array.to_pylist())] - if pa.types.is_nested(kind): - raise LogicalSetCanonicalOrderError(f"storage type {kind} cannot be ordered") - - # Use physical units for temporal values, including inside list keys, where - # Python date/time objects could otherwise drop sub-day or sub-microsecond bits. - if pa.types.is_date32(kind) or pa.types.is_time32(kind): - return [array.view(pa.int32())] - if pa.types.is_temporal(kind): - return [array.view(pa.int64())] - return [array] - - -def _adjacent_equal(array: pa.Array[Any]) -> pa.BooleanArray: - """Compare neighboring sorted keys, with null equal to null.""" - left, right = array.slice(0, len(array) - 1), array.slice(1) - equal = pc.equal(left, right) - if array.null_count: - both_null = pc.and_(pc.is_null(left), pc.is_null(right)) - equal = pc.or_kleene(equal, both_null) - equal = pc.fill_null(equal, pa.scalar(False)) - return cast(pa.BooleanArray, equal) - - -def ordered_set_storage( - elements: list[Any], - storage_type: pa.DataType, - *, - normalize: _StorageNormalizer | None = None, -) -> pa.Array[Any]: - """Encode a logical set's elements once and return them in canonical order. - - Args: - elements: The converted elements of one logical set. - storage_type: The declared Arrow element storage type. - normalize: Orders nested unordered fields once their values are encoded. - - Returns: - The exact Arrow storage values, in canonical order. - - Raises: - LogicalSetCanonicalOrderError: For an unorderable value (including NaN), - or two elements with equal storage keys. - """ - try: - array = pa.array(elements, type=storage_type) - if normalize is not None: - array = normalize(array) - columns = _sort_columns(array) - return _sort_set_array(array, columns) if len(array) > 1 else array - except (TypeError, pa.ArrowException) as exc: - raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc - - -def _validate_set_storage( - elements: list[Any], - storage_type: pa.DataType, - *, - normalize: _StorageNormalizer | None = None, - struct_elements: bool = False, -) -> pa.Array[Any]: - """Validate the stored keys of one set without changing its order.""" - try: - array = pa.array(elements, type=storage_type) - keys = _sort_columns(normalize(array) if normalize is not None else array) - if struct_elements and len(array) > 1: - # Eager function output validates one row before it can be yielded. - # Hashing its flat keys avoids setting up a second Arrow table per row. - tuples = zip(*(key.to_pylist() for key in keys), strict=True) - if len(set(tuples)) != len(array): - raise LogicalSetCanonicalOrderError("duplicate key or set element") - elif not struct_elements: - _require_distinct(keys) - return array - except (TypeError, pa.ArrowException) as exc: - raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc - - -def _require_distinct(columns: list[pa.Array[Any]]) -> None: - """Check stored equality, with nulls and both signs of zero comparing equal.""" - if len(columns[0]) <= 1: - return - # Arrow grouping distinguishes IEEE zero bit patterns. Normalize only the - # comparison key so storage keeps the original sign. - keys = [ - pc.if_else( - pc.equal(column, pa.scalar(0.0, type=column.type)), - pa.scalar(0.0, type=column.type), - column, - ) - if pa.types.is_floating(column.type) - else column - for column in columns - ] - names = [str(i) for i in range(len(keys))] - table = pa.Table.from_arrays(keys, names=names) - if ( - table.group_by(names, use_threads=False).aggregate([]).num_rows - != table.num_rows - ): - raise LogicalSetCanonicalOrderError("duplicate key or set element") - - -def _list_with_values( - storage: pa.LargeListArray[Any], values: pa.Array[Any] -) -> pa.LargeListArray[Any]: - """Rebuild list storage with the same offsets, type and validity.""" - return pa.LargeListArray.from_arrays( - storage.offsets, values, type=storage.type, mask=pc.is_null(storage) - ) - - -def _ordered_set_column( - rows: list[list[Any] | None], - storage_type: pa.LargeListType[Any], - *, - normalize: _StorageNormalizer | None = None, - order: bool = True, -) -> pa.LargeListArray[Any]: - """Encode a column of sets, keeping each set in its row.""" - try: - storage = cast("pa.LargeListArray[Any]", pa.array(rows, type=storage_type)) - if normalize is not None: - storage = _list_with_values(storage, normalize(storage.values)) - if order: - return _order_unordered_lists(storage) - if len(storage.values): - columns = _sort_columns(storage.values) - if pc.max(pc.list_value_length(storage)).as_py() > 1: - _require_distinct([pc.list_parent_indices(storage), *columns]) - return storage - except (TypeError, pa.ArrowException) as exc: - raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc - - -def _order_unordered_lists( - storage: pa.LargeListArray[Any], *, dict_keys: bool = False -) -> pa.LargeListArray[Any]: - """Sort and check dict keys or set items in one pass across their parents.""" - elements = storage.values - if not len(elements): - return storage - keys = cast(pa.StructArray, elements).field("key") if dict_keys else elements - columns = _sort_columns(keys) - if pc.max(pc.list_value_length(storage)).as_py() <= 1: - return storage - return _list_with_values( - storage, _sort_set_array(elements, [pc.list_parent_indices(storage), *columns]) - ) - - -def _nested_unordered_order( - logical_type: LogicalTypeProtocol, converter: TypeConverterProtocol -) -> _StorageNormalizer | None: - """Resolve the unordered fields of a struct from its declared Python annotations.""" - from orcapod.logical_types.user_class_logical_type import UserClassLogicalType - - def struct_order( - kind: pa.StructType, fields: Sequence[tuple[str, Any]] - ) -> _StorageNormalizer | None: - operations = { - i: operation - for i, (name, annotation) in enumerate(fields) - if (operation := resolve(kind.field(name).type, annotation)) is not None - } - if not operations: - return None - - def normalize_struct(array: pa.Array[Any]) -> pa.StructArray: - struct = cast(pa.StructArray, array) - children = [struct.field(i) for i in range(kind.num_fields)] - for i, operation in operations.items(): - children[i] = operation(children[i]) - return pa.StructArray.from_arrays( - children, fields=list(kind), mask=pc.is_null(struct) - ) - - return normalize_struct - - def resolve(kind: pa.DataType, annotation: Any) -> _StorageNormalizer | None: - if not isinstance(kind, (pa.LargeListType, pa.StructType)): - return None - origin = get_origin(annotation) - args = get_args(annotation) - if origin in (typing.Union, types.UnionType): - return resolve(kind, next(arg for arg in args if arg is not type(None))) - if isinstance(kind, pa.StructType): - if origin is tuple: - return struct_order( - kind, [(f"f{i}", arg) for i, arg in enumerate(args)] - ) - child_type = converter.get_logical_type_for_python_type(annotation) - if isinstance(child_type, UserClassLogicalType): - return struct_order(kind, child_type.field_annotations) - return None - if origin not in (list, tuple, dict, set) or not args: - return None - if origin is dict: - entry_type = cast(pa.StructType, kind.value_type) - normalize_items = struct_order( - entry_type, [("key", args[0]), ("value", args[1])] - ) - else: - normalize_items = resolve(kind.value_type, args[0]) - unordered = origin in (dict, set) - if not unordered and normalize_items is None: - return None - - def normalize_list(array: pa.Array[Any]) -> pa.LargeListArray[Any]: - storage = cast("pa.LargeListArray[Any]", array) - if normalize_items is not None: - storage = _list_with_values(storage, normalize_items(storage.values)) - if unordered: - storage = _order_unordered_lists(storage, dict_keys=origin is dict) - return storage - - return normalize_list - - if isinstance(logical_type, UserClassLogicalType): - return struct_order(logical_type.storage_type, logical_type.field_annotations) - return None - - -def _sort_set_array( - array: pa.Array[Any], columns: list[pa.Array[Any]] -) -> pa.Array[Any]: - """Sort stored values by the comparison columns and refuse equal neighbors.""" - names = [str(i) for i in range(len(columns))] - indices = pc.sort_indices( - pa.Table.from_arrays(columns, names=names), - sort_keys=[(name, "ascending") for name in names], - null_placement="at_start", - ) - # Intersect adjacent equality masks until no possible duplicate remains. - duplicates = None - for column in columns: - equal = _adjacent_equal(column.take(indices)) - duplicates = equal if duplicates is None else pc.and_(duplicates, equal) - if not pc.any(duplicates).as_py(): - try: - return array.take(indices) - except pa.ArrowNotImplementedError: - # View types lack a take kernel, including inside structs. - return pa.concat_arrays( - [array.slice(i, 1) for i in cast(list[int], indices.to_pylist())] - ) - raise LogicalSetCanonicalOrderError("duplicate key or set element") - - def canonical_python_value( value: _T, python_type: object, diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py new file mode 100644 index 000000000..4992d01d5 --- /dev/null +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -0,0 +1,680 @@ +"""Arrow ordering and validation for sets of logical values.""" + +from __future__ import annotations + +import types +import typing +from collections.abc import Callable +from dataclasses import dataclass +from itertools import pairwise +from typing import TYPE_CHECKING, Any, cast, get_args, get_origin + +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.errors import LogicalSetCanonicalOrderError + +if TYPE_CHECKING: + from orcapod.logical_types.protocols import TypeConverterProtocol + + _ListArray = ( + pa.ListArray[Any] + | pa.LargeListArray[Any] + | pa.FixedSizeListArray[Any] + | pa.ListViewArray[Any] + | pa.LargeListViewArray[Any] + ) + +_StorageNormalizer = Callable[["pa.Array[Any]"], "pa.Array[Any]"] + +_LIST_ARRAY_TYPES = ( + pa.ListArray, + pa.LargeListArray, + pa.FixedSizeListArray, + pa.ListViewArray, + pa.LargeListViewArray, +) + + +def _ordinal_column(keys: list[Any]) -> pa.Array[Any]: + """Represent each distinct non-null Python comparison key by its sorted rank.""" + ranks = {key: i for i, key in enumerate(sorted(set(keys) - {None}))} + return pa.array([ranks.get(key) for key in keys], type=pa.int64()) + + +def _list_sort_column( + array: pa.ListArray[Any] + | pa.LargeListArray[Any] + | pa.FixedSizeListArray[Any] + | pa.ListViewArray[Any] + | pa.LargeListViewArray[Any], +) -> pa.Array[Any]: + """Use one lexicographic key per stored list, comparing only its own children.""" + children = _sort_columns(array.flatten()) + # Polars ranks lists of native scalar keys. Use Arrow dense ranks for + # child types whose representation Polars cannot rank inside a list. + children = [ + child + if ( + pa.types.is_integer(child.type) + or pa.types.is_floating(child.type) + or pa.types.is_boolean(child.type) + or pa.types.is_string(child.type) + or pa.types.is_large_string(child.type) + or pa.types.is_binary(child.type) + or pa.types.is_large_binary(child.type) + ) + else pc.rank(child, tiebreaker="dense", null_placement="at_start") + for child in children + ] + if len(children) == 1: + child = children[0] + else: + # A list of struct-key ranks preserves the original lexicographic + # order. Rank the columns before putting them inside a list. + child = ( + pl.DataFrame(pa.table({str(i): col for i, col in enumerate(children)})) + .to_struct() + .rank("dense") + .to_arrow() + ) + if isinstance(array, pa.LargeListArray) and not array.null_count: + offsets = array.offsets + if array.offset or offsets[0].as_py() != 0: + offsets = pc.subtract(offsets, offsets[0]) + if ( + len(children) == 1 + and pa.types.is_integer(child.type) + and not child.null_count + ): + # Rank short, fixed-width keys as scalar fields instead of lists. + width, remainder = divmod(len(child), len(array)) + if 1 < width <= 4 and not remainder: + lengths_match = pc.equal(pc.list_value_length(array), pa.scalar(width)) + if pc.all(lengths_match).as_py(): + items = child.to_numpy().reshape(-1, width) + return ( + pl.DataFrame({f"item_{i}": items[:, i] for i in range(width)}) + .to_struct() + .rank("dense") + .to_arrow() + ) + return ( + pl.Series(pa.LargeListArray.from_arrays(offsets, child)) + .rank("dense") + .to_arrow() + ) + + # Rebuild offsets over the flattened children, which omit null parent lists. + offsets = pc.cumulative_sum( + pa.concat_arrays( + [ + pa.array([0], type=pa.int64()), + pc.list_value_length(array).cast(pa.int64()).fill_null(0), + ] + ) + ) + lists = pa.LargeListArray.from_arrays( + cast(pa.Int64Array, offsets), child, mask=pc.is_null(array) + ) + return pl.Series(lists).rank("dense").to_arrow() + + +def _sort_columns(array: pa.Array[Any]) -> list[pa.Array[Any]]: + """Flatten struct comparison keys in field order, preserving parent nulls.""" + if array.null_count == len(array): + # Arrow has no equality kernel for the null type. A constant key gives + # the same ties and also covers unsupported storage whose values are null. + return [pc.is_valid(array)] + if isinstance(array, pa.StructArray): + # flatten() masks the children where a struct is null. The validity key + # distinguishes a null struct from a present struct with all null fields. + columns: list[pa.Array[Any]] = ( + [pc.is_valid(array)] + if array.null_count or not array.type.num_fields + else [] + ) + for child in array.flatten(): + columns.extend(_sort_columns(child)) + return columns + if isinstance(array, _LIST_ARRAY_TYPES): + return [_list_sort_column(array)] + if isinstance(array, pa.ExtensionArray): + return _sort_columns(array.storage) + if isinstance(array, pa.DictionaryArray): + return _sort_columns(array.dictionary_decode()) + + kind = array.type + if pa.types.is_float16(kind): + array = array.cast(pa.float32()) + if pa.types.is_floating(kind): + if pc.any(pc.is_nan(array)).as_py(): + raise LogicalSetCanonicalOrderError( + "a NaN key or set element has no canonical order" + ) + return [array] + if pa.types.is_string_view(kind): + return [array.cast(pa.large_string())] + if pa.types.is_binary_view(kind): + return [array.cast(pa.large_binary())] + if isinstance(kind, (pa.Decimal32Type, pa.Decimal64Type)): + return [array.cast(pa.decimal128(kind.precision, kind.scale))] + if pa.types.is_interval(kind): + # Arrow has no sort/equality kernels for intervals. Its Python scalars + # expose their stored months, days and nanoseconds as a tuple. + return [_ordinal_column(array.to_pylist())] + if pa.types.is_nested(kind): + raise LogicalSetCanonicalOrderError(f"storage type {kind} cannot be ordered") + + # Use physical units for temporal values, including inside list keys, where + # Python date/time objects could otherwise drop sub-day or sub-microsecond bits. + if pa.types.is_date32(kind) or pa.types.is_time32(kind): + return [array.view(pa.int32())] + if pa.types.is_temporal(kind): + return [array.view(pa.int64())] + return [array] + + +def _adjacent_equal(array: pa.Array[Any]) -> pa.BooleanArray: + """Compare neighboring sorted keys, with null equal to null.""" + left, right = array.slice(0, len(array) - 1), array.slice(1) + equal = pc.equal(left, right) + if array.null_count: + both_null = pc.and_(pc.is_null(left), pc.is_null(right)) + equal = pc.or_kleene(equal, both_null) + equal = pc.fill_null(equal, pa.scalar(False)) + return cast(pa.BooleanArray, equal) + + +def ordered_set_storage( + elements: list[Any], + storage_type: pa.DataType, + *, + normalize: _StorageNormalizer | None = None, +) -> pa.Array[Any]: + """Encode a logical set's elements once and return them in canonical order. + + Args: + elements: The converted elements of one logical set. + storage_type: The declared Arrow element storage type. + normalize: Orders nested unordered fields once their values are encoded. + + Returns: + The exact Arrow storage values, in canonical order. + + Raises: + LogicalSetCanonicalOrderError: For an unorderable value (including NaN), + or two elements with equal storage keys. + """ + try: + array = pa.array(elements, type=storage_type) + if normalize is not None: + array = normalize(array) + columns = _sort_columns(array) + return _sort_set_array(array, columns) if len(array) > 1 else array + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + + +def _require_distinct(columns: list[pa.Array[Any]]) -> None: + """Check stored equality, with nulls and both signs of zero comparing equal.""" + if len(columns[0]) <= 1: + return + # Arrow grouping distinguishes IEEE zero bit patterns. Normalize only the + # comparison key so storage keeps the original sign. + keys = [ + pc.if_else( + pc.equal(column, pa.scalar(0.0, type=column.type)), + pa.scalar(0.0, type=column.type), + column, + ) + if pa.types.is_floating(column.type) + else column + for column in columns + ] + names = [str(i) for i in range(len(keys))] + table = pa.Table.from_arrays(keys, names=names) + if ( + table.group_by(names, use_threads=False).aggregate([]).num_rows + != table.num_rows + ): + raise LogicalSetCanonicalOrderError("duplicate key or set element") + + +def _list_with_values( + storage: pa.LargeListArray[Any], values: pa.Array[Any] +) -> pa.LargeListArray[Any]: + """Rebuild list storage with the same offsets, type and validity.""" + return pa.LargeListArray.from_arrays( + storage.offsets, values, type=storage.type, mask=pc.is_null(storage) + ) + + +def _validate_scalar_column(storage: pa.LargeListArray[Any]) -> pa.LargeListArray[Any]: + """Check stored scalar keys once for the entire column without reordering.""" + if not len(storage.values): + return storage + keys = _sort_columns(storage.values) + width = pc.max(pc.list_value_length(storage)).as_py() + if width == 2: + # With at most two items per set, a duplicate must be adjacent. + parents = pc.list_parent_indices(storage) + duplicate = _adjacent_equal(parents) + for key in keys: + duplicate = pc.and_(duplicate, _adjacent_equal(key)) + if pc.any(duplicate).as_py(): + raise LogicalSetCanonicalOrderError("duplicate key or set element") + elif width is not None and width > 2: + # Native scalar sorting can use a custom comparator, so equal stored + # values need not be adjacent within a larger set. + _require_distinct([pc.list_parent_indices(storage), *keys]) + return storage + + +def _order_unordered_lists( + storage: pa.LargeListArray[Any], *, dict_keys: bool = False +) -> pa.LargeListArray[Any]: + """Sort and check dict keys or set items in one pass across their parents.""" + elements = storage.values + if not len(elements): + return storage + keys = cast(pa.StructArray, elements).field("key") if dict_keys else elements + columns = _sort_columns(keys) + if pc.max(pc.list_value_length(storage)).as_py() <= 1: + return storage + return _list_with_values( + storage, _sort_set_array(elements, [pc.list_parent_indices(storage), *columns]) + ) + + +def _sort_set_array( + array: pa.Array[Any], columns: list[pa.Array[Any]] +) -> pa.Array[Any]: + """Sort stored values by the comparison columns and refuse equal neighbors.""" + names = [str(i) for i in range(len(columns))] + indices = pc.sort_indices( + pa.Table.from_arrays(columns, names=names), + sort_keys=[(name, "ascending") for name in names], + null_placement="at_start", + ) + # Intersect adjacent equality masks until no possible duplicate remains. + duplicates = None + for column in columns: + equal = _adjacent_equal(column.take(indices)) + duplicates = equal if duplicates is None else pc.and_(duplicates, equal) + if not pc.any(duplicates).as_py(): + try: + return array.take(indices) + except pa.ArrowNotImplementedError: + # View types lack a take kernel, including inside structs. + return pa.concat_arrays( + [array.slice(i, 1) for i in cast(list[int], indices.to_pylist())] + ) + raise LogicalSetCanonicalOrderError("duplicate key or set element") + + +_Encode = Callable[[Any], Any] +_Keys = Callable[["pa.Array[Any]"], list[Any]] + + +@dataclass(frozen=True) +class _StoragePlan: + """Encode Python values and resolve ordering on their coerced Arrow storage.""" + + encode: _Encode + normalize: _StorageNormalizer | None = None + keys: _Keys | None = None + element_keys: _Keys | None = None + + def encode_column( + self, values: list[Any], storage_type: pa.DataType + ) -> pa.Array[Any]: + """Apply each nested operation once over the entire typed column.""" + encoded = [ + self.encode(value) if value is not None else None for value in values + ] + return self.finish(encoded, storage_type) + + def finish(self, encoded: list[Any], storage_type: pa.DataType) -> pa.Array[Any]: + """Normalize an encoded column after Arrow coercion.""" + try: + array = pa.array(encoded, type=storage_type) + return self.normalize(array) if self.normalize is not None else array + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc + + +class _FieldEncoder: + """Supply prepared field encoders to a user class's existing storage method.""" + + def __init__( + self, converter: TypeConverterProtocol, fields: dict[Any, _Encode] + ) -> None: + self._converter = converter + self._fields = fields + + def python_to_storage(self, value: Any, annotation: Any) -> Any: + """Convert a field with its resolved converter.""" + return self._fields[annotation](value) + + def __getattr__(self, name: str) -> Any: + return getattr(self._converter, name) + + +def _stored_keys(array: pa.Array[Any]) -> list[Any]: + """Extract exact Arrow equality keys for a small eagerly validated row.""" + if array.null_count == len(array): + return [None] * len(array) + if isinstance(array, pa.StructArray): + return _struct_keys(array, [_stored_keys] * array.type.num_fields) + if isinstance(array, _LIST_ARRAY_TYPES): + return _list_keys(array, _stored_keys, tuple) + if isinstance(array, pa.ExtensionArray): + return _stored_keys(array.storage) + if isinstance(array, pa.DictionaryArray): + return _stored_keys(array.dictionary_decode()) + kind = array.type + if pa.types.is_nested(kind): + raise LogicalSetCanonicalOrderError(f"storage type {kind} cannot be ordered") + if pa.types.is_date32(kind) or pa.types.is_time32(kind): + array = array.view(pa.int32()) + elif pa.types.is_temporal(kind): + array = array.view(pa.int64()) + values = array.to_pylist() + if pa.types.is_floating(kind) and any( + value is not None and value != value for value in values + ): + raise LogicalSetCanonicalOrderError( + "a NaN key or set element has no canonical order" + ) + return values + + +def _struct_keys(array: pa.StructArray, keys: list[_Keys]) -> list[Any]: + """Preserve field order and distinguish a null struct from null fields.""" + rows: list[Any] = ( + list(zip(*(key(array.field(i)) for i, key in enumerate(keys)), strict=True)) + if keys + else [()] * len(array) + ) + if array.null_count: + return [ + row if valid else None + for row, valid in zip(rows, array.is_valid().to_pylist(), strict=True) + ] + return rows + + +def _list_keys( + array: pa.Array[Any], child_keys: _Keys, collect: Callable[[list[Any]], Any] +) -> list[Any]: + """Build bounded Python keys without sorting or ranking Arrow arrays.""" + if isinstance(array, pa.LargeListArray) and not array.null_count: + # Arrow offsets are non-null even when a parent list can be null. + offsets = cast(list[int], array.offsets.to_pylist()) + values = array.values + first = offsets[0] + if first or offsets[-1] != len(values): + values = values.slice(first, offsets[-1] - first) + children = child_keys(values) + return [ + collect(children[start - first : end - first]) + for start, end in pairwise(offsets) + ] + children = child_keys(cast("_ListArray", array).flatten()) + offset = 0 + rows: list[Any] = [] + for length in pc.list_value_length(array).to_pylist(): + if length is None: + rows.append(None) + else: + rows.append(collect(children[offset : offset + length])) + offset += length + return rows + + +def _validate_unique(keys: list[Any]) -> frozenset[Any]: + """Compare all keys in a single unordered container.""" + distinct = frozenset(keys) + if len(distinct) != len(keys): + raise LogicalSetCanonicalOrderError("duplicate key or set element") + return distinct + + +def _dict_key(entries: list[tuple[Any, Any]]) -> frozenset[tuple[Any, Any]]: + """Check dictionary key uniqueness independently of entry values.""" + _validate_unique([key for key, _ in entries]) + return frozenset(entries) + + +def _struct_normalizer( + kind: pa.StructType, fields: dict[int, _StorageNormalizer] +) -> _StorageNormalizer | None: + """Combine the fields that need storage ordering.""" + if not fields: + return None + + def normalize(array: pa.Array[Any]) -> pa.StructArray: + struct = cast(pa.StructArray, array) + children = [struct.field(i) for i in range(kind.num_fields)] + for i, operation in fields.items(): + children[i] = operation(children[i]) + return pa.StructArray.from_arrays( + children, + fields=list(kind), + mask=pc.is_null(struct) if struct.null_count else None, + ) + + return normalize + + +def _list_plan( + encode: _Encode, + normalize_child: _StorageNormalizer | None, + child_keys: _Keys, + *, + canonical_set: bool = False, + canonical_dict: bool = False, + scalar_set: bool = False, +) -> _StoragePlan: + """Resolve an ordered list or an unordered container and its descendants.""" + + def normalize(array: pa.Array[Any]) -> pa.LargeListArray[Any]: + storage = cast("pa.LargeListArray[Any]", array) + if normalize_child is not None: + storage = _list_with_values(storage, normalize_child(storage.values)) + if canonical_set or canonical_dict: + return _order_unordered_lists(storage, dict_keys=canonical_dict) + if scalar_set: + return _validate_scalar_column(storage) + return storage + + collect = ( + _dict_key if canonical_dict else _validate_unique if canonical_set else tuple + ) + return _StoragePlan( + encode, + normalize + if normalize_child is not None or canonical_set or canonical_dict or scalar_set + else None, + lambda array: _list_keys(array, child_keys, collect), + child_keys if canonical_set else None, + ) + + +def storage_plan( + annotation: Any, + kind: pa.DataType, + converter: TypeConverterProtocol, + fallback: Callable[[Any], _Encode], + *, + canonical: bool = False, +) -> _StoragePlan: + """Resolve the operations for a column containing sets of logical types.""" + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType + from orcapod.semantic_types.universal_converter import _none_not_admitted + + logical_type = converter.get_logical_type_for_python_type(annotation) + origin = get_origin(annotation) + args = get_args(annotation) + + def resolve( + child_annotation: Any, child_kind: pa.DataType, *, ordered: bool = canonical + ) -> _StoragePlan: + return storage_plan( + child_annotation, child_kind, converter, fallback, canonical=ordered + ) + + if ( + origin in (types.UnionType, typing.Union) + and len(args) == 2 + and type(None) in args + ): + child = resolve(next(arg for arg in args if arg is not type(None)), kind) + return _StoragePlan( + lambda value: None if value is None else child.encode(value), + child.normalize, + child.keys, + ) + + if isinstance(logical_type, UserClassLogicalType) and isinstance( + kind, pa.StructType + ): + fields = [ + resolve(field_annotation, kind.field(name).type) + for name, field_annotation in logical_type.field_annotations + ] + operations = { + i: field.normalize + for i, field in enumerate(fields) + if field.normalize is not None + } + if canonical or operations: + field_encoder = _FieldEncoder( + converter, + { + field_annotation: field.encode + for (_, field_annotation), field in zip( + logical_type.field_annotations, fields, strict=True + ) + }, + ) + + def encode_struct(value: Any) -> Any: + if value is None: + raise _none_not_admitted(annotation) + return logical_type.python_to_storage( + value, cast("TypeConverterProtocol", cast(object, field_encoder)) + ) + + keys = [field.keys or _stored_keys for field in fields] + return _StoragePlan( + encode_struct, + _struct_normalizer(kind, operations), + lambda array: _struct_keys(cast(pa.StructArray, array), keys), + ) + + if ( + isinstance(kind, pa.LargeListType) + and origin in (list, set, dict, tuple) + and args + ): + if origin is dict: + if not canonical: + return _StoragePlan(fallback(annotation)) + entry = cast(pa.StructType, kind.value_type) + key = resolve(args[0], entry.field("key").type) + item = resolve(args[1], entry.field("value").type) + + def encode_dict(value: Any) -> list[dict[str, Any]]: + if value is None: + raise _none_not_admitted(annotation) + return [ + {"key": key.encode(k), "value": item.encode(v)} + for k, v in value.items() + ] + + operations = { + i: field.normalize + for i, field in enumerate((key, item)) + if field.normalize is not None + } + entry_keys = [key.keys or _stored_keys, item.keys or _stored_keys] + return _list_plan( + encode_dict, + _struct_normalizer(entry, operations), + lambda array: _struct_keys(cast(pa.StructArray, array), entry_keys), + canonical_dict=True, + ) + + struct_set = scalar_set = False + if origin is set and isinstance(logical_type, ListLogicalType): + struct_set = logical_type._orders_stored_sets + scalar_set = logical_type._validates_scalar_sets + child = resolve(args[0], kind.value_type, ordered=canonical or struct_set) + if canonical or struct_set or scalar_set or child.normalize is not None: + encode_item = child.encode + + def encode_container(value: Any) -> Any: + if value is None: + raise _none_not_admitted(annotation) + items = [encode_item(item) for item in value] + if scalar_set and not canonical: + try: + return sorted(items) + except TypeError: + return sorted(items, key=repr) + if canonical and origin is list and isinstance(value, set): + return ordered_set_storage( + items, kind.value_type, normalize=child.normalize + ) + return items + + return _list_plan( + encode_container, + child.normalize, + child.keys or _stored_keys, + canonical_set=struct_set or (canonical and origin is set), + scalar_set=scalar_set and not canonical, + ) + + if canonical and origin is tuple and isinstance(kind, pa.StructType): + fields = [ + resolve(arg, field.type) for arg, field in zip(args, kind, strict=True) + ] + + def encode_tuple(value: Any) -> dict[str, Any]: + return {f"f{i}": fields[i].encode(item) for i, item in enumerate(value)} + + operations = { + i: field.normalize + for i, field in enumerate(fields) + if field.normalize is not None + } + keys = [field.keys or _stored_keys for field in fields] + return _StoragePlan( + encode_tuple, + _struct_normalizer(kind, operations), + lambda array: _struct_keys(cast(pa.StructArray, array), keys), + ) + + return _StoragePlan(fallback(annotation)) + + +def validate_struct_set( + plan: _StoragePlan, value: Any, storage_type: pa.LargeListType[Any] +) -> None: + """Refuse invalid stored keys before exposing a function's Python output.""" + if not value: + return + try: + encoded = plan.encode(value) + array = pa.array(encoded, type=storage_type.value_type) + assert plan.element_keys is not None + keys = plan.element_keys(array) + if len(keys) > 1: + _validate_unique(keys) + except (TypeError, pa.ArrowException) as exc: + raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 6c4327801..b4e7d8fee 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -50,15 +50,34 @@ def __init__( self._arrow_to_python_converters: dict[str, Callable[[Any], Any]] = {} for field_name, python_type in self.python_schema.items(): - self._python_to_arrow_converters[field_name] = ( - self.universal_converter.get_python_to_arrow_converter(python_type) + encode = self.universal_converter.get_python_to_arrow_converter(python_type) + field_type = self.arrow_schema.field(field_name).type + storage = ( + field_type.storage_type + if isinstance(field_type, pa.ExtensionType) + else field_type ) + if self.universal_converter._contains_checked_set(python_type, storage): + encode = self._with_column(encode, field_name) + self._python_to_arrow_converters[field_name] = encode for field in self.arrow_schema: self._arrow_to_python_converters[field.name] = ( self.universal_converter.get_arrow_to_python_converter(field.type) ) + @staticmethod + def _with_column(encode: Callable[[Any], Any], name: str) -> Callable[[Any], Any]: + """Add the column to errors from a logical-set converter.""" + + def convert(value: Any) -> Any: + try: + return encode(value) + except LogicalSetCanonicalOrderError as exc: + raise LogicalSetCanonicalOrderError(f"Column {name!r}: {exc}") from exc + + return convert + def python_dict_to_struct_dict(self, record: dict[str, Any]) -> dict[str, Any]: """ Convert a single Python dictionary to an Arrow-compatible struct dictionary. @@ -93,12 +112,7 @@ def _convert_rows( converted_record[field_name] = None else: # Convert using the pre-computed converter - try: - converted_record[field_name] = converter(value) - except LogicalSetCanonicalOrderError as exc: - raise LogicalSetCanonicalOrderError( - f"Column {field_name!r}: {exc}" - ) from exc + converted_record[field_name] = converter(value) converted_data.append(converted_record) return converted_data @@ -157,14 +171,17 @@ def python_dicts_to_arrow_table( encoded_columns = self.universal_converter._encode_set_columns( data, self.python_schema, schema, allow_explicit_null=True ) - converters = self._python_to_arrow_converters - if encoded_columns: - encoded_names = {schema.field(index).name for index in encoded_columns} - converters = { - name: converter - for name, converter in converters.items() - if name not in encoded_names - } + if not encoded_columns: + return pa.Table.from_pylist( + self.python_dicts_to_struct_dicts(data), schema=schema + ) + + encoded_names = {schema.field(index).name for index in encoded_columns} + converters = { + name: converter + for name, converter in self._python_to_arrow_converters.items() + if name not in encoded_names + } return table_from_storage( self._convert_rows(data, converters), schema, diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index cf68eb098..cd08581e8 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -34,8 +34,6 @@ UnsupportedValueError, ) from orcapod.semantic_types.canonical_order import ( - _in_logical_set, - ordered_set_storage, sort_dict_entries, sort_set_elements, ) @@ -55,6 +53,7 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: + from orcapod.semantic_types.logical_set_storage import _StoragePlan from orcapod.logical_types.registry import LogicalTypeRegistry from orcapod.logical_types.protocols import ( LogicalTypeFactoryProtocol, @@ -277,6 +276,8 @@ def __init__( self._python_to_arrow_converters: dict[DataType, Callable] = {} self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} + self._set_storage_plans: dict[tuple[DataType, pa.DataType], _StoragePlan] = {} + # Cache for type mappings self._python_to_arrow_types: dict[DataType, pa.DataType] = {} self._arrow_to_python_types: dict[pa.DataType, DataType] = {} @@ -1405,57 +1406,128 @@ def _storage_table( ) -> pa.Table: """Batch logical set columns and convert the remaining cells as usual.""" encoded_columns = self._encode_set_columns(rows, python_schema, arrow_schema) + if not encoded_columns: + struct_dicts = self.python_dicts_to_struct_dicts( + rows, python_schema=python_schema + ) + return pa.Table.from_pylist(struct_dicts, schema=arrow_schema) + encoded_names = {arrow_schema.field(index).name for index in encoded_columns} - remaining_schema = ( - { - name: annotation - for name, annotation in python_schema.items() - if name not in encoded_names - } - if encoded_columns - else python_schema - ) + remaining_schema = { + name: annotation + for name, annotation in python_schema.items() + if name not in encoded_names + } struct_dicts = self.python_dicts_to_struct_dicts(rows, remaining_schema) return arrow_utils.table_from_storage( struct_dicts, arrow_schema, encoded_columns=encoded_columns ) - def _validate_output_storage( - self, row: dict[str, Any], python_schema: SchemaLike - ) -> None: - """Validate a function's output row before exposing its Python values.""" + def _set_storage_plan( + self, annotation: DataType, storage_type: pa.DataType + ) -> _StoragePlan: + """Resolve and cache the converters for a logical-set column.""" + from orcapod.semantic_types.logical_set_storage import storage_plan + + key = (annotation, storage_type) + plan = self._set_storage_plans.get(key) + if plan is None: + plan = storage_plan( + annotation, storage_type, self, self.get_python_to_arrow_converter + ) + self._set_storage_plans[key] = plan + return plan + + def _contains_checked_set(self, annotation: DataType, kind: pa.DataType) -> bool: + """Select specialized storage at the schema boundary.""" + if not isinstance(kind, (pa.LargeListType, pa.StructType)): + return False + if self._logical_type_registry is None: + return False + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType - validated = set() + origin = get_origin(annotation) + args = get_args(annotation) + if ( + origin in (typing.Union, types.UnionType) + and len(args) == 2 + and type(None) in args + ): + return self._contains_checked_set( + next(arg for arg in args if arg is not type(None)), kind + ) + if isinstance(kind, pa.LargeListType): + if origin is set: + logical_type = self._logical_type_registry.get_by_python_type( + typing.cast(type, annotation) + ) + return isinstance(logical_type, ListLogicalType) and ( + logical_type._orders_stored_sets + or logical_type._validates_scalar_sets + ) + return ( + origin is list + and bool(args) + and self._contains_checked_set(args[0], kind.value_type) + ) + + logical_type = self._logical_type_registry.get_by_python_type( + typing.cast(type, annotation) + ) + return isinstance(logical_type, UserClassLogicalType) and any( + self._contains_checked_set(field_annotation, kind.field(name).type) + for name, field_annotation in logical_type.field_annotations + ) + + def _eager_set_output_validator( + self, python_schema: SchemaLike + ) -> Callable[[list[dict[str, Any]], SchemaLike], None] | None: + """Resolve eager struct-set validation once for a function's output schema.""" + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + + checked: dict[str, tuple[_StoragePlan, pa.LargeListType[Any]]] = {} for name, annotation in python_schema.items(): - value = row.get(name) - if not isinstance(value, set): - continue - if get_origin(annotation) in (typing.Union, types.UnionType): + origin = get_origin(annotation) + if origin in (typing.Union, types.UnionType): args = get_args(annotation) if len(args) == 2 and type(None) in args: annotation = next(arg for arg in args if arg is not type(None)) + if get_origin(annotation) is not set: + continue logical_type = self.get_logical_type(typing.cast(type, annotation)) if ( not isinstance(logical_type, ListLogicalType) or not logical_type._orders_stored_sets ): continue - try: - logical_type._validate_python_set(value, self) - except CanonicalOrderError as exc: - raise type(exc)(f"Column {name!r}: {exc}") from exc - validated.add(name) - - if not validated: - self.python_dicts_to_arrow_table([row], python_schema=python_schema) - elif len(validated) != len(python_schema): - remaining = { - name: annotation - for name, annotation in python_schema.items() - if name not in validated - } - self.python_dicts_to_arrow_table([row], python_schema=remaining) + storage = logical_type.get_arrow_extension_type().storage_type + assert isinstance(storage, pa.LargeListType) + checked[name] = (self._set_storage_plan(annotation, storage), storage) + + if not checked: + return None + + from orcapod.semantic_types.logical_set_storage import validate_struct_set + + remaining = { + name: annotation + for name, annotation in python_schema.items() + if name not in checked + } + + def validate(rows: list[dict[str, Any]], _schema: SchemaLike) -> None: + row = rows[0] + for name, (plan, storage) in checked.items(): + try: + validate_struct_set(plan, row.get(name), storage) + except CanonicalOrderError as exc: + raise type(exc)(f"Column {name!r}: {exc}") from exc + if remaining: + self.python_dicts_to_arrow_table(rows, python_schema=remaining) + + return validate def _encode_set_columns( self, @@ -1465,51 +1537,50 @@ def _encode_set_columns( *, allow_explicit_null: bool = False, ) -> dict[int, pa.Array[Any]]: - """Encode each canonical set column in one pass, by Arrow field index.""" - if len(rows) <= 1 or self._logical_type_registry is None: + """Encode each eligible column once, by Arrow field index.""" + if not rows or self._logical_type_registry is None: return {} - from orcapod.logical_types.list_logical_type_factory import ListLogicalType - encoded_columns: dict[int, pa.Array[Any]] = {} - registry = self._logical_type_registry for index, field in enumerate(arrow_schema): field_type = field.type - if not isinstance( - field_type, pa.ExtensionType - ) or not field_type.extension_name.startswith(("set[", "list[")): - continue + storage_type = ( + field_type.storage_type + if isinstance(field_type, pa.ExtensionType) + else field_type + ) annotation = python_schema.get(field.name) - nullable = allow_explicit_null - if get_origin(annotation) in (typing.Union, types.UnionType): - args = get_args(annotation) - if len(args) == 2 and type(None) in args: - annotation = next(arg for arg in args if arg is not type(None)) - nullable = True - if get_origin(annotation) not in (set, list): - continue - logical_type = registry.get_by_python_type(typing.cast(type, annotation)) - if ( - not isinstance(logical_type, ListLogicalType) - or not logical_type._batches_sets - or not field_type.equals(logical_type.get_arrow_extension_type()) + if annotation is None or not self._contains_checked_set( + annotation, storage_type ): continue + if not field_type.equals(self.python_type_to_arrow_type(annotation)): + continue + args = get_args(annotation) + nullable = allow_explicit_null or ( + get_origin(annotation) in (typing.Union, types.UnionType) + and len(args) == 2 + and type(None) in args + ) values = [row.get(field.name) for row in rows] - # A present None for a required type still takes the converter's - # usual error path. A missing cell is handled as a null as before. + # The ordinary converter diagnoses a present null of a required type. if not nullable and any( value is None and field.name in row for value, row in zip(values, rows, strict=True) ): continue try: - storage = logical_type._python_values_to_storage(values, self) + plan = self._set_storage_plan(annotation, storage_type) + storage = plan.encode_column(values, storage_type) except CanonicalOrderError as exc: raise type(exc)(f"Column {field.name!r}: {exc}") from exc except UnsupportedValueError as exc: raise UnsupportedValueError(f"Column {field.name!r}: {exc}") from exc - encoded_columns[index] = pa.ExtensionArray.from_storage(field_type, storage) + encoded_columns[index] = ( + pa.ExtensionArray.from_storage(field_type, storage) + if isinstance(field_type, pa.ExtensionType) + else storage + ) return encoded_columns def arrow_table_to_python_dicts( @@ -2017,20 +2088,16 @@ def _convert_datetime(dt: datetime) -> datetime: elif origin is list: element_converter = self.get_python_to_arrow_converter(args[0]) - def convert_list(value: Any) -> list[Any] | pa.Array[Any]: + def convert_list(value: Any) -> list[Any]: """Convert list storage, preserving set order independence on updates.""" if value is None: raise _none_not_admitted(python_type) elements = [element_converter(item) for item in value] # An Arrow schema remembers a plain set only as a list. Python set # inputs still need canonical storage order; actual lists keep theirs. - if not isinstance(value, set): - return elements - if _in_logical_set.get(): - return ordered_set_storage( - elements, self.python_type_to_arrow_type(args[0]) - ) - return sort_set_elements(elements) + return ( + sort_set_elements(elements) if isinstance(value, set) else elements + ) return convert_list @@ -2043,11 +2110,12 @@ def convert_list(value: Any) -> list[Any] | pa.Array[Any]: def convert_dict(value: Any) -> list[dict[str, Any]]: if value is None: raise _none_not_admitted(python_type) - entries = [ - {"key": key_converter(k), "value": value_converter(v)} - for k, v in value.items() - ] - return entries if _in_logical_set.get() else sort_dict_entries(entries) + return sort_dict_entries( + [ + {"key": key_converter(k), "value": value_converter(v)} + for k, v in value.items() + ] + ) return convert_dict @@ -2059,10 +2127,7 @@ def convert_dict(value: Any) -> list[dict[str, Any]]: def convert_set(value: Any) -> list[Any]: if value is None: raise _none_not_admitted(python_type) - elements = [element_converter(item) for item in value] - return ( - elements if _in_logical_set.get() else sort_set_elements(elements) - ) + return sort_set_elements([element_converter(item) for item in value]) return convert_set @@ -2279,6 +2344,7 @@ def clear_cache(self) -> None: self._typeddict_to_struct_signature.clear() self._created_type_names.clear() self._python_to_arrow_converters.clear() + self._set_storage_plans.clear() self._arrow_to_python_converters.clear() self._python_to_arrow_types.clear() self._arrow_to_python_types.clear() diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index c39cf905e..007d2e40e 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -1323,3 +1323,46 @@ def test_function_iteration_refuses_equal_logical_set_storage() -> None: ).pod(make_source()) with pytest.raises(errors.CanonicalOrderError, match=r"Column 'y': .*duplicate"): next(stream.iter_data()) + + +def test_eager_nested_dict_set_validation_does_not_sort_storage( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Eager iteration checks the stored keys without sorting Arrow arrays.""" + sorts: list[int] = [] + original_sort = pc.sort_indices + + def record_size(values: Any, *args: Any, **kwargs: Any) -> Any: + sorts.append(len(values)) + return original_sort(values, *args, **kwargs) + + monkeypatch.setattr(pc, "sort_indices", record_size) + pod = make_pod(set[WithDict], {WithDict({2.0: 2, 1.0: 1})}, name="result") + assert len(list(pod.pod(make_source((0, 1))).iter_data())) == 2 + assert sorts == [] + + +def test_plain_output_iteration_uses_native_storage() -> None: + """Ordinary function outputs retain their native row converter.""" + import sys + + pod = make_pod(dict[int, int], {2: 3}, name="mapping") + stream = pod.pod(make_source((0, 1))) + entered: set[str] = set() + + def record_call(frame: types.FrameType, event: str, _arg: Any) -> None: + if event == "call": + code = frame.f_code + if code.co_filename.endswith("/logical_set_storage.py") or code.co_name == ( + "_validate_output_storage" + ): + entered.add(code.co_name) + + previous = sys.getprofile() + sys.setprofile(record_call) + try: + assert len(list(stream.iter_data())) == 2 + finally: + sys.setprofile(previous) + + assert entered == set() diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index 0d7b3c6f9..d873c0bf7 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -40,10 +40,8 @@ make_arrow_extension_type, make_polars_extension_type, ) -from orcapod.semantic_types.canonical_order import ( - ordered_set_storage, - sort_set_elements, -) +from orcapod.semantic_types.canonical_order import sort_set_elements +from orcapod.semantic_types.logical_set_storage import ordered_set_storage from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.sources import DictSource from orcapod.types import Schema @@ -883,12 +881,12 @@ def test_list_keys_skip_python_ranking( monkeypatch: pytest.MonkeyPatch, item_type: pa.DataType, low: Any, high: Any ) -> None: """Rank variable-width nullable list keys without decoding Python values.""" - from orcapod.semantic_types import canonical_order + from orcapod.semantic_types import logical_set_storage def unexpected(_keys: object) -> Never: pytest.fail("list keys entered Python ranking") - monkeypatch.setattr(canonical_order, "_ordinal_column", unexpected) + monkeypatch.setattr(logical_set_storage, "_ordinal_column", unexpected) shape = pa.struct([("items", pa.large_list(item_type)), ("value", pa.int64())]) tied = -0.0 if pa.types.is_floating(item_type) else low first = 0.0 if pa.types.is_floating(item_type) else low @@ -1055,16 +1053,16 @@ def test_scalar_logical_sets_validate_once_per_column( monkeypatch: pytest.MonkeyPatch, ) -> None: """Check for duplicates across a column without mixing set rows.""" - from orcapod.semantic_types import canonical_order + from orcapod.semantic_types import logical_set_storage - require_distinct = canonical_order._require_distinct + validate = logical_set_storage._validate_scalar_column sizes: list[int] = [] - def record_size(columns: list[pa.Array[Any]]) -> None: - sizes.append(len(columns[0])) - require_distinct(columns) + def record_size(storage: pa.LargeListArray[Any]) -> pa.LargeListArray[Any]: + sizes.append(len(storage.values)) + return validate(storage) - monkeypatch.setattr(canonical_order, "_require_distinct", record_size) + monkeypatch.setattr(logical_set_storage, "_validate_scalar_column", record_size) converter = get_default_context().type_converter schema = {"s": set[Word]} converter.ensure_types_registered_for_schemas(Schema(schema)) @@ -1072,3 +1070,111 @@ def record_size(columns: list[pa.Array[Any]]) -> None: table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) assert table["s"].to_pylist() == [["a", "z"]] * 8 assert sizes == [16] + + +@dataclasses.dataclass +class PointSetWrapper: + """A user class nesting a logical set inside an ordered list column.""" + + entries: set[ExactPoint] + + +def test_wrapped_struct_sets_share_one_sort(monkeypatch: pytest.MonkeyPatch) -> None: + """Batch an array of wrapper structs without changing list positions.""" + original_sort = pc.sort_indices + sort_sizes: list[int] = [] + + def record_size(values: Any, *args: Any, **kwargs: Any) -> Any: + sort_sizes.append(len(values)) + return original_sort(values, *args, **kwargs) + + monkeypatch.setattr(pc, "sort_indices", record_size) + converter = get_default_context().type_converter + schema = {"s": list[PointSetWrapper]} + values = [ + PointSetWrapper({ExactPoint(i + 10, "z"), ExactPoint(i + 2, "a")}) + for i in range(32) + ] + [PointSetWrapper(set())] + result = converter.python_dicts_to_arrow_table( + [{"s": values}], python_schema=schema + ) + assert sort_sizes == [64] + assert result["s"].to_pylist() == [ + [ + {"entries": [{"a": i + 2, "b": "a"}, {"a": i + 10, "b": "z"}]} + for i in range(32) + ] + + [{"entries": []}] + ] + + +def test_plain_columns_use_native_converters() -> None: + """Keep built-in sets and plain values out of the logical-set implementation.""" + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter + + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema = { + "path": set[Path], + "mapping": dict[int, int], + "items": list[int], + "binary": bytes, + "scalar": int, + } + converter.ensure_types_registered_for_schemas(Schema(schema)) + writer = SemanticSchemaConverter(converter, schema) + rows = [ + { + "path": {Path("/b")}, + "mapping": {}, + "items": [2], + "binary": b"b", + "scalar": 7, + }, + {"path": set(), "mapping": {1: 2}, "items": [], "binary": b"a", "scalar": 2}, + ] + entered: set[str] = set() + + def record_call(frame: Any, event: str, _arg: Any) -> None: + if event == "call": + code = frame.f_code + if code.co_filename.endswith("/logical_set_storage.py") or code.co_name in { + "_encode_elements", + "_native_sort", + "table_from_storage", + }: + entered.add(code.co_name) + + previous = sys.getprofile() + sys.setprofile(record_call) + try: + result = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + precomputed = writer.python_dicts_to_arrow_table(rows) + finally: + sys.setprofile(previous) + + assert result["path"].to_pylist() == [["/b"], []] + assert result.equals(precomputed) + assert entered == set() + + +@pytest.mark.usefixtures("registered_types") +def test_short_scalar_sets_validate_without_grouping( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """One- and two-item sets use column-wide adjacency with row boundaries.""" + from orcapod.semantic_types import logical_set_storage + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("small custom scalar sets entered Arrow grouping") + + monkeypatch.setattr(logical_set_storage, "_require_distinct", unexpected) + converter = get_default_context().type_converter + schema = {"s": set[Word]} + rows = [{"s": {Word("z"), Word("A")}}, {"s": {Word("Z")}}, {"s": set()}] + result = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + assert result["s"].to_pylist() == [["a", "z"], ["z"], []] + + rows[1]["s"] = {Word("Z"), Word("z")} + with pytest.raises(CanonicalOrderError, match=r"Column 's': duplicate"): + converter.python_dicts_to_arrow_table(rows, python_schema=schema) From a44f381aac4d79e9ec2ef7d7eeb9dd563adaae40 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 10:44:39 -0800 Subject: [PATCH 08/18] fix(logical_types): restore direct set decoding and speed small writes --- changelog.d/ITL-922.md | 2 + docs/dev/design_issues/ITL-922-DO2.md | 3 + .../list_logical_type_factory.py | 8 ++ .../semantic_types/logical_set_storage.py | 71 +++++++++++- .../semantic_types/precomputed_converters.py | 19 ++- .../semantic_types/universal_converter.py | 108 ++++++++++++++---- .../test_set_of_logical_elements.py | 105 ++++++++++++++++- 7 files changed, 285 insertions(+), 31 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index fc22a53bb..ee2bfdd2e 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -17,3 +17,5 @@ - Table conversion batches struct sets in columns, including sets nested in lists and user classes. Nested dictionary keys, set items, and list comparison keys use Arrow or Polars kernels. +- Direct structural-dictionary conversion round-trips sets of logical values, + including struct fields with their own logical decoders. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index a5ca4060c..6a8f54a7d 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -16,6 +16,9 @@ list field. Sort nested dict keys and set items in their own declared storage types before comparing the enclosing elements. Check adjacent sorted values for duplicates within each set. Multi-row table conversion encodes and sorts each set column in one pass, including sets nested in lists and user classes. +Small sets with flat exact keys compare the coerced Arrow values without +constructing a sort table. Direct structural-dictionary reads pass Python +storage values to each logical decoder. Function iteration checks the coerced storage keys for NaNs and duplicates without sorting the row. Sets of other logical types keep their native sort. For user-defined scalar diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 722d1f331..a7e3e274c 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -456,6 +456,14 @@ def storage_to_python( class _ValidatedSetLogicalType(ListLogicalType): """A logical set whose storage must be checked after Arrow conversion.""" + def storage_to_python( + self, storage_value: Any, converter: TypeConverterProtocol | None + ) -> list[Any] | set[Any]: + """Give the element decoders Python values on direct dictionary reads.""" + if isinstance(storage_value, pa.Array): + storage_value = storage_value.to_pylist() + return super().storage_to_python(storage_value, converter) + def python_to_storage( self, value: Any, converter: TypeConverterProtocol | None ) -> Any: diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py index 4992d01d5..9b7615f30 100644 --- a/src/orcapod/semantic_types/logical_set_storage.py +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -247,7 +247,10 @@ def _list_with_values( ) -> pa.LargeListArray[Any]: """Rebuild list storage with the same offsets, type and validity.""" return pa.LargeListArray.from_arrays( - storage.offsets, values, type=storage.type, mask=pc.is_null(storage) + storage.offsets, + values, + type=storage.type, + mask=pc.is_null(storage) if storage.null_count else None, ) @@ -273,12 +276,27 @@ def _validate_scalar_column(storage: pa.LargeListArray[Any]) -> pa.LargeListArra def _order_unordered_lists( - storage: pa.LargeListArray[Any], *, dict_keys: bool = False + storage: pa.LargeListArray[Any], + *, + dict_keys: bool = False, + small_struct_keys: bool = False, ) -> pa.LargeListArray[Any]: """Sort and check dict keys or set items in one pass across their parents.""" elements = storage.values if not len(elements): return storage + # Keep the Python comparison and offset walk bounded. Larger columns use + # one parent-aware Arrow sort, regardless of the number of individual sets. + if ( + small_struct_keys + and len(elements) <= 32 + and len(storage) <= 32 + and not elements.null_count + ): + struct = cast(pa.StructArray, elements) + fields = struct.flatten() + if not any(field.null_count for field in fields): + return _order_small_struct_sets(storage, fields) keys = cast(pa.StructArray, elements).field("key") if dict_keys else elements columns = _sort_columns(keys) if pc.max(pc.list_value_length(storage)).as_py() <= 1: @@ -288,6 +306,31 @@ def _order_unordered_lists( ) +def _order_small_struct_sets( + storage: pa.LargeListArray[Any], fields: list[pa.Array[Any]] +) -> pa.LargeListArray[Any]: + """Compare small non-null flat sets using keys from coerced Arrow columns.""" + keys = list(zip(*(field.to_pylist() for field in fields), strict=True)) + key_at = keys.__getitem__ + indices: list[int] = [] + changed = False + # This is a fresh list array and its offsets have no nulls. + offsets = cast(list[int], storage.offsets.to_pylist()) + for start, stop in pairwise(offsets): + if stop - start <= 1: + indices.extend(range(start, stop)) + continue + ordered = sorted(range(start, stop), key=key_at) + for left, right in pairwise(ordered): + if keys[left] == keys[right]: + raise LogicalSetCanonicalOrderError("duplicate key or set element") + changed |= left > right + indices.extend(ordered) + if not changed: + return storage + return _list_with_values(storage, storage.values.take(indices)) + + def _sort_set_array( array: pa.Array[Any], columns: list[pa.Array[Any]] ) -> pa.Array[Any]: @@ -477,6 +520,7 @@ def _list_plan( canonical_set: bool = False, canonical_dict: bool = False, scalar_set: bool = False, + small_struct_keys: bool = False, ) -> _StoragePlan: """Resolve an ordered list or an unordered container and its descendants.""" @@ -485,7 +529,9 @@ def normalize(array: pa.Array[Any]) -> pa.LargeListArray[Any]: if normalize_child is not None: storage = _list_with_values(storage, normalize_child(storage.values)) if canonical_set or canonical_dict: - return _order_unordered_lists(storage, dict_keys=canonical_dict) + return _order_unordered_lists( + storage, dict_keys=canonical_dict, small_struct_keys=small_struct_keys + ) if scalar_set: return _validate_scalar_column(storage) return storage @@ -638,6 +684,7 @@ def encode_container(value: Any) -> Any: child.keys or _stored_keys, canonical_set=struct_set or (canonical and origin is set), scalar_set=scalar_set and not canonical, + small_struct_keys=struct_set and _has_flat_exact_keys(kind.value_type), ) if canonical and origin is tuple and isinstance(kind, pa.StructType): @@ -663,6 +710,24 @@ def encode_tuple(value: Any) -> dict[str, Any]: return _StoragePlan(fallback(annotation)) +def _has_flat_exact_keys(kind: pa.DataType) -> bool: + """Select flat scalar keys with lossless Python and Arrow comparison.""" + return ( + isinstance(kind, pa.StructType) + and kind.num_fields > 0 + and all( + pa.types.is_integer(field.type) + or pa.types.is_boolean(field.type) + or pa.types.is_string(field.type) + or pa.types.is_large_string(field.type) + or pa.types.is_binary(field.type) + or pa.types.is_large_binary(field.type) + or pa.types.is_fixed_size_binary(field.type) + for field in kind + ) + ) + + def validate_struct_set( plan: _StoragePlan, value: Any, storage_type: pa.LargeListType[Any] ) -> None: diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index b4e7d8fee..f7a5fe59a 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -46,6 +46,9 @@ def __init__( ) # Pre-compute converters for each field + self._checked_columns = self.universal_converter._checked_set_columns( + self.python_schema, self.arrow_schema + ) self._python_to_arrow_converters: dict[str, Callable[[Any], Any]] = {} self._arrow_to_python_converters: dict[str, Callable[[Any], Any]] = {} @@ -167,9 +170,19 @@ def python_dicts_to_arrow_table( when the caller needs to enforce specific field types or nullable flags that differ from what was inferred at construction time. """ - schema = arrow_schema or self.arrow_schema - encoded_columns = self.universal_converter._encode_set_columns( - data, self.python_schema, schema, allow_explicit_null=True + schema, checked_columns = ( + (self.arrow_schema, self._checked_columns) + if not arrow_schema or arrow_schema is self.arrow_schema + else self.universal_converter._prepare_table_schema( + self.python_schema, arrow_schema + ) + ) + encoded_columns = ( + self.universal_converter._encode_set_columns( + data, checked_columns, allow_explicit_null=True + ) + if checked_columns + else {} ) if not encoded_columns: return pa.Table.from_pylist( diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index cd08581e8..8d406b0d9 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -20,7 +20,7 @@ from datetime import date, datetime, timezone # Handle generic types -from typing import TYPE_CHECKING, Any, TypedDict, get_args, get_origin +from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict, get_args, get_origin import pyarrow as pa @@ -83,6 +83,16 @@ ) +class _CheckedSetColumn(NamedTuple): + """A field that needs specialized set storage.""" + + field_index: int + field: pa.Field[Any] + storage_type: pa.DataType + plan: _StoragePlan + nullable: bool + + def _get_python_to_arrow_map() -> dict: """Return the Python→Arrow type map, building it on first call.""" global _PYTHON_TO_ARROW_MAP @@ -277,6 +287,15 @@ def __init__( self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} self._set_storage_plans: dict[tuple[DataType, pa.DataType], _StoragePlan] = {} + self._last_table_schema: ( + tuple[ + tuple[tuple[str, DataType], ...], + pa.Schema | None, + pa.Schema, + tuple[_CheckedSetColumn, ...], + ] + | None + ) = None # Cache for type mappings self._python_to_arrow_types: dict[DataType, pa.DataType] = {} @@ -1388,7 +1407,6 @@ def python_dicts_to_arrow_table( # a no-op for primitives and already-registered types. assert python_schema is not None, "Python schema should not be None here" self.ensure_types_registered_for_schemas(python_schema) - arrow_schema = self.python_schema_to_arrow_schema(python_schema) if python_schema is None: assert arrow_schema is not None, ( @@ -1402,10 +1420,15 @@ def _storage_table( self, rows: list[dict[str, Any]], python_schema: SchemaLike, - arrow_schema: pa.Schema, + arrow_schema: pa.Schema | None, ) -> pa.Table: """Batch logical set columns and convert the remaining cells as usual.""" - encoded_columns = self._encode_set_columns(rows, python_schema, arrow_schema) + arrow_schema, checked_columns = self._prepare_table_schema( + python_schema, arrow_schema + ) + encoded_columns = ( + self._encode_set_columns(rows, checked_columns) if checked_columns else {} + ) if not encoded_columns: struct_dicts = self.python_dicts_to_struct_dicts( rows, python_schema=python_schema @@ -1423,15 +1446,34 @@ def _storage_table( struct_dicts, arrow_schema, encoded_columns=encoded_columns ) + def _prepare_table_schema( + self, python_schema: SchemaLike, arrow_schema: pa.Schema | None + ) -> tuple[pa.Schema, tuple[_CheckedSetColumn, ...]]: + """Reuse the most recent table's schema and resolved set columns.""" + # Freeze the input so an edited dict cannot reuse a stale schema. Compare + # an explicit Arrow schema by identity to retain its extension metadata. + fields = tuple(python_schema.items()) + cached = self._last_table_schema + if cached is not None and arrow_schema is cached[1] and fields == cached[0]: + return cached[2], cached[3] + schema = ( + self.python_schema_to_arrow_schema(python_schema) + if arrow_schema is None + else arrow_schema + ) + checked_columns = self._checked_set_columns(python_schema, schema) + self._last_table_schema = (fields, arrow_schema, schema, checked_columns) + return schema, checked_columns + def _set_storage_plan( self, annotation: DataType, storage_type: pa.DataType ) -> _StoragePlan: """Resolve and cache the converters for a logical-set column.""" - from orcapod.semantic_types.logical_set_storage import storage_plan - key = (annotation, storage_type) plan = self._set_storage_plans.get(key) if plan is None: + from orcapod.semantic_types.logical_set_storage import storage_plan + plan = storage_plan( annotation, storage_type, self, self.get_python_to_arrow_converter ) @@ -1529,19 +1571,16 @@ def validate(rows: list[dict[str, Any]], _schema: SchemaLike) -> None: return validate - def _encode_set_columns( + def _checked_set_columns( self, - rows: list[dict[str, Any]], python_schema: SchemaLike, arrow_schema: pa.Schema, - *, - allow_explicit_null: bool = False, - ) -> dict[int, pa.Array[Any]]: - """Encode each eligible column once, by Arrow field index.""" - if not rows or self._logical_type_registry is None: - return {} + ) -> tuple[_CheckedSetColumn, ...]: + """Resolve the eligible columns and their converters once per schema.""" + if self._logical_type_registry is None: + return () - encoded_columns: dict[int, pa.Array[Any]] = {} + columns: list[_CheckedSetColumn] = [] for index, field in enumerate(arrow_schema): field_type = field.type storage_type = ( @@ -1557,25 +1596,49 @@ def _encode_set_columns( if not field_type.equals(self.python_type_to_arrow_type(annotation)): continue args = get_args(annotation) - nullable = allow_explicit_null or ( + nullable = ( get_origin(annotation) in (typing.Union, types.UnionType) and len(args) == 2 and type(None) in args ) - values = [row.get(field.name) for row in rows] + columns.append( + _CheckedSetColumn( + index, + field, + storage_type, + self._set_storage_plan(annotation, storage_type), + nullable, + ) + ) + return tuple(columns) + + def _encode_set_columns( + self, + rows: list[dict[str, Any]], + columns: tuple[_CheckedSetColumn, ...], + *, + allow_explicit_null: bool = False, + ) -> dict[int, pa.Array[Any]]: + """Encode each eligible column once, by Arrow field index.""" + if not rows: + return {} + encoded_columns: dict[int, pa.Array[Any]] = {} + for index, field, storage_type, plan, nullable in columns: + name = field.name + values = [row.get(name) for row in rows] # The ordinary converter diagnoses a present null of a required type. - if not nullable and any( - value is None and field.name in row + if not (allow_explicit_null or nullable) and any( + value is None and name in row for value, row in zip(values, rows, strict=True) ): continue try: - plan = self._set_storage_plan(annotation, storage_type) storage = plan.encode_column(values, storage_type) except CanonicalOrderError as exc: - raise type(exc)(f"Column {field.name!r}: {exc}") from exc + raise type(exc)(f"Column {name!r}: {exc}") from exc except UnsupportedValueError as exc: - raise UnsupportedValueError(f"Column {field.name!r}: {exc}") from exc + raise UnsupportedValueError(f"Column {name!r}: {exc}") from exc + field_type = field.type encoded_columns[index] = ( pa.ExtensionArray.from_storage(field_type, storage) if isinstance(field_type, pa.ExtensionType) @@ -2345,6 +2408,7 @@ def clear_cache(self) -> None: self._created_type_names.clear() self._python_to_arrow_converters.clear() self._set_storage_plans.clear() + self._last_table_schema = None self._arrow_to_python_converters.clear() self._python_to_arrow_types.clear() self._arrow_to_python_types.clear() diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index d873c0bf7..2f56f6c19 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -994,14 +994,14 @@ def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: converter.ensure_types_registered_for_schemas(Schema(schema)) data = [ { - "s": [{ExactPoint(i + 10, "z"), ExactPoint(i + 2, "a")} for i in range(8)] + "s": [{ExactPoint(i + 10, "z"), ExactPoint(i + 2, "a")} for i in range(32)] + [set()] } ] result = converter.python_dicts_to_arrow_table(data, python_schema=schema) - assert sizes == [16] + assert sizes == [64] assert result["s"].to_pylist() == [ - [[{"a": i + 2, "b": "a"}, {"a": i + 10, "b": "z"}] for i in range(8)] + [[]] + [[{"a": i + 2, "b": "a"}, {"a": i + 10, "b": "z"}] for i in range(32)] + [[]] ] @@ -1108,6 +1108,105 @@ def record_size(values: Any, *args: Any, **kwargs: Any) -> Any: ] +@dataclasses.dataclass(frozen=True) +class PathEntry: + """A structural set item whose nested Path needs logical decoding.""" + + number: int + path: Path + + +@pytest.mark.usefixtures("registered_types") +@pytest.mark.parametrize("precomputed", [False, True]) +def test_logical_sets_round_trip_through_struct_dicts(precomputed: bool) -> None: + """Pass Python storage values to logical decoders in both direct writers.""" + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter + + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema = {"entries": set[PathEntry], "words": set[Word]} + converter.ensure_types_registered_for_schemas(Schema(schema)) + row = {"entries": {PathEntry(2, Path("/a"))}, "words": {Word("a")}} + if precomputed: + writer = SemanticSchemaConverter(converter, schema) + restored = writer.struct_dict_to_python_dict( + writer.python_dict_to_struct_dict(row) + ) + else: + encoded = converter.python_dicts_to_struct_dicts([row], schema) + (restored,) = converter.struct_dict_to_python_dict( + encoded, converter.python_schema_to_arrow_schema(schema) + ) + assert restored == row + (word,) = restored["words"] + assert type(word.text) is str + + +@dataclasses.dataclass(frozen=True, eq=False) +class IdentityPoint: + """Distinct Python objects can have equal stored keys.""" + + value: int + + +def test_small_wrapped_struct_sets_skip_column_sort( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Order small sets by their stored keys without a column-wide sort.""" + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("small struct sets entered the column-wide sort") + + monkeypatch.setattr(pc, "sort_indices", unexpected) + converter = get_default_context().type_converter + schema = {"s": list[PointSetWrapper]} + values = [ + PointSetWrapper({ExactPoint(10, "z"), ExactPoint(2, "a")}), + PointSetWrapper(set()), + PointSetWrapper({ExactPoint(2, "z"), ExactPoint(2, "a")}), + ] + result = converter.python_dicts_to_arrow_table( + [{"s": values}], python_schema=schema + ) + assert result["s"].to_pylist() == [ + [ + {"entries": [{"a": 2, "b": "a"}, {"a": 10, "b": "z"}]}, + {"entries": []}, + {"entries": [{"a": 2, "b": "a"}, {"a": 2, "b": "z"}]}, + ] + ] + + duplicates = {"s": {IdentityPoint(2), IdentityPoint(2)}} + with pytest.raises(CanonicalOrderError, match=r"Column 's': duplicate"): + converter.python_dicts_to_arrow_table( + [duplicates], python_schema={"s": set[IdentityPoint]} + ) + + +def test_warm_native_table_writers_skip_checked_set_dispatch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Reuse native dispatch for the same schema without another field scan.""" + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter + + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema = {"path": set[Path], "mapping": dict[int, int]} + rows = [{"path": set(), "mapping": {}}] + expected = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + writer = SemanticSchemaConverter(converter, schema) + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("native write entered checked-set column encoding") + + monkeypatch.setattr(converter, "_encode_set_columns", unexpected) + monkeypatch.setattr(converter, "_checked_set_columns", unexpected, raising=False) + assert converter.python_dicts_to_arrow_table(rows, python_schema=schema).equals( + expected + ) + assert writer.python_dicts_to_arrow_table(rows).equals(expected) + + def test_plain_columns_use_native_converters() -> None: """Keep built-in sets and plain values out of the logical-set implementation.""" from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter From b522c550930bf87fb0fa1bba9a34d7ba2474b03f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 11:42:46 -0800 Subject: [PATCH 09/18] fix(logical_types): restore schema overrides and wrapped set iteration --- changelog.d/ITL-922.md | 2 + docs/dev/design_issues/ITL-922-DO2.md | 4 +- src/orcapod/core/function_pod.py | 8 +- .../semantic_types/logical_set_storage.py | 51 ++++- .../semantic_types/precomputed_converters.py | 11 +- .../semantic_types/universal_converter.py | 174 +++++++++++------- .../function_pod/test_output_conformance.py | 42 +++++ .../test_set_of_logical_elements.py | 95 ++++++++++ 8 files changed, 304 insertions(+), 83 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index ee2bfdd2e..f20e74b9d 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -19,3 +19,5 @@ keys use Arrow or Polars kernels. - Direct structural-dictionary conversion round-trips sets of logical values, including struct fields with their own logical decoders. +- Explicit Arrow schema overrides use the requested field types for logical set + writes. Function iteration validates wrapped sets without sorting each output. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 6a8f54a7d..25d926499 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -20,7 +20,9 @@ Small sets with flat exact keys compare the coerced Arrow values without constructing a sort table. Direct structural-dictionary reads pass Python storage values to each logical decoder. Function iteration checks the coerced storage keys for NaNs and duplicates -without sorting the row. +without sorting the row, including when a list or class wraps the set. +An explicit Arrow schema override uses its target field types and keeps the +user class's declared field order for comparison. Sets of other logical types keep their native sort. For user-defined scalar storage, one Arrow pass per table column rejects NaNs and duplicate stored values. The same ordering rules apply to classes rebuilt from metadata. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8d59da61b..3f382db14 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1575,9 +1575,13 @@ def _table_from_pairs( python_schema.update(self.output_schema()[1]) all_tags_as_tables = arrow_utils.concat_tables_by_name(tag_tables) assert data_schema is not None - if isinstance(converter, UniversalTypeConverter): + if isinstance(converter, UniversalTypeConverter) and ( + checked_columns := converter._explicit_checked_columns( + python_schema, data_schema + ) + ): all_data_as_tables = converter._storage_table( - all_data, python_schema, data_schema + all_data, python_schema, data_schema, checked_columns ) else: struct_data = converter.python_dicts_to_struct_dicts( diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py index 9b7615f30..9f780e424 100644 --- a/src/orcapod/semantic_types/logical_set_storage.py +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -359,6 +359,7 @@ def _sort_set_array( _Encode = Callable[[Any], Any] _Keys = Callable[["pa.Array[Any]"], list[Any]] +_Validate = Callable[["pa.Array[Any]"], None] @dataclass(frozen=True) @@ -369,6 +370,7 @@ class _StoragePlan: normalize: _StorageNormalizer | None = None keys: _Keys | None = None element_keys: _Keys | None = None + validate: _Validate | None = None def encode_column( self, values: list[Any], storage_type: pa.DataType @@ -521,6 +523,7 @@ def _list_plan( canonical_dict: bool = False, scalar_set: bool = False, small_struct_keys: bool = False, + validate_child: _Validate | None = None, ) -> _StoragePlan: """Resolve an ordered list or an unordered container and its descendants.""" @@ -539,6 +542,15 @@ def normalize(array: pa.Array[Any]) -> pa.LargeListArray[Any]: collect = ( _dict_key if canonical_dict else _validate_unique if canonical_set else tuple ) + + def validate(array: pa.Array[Any]) -> None: + if canonical_set: + _list_keys(array, child_keys, _validate_unique) + elif scalar_set: + _validate_scalar_column(cast("pa.LargeListArray[Any]", array)) + elif validate_child is not None: + validate_child(cast("pa.LargeListArray[Any]", array).values) + return _StoragePlan( encode, normalize @@ -546,6 +558,7 @@ def normalize(array: pa.Array[Any]) -> pa.LargeListArray[Any]: else None, lambda array: _list_keys(array, child_keys, collect), child_keys if canonical_set else None, + validate if canonical_set or scalar_set or validate_child is not None else None, ) @@ -583,6 +596,8 @@ def resolve( lambda value: None if value is None else child.encode(value), child.normalize, child.keys, + child.element_keys, + child.validate, ) if isinstance(logical_type, UserClassLogicalType) and isinstance( @@ -616,10 +631,22 @@ def encode_struct(value: Any) -> Any: ) keys = [field.keys or _stored_keys for field in fields] + validations = [ + (i, field.validate) + for i, field in enumerate(fields) + if field.validate is not None + ] + + def validate_fields(array: pa.Array[Any]) -> None: + struct = cast(pa.StructArray, array) + for i, validate in validations: + validate(struct.field(i)) + return _StoragePlan( encode_struct, _struct_normalizer(kind, operations), lambda array: _struct_keys(cast(pa.StructArray, array), keys), + validate=validate_fields if validations else None, ) if ( @@ -685,6 +712,7 @@ def encode_container(value: Any) -> Any: canonical_set=struct_set or (canonical and origin is set), scalar_set=scalar_set and not canonical, small_struct_keys=struct_set and _has_flat_exact_keys(kind.value_type), + validate_child=child.validate, ) if canonical and origin is tuple and isinstance(kind, pa.StructType): @@ -728,18 +756,23 @@ def _has_flat_exact_keys(kind: pa.DataType) -> bool: ) -def validate_struct_set( - plan: _StoragePlan, value: Any, storage_type: pa.LargeListType[Any] +def validate_set_output( + plan: _StoragePlan, value: Any, storage_type: pa.DataType ) -> None: - """Refuse invalid stored keys before exposing a function's Python output.""" - if not value: + """Validate declared storage without ordering the function's output row.""" + if value is None: return try: encoded = plan.encode(value) - array = pa.array(encoded, type=storage_type.value_type) - assert plan.element_keys is not None - keys = plan.element_keys(array) - if len(keys) > 1: - _validate_unique(keys) + if plan.element_keys is not None: + assert isinstance(storage_type, pa.LargeListType) + if encoded: + array = pa.array(encoded, type=storage_type.value_type) + keys = plan.element_keys(array) + if len(keys) > 1: + _validate_unique(keys) + else: + assert plan.validate is not None + plan.validate(pa.array([encoded], type=storage_type)) except (TypeError, pa.ArrowException) as exc: raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index f7a5fe59a..a9e9242e0 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -170,11 +170,12 @@ def python_dicts_to_arrow_table( when the caller needs to enforce specific field types or nullable flags that differ from what was inferred at construction time. """ - schema, checked_columns = ( - (self.arrow_schema, self._checked_columns) - if not arrow_schema or arrow_schema is self.arrow_schema - else self.universal_converter._prepare_table_schema( - self.python_schema, arrow_schema + schema = arrow_schema or self.arrow_schema + checked_columns = ( + self._checked_columns + if schema is self.arrow_schema + else self.universal_converter._explicit_checked_columns( + self.python_schema, schema ) ) encoded_columns = ( diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 8d406b0d9..99e50fd3d 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -18,6 +18,7 @@ import typing from collections.abc import Callable, Iterable, Mapping from datetime import date, datetime, timezone +from functools import lru_cache # Handle generic types from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict, get_args, get_origin @@ -91,6 +92,32 @@ class _CheckedSetColumn(NamedTuple): storage_type: pa.DataType plan: _StoragePlan nullable: bool + override_type: pa.DataType | None + + +def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataType: + """Use target field types while retaining the containers and field order.""" + if declared.equals(target): + return declared + if isinstance(declared, pa.LargeListType): + if isinstance(target, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): + return pa.large_list( + _override_plan_type(declared.value_type, target.value_type) + ) + return declared + if isinstance(declared, pa.StructType): + if not isinstance(target, pa.StructType): + return declared + fields = [] + for field in declared: + index = target.get_field_index(field.name) + if index >= 0: + field = field.with_type( + _override_plan_type(field.type, target[index].type) + ) + fields.append(field) + return pa.struct(fields) + return target def _get_python_to_arrow_map() -> dict: @@ -287,10 +314,13 @@ def __init__( self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} self._set_storage_plans: dict[tuple[DataType, pa.DataType], _StoragePlan] = {} - self._last_table_schema: ( + self._checked_set_storage: dict[DataType, pa.DataType] = {} + self._inferred_table_schema = lru_cache(maxsize=128)( + self._prepare_inferred_table_schema + ) + self._last_explicit_table_schema: ( tuple[ tuple[tuple[str, DataType], ...], - pa.Schema | None, pa.Schema, tuple[_CheckedSetColumn, ...], ] @@ -1088,6 +1118,10 @@ def python_type_to_arrow_type(self, python_type: DataType) -> pa.DataType: # Convert and cache result arrow_type = self._convert_python_to_arrow(python_type) + if isinstance(arrow_type, pa.ExtensionType) and self._contains_checked_set( + python_type, arrow_type.storage_type + ): + self._checked_set_storage[python_type] = arrow_type.storage_type self._python_to_arrow_types[python_type] = arrow_type return arrow_type @@ -1414,21 +1448,33 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) - return self._storage_table(python_dicts, python_schema, arrow_schema) + if arrow_schema is None: + schema, checked_columns = self._inferred_table_schema( + tuple(python_schema.items()) + ) + else: + schema = arrow_schema + checked_columns = self._explicit_checked_columns( + python_schema, arrow_schema + ) + if checked_columns: + return self._storage_table( + python_dicts, python_schema, schema, checked_columns + ) + struct_dicts = self.python_dicts_to_struct_dicts( + python_dicts, python_schema=python_schema + ) + return pa.Table.from_pylist(struct_dicts, schema=schema) def _storage_table( self, rows: list[dict[str, Any]], python_schema: SchemaLike, - arrow_schema: pa.Schema | None, + arrow_schema: pa.Schema, + checked_columns: tuple[_CheckedSetColumn, ...], ) -> pa.Table: """Batch logical set columns and convert the remaining cells as usual.""" - arrow_schema, checked_columns = self._prepare_table_schema( - python_schema, arrow_schema - ) - encoded_columns = ( - self._encode_set_columns(rows, checked_columns) if checked_columns else {} - ) + encoded_columns = self._encode_set_columns(rows, checked_columns) if not encoded_columns: struct_dicts = self.python_dicts_to_struct_dicts( rows, python_schema=python_schema @@ -1446,24 +1492,29 @@ def _storage_table( struct_dicts, arrow_schema, encoded_columns=encoded_columns ) - def _prepare_table_schema( - self, python_schema: SchemaLike, arrow_schema: pa.Schema | None + def _prepare_inferred_table_schema( + self, fields: tuple[tuple[str, DataType], ...] ) -> tuple[pa.Schema, tuple[_CheckedSetColumn, ...]]: - """Reuse the most recent table's schema and resolved set columns.""" + """Prepare an inferred schema and select only logical set columns.""" + python_schema = dict(fields) + schema = self.python_schema_to_arrow_schema(python_schema) + if not self._checked_set_storage.keys().isdisjoint(python_schema.values()): + return schema, self._checked_set_columns(python_schema, schema) + return schema, () + + def _explicit_checked_columns( + self, python_schema: SchemaLike, arrow_schema: pa.Schema + ) -> tuple[_CheckedSetColumn, ...]: + """Resolve set columns for an explicit Arrow schema.""" # Freeze the input so an edited dict cannot reuse a stale schema. Compare # an explicit Arrow schema by identity to retain its extension metadata. fields = tuple(python_schema.items()) - cached = self._last_table_schema + cached = self._last_explicit_table_schema if cached is not None and arrow_schema is cached[1] and fields == cached[0]: - return cached[2], cached[3] - schema = ( - self.python_schema_to_arrow_schema(python_schema) - if arrow_schema is None - else arrow_schema - ) - checked_columns = self._checked_set_columns(python_schema, schema) - self._last_table_schema = (fields, arrow_schema, schema, checked_columns) - return schema, checked_columns + return cached[2] + checked_columns = self._checked_set_columns(python_schema, arrow_schema) + self._last_explicit_table_schema = (fields, arrow_schema, checked_columns) + return checked_columns def _set_storage_plan( self, annotation: DataType, storage_type: pa.DataType @@ -1526,44 +1577,26 @@ def _contains_checked_set(self, annotation: DataType, kind: pa.DataType) -> bool def _eager_set_output_validator( self, python_schema: SchemaLike ) -> Callable[[list[dict[str, Any]], SchemaLike], None] | None: - """Resolve eager struct-set validation once for a function's output schema.""" - from orcapod.logical_types.list_logical_type_factory import ListLogicalType - - checked: dict[str, tuple[_StoragePlan, pa.LargeListType[Any]]] = {} - for name, annotation in python_schema.items(): - origin = get_origin(annotation) - if origin in (typing.Union, types.UnionType): - args = get_args(annotation) - if len(args) == 2 and type(None) in args: - annotation = next(arg for arg in args if arg is not type(None)) - if get_origin(annotation) is not set: - continue - logical_type = self.get_logical_type(typing.cast(type, annotation)) - if ( - not isinstance(logical_type, ListLogicalType) - or not logical_type._orders_stored_sets - ): - continue - storage = logical_type.get_arrow_extension_type().storage_type - assert isinstance(storage, pa.LargeListType) - checked[name] = (self._set_storage_plan(annotation, storage), storage) - + """Resolve eager set validation once for a function's output schema.""" + _, checked = self._inferred_table_schema(tuple(python_schema.items())) if not checked: return None - from orcapod.semantic_types.logical_set_storage import validate_struct_set + from orcapod.semantic_types.logical_set_storage import validate_set_output + names = {column.field.name for column in checked} remaining = { name: annotation for name, annotation in python_schema.items() - if name not in checked + if name not in names } def validate(rows: list[dict[str, Any]], _schema: SchemaLike) -> None: row = rows[0] - for name, (plan, storage) in checked.items(): + for column in checked: + name = column.field.name try: - validate_struct_set(plan, row.get(name), storage) + validate_set_output(column.plan, row.get(name), column.storage_type) except CanonicalOrderError as exc: raise type(exc)(f"Column {name!r}: {exc}") from exc if remaining: @@ -1582,32 +1615,33 @@ def _checked_set_columns( columns: list[_CheckedSetColumn] = [] for index, field in enumerate(arrow_schema): + annotation = python_schema.get(field.name) + if annotation is None: + continue + if ( + annotation not in self._python_to_arrow_types + and isinstance(field.type, pa.ExtensionType) + and self._contains_checked_set(annotation, field.type.storage_type) + ): + self.python_type_to_arrow_type(annotation) + declared = self._checked_set_storage.get(annotation) + if declared is None: + continue field_type = field.type - storage_type = ( + target = ( field_type.storage_type if isinstance(field_type, pa.ExtensionType) else field_type ) - annotation = python_schema.get(field.name) - if annotation is None or not self._contains_checked_set( - annotation, storage_type - ): - continue - if not field_type.equals(self.python_type_to_arrow_type(annotation)): - continue - args = get_args(annotation) - nullable = ( - get_origin(annotation) in (typing.Union, types.UnionType) - and len(args) == 2 - and type(None) in args - ) + storage_type = _override_plan_type(declared, target) columns.append( _CheckedSetColumn( index, field, storage_type, self._set_storage_plan(annotation, storage_type), - nullable, + _is_optional_type(annotation), + None if storage_type.equals(target) else target, ) ) return tuple(columns) @@ -1623,7 +1657,7 @@ def _encode_set_columns( if not rows: return {} encoded_columns: dict[int, pa.Array[Any]] = {} - for index, field, storage_type, plan, nullable in columns: + for index, field, storage_type, plan, nullable, override_type in columns: name = field.name values = [row.get(name) for row in rows] # The ordinary converter diagnoses a present null of a required type. @@ -1639,6 +1673,12 @@ def _encode_set_columns( except UnsupportedValueError as exc: raise UnsupportedValueError(f"Column {name!r}: {exc}") from exc field_type = field.type + if override_type is not None: + try: + storage = storage.cast(override_type) + except pa.ArrowException: + # Some builders accept shapes Arrow has no cast kernel for. + storage = pa.array(storage.to_pylist(), type=override_type) encoded_columns[index] = ( pa.ExtensionArray.from_storage(field_type, storage) if isinstance(field_type, pa.ExtensionType) @@ -2408,7 +2448,9 @@ def clear_cache(self) -> None: self._created_type_names.clear() self._python_to_arrow_converters.clear() self._set_storage_plans.clear() - self._last_table_schema = None + self._checked_set_storage.clear() + self._inferred_table_schema.cache_clear() + self._last_explicit_table_schema = None self._arrow_to_python_converters.clear() self._python_to_arrow_types.clear() self._arrow_to_python_types.clear() diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index 007d2e40e..a4e50a356 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -1366,3 +1366,45 @@ def record_call(frame: types.FrameType, event: str, _arg: Any) -> None: sys.setprofile(previous) assert entered == set() + + +@dataclass +class WrappedOutputSet: + entries: set[WithDict] + score: float = 0.0 + + +def test_wrapped_function_set_sorts_only_during_table_assembly( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Eager iteration validates wrapped sets and table assembly orders the column.""" + sizes: list[int] = [] + original_sort = pc.sort_indices + + def record_size(values: Any, *args: Any, **kwargs: Any) -> Any: + sizes.append(len(values)) + return original_sort(values, *args, **kwargs) + + monkeypatch.setattr(pc, "sort_indices", record_size) + # A NaN outside the set is an ordinary field, not an ordering key. + value = WrappedOutputSet( + {WithDict({5.0: 0, 2.0: 3, 3.0: 4}), WithDict({8.0: 2})}, + score=float("nan"), + ) + stream = make_pod(list[WrappedOutputSet], [value]).pod( + make_source(tuple(range(32))) + ) + assert len(list(stream.iter_data())) == 32 + assert sizes == [] + table = stream.as_table() + assert sizes == [128, 64] + first = table["y"].to_pylist()[0][0]["entries"] + assert [entry["d"][0]["key"] for entry in first] == [2, 8] + + +def test_wrapped_function_set_refuses_duplicate_storage_eagerly() -> None: + """Eager validation retains duplicate checks through a list and a struct.""" + value = WrappedOutputSet({WithDict({-0.0: 1}), WithDict({0.0: 1})}) + stream = make_pod(list[WrappedOutputSet], [value]).pod(make_source()) + with pytest.raises(errors.CanonicalOrderError, match=r"Column 'y': .*duplicate"): + next(stream.iter_data()) diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index 2f56f6c19..15ba0b87c 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -1277,3 +1277,98 @@ def unexpected(*_args: Any, **_kwargs: Any) -> Never: rows[1]["s"] = {Word("Z"), Word("z")} with pytest.raises(CanonicalOrderError, match=r"Column 's': duplicate"): converter.python_dicts_to_arrow_table(rows, python_schema=schema) + + +@dataclasses.dataclass(frozen=True) +class OverridePoint: + z: int + label: str + + +@pytest.mark.parametrize( + "override_type", + [ + pa.large_list(pa.struct([("z", pa.int64()), ("label", pa.large_string())])), + pa.large_list(pa.struct([("z", pa.int32()), ("label", pa.large_string())])), + pa.list_(pa.struct([("z", pa.float64()), ("label", pa.string())])), + pa.list_(pa.struct([("z", pa.int16()), ("label", pa.string())]), 2), + pa.large_list(pa.struct([("label", pa.string()), ("z", pa.int32())])), + pa.large_list(pa.struct([("z", pa.int32())])), + ], +) +def test_precomputed_logical_set_arrow_override(override_type: pa.DataType) -> None: + """An explicit Arrow builder can coerce the stored values to another type.""" + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter + + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = {"s": set[OverridePoint]} + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + writer = SemanticSchemaConverter(converter, python_schema) + schema = pa.schema([("s", override_type)], metadata={b"override": b"yes"}) + # These values have the same order under main's repr sort and the declared + # struct order, so the same assertions exercise both revisions. + values = [{"s": {OverridePoint(12, "b"), OverridePoint(11, "a")}}] + expected = pa.Table.from_pylist( + [{"s": [{"z": 11, "label": "a"}, {"z": 12, "label": "b"}]}], + schema=schema, + ) + assert writer.python_dicts_to_arrow_table(values, schema).equals( + expected, check_metadata=True + ) + + +@dataclasses.dataclass(frozen=True) +class OverrideDate: + day: date + + +def test_precomputed_logical_set_override_keeps_timestamp_precision() -> None: + """The override can store precision that the inferred field would discard.""" + from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter + + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = {"s": set[OverrideDate]} + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + writer = SemanticSchemaConverter(converter, python_schema) + schema = pa.schema([("s", pa.list_(pa.struct([("day", pa.timestamp("us"))])))]) + first, second = datetime(2026, 1, 1, 11), datetime(2026, 1, 1, 15) + expected = pa.Table.from_pylist( + [{"s": [{"day": first}, {"day": second}]}], schema=schema + ) + rows = [{"s": {OverrideDate(second), OverrideDate(first)}}] + assert writer.python_dicts_to_arrow_table(rows, schema).equals(expected) + + +def test_alternating_native_writes_skip_checked_set_dispatch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Native columns bypass checked-set dispatch even when schemas alternate.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + cases: list[tuple[list[dict[str, Any]], dict[str, type]]] = [ + ([{"p": set()}], {"p": set[Path]}), + ([{"d": {}}], {"d": dict[int, int]}), + ([{"items": [1]}], {"items": list[int]}), + ([{"items": ["x"]}], {"items": list[str]}), + ] + expected = [ + converter.python_dicts_to_arrow_table(rows, python_schema=schema) + for rows, schema in cases + ] + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("native write entered checked-set dispatch") + + for name in ("_checked_set_columns", "_encode_set_columns", "_storage_table"): + monkeypatch.setattr(converter, name, unexpected, raising=False) + for _ in range(2): + for (rows, schema), table in zip(cases, expected, strict=True): + assert converter.python_dicts_to_arrow_table( + rows, python_schema=schema + ).equals(table) + # A previously unseen native list schema also skips specialization. + assert converter.python_dicts_to_arrow_table( + [{"extra": [2]}], python_schema={"extra": list[int]} + ).to_pylist() == [{"extra": [2]}] From 3c67c7685767dbc450f35019b6ea27868f4ae0af Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:23:17 -0800 Subject: [PATCH 10/18] fix(logical_types): honor explicit Arrow set schemas --- changelog.d/ITL-922.md | 5 +- docs/dev/design_issues/ITL-922-DO2.md | 4 +- .../logical_types/user_class_logical_type.py | 14 +- .../semantic_types/logical_set_storage.py | 64 ++-- .../semantic_types/precomputed_converters.py | 5 + .../semantic_types/universal_converter.py | 48 ++- .../test_arrow_schema_overrides.py | 317 ++++++++++++++++++ 7 files changed, 399 insertions(+), 58 deletions(-) create mode 100644 tests/test_semantic_types/test_arrow_schema_overrides.py diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index f20e74b9d..256996037 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -19,5 +19,6 @@ keys use Arrow or Polars kernels. - Direct structural-dictionary conversion round-trips sets of logical values, including struct fields with their own logical decoders. -- Explicit Arrow schema overrides use the requested field types for logical set - writes. Function iteration validates wrapped sets without sorting each output. +- Explicit Arrow schema overrides use the requested field types and compare only + the fields stored in the target schema. Function iteration validates wrapped + sets without sorting each output. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 25d926499..6bf82dfea 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -21,8 +21,8 @@ constructing a sort table. Direct structural-dictionary reads pass Python storage values to each logical decoder. Function iteration checks the coerced storage keys for NaNs and duplicates without sorting the row, including when a list or class wraps the set. -An explicit Arrow schema override uses its target field types and keeps the -user class's declared field order for comparison. +An explicit Arrow schema override compares its retained fields in the user +class's declared order after coercing them to their target Arrow types. Sets of other logical types keep their native sort. For user-defined scalar storage, one Arrow pass per table column rejects NaNs and duplicate stored values. The same ordering rules apply to classes rebuilt from metadata. diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 6addac401..eee4de5d1 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -188,16 +188,22 @@ def python_to_storage( f"{type(self).__name__}.python_to_storage requires a converter — " "pass a TypeConverterProtocol instance for field-level conversion." ) + self._require_storage_instance(value, converter) + return { + name: converter.python_to_storage(getattr(value, name), annotation) + for name, annotation in self._field_annotations + } + + def _require_storage_instance( + self, value: Any, converter: TypeConverterProtocol + ) -> None: + """Validate the value before extracting its stored fields.""" if not self.accepts_instance(value, converter): raise TypeError( f"Cannot store a value of class {uci.class_path(type(value))} as " f"{uci.class_path(self._python_type)}: " f"{self.instance_requirement}" ) - return { - name: converter.python_to_storage(getattr(value, name), annotation) - for name, annotation in self._field_annotations - } #: What ``accepts_instance`` requires, for the error message. instance_requirement: str = ( diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py index 9f780e424..f0d9b8f2e 100644 --- a/src/orcapod/semantic_types/logical_set_storage.py +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -138,6 +138,10 @@ def _sort_columns(array: pa.Array[Any]) -> list[pa.Array[Any]]: for child in array.flatten(): columns.extend(_sort_columns(child)) return columns + if isinstance(array, pa.MapArray): + # Map storage is a list of non-null entry structs. View it as a list so + # the same comparison kernels can process the stored entries. + array = array.view(pa.list_(array.type.field(0))) if isinstance(array, _LIST_ARRAY_TYPES): return [_list_sort_column(array)] if isinstance(array, pa.ExtensionArray): @@ -390,23 +394,6 @@ def finish(self, encoded: list[Any], storage_type: pa.DataType) -> pa.Array[Any] raise LogicalSetCanonicalOrderError("values cannot be ordered") from exc -class _FieldEncoder: - """Supply prepared field encoders to a user class's existing storage method.""" - - def __init__( - self, converter: TypeConverterProtocol, fields: dict[Any, _Encode] - ) -> None: - self._converter = converter - self._fields = fields - - def python_to_storage(self, value: Any, annotation: Any) -> Any: - """Convert a field with its resolved converter.""" - return self._fields[annotation](value) - - def __getattr__(self, name: str) -> Any: - return getattr(self._converter, name) - - def _stored_keys(array: pa.Array[Any]) -> list[Any]: """Extract exact Arrow equality keys for a small eagerly validated row.""" if array.null_count == len(array): @@ -603,37 +590,28 @@ def resolve( if isinstance(logical_type, UserClassLogicalType) and isinstance( kind, pa.StructType ): + annotations = dict(logical_type.field_annotations) fields = [ - resolve(field_annotation, kind.field(name).type) - for name, field_annotation in logical_type.field_annotations + (field.name, resolve(annotations[field.name], field.type)) for field in kind ] operations = { i: field.normalize - for i, field in enumerate(fields) + for i, (_, field) in enumerate(fields) if field.normalize is not None } - if canonical or operations: - field_encoder = _FieldEncoder( - converter, - { - field_annotation: field.encode - for (_, field_annotation), field in zip( - logical_type.field_annotations, fields, strict=True - ) - }, - ) + if canonical or operations or len(fields) != len(annotations): + encoders = [(name, field.encode) for name, field in fields] def encode_struct(value: Any) -> Any: if value is None: raise _none_not_admitted(annotation) - return logical_type.python_to_storage( - value, cast("TypeConverterProtocol", cast(object, field_encoder)) - ) + logical_type._require_storage_instance(value, converter) + return {name: encode(getattr(value, name)) for name, encode in encoders} - keys = [field.keys or _stored_keys for field in fields] + keys = [field.keys or _stored_keys for _, field in fields] validations = [ (i, field.validate) - for i, field in enumerate(fields) + for i, (_, field) in enumerate(fields) if field.validate is not None ] @@ -658,23 +636,33 @@ def validate_fields(array: pa.Array[Any]) -> None: if not canonical: return _StoragePlan(fallback(annotation)) entry = cast(pa.StructType, kind.value_type) + if entry.get_field_index("key") < 0: + # With no stored key, retain the original dictionary conversion + # order. The enclosing set compares only the projected entries. + return _StoragePlan(fallback(annotation)) key = resolve(args[0], entry.field("key").type) - item = resolve(args[1], entry.field("value").type) + value_index = entry.get_field_index("value") + item = ( + resolve(args[1], entry[value_index].type) if value_index >= 0 else None + ) def encode_dict(value: Any) -> list[dict[str, Any]]: if value is None: raise _none_not_admitted(annotation) + if item is None: + return [{"key": key.encode(k)} for k in value] return [ {"key": key.encode(k), "value": item.encode(v)} for k, v in value.items() ] + fields = (key,) if item is None else (key, item) operations = { i: field.normalize - for i, field in enumerate((key, item)) + for i, field in enumerate(fields) if field.normalize is not None } - entry_keys = [key.keys or _stored_keys, item.keys or _stored_keys] + entry_keys = [field.keys or _stored_keys for field in fields] return _list_plan( encode_dict, _struct_normalizer(entry, operations), diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index a9e9242e0..6634eab0c 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -171,6 +171,11 @@ def python_dicts_to_arrow_table( flags that differ from what was inferred at construction time. """ schema = arrow_schema or self.arrow_schema + if not self._checked_columns: + return pa.Table.from_pylist( + self.python_dicts_to_struct_dicts(data), schema=schema + ) + checked_columns = ( self._checked_columns if schema is self.arrow_schema diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 99e50fd3d..3ab2a29b7 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -96,14 +96,29 @@ class _CheckedSetColumn(NamedTuple): def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataType: - """Use target field types while retaining the containers and field order.""" + """Use stored target fields in declared order and retain internal list storage.""" if declared.equals(target): return declared if isinstance(declared, pa.LargeListType): - if isinstance(target, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): + if isinstance( + target, + ( + pa.ListType, + pa.LargeListType, + pa.FixedSizeListType, + pa.ListViewType, + pa.LargeListViewType, + ), + ): return pa.large_list( _override_plan_type(declared.value_type, target.value_type) ) + if isinstance(target, pa.MapType) and isinstance( + declared.value_type, pa.StructType + ): + return pa.large_list( + _override_plan_type(declared.value_type, target.field(0).type) + ) return declared if isinstance(declared, pa.StructType): if not isinstance(target, pa.StructType): @@ -112,10 +127,9 @@ def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataTy for field in declared: index = target.get_field_index(field.name) if index >= 0: - field = field.with_type( - _override_plan_type(field.type, target[index].type) + fields.append( + field.with_type(_override_plan_type(field.type, target[index].type)) ) - fields.append(field) return pa.struct(fields) return target @@ -1513,7 +1527,8 @@ def _explicit_checked_columns( if cached is not None and arrow_schema is cached[1] and fields == cached[0]: return cached[2] checked_columns = self._checked_set_columns(python_schema, arrow_schema) - self._last_explicit_table_schema = (fields, arrow_schema, checked_columns) + if checked_columns: + self._last_explicit_table_schema = (fields, arrow_schema, checked_columns) return checked_columns def _set_storage_plan( @@ -1618,12 +1633,21 @@ def _checked_set_columns( annotation = python_schema.get(field.name) if annotation is None: continue - if ( - annotation not in self._python_to_arrow_types - and isinstance(field.type, pa.ExtensionType) - and self._contains_checked_set(annotation, field.type.storage_type) - ): - self.python_type_to_arrow_type(annotation) + if annotation not in self._python_to_arrow_types: + # Explicit writes do not register classes. An already registered + # annotation can still be cold in the Python-to-Arrow cache. + base = ( + next(arg for arg in get_args(annotation) if arg is not type(None)) + if _is_optional_type(annotation) + else annotation + ) + logical_type = self._logical_type_registry.get_by_python_type( + typing.cast(type, base) + ) + if logical_type is not None and self._contains_checked_set( + annotation, logical_type.get_arrow_extension_type().storage_type + ): + self.python_type_to_arrow_type(annotation) declared = self._checked_set_storage.get(annotation) if declared is None: continue diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py new file mode 100644 index 000000000..4530f8497 --- /dev/null +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -0,0 +1,317 @@ +"""Compatibility of explicit Arrow schemas for logical-set table writes.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from dataclasses import dataclass, field +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from pathlib import Path +from typing import Any, Never + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.contexts import create_registry +from orcapod.errors import CanonicalOrderError +from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.types import Schema + + +@dataclass(frozen=True) +class OverrideValue: + """A value whose field can be sent to any compatible Arrow builder.""" + + order: int + value: Any = field(hash=False) + + +@dataclass(frozen=True) +class Reading: + """The time component can survive an explicit timestamp override.""" + + day: date + + +@dataclass(frozen=True) +class NestedReading: + """A stored value with container and user-class fields.""" + + order: int + reading: Reading + series: list[date] = field(hash=False) + mapping: dict[str, int] = field(hash=False) + + +def _override_cases() -> Iterator[Any]: + """Enumerate targets accepted by main's conversion and Arrow builder.""" + # Main has no field-type whitelist. Cover the builders reached by its + # native type map and its list, struct, dict and logical conversion paths, + # including alternate physical types accepted by those builders. + scalar_cases = [ + (pa.bool_(), False, True), + *( + (kind(), 11, 12) + for kind in ( + pa.int8, + pa.int16, + pa.int32, + pa.int64, + pa.uint8, + pa.uint16, + pa.uint32, + pa.uint64, + ) + ), + (pa.float16(), np.float16(11), np.float16(12)), + (pa.float32(), 11.0, 12.0), + (pa.float64(), 11.0, 12.0), + *( + (kind(8, 2), Decimal("1.11"), Decimal("1.12")) + for kind in ( + pa.decimal32, + pa.decimal64, + pa.decimal128, + pa.decimal256, + ) + ), + *( + (kind(), "aa", "ab") + for kind in (pa.string, pa.large_string, pa.string_view) + ), + *( + (kind(), b"aa", b"ab") + for kind in (pa.binary, pa.large_binary, pa.binary_view) + ), + (pa.binary(2), b"aa", b"ab"), + (pa.null(), None, None), + *( + (kind(), date(2026, 1, 11), date(2026, 1, 12)) + for kind in (pa.date32, pa.date64) + ), + *((pa.time32(unit), time(11), time(12)) for unit in ("s", "ms")), + *((pa.time64(unit), time(11), time(12)) for unit in ("us", "ns")), + *( + (pa.duration(unit), timedelta(seconds=11), timedelta(seconds=12)) + for unit in ("s", "ms", "us", "ns") + ), + (pa.month_day_nano_interval(), (0, 0, 11), (0, 0, 12)), + (pa.dictionary(pa.int8(), pa.string()), "aa", "ab"), + (pa.map_(pa.string(), pa.int16()), [("a", 11)], [("a", 12)]), + (pa.struct([("child", pa.int16())]), {"child": 11}, {"child": 12}), + ] + for kind, first, second in scalar_cases: + yield pytest.param( + OverrideValue, + (OverrideValue(11, first), OverrideValue(12, second)), + [{"order": 11, "value": first}, {"order": 12, "value": second}], + lambda _declared, kind=kind: pa.large_list( + pa.struct([("order", pa.int16()), ("value", kind)]) + ), + id=str(kind), + ) + + first, second = datetime(2026, 1, 1, 11), datetime(2026, 1, 1, 15) + for list_type in ( + pa.list_, + pa.large_list, + pa.list_view, + pa.large_list_view, + lambda typ: pa.list_(typ, 2), + ): + for unit in ("s", "ms", "us", "ns"): + for stamp in ( + pa.timestamp(unit), + pa.timestamp(unit, tz="America/New_York"), + ): + target = list_type(pa.struct([("day", stamp)])) + yield pytest.param( + Reading, + (Reading(first), Reading(second)), + [{"day": first}, {"day": second}], + lambda _declared, target=target: target, + id=str(target), + ) + + members = ( + NestedReading(11, Reading(first), [first], {"b": 2, "a": 1}), + NestedReading(12, Reading(second), [second], {"c": 3}), + ) + structural = [ + { + "order": member.order, + "reading": {"day": member.reading.day}, + "series": member.series, + "mapping": [ + {"key": key, "value": value} + for key, value in sorted(member.mapping.items()) + ], + } + for member in members + ] + for mapping in ( + pa.map_(pa.string(), pa.int16()), + pa.list_(pa.struct([("value", pa.int16()), ("key", pa.string())])), + pa.list_(pa.struct([("key", pa.string())])), + pa.list_(pa.struct([("value", pa.int16())])), + pa.list_(pa.struct([])), + ): + target = pa.large_list( + pa.struct( + [ + ("extra", pa.int32()), + ("mapping", mapping), + ("series", pa.list_view(pa.timestamp("us"))), + ("reading", pa.struct([("day", pa.timestamp("us"))])), + ("order", pa.int32()), + ] + ) + ) + yield pytest.param( + NestedReading, + members, + structural, + lambda _declared, target=target: target, + id=f"reordered-with-added-field-{mapping}", + ) + + # Field and column projection, nullable/metadata overrides, the declared + # extension type and its unwrapped physical storage. + for label, target_for in ( + ("projection", lambda _: pa.large_list(pa.struct([("order", pa.int32())]))), + ("extension", lambda declared: declared), + ("physical", lambda declared: declared.storage_type), + ): + yield pytest.param(NestedReading, members, structural, target_for, id=label) + + yield pytest.param( + OverrideValue, + (OverrideValue(11, "omitted"),), + [{"order": 11, "value": "omitted"}], + lambda _: pa.large_list(pa.struct([])), + id="empty-element-projection", + ) + + +@pytest.mark.parametrize( + "record_type,members,structural,target_for", list(_override_cases()) +) +def test_explicit_arrow_schema_matches_main( + record_type: type, + members: tuple[Any, ...], + structural: list[dict[str, Any]], + target_for: Callable[[pa.ExtensionType], pa.DataType], +) -> None: + """Compare cold and warm public writes against main's structural builder.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = {"omitted": int, "data": set[record_type]} + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + logical_type = converter.get_logical_type_for_python_type(set[record_type]) + assert logical_type is not None + declared = logical_type.get_arrow_extension_type() + target = pa.schema( + [ + pa.field("extra", pa.int16()), + pa.field( + "data", + target_for(declared), + nullable=False, + metadata={b"field": b"changed"}, + ), + ], + metadata={b"schema": b"changed"}, + ) + rows = [{"data": set(members), "omitted": 42}] + # Main sorted by the repr of each converted dict, then called from_pylist. + # These fixtures align that order with the declared stored-field order. + expected = pa.Table.from_pylist( + [{"data": sorted(structural, key=repr)}], schema=target + ) + cold = converter.python_dicts_to_arrow_table( + rows, python_schema=python_schema, arrow_schema=target + ) + writer = SemanticSchemaConverter(converter, python_schema) + tables = [ + cold, + writer.python_dicts_to_arrow_table(rows, target), + converter.python_dicts_to_arrow_table( + rows, python_schema=python_schema, arrow_schema=target + ), + ] + if target.field("data").type.equals(declared): + tables.append(converter.python_dicts_to_arrow_table(rows, arrow_schema=target)) + arrow_writer = SemanticSchemaConverter(converter, arrow_schema=target) + tables.append(arrow_writer.python_dicts_to_arrow_table(rows)) + for table in tables: + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected, check_metadata=True) + + +@dataclass(frozen=True) +class ProjectedRecord: + """The leading field is deliberately omitted from the target storage.""" + + omitted: int + kept: int + + +def test_logical_set_orders_and_checks_only_projected_fields() -> None: + """Equal projected sets have the same storage and reject equal kept keys.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = {"data": set[ProjectedRecord]} + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + writer = SemanticSchemaConverter(converter, python_schema) + target = pa.schema([("data", pa.list_(pa.struct([("kept", pa.int64())])))]) + rows = [ + {"data": {ProjectedRecord(1, 20), ProjectedRecord(2, 10)}}, + {"data": {ProjectedRecord(2, 20), ProjectedRecord(1, 10)}}, + ] + expected = [{"data": [{"kept": 10}, {"kept": 20}]}] * 2 + assert writer.python_dicts_to_arrow_table(rows, target).to_pylist() == expected + assert ( + converter.python_dicts_to_arrow_table( + rows, python_schema=python_schema, arrow_schema=target + ).to_pylist() + == expected + ) + with pytest.raises(CanonicalOrderError, match="Column 'data': duplicate"): + writer.python_dicts_to_arrow_table( + [{"data": {ProjectedRecord(1, 20), ProjectedRecord(2, 20)}}], target + ) + + +def test_alternating_explicit_native_writes_bypass_set_dispatch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A precomputed native-only writer uses Arrow's original table route.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = { + "count": int, + "items": list[int], + "paths": set[Path], + "pairs": dict[int, int], + } + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + writer = SemanticSchemaConverter(converter, python_schema) + rows = [{"count": 1, "items": [2], "paths": {Path("/a")}, "pairs": {3: 4}}] + targets = [ + writer.arrow_schema.with_metadata({b"case": case}) for case in (b"a", b"b") + ] + expected = [ + pa.Table.from_pylist(writer.python_dicts_to_struct_dicts(rows), schema=target) + for target in targets + ] + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("native-only writer entered checked-set dispatch") + + monkeypatch.setattr(converter, "_explicit_checked_columns", unexpected) + for target, table in zip(targets * 2, expected * 2, strict=True): + assert writer.python_dicts_to_arrow_table(rows, target).equals( + table, check_metadata=True + ) From 32a7c0a47c828f1d4d5f137f708b1207a112f56f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:25:28 -0800 Subject: [PATCH 11/18] test(logical_types): reuse default Arrow extensions in native writes --- tests/test_semantic_types/test_arrow_schema_overrides.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index 4530f8497..a1dca79c6 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -13,7 +13,7 @@ import pyarrow as pa import pytest -from orcapod.contexts import create_registry +from orcapod.contexts import create_registry, get_default_context from orcapod.errors import CanonicalOrderError from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter from orcapod.semantic_types.universal_converter import UniversalTypeConverter @@ -288,7 +288,8 @@ def test_alternating_explicit_native_writes_bypass_set_dispatch( monkeypatch: pytest.MonkeyPatch, ) -> None: """A precomputed native-only writer uses Arrow's original table route.""" - converter = create_registry().get_context().type_converter + # Reuse the default context's globally registered built-in Arrow types. + converter = get_default_context().type_converter assert isinstance(converter, UniversalTypeConverter) python_schema = { "count": int, From c9236ff6d193729da7a3ff22008091657990c692 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:45:41 -0800 Subject: [PATCH 12/18] perf(logical_types): resolve explicit writer dispatch by type --- docs/dev/design_issues/ITL-922-DO2.md | 2 + .../semantic_types/universal_converter.py | 99 ++++++++++++++----- .../test_arrow_schema_overrides.py | 31 ++++++ 3 files changed, 108 insertions(+), 24 deletions(-) diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 6bf82dfea..3fdb162db 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -23,6 +23,8 @@ Function iteration checks the coerced storage keys for NaNs and duplicates without sorting the row, including when a list or class wraps the set. An explicit Arrow schema override compares its retained fields in the user class's declared order after coercing them to their target Arrow types. +Explicit native writes reuse converters by Python type, even when Arrow +schema metadata changes between writes. Sets of other logical types keep their native sort. For user-defined scalar storage, one Arrow pass per table column rejects NaNs and duplicate stored values. The same ordering rules apply to classes rebuilt from metadata. diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 3ab2a29b7..4192cfd3f 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -84,6 +84,10 @@ ) +class _UseCheckedSetStorage(Exception): + """Switch table builders when resolving an annotation with a checked set.""" + + class _CheckedSetColumn(NamedTuple): """A field that needs specialized set storage.""" @@ -326,6 +330,7 @@ def __init__( # Cache for conversion functions self._python_to_arrow_converters: dict[DataType, Callable] = {} self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} + self._explicit_value_converters: dict[DataType, Callable[[Any], Any]] = {} self._set_storage_plans: dict[tuple[DataType, pa.DataType], _StoragePlan] = {} self._checked_set_storage: dict[DataType, pa.DataType] = {} @@ -1356,7 +1361,14 @@ def python_dicts_to_struct_dicts( field_name: self.get_python_to_arrow_converter(python_type) for field_name, python_type in python_schema.items() } + return self._convert_struct_rows(python_dicts, converters) + @staticmethod + def _convert_struct_rows( + python_dicts: list[dict[str, Any]], + converters: dict[str, Callable[[Any], Any]], + ) -> list[dict[str, Any]]: + """Convert rows with the resolved value converters.""" converted_data = [] for record in python_dicts: converted_record = {} @@ -1462,15 +1474,28 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) - if arrow_schema is None: - schema, checked_columns = self._inferred_table_schema( - tuple(python_schema.items()) - ) - else: - schema = arrow_schema - checked_columns = self._explicit_checked_columns( - python_schema, arrow_schema + if arrow_schema is not None: + # Reuse the normal converter lookup pass. Only a checked-set + # annotation needs a plan tied to the target Arrow fields. + try: + converters = { + name: self._get_explicit_value_converter(annotation) + for name, annotation in python_schema.items() + } + except _UseCheckedSetStorage: + return self._storage_table( + python_dicts, + python_schema, + arrow_schema, + self._explicit_checked_columns(python_schema, arrow_schema), + ) + return pa.Table.from_pylist( + self._convert_struct_rows(python_dicts, converters), schema=arrow_schema ) + + schema, checked_columns = self._inferred_table_schema( + tuple(python_schema.items()) + ) if checked_columns: return self._storage_table( python_dicts, python_schema, schema, checked_columns @@ -1480,6 +1505,22 @@ def python_dicts_to_arrow_table( ) return pa.Table.from_pylist(struct_dicts, schema=schema) + def _get_explicit_value_converter( + self, annotation: DataType + ) -> Callable[[Any], Any]: + """Cache ordinary table converters by type, independently of Arrow schemas.""" + try: + return self._explicit_value_converters[annotation] + except KeyError: + pass + if self._checked_storage_for_annotation(annotation) is not None: + raise _UseCheckedSetStorage + converter = self.get_python_to_arrow_converter(annotation) + if annotation in self._checked_set_storage: + raise _UseCheckedSetStorage + self._explicit_value_converters[annotation] = converter + return converter + def _storage_table( self, rows: list[dict[str, Any]], @@ -1633,22 +1674,7 @@ def _checked_set_columns( annotation = python_schema.get(field.name) if annotation is None: continue - if annotation not in self._python_to_arrow_types: - # Explicit writes do not register classes. An already registered - # annotation can still be cold in the Python-to-Arrow cache. - base = ( - next(arg for arg in get_args(annotation) if arg is not type(None)) - if _is_optional_type(annotation) - else annotation - ) - logical_type = self._logical_type_registry.get_by_python_type( - typing.cast(type, base) - ) - if logical_type is not None and self._contains_checked_set( - annotation, logical_type.get_arrow_extension_type().storage_type - ): - self.python_type_to_arrow_type(annotation) - declared = self._checked_set_storage.get(annotation) + declared = self._checked_storage_for_annotation(annotation) if declared is None: continue field_type = field.type @@ -1670,6 +1696,30 @@ def _checked_set_columns( ) return tuple(columns) + def _checked_storage_for_annotation( + self, annotation: DataType + ) -> pa.DataType | None: + """Resolve checked storage for a registered type, including on a cold write.""" + if ( + self._logical_type_registry is not None + and annotation not in self._python_to_arrow_types + ): + # Explicit writes do not register classes. A registered annotation + # can still be cold in the Python-to-Arrow cache. + base = ( + next(arg for arg in get_args(annotation) if arg is not type(None)) + if _is_optional_type(annotation) + else annotation + ) + logical_type = self._logical_type_registry.get_by_python_type( + typing.cast(type, base) + ) + if logical_type is not None and self._contains_checked_set( + annotation, logical_type.get_arrow_extension_type().storage_type + ): + self.python_type_to_arrow_type(annotation) + return self._checked_set_storage.get(annotation) + def _encode_set_columns( self, rows: list[dict[str, Any]], @@ -2471,6 +2521,7 @@ def clear_cache(self) -> None: self._typeddict_to_struct_signature.clear() self._created_type_names.clear() self._python_to_arrow_converters.clear() + self._explicit_value_converters.clear() self._set_storage_plans.clear() self._checked_set_storage.clear() self._inferred_table_schema.cache_clear() diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index a1dca79c6..0fb168c51 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -250,6 +250,37 @@ def test_explicit_arrow_schema_matches_main( assert table.equals(expected, check_metadata=True) +def test_universal_native_override_reuses_type_resolution( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Explicit native writes reuse type resolution even in a registry with sets.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.ensure_types_registered_for_schemas({"data": set[Reading]}) + native = pa.schema([("data", pa.int64())]) + marked = native.with_metadata({b"version": b"second"}) + rows = [{"data": 42}] + + def unexpected(*_args: Any, **_kwargs: Any) -> Never: + pytest.fail("native write entered explicit checked-set planning") + + monkeypatch.setattr(converter, "_explicit_checked_columns", unexpected) + assert converter.python_dicts_to_arrow_table(rows, arrow_schema=native).equals( + pa.Table.from_pylist(rows, schema=native) + ) + annotations = {"data": int} + converter.python_dicts_to_arrow_table(rows, annotations, native) + monkeypatch.setattr(converter, "_checked_storage_for_annotation", unexpected) + for target in (marked, native, marked): + expected = pa.Table.from_pylist(rows, schema=target) + assert converter.python_dicts_to_arrow_table(rows, annotations, target).equals( + expected, check_metadata=True + ) + assert converter.python_dicts_to_arrow_table(rows, arrow_schema=target).equals( + expected, check_metadata=True + ) + + @dataclass(frozen=True) class ProjectedRecord: """The leading field is deliberately omitted from the target storage.""" From 98d89f5a1904e7335f11baa7754086f1353fadcc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:47:19 -0800 Subject: [PATCH 13/18] test(logical_types): use a concrete schema for registration --- tests/test_semantic_types/test_arrow_schema_overrides.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index 0fb168c51..8fc1c294d 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -256,7 +256,7 @@ def test_universal_native_override_reuses_type_resolution( """Explicit native writes reuse type resolution even in a registry with sets.""" converter = create_registry().get_context().type_converter assert isinstance(converter, UniversalTypeConverter) - converter.ensure_types_registered_for_schemas({"data": set[Reading]}) + converter.ensure_types_registered_for_schemas(Schema({"data": set[Reading]})) native = pa.schema([("data", pa.int64())]) marked = native.with_metadata({b"version": b"second"}) rows = [{"data": 42}] From ef72f45a0f05a7d1693f54d82bbe0d52efbd6a12 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:37:20 -0800 Subject: [PATCH 14/18] fix(logical_types): skip projected-away set columns --- changelog.d/ITL-922.md | 5 +- docs/dev/design_issues/ITL-922-DO2.md | 2 + .../semantic_types/precomputed_converters.py | 29 +++++----- .../semantic_types/universal_converter.py | 10 +++- .../test_arrow_schema_overrides.py | 54 +++++++++++++++++++ 5 files changed, 81 insertions(+), 19 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 256996037..fd8c4bf02 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -20,5 +20,6 @@ - Direct structural-dictionary conversion round-trips sets of logical values, including struct fields with their own logical decoders. - Explicit Arrow schema overrides use the requested field types and compare only - the fields stored in the target schema. Function iteration validates wrapped - sets without sorting each output. + the fields stored in the target schema. A logical set column omitted by the + override is skipped. Function iteration validates wrapped sets without + sorting each output. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 3fdb162db..cf42dd67e 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -23,6 +23,8 @@ Function iteration checks the coerced storage keys for NaNs and duplicates without sorting the row, including when a list or class wraps the set. An explicit Arrow schema override compares its retained fields in the user class's declared order after coercing them to their target Arrow types. +Columns omitted by an Arrow schema override are skipped during checked-set +writes. Explicit native writes reuse converters by Python type, even when Arrow schema metadata changes between writes. Sets of other logical types keep their native sort. For user-defined scalar diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 6634eab0c..50494c449 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -190,22 +190,21 @@ def python_dicts_to_arrow_table( if checked_columns else {} ) - if not encoded_columns: - return pa.Table.from_pylist( - self.python_dicts_to_struct_dicts(data), schema=schema + converters = self._python_to_arrow_converters + if encoded_columns or schema is not self.arrow_schema: + remaining_names = set(schema.names) + remaining_names.difference_update( + schema.field(index).name for index in encoded_columns ) - - encoded_names = {schema.field(index).name for index in encoded_columns} - converters = { - name: converter - for name, converter in self._python_to_arrow_converters.items() - if name not in encoded_names - } - return table_from_storage( - self._convert_rows(data, converters), - schema, - encoded_columns=encoded_columns, - ) + converters = { + name: converter + for name, converter in converters.items() + if name in remaining_names + } + struct_dicts = self._convert_rows(data, converters) + if not encoded_columns: + return pa.Table.from_pylist(struct_dicts, schema=schema) + return table_from_storage(struct_dicts, schema, encoded_columns=encoded_columns) def arrow_table_to_python_dicts(self, table: pa.Table) -> list[dict[str, Any]]: """ diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 4192cfd3f..3ff6fbaa3 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1483,11 +1483,17 @@ def python_dicts_to_arrow_table( for name, annotation in python_schema.items() } except _UseCheckedSetStorage: + written_names = set(arrow_schema.names) + projected_schema = { + name: annotation + for name, annotation in python_schema.items() + if name in written_names + } return self._storage_table( python_dicts, - python_schema, + projected_schema, arrow_schema, - self._explicit_checked_columns(python_schema, arrow_schema), + self._explicit_checked_columns(projected_schema, arrow_schema), ) return pa.Table.from_pylist( self._convert_struct_rows(python_dicts, converters), schema=arrow_schema diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index 8fc1c294d..b019913fa 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -289,6 +289,60 @@ class ProjectedRecord: kept: int +@dataclass(frozen=True, eq=False) +class ProjectionPoint: + """Distinct instances can have identical Arrow storage.""" + + coordinate: float + + +@pytest.mark.parametrize("writer_kind", ["universal", "precomputed"]) +@pytest.mark.parametrize( + "columns", [("keep",), ("keep", "retained"), ("retained", "keep")] +) +@pytest.mark.parametrize( + "omitted_values", [(2.0, 2.0), (float("nan"),)], ids=["duplicate", "nan"] +) +def test_explicit_arrow_schema_skips_projected_away_logical_sets( + writer_kind: str, columns: tuple[str, ...], omitted_values: tuple[float, ...] +) -> None: + """Both writers match main when an invalid set never enters Arrow storage.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = { + "keep": int, + "discard": set[ProjectionPoint], + "retained": set[ProjectionPoint], + } + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + logical_type = converter.get_logical_type_for_python_type(set[ProjectionPoint]) + assert logical_type is not None + fields = { + "keep": pa.int64(), + "retained": logical_type.get_arrow_extension_type(), + } + target = pa.schema( + [(name, fields[name]) for name in columns], metadata={b"case": b"projection"} + ) + rows = [ + { + "keep": 2, + "discard": {ProjectionPoint(value) for value in omitted_values}, + "retained": {ProjectionPoint(2.0), ProjectionPoint(1.0)}, + } + ] + expected = pa.Table.from_pylist( + [{"keep": 2, "retained": [{"coordinate": 1.0}, {"coordinate": 2.0}]}], + schema=target, + ) + if writer_kind == "universal": + actual = converter.python_dicts_to_arrow_table(rows, python_schema, target) + else: + writer = SemanticSchemaConverter(converter, python_schema) + actual = writer.python_dicts_to_arrow_table(rows, target) + assert actual.equals(expected, check_metadata=True) + + def test_logical_set_orders_and_checks_only_projected_fields() -> None: """Equal projected sets have the same storage and reject equal kept keys.""" converter = create_registry().get_context().type_converter From 14434e05c75163ee5e6da9c1bca0e2c6c8a205d1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:18:05 -0800 Subject: [PATCH 15/18] fix(logical-types): preserve set validation across conversion paths --- changelog.d/ITL-922.md | 9 +- docs/dev/design_issues/ITL-922-DO2.md | 12 ++- docs/reference/hashing.md | 4 +- src/orcapod/core/data_function.py | 16 +++- src/orcapod/core/function_pod.py | 3 +- .../list_logical_type_factory.py | 5 +- .../semantic_types/logical_set_storage.py | 14 ++- .../semantic_types/universal_converter.py | 54 +++++++++-- .../function_pod/test_output_conformance.py | 71 ++++++++++++++ .../test_set_of_logical_elements.py | 94 ++++++++++++++++++- .../test_arrow_schema_overrides.py | 30 ++++++ 11 files changed, 284 insertions(+), 28 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 8b770a2ef..183766d90 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -19,7 +19,8 @@ keys use Arrow or Polars kernels. - Direct structural-dictionary conversion round-trips sets of logical values, including struct fields with their own logical decoders. -- Explicit Arrow schema overrides use the requested field types and compare only - the fields stored in the target schema. A logical set column omitted by the - override is skipped, including for an empty projection. Function iteration - validates wrapped sets without sorting each output. +- Explicit Arrow schema overrides use the requested field types. Struct-set + comparison uses the projected storage, and list-view overrides preserve + stored precision. A logical set column omitted by the override is skipped, + including for an empty projection. Function iteration validates wrapped + sets without sorting each output. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index fbd7d6832..200448d69 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -20,11 +20,16 @@ Small sets with flat exact keys compare the coerced Arrow values without constructing a sort table. Direct structural-dictionary reads pass Python storage values to each logical decoder. Function iteration checks the coerced storage keys for NaNs and duplicates -without sorting the row, including when a list or class wraps the set. +without sorting the row, including when a list or class wraps the set. Both +function iteration and table assembly compare Arrow map storage as entry lists. Function table assembly carries the typed source-info columns directly from -the rows so it can encode and order the payload once per column. +the rows so it can encode and order the payload once per column. Rows without +tokens stay aligned with rows that carry them. A custom table writer still +validates function output through the supplied writer. An explicit Arrow schema override compares its retained fields in the user -class's declared order after coercing them to their target Arrow types. +class's declared order after coercing them to their target Arrow types. A +list-view override carries the Arrow values into the view at their stored +precision. Columns omitted by an Arrow schema override are skipped during checked-set writes, including when the override has no fields. Explicit native writes reuse converters by Python type, even when Arrow @@ -32,5 +37,6 @@ schema metadata changes between writes. Sets of other logical types keep their native sort. For user-defined scalar storage, one Arrow pass per table column rejects NaNs and duplicate stored values. The same ordering rules apply to classes rebuilt from metadata. +Directly constructed set codecs validate even without a set registry entry. The conversion boundary supplies the column name. Rebuilding sets of user classes can change affected row hashes. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 11ff7964e..67ec0f03e 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1061,7 +1061,9 @@ canonical JSON text (ITL-942); that order is never stored and never seen. The tw different on purpose (JSON text puts `10` before `2`; storage order is numeric) and neither is defined in terms of the other: changing the hasher's order would move semantic hashes of affected inputs, and changing storage order would move row hashes and what a pod reads back. -`ListLogicalType` applies the same storage rule to `set[T]` of a logical type. +`ListLogicalType` applies the canonical storage rule to sets of struct-stored logical +types. Sets of scalar-stored logical types keep their native sort, which can produce a +different stored order and row hash from canonical ordering. **The set's identity is part of the row hash** (ITL-611). A set of a primitive is stored under its native container type, and the Arrow hasher hashes an extension column's diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 5f5b71405..1daa050dc 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1154,12 +1154,22 @@ def _executor_return_options(self) -> dict[str, object] | None: def _resolve_output_table_converter( self, converter: TypeConverterProtocol ) -> _OutputTableConverter: - """Keep native output conversion unless the schema has a struct set.""" - if isinstance(converter, UniversalTypeConverter): + """Use eager set validation when the standard writer owns the storage policy.""" + writer = converter.python_dicts_to_arrow_table + if ( + isinstance(converter, UniversalTypeConverter) + and getattr(writer, "__func__", None) + is UniversalTypeConverter.python_dicts_to_arrow_table + ): validate = converter._eager_set_output_validator(self.output_data_schema) if validate is not None: return validate - return converter.python_dicts_to_arrow_table + return writer + + def write(rows: list[dict[str, Any]], schema: SchemaLike) -> pa.Table: + return writer(rows, python_schema=schema) + + return write def _convert_outputs( self, output_data: dict[str, DataValue], output_schema: Schema diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 9ac0a1abd..73fef0ad8 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1208,10 +1208,11 @@ def _token_rows(rows: "Sequence[pa.Table]") -> pa.Table: tables.append(row) continue columns = dict(zip(row.column_names, row.columns, strict=True)) + # A tokenless table can have zero rows, but still represents one output. tables.append( pa.Table.from_arrays( [ - columns[name] if name in columns else pa.nulls(row.num_rows, kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type + columns[name] if name in columns else pa.nulls(1, kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type for name, kind in types.items() ], schema=schema, diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index a7e3e274c..6dafbe2e0 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -480,7 +480,9 @@ def python_to_storage( if value is None: return [] if isinstance(converter, UniversalTypeConverter): - plan = converter._set_storage_plan(self.python_type, self._storage_type) + plan = converter._set_storage_plan( + self.python_type, self._storage_type, set_codec=self + ) elif converter is not None: plan = storage_plan( self.python_type, @@ -489,6 +491,7 @@ def python_to_storage( lambda annotation: partial( converter.python_to_storage, annotation=annotation ), + set_codec=self, ) elif self._orders_stored_sets: return ordered_set_storage(list(value), self._storage_type.value_type) diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py index f0d9b8f2e..c82b41667 100644 --- a/src/orcapod/semantic_types/logical_set_storage.py +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -16,7 +16,10 @@ from orcapod.errors import LogicalSetCanonicalOrderError if TYPE_CHECKING: - from orcapod.logical_types.protocols import TypeConverterProtocol + from orcapod.logical_types.protocols import ( + LogicalTypeProtocol, + TypeConverterProtocol, + ) _ListArray = ( pa.ListArray[Any] @@ -400,6 +403,8 @@ def _stored_keys(array: pa.Array[Any]) -> list[Any]: return [None] * len(array) if isinstance(array, pa.StructArray): return _struct_keys(array, [_stored_keys] * array.type.num_fields) + if isinstance(array, pa.MapArray): + array = array.view(pa.list_(array.type.field(0))) if isinstance(array, _LIST_ARRAY_TYPES): return _list_keys(array, _stored_keys, tuple) if isinstance(array, pa.ExtensionArray): @@ -556,13 +561,18 @@ def storage_plan( fallback: Callable[[Any], _Encode], *, canonical: bool = False, + set_codec: LogicalTypeProtocol | None = None, ) -> _StoragePlan: """Resolve the operations for a column containing sets of logical types.""" from orcapod.logical_types.list_logical_type_factory import ListLogicalType from orcapod.logical_types.user_class_logical_type import UserClassLogicalType from orcapod.semantic_types.universal_converter import _none_not_admitted - logical_type = converter.get_logical_type_for_python_type(annotation) + logical_type = ( + set_codec + if set_codec is not None + else converter.get_logical_type_for_python_type(annotation) + ) origin = get_origin(annotation) args = get_args(annotation) diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 3ff6fbaa3..4cd88fd96 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -24,6 +24,7 @@ from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict, get_args, get_origin import pyarrow as pa +import pyarrow.compute as pc from orcapod.contexts import DataContext, resolve_context from orcapod.errors import ( @@ -138,6 +139,35 @@ def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataTy return target +def _cast_set_storage(storage: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: + """Apply a storage override while retaining the Arrow values where possible.""" + try: + if not isinstance(storage, pa.LargeListArray) or not isinstance( + target, (pa.ListViewType, pa.LargeListViewType) + ): + return storage.cast(target) + + # Arrow has no cast from a list to a list view. Reuse the values and + # derive each view's size from the list offsets. + values = storage.values.cast(target.value_type) + offsets = storage.offsets.slice(0, len(storage)) + sizes = pc.subtract(storage.offsets.slice(1), offsets) + if isinstance(target, pa.ListViewType): + return pa.ListViewArray.from_arrays( # pyright: ignore[reportCallIssue] # stubs omit sizes + offsets.cast(pa.int32()), + sizes.cast(pa.int32()), + values, + type=target, + mask=storage.is_null(), + ) + return pa.LargeListViewArray.from_arrays( # pyright: ignore[reportCallIssue] # stubs omit sizes + offsets, sizes, values, type=target, mask=storage.is_null() + ) + except pa.ArrowException: + # Some builders accept shapes Arrow has no cast kernel for. + return pa.array(typing.cast("pa.Array[Any]", storage).to_pylist(), type=target) + + def _get_python_to_arrow_map() -> dict: """Return the Python→Arrow type map, building it on first call.""" global _PYTHON_TO_ARROW_MAP @@ -332,7 +362,9 @@ def __init__( self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} self._explicit_value_converters: dict[DataType, Callable[[Any], Any]] = {} - self._set_storage_plans: dict[tuple[DataType, pa.DataType], _StoragePlan] = {} + self._set_storage_plans: dict[ + tuple[DataType, pa.DataType, LogicalTypeProtocol | None], _StoragePlan + ] = {} self._checked_set_storage: dict[DataType, pa.DataType] = {} self._inferred_table_schema = lru_cache(maxsize=128)( self._prepare_inferred_table_schema @@ -1579,16 +1611,24 @@ def _explicit_checked_columns( return checked_columns def _set_storage_plan( - self, annotation: DataType, storage_type: pa.DataType + self, + annotation: DataType, + storage_type: pa.DataType, + *, + set_codec: LogicalTypeProtocol | None = None, ) -> _StoragePlan: """Resolve and cache the converters for a logical-set column.""" - key = (annotation, storage_type) + key = (annotation, storage_type, set_codec) plan = self._set_storage_plans.get(key) if plan is None: from orcapod.semantic_types.logical_set_storage import storage_plan plan = storage_plan( - annotation, storage_type, self, self.get_python_to_arrow_converter + annotation, + storage_type, + self, + self.get_python_to_arrow_converter, + set_codec=set_codec, ) self._set_storage_plans[key] = plan return plan @@ -1754,11 +1794,7 @@ def _encode_set_columns( raise UnsupportedValueError(f"Column {name!r}: {exc}") from exc field_type = field.type if override_type is not None: - try: - storage = storage.cast(override_type) - except pa.ArrowException: - # Some builders accept shapes Arrow has no cast kernel for. - storage = pa.array(storage.to_pylist(), type=override_type) + storage = _cast_set_storage(storage, override_type) encoded_columns[index] = ( pa.ExtensionArray.from_storage(field_type, storage) if isinstance(field_type, pa.ExtensionType) diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index c292b0c60..ec82c6d23 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -35,17 +35,24 @@ import pyarrow as pa import pyarrow.compute as pc import pytest +from typing_extensions import override from pydantic import BaseModel from orcapod import PipelineJob, errors, function_pod +from orcapod.contexts import create_registry from orcapod.core.data_function import PythonDataFunction from orcapod.core.datagrams import Data from orcapod.core.function_pod import FunctionPod from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.logical_types.registry import LogicalTypeRegistry from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.core_protocols import DataFunctionProtocol, DataProtocol +from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.sources import DictSource +from orcapod.types import SchemaLike @dataclass @@ -1413,3 +1420,67 @@ def test_wrapped_function_set_refuses_duplicate_storage_eagerly() -> None: stream = make_pod(list[WrappedOutputSet], [value]).pod(make_source()) with pytest.raises(errors.CanonicalOrderError, match=r"Column 'y': .*duplicate"): next(stream.iter_data()) + + +def test_function_table_keeps_rows_without_source_info() -> None: + """A row without tokens contributes a null beside rows that carry tokens.""" + + class OptionalTokens(PythonDataFunction): + @override + def call(self, data: DataProtocol, **kwargs: Any) -> Data: + value = cast(int, data["x"]) + tokens = {"y": "present"} if value == 1 else None + return Data({"y": value}, source_info=tokens) + + def identity(x: int) -> int: + return x + + data_function = cast( + DataFunctionProtocol, cast(object, OptionalTokens(identity, output_keys="y")) + ) + stream = FunctionPod(data_function)(make_source((0, 1))) + table = stream.as_table(columns={"source": True}) + assert table.select(["y", "_source_y"]).to_pylist() == [ + {"y": 0, "_source_y": None}, + {"y": 1, "_source_y": "present"}, + ] + + +def test_function_set_output_uses_custom_writer_validation() -> None: + """A context's writer can enforce a storage policy for its logical sets.""" + + class PositivePointsConverter(UniversalTypeConverter): + @override + def python_dicts_to_arrow_table( + self, + python_dicts: list[dict[str, Any]], + python_schema: SchemaLike | None = None, + arrow_schema: pa.Schema | None = None, + ) -> pa.Table: + if any( + point.value < 0 + for row in python_dicts + for point in row.get("y", ()) + if isinstance(point, SetOutputFloat) + ): + raise ValueError("Points must be nonnegative") + return super().python_dicts_to_arrow_table( + python_dicts, python_schema, arrow_schema + ) + + context = create_registry().get_context() + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + logical_type = converter.get_logical_type_for_python_type(SetOutputFloat) + assert logical_type is not None + custom_writer = PositivePointsConverter( + logical_type_registry=LogicalTypeRegistry(logical_types=[logical_type]) + ) + context.type_converter = cast(TypeConverterProtocol, cast(object, custom_writer)) + + @function_pod(output_keys="y", data_context=context) + def negative_point(x: int) -> set[SetOutputFloat]: + return {SetOutputFloat(-float(x))} + + with pytest.raises(errors.OutputTypeError, match=r"output 'y'"): + _ = next(negative_point.pod(make_source()).iter_data()) diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index 15ba0b87c..05088833a 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -33,6 +33,7 @@ import orcapod as op from orcapod.contexts import create_registry, get_default_context from orcapod.errors import CanonicalOrderError, RowFailuresWarning +from orcapod.logical_types import ListLogicalType from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.identifier import version_metadata from orcapod.logical_types.protocols import TypeConverterProtocol @@ -144,6 +145,85 @@ def registered_types(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(get_default_context(), "type_converter", converter) +def test_unregistered_set_codec_checks_duplicate_scalar_storage() -> None: + """A directly constructed codec validates its set without a registry binding.""" + word_type = LogicalWord() + + class ElementConverter: + def get_logical_type_for_python_type( + self, annotation: Any + ) -> LogicalWord | None: + return word_type if annotation is Word else None + + def python_to_storage(self, value: Any, annotation: Any) -> Any: + if annotation is Word: + return word_type.python_to_storage(value) + return sorted(word_type.python_to_storage(item) for item in value) + + converter = cast(TypeConverterProtocol, cast(object, ElementConverter())) + codec = ListLogicalType(word_type, is_set=True) + values = codec.python_to_storage({Word("Z"), Word("a")}, converter) + assert isinstance(values, pa.Array) + assert values.to_pylist() == ["a", "z"] + with pytest.raises(CanonicalOrderError, match="duplicate"): + codec.python_to_storage({Word("A"), Word("a")}, converter) + + +@dataclasses.dataclass(frozen=True) +class WithMap: + word: Word + + +def test_function_set_with_map_storage_validates_and_writes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Eager validation accepts the same map storage as the table writer.""" + + class LogicalMap(LogicalWord): + logical_type_name = "example.itl922.map" + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + extension = make_arrow_extension_type( + self.logical_type_name, pa.map_(pa.string(), pa.int64()) + ) + return extension() # pyright: ignore[reportCallIssue] # generated constructor + + @override + def get_polars_extension_type(self) -> pl.BaseExtension: + extension = make_polars_extension_type( + self.logical_type_name, + pa.list_(pa.struct([("key", pa.string()), ("value", pa.int64())])), + ) + return cast("Callable[[], pl.BaseExtension]", extension)() + + @override + def python_to_storage( + self, value: Word, converter: TypeConverterProtocol | None = None + ) -> Any: + return [(value.text, 1)] + + @override + def storage_to_python( + self, storage_value: Any, converter: TypeConverterProtocol | None = None + ) -> Word: + return Word(storage_value[0][0]) + + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(LogicalMap()) + monkeypatch.setattr(get_default_context(), "type_converter", converter) + + def emit(x: int) -> set[WithMap]: + return {WithMap(Word("b")), WithMap(Word("a"))} + + stream = op.function_pod(output_keys="y")(emit).pod(DictSource([{"x": 1}])) + assert len(list(stream.iter_data())) == 1 + assert stream.as_table()["y"].to_pylist() == [ + [{"word": [("a", 1)]}, {"word": [("b", 1)]}] + ] + + # ── sources with several tag and data columns, in two arrangements ─────────── ARRANGEMENTS = ("tags_first", "data_first_reversed") @@ -663,6 +743,9 @@ def unexpected(*_args: object, **_kwargs: object) -> Never: monkeypatch.setattr( "orcapod.semantic_types.canonical_order.sort_set_elements", unexpected ) + monkeypatch.setattr( + "orcapod.semantic_types.universal_converter.sort_set_elements", unexpected + ) for name in ("b", "a"): (tmp_path / name).write_text(name) (tmp_path / f"{name}-dir").mkdir() @@ -918,12 +1001,13 @@ def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: return sort_indices(table, *args, **kwargs) monkeypatch.setattr(pc, "sort_indices", record_size) - small = ExactPoint(2, "x") - large = ExactPoint(10, "y") converter = get_default_context().type_converter assert isinstance(converter, UniversalTypeConverter) schema: dict[str, Any] = {"s": set[ExactPoint]} - rows = [{"s": {small, large}} for _ in range(32)] + rows = [ + {"s": {ExactPoint(100 * i + 2, "x"), ExactPoint(100 * i + 10, "y")}} + for i in range(32) + ] converter.ensure_types_registered_for_schemas(Schema(schema)) if precomputed: writer = SemanticSchemaConverter(converter, python_schema=schema) @@ -931,7 +1015,9 @@ def record_size(table: pa.Table, *args: Any, **kwargs: Any) -> Any: else: table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) assert sizes == [64] - assert table["s"].to_pylist() == [[{"a": 2, "b": "x"}, {"a": 10, "b": "y"}]] * 32 + assert table["s"].to_pylist() == [ + [{"a": 100 * i + 2, "b": "x"}, {"a": 100 * i + 10, "b": "y"}] for i in range(32) + ] def test_fixed_width_integer_list_keys_rank_columns( diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index fdcfce80e..241461104 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -28,6 +28,36 @@ class OverrideValue: value: Any = field(hash=False) +@pytest.mark.parametrize("precomputed", [False, True]) +@pytest.mark.parametrize("list_view", [pa.list_view, pa.large_list_view]) +def test_reordered_set_list_view_preserves_nanosecond_storage( + precomputed: bool, list_view: Callable[[pa.DataType], pa.DataType] +) -> None: + """A list-view override retains Arrow values finer than Python can represent.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema: dict[str, Any] = {"data": set[OverrideValue] | None} + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + element_type = pa.struct([("value", pa.time64("ns")), ("order", pa.int64())]) + target = pa.schema([("data", list_view(element_type))]) + rows = [ + {"data": {OverrideValue(2, 123), OverrideValue(1, 456)}}, + {"data": None}, + {"data": set()}, + ] + if precomputed: + writer = SemanticSchemaConverter(converter, python_schema) + table = writer.python_dicts_to_arrow_table(rows, target) + else: + table = converter.python_dicts_to_arrow_table(rows, python_schema, target) + column = table["data"].combine_chunks() + assert isinstance(column, (pa.ListViewArray, pa.LargeListViewArray)) + assert column.is_valid().to_pylist() == [True, False, True] + values = column.values + assert isinstance(values, pa.StructArray) + assert values.field("value").cast(pa.int64()).to_pylist() == [456, 123] + + @dataclass(frozen=True) class Reading: """The time component can survive an explicit timestamp override.""" From c59f8934575be5bdef1af8e4849f8c23729ab457 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:19:02 -0800 Subject: [PATCH 16/18] fix(logical-types): preserve values in set projections --- changelog.d/ITL-922.md | 4 +- docs/dev/design_issues/ITL-922-DO2.md | 6 +- .../list_logical_type_factory.py | 5 +- .../semantic_types/logical_set_storage.py | 12 +-- .../semantic_types/precomputed_converters.py | 5 +- .../semantic_types/universal_converter.py | 80 +++++++++---------- .../test_set_of_logical_elements.py | 25 ------ .../test_arrow_schema_overrides.py | 72 +++++++++++++++++ 8 files changed, 119 insertions(+), 90 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 183766d90..cd9a26c25 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -20,7 +20,7 @@ - Direct structural-dictionary conversion round-trips sets of logical values, including struct fields with their own logical decoders. - Explicit Arrow schema overrides use the requested field types. Struct-set - comparison uses the projected storage, and list-view overrides preserve - stored precision. A logical set column omitted by the override is skipped, + comparison uses the projected storage, and nested list-view and map overrides + preserve stored temporal precision. A logical set column omitted by the override is skipped, including for an empty projection. Function iteration validates wrapped sets without sorting each output. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index 200448d69..d8962d330 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -27,9 +27,8 @@ the rows so it can encode and order the payload once per column. Rows without tokens stay aligned with rows that carry them. A custom table writer still validates function output through the supplied writer. An explicit Arrow schema override compares its retained fields in the user -class's declared order after coercing them to their target Arrow types. A -list-view override carries the Arrow values into the view at their stored -precision. +class's declared order after coercing them to their target Arrow types. Nested list-view and map overrides retain stored temporal +precision when the Arrow builder rebuilds the projection. Columns omitted by an Arrow schema override are skipped during checked-set writes, including when the override has no fields. Explicit native writes reuse converters by Python type, even when Arrow @@ -37,6 +36,5 @@ schema metadata changes between writes. Sets of other logical types keep their native sort. For user-defined scalar storage, one Arrow pass per table column rejects NaNs and duplicate stored values. The same ordering rules apply to classes rebuilt from metadata. -Directly constructed set codecs validate even without a set registry entry. The conversion boundary supplies the column name. Rebuilding sets of user classes can change affected row hashes. diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 6dafbe2e0..a7e3e274c 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -480,9 +480,7 @@ def python_to_storage( if value is None: return [] if isinstance(converter, UniversalTypeConverter): - plan = converter._set_storage_plan( - self.python_type, self._storage_type, set_codec=self - ) + plan = converter._set_storage_plan(self.python_type, self._storage_type) elif converter is not None: plan = storage_plan( self.python_type, @@ -491,7 +489,6 @@ def python_to_storage( lambda annotation: partial( converter.python_to_storage, annotation=annotation ), - set_codec=self, ) elif self._orders_stored_sets: return ordered_set_storage(list(value), self._storage_type.value_type) diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py index c82b41667..e1cb91144 100644 --- a/src/orcapod/semantic_types/logical_set_storage.py +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -16,10 +16,7 @@ from orcapod.errors import LogicalSetCanonicalOrderError if TYPE_CHECKING: - from orcapod.logical_types.protocols import ( - LogicalTypeProtocol, - TypeConverterProtocol, - ) + from orcapod.logical_types.protocols import TypeConverterProtocol _ListArray = ( pa.ListArray[Any] @@ -561,18 +558,13 @@ def storage_plan( fallback: Callable[[Any], _Encode], *, canonical: bool = False, - set_codec: LogicalTypeProtocol | None = None, ) -> _StoragePlan: """Resolve the operations for a column containing sets of logical types.""" from orcapod.logical_types.list_logical_type_factory import ListLogicalType from orcapod.logical_types.user_class_logical_type import UserClassLogicalType from orcapod.semantic_types.universal_converter import _none_not_admitted - logical_type = ( - set_codec - if set_codec is not None - else converter.get_logical_type_for_python_type(annotation) - ) + logical_type = converter.get_logical_type_for_python_type(annotation) origin = get_origin(annotation) args = get_args(annotation) diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 1a23347ab..9949509a4 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -170,12 +170,13 @@ def python_dicts_to_arrow_table( when the caller needs to enforce specific field types or nullable flags that differ from what was inferred at construction time. """ - schema = self.arrow_schema if arrow_schema is None else arrow_schema if not self._checked_columns: return pa.Table.from_pylist( - self.python_dicts_to_struct_dicts(data), schema=schema + self.python_dicts_to_struct_dicts(data), + schema=arrow_schema or self.arrow_schema, ) + schema = self.arrow_schema if arrow_schema is None else arrow_schema checked_columns = ( self._checked_columns if schema is self.arrow_schema diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 4cd88fd96..ac7a0ef69 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -24,7 +24,6 @@ from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict, get_args, get_origin import pyarrow as pa -import pyarrow.compute as pc from orcapod.contexts import DataContext, resolve_context from orcapod.errors import ( @@ -139,33 +138,31 @@ def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataTy return target -def _cast_set_storage(storage: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: - """Apply a storage override while retaining the Arrow values where possible.""" - try: - if not isinstance(storage, pa.LargeListArray) or not isinstance( - target, (pa.ListViewType, pa.LargeListViewType) - ): - return storage.cast(target) - - # Arrow has no cast from a list to a list view. Reuse the values and - # derive each view's size from the list offsets. - values = storage.values.cast(target.value_type) - offsets = storage.offsets.slice(0, len(storage)) - sizes = pc.subtract(storage.offsets.slice(1), offsets) - if isinstance(target, pa.ListViewType): - return pa.ListViewArray.from_arrays( # pyright: ignore[reportCallIssue] # stubs omit sizes - offsets.cast(pa.int32()), - sizes.cast(pa.int32()), - values, - type=target, - mask=storage.is_null(), - ) - return pa.LargeListViewArray.from_arrays( # pyright: ignore[reportCallIssue] # stubs omit sizes - offsets, sizes, values, type=target, mask=storage.is_null() - ) - except pa.ArrowException: - # Some builders accept shapes Arrow has no cast kernel for. - return pa.array(typing.cast("pa.Array[Any]", storage).to_pylist(), type=target) +def _set_storage_builder_value(value: pa.Scalar[Any] | None) -> Any: + """Retain typed temporal ticks when the Arrow builder must rebuild a set.""" + if value is None or not value.is_valid: + return None + if isinstance(value, (pa.Time64Scalar, pa.TimestampScalar, pa.DurationScalar)): + return value.value + if isinstance(value, pa.StructScalar): + return { + name: _set_storage_builder_value(child) for name, child in value.items() + } + if isinstance(value, pa.ListScalar): + children = value.values + assert children is not None + if isinstance(value, pa.MapScalar): + return [ + ( + _set_storage_builder_value(entry[0]), + _set_storage_builder_value(entry[1]), + ) + for entry in children + ] + return [_set_storage_builder_value(child) for child in children] + if isinstance(value, (pa.DictionaryScalar, pa.ExtensionScalar, pa.UnionScalar)): + return _set_storage_builder_value(value.value) + return value.as_py() def _get_python_to_arrow_map() -> dict: @@ -362,9 +359,7 @@ def __init__( self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} self._explicit_value_converters: dict[DataType, Callable[[Any], Any]] = {} - self._set_storage_plans: dict[ - tuple[DataType, pa.DataType, LogicalTypeProtocol | None], _StoragePlan - ] = {} + self._set_storage_plans: dict[tuple[DataType, pa.DataType], _StoragePlan] = {} self._checked_set_storage: dict[DataType, pa.DataType] = {} self._inferred_table_schema = lru_cache(maxsize=128)( self._prepare_inferred_table_schema @@ -1611,24 +1606,16 @@ def _explicit_checked_columns( return checked_columns def _set_storage_plan( - self, - annotation: DataType, - storage_type: pa.DataType, - *, - set_codec: LogicalTypeProtocol | None = None, + self, annotation: DataType, storage_type: pa.DataType ) -> _StoragePlan: """Resolve and cache the converters for a logical-set column.""" - key = (annotation, storage_type, set_codec) + key = (annotation, storage_type) plan = self._set_storage_plans.get(key) if plan is None: from orcapod.semantic_types.logical_set_storage import storage_plan plan = storage_plan( - annotation, - storage_type, - self, - self.get_python_to_arrow_converter, - set_codec=set_codec, + annotation, storage_type, self, self.get_python_to_arrow_converter ) self._set_storage_plans[key] = plan return plan @@ -1794,7 +1781,14 @@ def _encode_set_columns( raise UnsupportedValueError(f"Column {name!r}: {exc}") from exc field_type = field.type if override_type is not None: - storage = _cast_set_storage(storage, override_type) + try: + storage = storage.cast(override_type) + except pa.ArrowException: + # Some builders accept shapes Arrow has no cast kernel for. + storage = pa.array( + [_set_storage_builder_value(value) for value in storage], + type=override_type, + ) encoded_columns[index] = ( pa.ExtensionArray.from_storage(field_type, storage) if isinstance(field_type, pa.ExtensionType) diff --git a/tests/test_logical_types/test_set_of_logical_elements.py b/tests/test_logical_types/test_set_of_logical_elements.py index 05088833a..655c56b7c 100644 --- a/tests/test_logical_types/test_set_of_logical_elements.py +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -33,7 +33,6 @@ import orcapod as op from orcapod.contexts import create_registry, get_default_context from orcapod.errors import CanonicalOrderError, RowFailuresWarning -from orcapod.logical_types import ListLogicalType from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.identifier import version_metadata from orcapod.logical_types.protocols import TypeConverterProtocol @@ -145,30 +144,6 @@ def registered_types(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(get_default_context(), "type_converter", converter) -def test_unregistered_set_codec_checks_duplicate_scalar_storage() -> None: - """A directly constructed codec validates its set without a registry binding.""" - word_type = LogicalWord() - - class ElementConverter: - def get_logical_type_for_python_type( - self, annotation: Any - ) -> LogicalWord | None: - return word_type if annotation is Word else None - - def python_to_storage(self, value: Any, annotation: Any) -> Any: - if annotation is Word: - return word_type.python_to_storage(value) - return sorted(word_type.python_to_storage(item) for item in value) - - converter = cast(TypeConverterProtocol, cast(object, ElementConverter())) - codec = ListLogicalType(word_type, is_set=True) - values = codec.python_to_storage({Word("Z"), Word("a")}, converter) - assert isinstance(values, pa.Array) - assert values.to_pylist() == ["a", "z"] - with pytest.raises(CanonicalOrderError, match="duplicate"): - codec.python_to_storage({Word("A"), Word("a")}, converter) - - @dataclasses.dataclass(frozen=True) class WithMap: word: Word diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index 241461104..d9a672405 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -58,6 +58,74 @@ def test_reordered_set_list_view_preserves_nanosecond_storage( assert values.field("value").cast(pa.int64()).to_pylist() == [456, 123] +@dataclass(frozen=True) +class ListTicks: + order: int + ticks: list[int] = field(hash=False) + + +@dataclass(frozen=True) +class MapTicks: + order: int + ticks: dict[str, int] = field(hash=False) + + +@pytest.mark.parametrize("precomputed", [False, True]) +@pytest.mark.parametrize("outer", [pa.list_, pa.list_view, pa.large_list_view]) +@pytest.mark.parametrize("inner", ["list-view", "large-list-view", "map"]) +def test_nested_set_projection_preserves_nanosecond_storage( + precomputed: bool, outer: Callable[[pa.DataType], pa.DataType], inner: str +) -> None: + """Both public writers preserve the raw ticks that distinguish two members.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + tick_type = pa.time64("ns") + if inner == "map": + python_schema = {"data": set[MapTicks]} + rows = [{"data": {MapTicks(1, {"t": 456}), MapTicks(1, {"t": 123})}}] + nested = pa.map_(pa.string(), tick_type) + else: + python_schema = {"data": set[ListTicks]} + rows = [{"data": {ListTicks(1, [456]), ListTicks(1, [123])}}] + nested = ( + pa.list_view(tick_type) + if inner == "list-view" + else pa.large_list_view(tick_type) + ) + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + target = pa.schema( + [("data", outer(pa.struct([("order", pa.int64()), ("ticks", nested)])))] + ) + if precomputed: + table = SemanticSchemaConverter( + converter, python_schema + ).python_dicts_to_arrow_table(rows, target) + else: + table = converter.python_dicts_to_arrow_table(rows, python_schema, target) + column = table["data"].combine_chunks() + assert isinstance(column, (pa.ListArray, pa.ListViewArray, pa.LargeListViewArray)) + points = column.values + assert isinstance(points, pa.StructArray) + ticks = points.field("ticks") + if isinstance(ticks, pa.MapArray): + values = ticks.items + else: + assert isinstance(ticks, (pa.ListViewArray, pa.LargeListViewArray)) + values = ticks.values + assert values.cast(pa.int64()).to_pylist() == [123, 456] + + +def test_precomputed_native_empty_override_uses_default_schema() -> None: + """A native-only empty Arrow override falls back to the inferred schema.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + writer = SemanticSchemaConverter(converter, {"n": int}) + table = writer.python_dicts_to_arrow_table([{"n": 7}], pa.schema([])) + assert table.schema == writer.arrow_schema + assert table.num_rows == 1 + assert table.to_pylist() == [{"n": 7}] + + @dataclass(frozen=True) class Reading: """The time component can survive an explicit timestamp override.""" @@ -123,6 +191,10 @@ def _override_cases() -> Iterator[Any]: ), *((pa.time32(unit), time(11), time(12)) for unit in ("s", "ms")), *((pa.time64(unit), time(11), time(12)) for unit in ("us", "ns")), + (pa.time64("ns"), 123, 456), + (pa.list_view(pa.time64("ns")), [123], [456]), + (pa.large_list_view(pa.time64("ns")), [123], [456]), + (pa.map_(pa.string(), pa.time64("ns")), [("t", 123)], [("t", 456)]), *( (pa.duration(unit), timedelta(seconds=11), timedelta(seconds=12)) for unit in ("s", "ms", "us", "ns") From 6ab9b67d834812d99a95ef7e9263ca36659c9c76 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:54:08 -0800 Subject: [PATCH 17/18] fix(logical-types): restore reviewed set conversion behavior --- changelog.d/ITL-922.md | 9 ++- docs/dev/design_issues/ITL-922-DO2.md | 10 +-- src/orcapod/core/data_function.py | 2 +- src/orcapod/core/function_pod.py | 1 - .../semantic_types/logical_set_storage.py | 14 +++- .../semantic_types/universal_converter.py | 38 +++++----- .../test_arrow_schema_overrides.py | 71 +++++++++++++++++++ 7 files changed, 113 insertions(+), 32 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index cd9a26c25..8b770a2ef 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -19,8 +19,7 @@ keys use Arrow or Polars kernels. - Direct structural-dictionary conversion round-trips sets of logical values, including struct fields with their own logical decoders. -- Explicit Arrow schema overrides use the requested field types. Struct-set - comparison uses the projected storage, and nested list-view and map overrides - preserve stored temporal precision. A logical set column omitted by the override is skipped, - including for an empty projection. Function iteration validates wrapped - sets without sorting each output. +- Explicit Arrow schema overrides use the requested field types and compare only + the fields stored in the target schema. A logical set column omitted by the + override is skipped, including for an empty projection. Function iteration + validates wrapped sets without sorting each output. diff --git a/docs/dev/design_issues/ITL-922-DO2.md b/docs/dev/design_issues/ITL-922-DO2.md index d8962d330..fbd7d6832 100644 --- a/docs/dev/design_issues/ITL-922-DO2.md +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -20,15 +20,11 @@ Small sets with flat exact keys compare the coerced Arrow values without constructing a sort table. Direct structural-dictionary reads pass Python storage values to each logical decoder. Function iteration checks the coerced storage keys for NaNs and duplicates -without sorting the row, including when a list or class wraps the set. Both -function iteration and table assembly compare Arrow map storage as entry lists. +without sorting the row, including when a list or class wraps the set. Function table assembly carries the typed source-info columns directly from -the rows so it can encode and order the payload once per column. Rows without -tokens stay aligned with rows that carry them. A custom table writer still -validates function output through the supplied writer. +the rows so it can encode and order the payload once per column. An explicit Arrow schema override compares its retained fields in the user -class's declared order after coercing them to their target Arrow types. Nested list-view and map overrides retain stored temporal -precision when the Arrow builder rebuilds the projection. +class's declared order after coercing them to their target Arrow types. Columns omitted by an Arrow schema override are skipped during checked-set writes, including when the override has no fields. Explicit native writes reuse converters by Python type, even when Arrow diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 1daa050dc..c67673676 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1154,7 +1154,7 @@ def _executor_return_options(self) -> dict[str, object] | None: def _resolve_output_table_converter( self, converter: TypeConverterProtocol ) -> _OutputTableConverter: - """Use eager set validation when the standard writer owns the storage policy.""" + """Use eager set validation when the standard writer owns storage.""" writer = converter.python_dicts_to_arrow_table if ( isinstance(converter, UniversalTypeConverter) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 73fef0ad8..0372a363c 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1208,7 +1208,6 @@ def _token_rows(rows: "Sequence[pa.Table]") -> pa.Table: tables.append(row) continue columns = dict(zip(row.column_names, row.columns, strict=True)) - # A tokenless table can have zero rows, but still represents one output. tables.append( pa.Table.from_arrays( [ diff --git a/src/orcapod/semantic_types/logical_set_storage.py b/src/orcapod/semantic_types/logical_set_storage.py index e1cb91144..c8dad5b36 100644 --- a/src/orcapod/semantic_types/logical_set_storage.py +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -43,6 +43,16 @@ def _ordinal_column(keys: list[Any]) -> pa.Array[Any]: return pa.array([ranks.get(key) for key in keys], type=pa.int64()) +def _flatten_list(array: "_ListArray") -> pa.Array[Any]: + """Flatten valid list slots, including fixed-size lists with null children.""" + if isinstance(array, pa.FixedSizeListArray) and pa.types.is_null( + array.type.value_type + ): + # Arrow's flatten kernel can abort on null slots with a null child type. + return pa.nulls((len(array) - array.null_count) * array.type.list_size) + return array.flatten() + + def _list_sort_column( array: pa.ListArray[Any] | pa.LargeListArray[Any] @@ -51,7 +61,7 @@ def _list_sort_column( | pa.LargeListViewArray[Any], ) -> pa.Array[Any]: """Use one lexicographic key per stored list, comparing only its own children.""" - children = _sort_columns(array.flatten()) + children = _sort_columns(_flatten_list(array)) # Polars ranks lists of native scalar keys. Use Arrow dense ranks for # child types whose representation Polars cannot rank inside a list. children = [ @@ -456,7 +466,7 @@ def _list_keys( collect(children[start - first : end - first]) for start, end in pairwise(offsets) ] - children = child_keys(cast("_ListArray", array).flatten()) + children = child_keys(_flatten_list(cast("_ListArray", array))) offset = 0 rows: list[Any] = [] for length in pc.list_value_length(array).to_pylist(): diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index ac7a0ef69..b921d1f81 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -138,30 +138,34 @@ def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataTy return target -def _set_storage_builder_value(value: pa.Scalar[Any] | None) -> Any: - """Retain typed temporal ticks when the Arrow builder must rebuild a set.""" +def _override_builder_value(value: pa.Scalar[Any] | None) -> Any: + """Expose coerced values to the Arrow builder without losing temporal bits.""" if value is None or not value.is_valid: return None - if isinstance(value, (pa.Time64Scalar, pa.TimestampScalar, pa.DurationScalar)): + if isinstance( + value, + ( + pa.Date32Scalar, + pa.Date64Scalar, + pa.Time64Scalar, + pa.TimestampScalar, + pa.DurationScalar, + ), + ): return value.value if isinstance(value, pa.StructScalar): - return { - name: _set_storage_builder_value(child) for name, child in value.items() - } + return {name: _override_builder_value(child) for name, child in value.items()} if isinstance(value, pa.ListScalar): children = value.values assert children is not None if isinstance(value, pa.MapScalar): return [ - ( - _set_storage_builder_value(entry[0]), - _set_storage_builder_value(entry[1]), - ) + (_override_builder_value(entry[0]), _override_builder_value(entry[1])) for entry in children ] - return [_set_storage_builder_value(child) for child in children] + return [_override_builder_value(child) for child in children] if isinstance(value, (pa.DictionaryScalar, pa.ExtensionScalar, pa.UnionScalar)): - return _set_storage_builder_value(value.value) + return _override_builder_value(value.value) return value.as_py() @@ -1782,13 +1786,15 @@ def _encode_set_columns( field_type = field.type if override_type is not None: try: - storage = storage.cast(override_type) + projected = storage.cast(override_type) + projected.validate() except pa.ArrowException: - # Some builders accept shapes Arrow has no cast kernel for. - storage = pa.array( - [_set_storage_builder_value(value) for value in storage], + # Arrow's builder also handles projections the cast cannot produce. + projected = pa.array( + [_override_builder_value(value) for value in storage], type=override_type, ) + storage = projected encoded_columns[index] = ( pa.ExtensionArray.from_storage(field_type, storage) if isinstance(field_type, pa.ExtensionType) diff --git a/tests/test_semantic_types/test_arrow_schema_overrides.py b/tests/test_semantic_types/test_arrow_schema_overrides.py index d9a672405..863b41531 100644 --- a/tests/test_semantic_types/test_arrow_schema_overrides.py +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -126,6 +126,77 @@ def test_precomputed_native_empty_override_uses_default_schema() -> None: assert table.to_pylist() == [{"n": 7}] +@pytest.mark.parametrize("precomputed", [False, True]) +@pytest.mark.parametrize( + "outer,inner,first,second", + [ + pytest.param( + pa.large_list, + pa.map_(pa.string(), pa.list_(pa.null(), 2)), + [("b", [None, None]), ("a", None)], + [("b", [None, None]), ("a", None)], + id="map-fixed-size-list-of-null", + ), + pytest.param( + pa.large_list, + pa.list_(pa.null()), + [None, None], + [None, None], + id="list-of-null", + ), + pytest.param( + pa.list_view, + pa.list_view(pa.list_(pa.null(), 2)), + [[None, None], None], + [[None, None], None], + id="list-view-fixed-size-list-of-null", + ), + pytest.param( + pa.list_view, + pa.list_view(pa.date32()), + [9_999_999], + [10_000_000], + id="raw-date32", + ), + pytest.param( + pa.list_view, + pa.list_view(pa.date64()), + [9_999_999 * 86_400_000], + [10_000_000 * 86_400_000], + id="raw-date64", + ), + ], +) +def test_reordered_set_override_matches_arrow_builder( + precomputed: bool, + outer: Callable[[pa.DataType], pa.DataType], + inner: pa.DataType, + first: Any, + second: Any, +) -> None: + """Both public writers retain the valid storage built by main.""" + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema = {"data": set[OverrideValue]} + converter.ensure_types_registered_for_schemas(Schema(python_schema)) + target = pa.schema( + [("data", outer(pa.struct([("value", inner), ("order", pa.int16())])))] + ) + rows = [{"data": {OverrideValue(11, first), OverrideValue(12, second)}}] + expected = pa.Table.from_pylist( + [{"data": [{"order": 11, "value": first}, {"order": 12, "value": second}]}], + schema=target, + ) + if precomputed: + table = SemanticSchemaConverter( + converter, python_schema + ).python_dicts_to_arrow_table(rows, target) + else: + table = converter.python_dicts_to_arrow_table(rows, python_schema, target) + table.validate(full=True) + assert table.equals(expected, check_metadata=True) + + @dataclass(frozen=True) class Reading: """The time component can survive an explicit timestamp override.""" From 39faca31d0a03e1de041934ca77e5cfcfceb425a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:55:49 -0800 Subject: [PATCH 18/18] fix(typing): record Arrow date scalar stub omission --- src/orcapod/semantic_types/universal_converter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index b921d1f81..02a5a03f6 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -152,7 +152,7 @@ def _override_builder_value(value: pa.Scalar[Any] | None) -> Any: pa.DurationScalar, ), ): - return value.value + return value.value # pyright: ignore[reportAttributeAccessIssue] # Date32Scalar.value is present at runtime; the stubs omit it. if isinstance(value, pa.StructScalar): return {name: _override_builder_value(child) for name, child in value.items()} if isinstance(value, pa.ListScalar):