diff --git a/.zed/rules b/.zed/rules index c42e2dddc..22e90002d 100644 --- a/.zed/rules +++ b/.zed/rules @@ -385,6 +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 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`. + 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 88233057c..ff952d038 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -396,6 +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 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`. + 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 new file mode 100644 index 000000000..8b770a2ef --- /dev/null +++ b/changelog.d/ITL-922.md @@ -0,0 +1,25 @@ +### 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 + +- 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. +- 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 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. +- 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/api/errors.md b/docs/api/errors.md index 16a8fcd8a..e94efcae6 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/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..fbd7d6832 --- /dev/null +++ b/docs/dev/design_issues/ITL-922-DO2.md @@ -0,0 +1,36 @@ +## `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 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 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, 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. +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, including when the override has no fields. +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. +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 1867eb84b..9bfdc1737 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1074,14 +1074,24 @@ 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) | - -A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`) 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. +| 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 | + +Struct fields and list items follow the same rules recursively, including `None` first. +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 +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 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). **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 @@ -1107,8 +1117,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. -`set[T]` of a logical type (`set[Path]`, `set[UUID]`) is ordered by `ListLogicalType`, not -by this rule. +`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 286c6a0ea..2ebee89eb 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -36,6 +36,7 @@ context_result_path, ) from orcapod.errors import ( + LogicalSetCanonicalOrderError, NoOutputsDeclaredError, OutputContainerTypeError, OutputTypeError, @@ -48,10 +49,12 @@ 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, ) +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 @@ -817,6 +820,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: @@ -897,6 +903,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, @@ -1149,28 +1158,50 @@ def _executor_return_options(self) -> dict[str, object] | None: return self._executor.return_container_options(self._return_container) return None + def _resolve_output_table_converter( + self, converter: TypeConverterProtocol + ) -> _OutputTableConverter: + """Use eager set validation when the standard writer owns storage.""" + 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 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 - ) -> pa.Table: - """Convert checked outputs to a one-row Arrow table with the declared types. + ) -> None: + """Check that 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. 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: - return 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: # 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/core/function_pod.py b/src/orcapod/core/function_pod.py index fd8910acb..a4e8492be 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -66,6 +66,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, @@ -1218,7 +1219,7 @@ def _token_rows(rows: "Sequence[pa.Table]") -> pa.Table: 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, @@ -1660,15 +1661,21 @@ def _table_from_pairs( # 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})) - # So are the source-info tokens: each row's own token columns, with - # the types the row carries, never converted from their Python - # values (ITL-1491). - row_table = data.as_table(columns={"source": True}) - token_tables.append( - row_table.select( - [n for n in row_table.column_names if n.startswith(source_prefix)] + # Keep the declared token fields (ITL-1491) without building a + # payload table for each row. Encode the payload column-wide below. + if isinstance(data, Data): + token_tables.append(data._source_info_for_transport()) # pyright: ignore[reportPrivateUsage] # transport keeps the row's declaration + else: + row_table = data.as_table(columns={"source": True}) + token_tables.append( + row_table.select( + [ + n + for n in row_table.column_names + if n.startswith(source_prefix) + ] + ) ) - ) row = data.as_dict(all_info=True) all_data.append( { @@ -1688,13 +1695,21 @@ def _table_from_pairs( # 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: pa.Table = pa.Table.from_pylist( - struct_data, schema=data_schema - ) + assert data_schema is not None + 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, checked_columns + ) + else: + struct_data = converter.python_dicts_to_struct_dicts( + all_data, python_schema=python_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, _token_rows(token_tables) ) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index c9e6b86f2..91a69d35d 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 accb1f88a..a7e3e274c 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 @@ -139,6 +139,45 @@ class ListLogicalType(BaseLogicalType): binds_python_type: bool = True + # 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", + ) + ) + + _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", @@ -414,6 +453,71 @@ 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 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: + """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/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 7f9578b3b..eee4de5d1 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.""" @@ -183,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 new file mode 100644 index 000000000..c8dad5b36 --- /dev/null +++ b/src/orcapod/semantic_types/logical_set_storage.py @@ -0,0 +1,778 @@ +"""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 _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] + | 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(_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 = [ + 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, 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): + 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) if storage.null_count else None, + ) + + +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, + 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: + return storage + return _list_with_values( + storage, _sort_set_array(elements, [pc.list_parent_indices(storage), *columns]) + ) + + +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]: + """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]] +_Validate = Callable[["pa.Array[Any]"], None] + + +@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 + validate: _Validate | 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 + + +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, 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): + 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(_flatten_list(cast("_ListArray", array))) + 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, + small_struct_keys: bool = False, + validate_child: _Validate | None = None, +) -> _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, small_struct_keys=small_struct_keys + ) + if scalar_set: + return _validate_scalar_column(storage) + return storage + + 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 + 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, + validate if canonical_set or scalar_set or validate_child is not None 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, + child.element_keys, + child.validate, + ) + + if isinstance(logical_type, UserClassLogicalType) and isinstance( + kind, pa.StructType + ): + annotations = dict(logical_type.field_annotations) + fields = [ + (field.name, resolve(annotations[field.name], field.type)) for field in kind + ] + operations = { + i: field.normalize + for i, (_, field) in enumerate(fields) + if field.normalize is not None + } + 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) + 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] + 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 ( + 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) + 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) + 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(fields) + if field.normalize is not None + } + entry_keys = [field.keys or _stored_keys for field in fields] + 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, + 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): + 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 _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_set_output( + plan: _StoragePlan, value: Any, storage_type: pa.DataType +) -> None: + """Validate declared storage without ordering the function's output row.""" + if value is None: + return + try: + encoded = plan.encode(value) + 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 3e56bc801..9949509a4 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -13,7 +13,9 @@ 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 class SemanticSchemaConverter: @@ -44,19 +46,41 @@ 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]] = {} 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. @@ -72,13 +96,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: @@ -140,10 +170,42 @@ 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( - self.python_dicts_to_struct_dicts(data), - 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=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 + else self.universal_converter._explicit_checked_columns( + self.python_schema, schema + ) ) + encoded_columns = ( + self.universal_converter._encode_set_columns( + data, checked_columns, allow_explicit_null=True + ) + if checked_columns + else {} + ) + 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 + ) + 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 678270275..02a5a03f6 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -18,9 +18,10 @@ 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, TypedDict, get_args, get_origin +from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict, get_args, get_origin import pyarrow as pa @@ -53,6 +54,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, @@ -82,6 +84,91 @@ ) +class _UseCheckedSetStorage(Exception): + """Switch table builders when resolving an annotation with a checked set.""" + + +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 + override_type: pa.DataType | None + + +def _override_plan_type(declared: pa.DataType, target: pa.DataType) -> pa.DataType: + """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, + 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): + return declared + fields = [] + for field in declared: + index = target.get_field_index(field.name) + if index >= 0: + fields.append( + field.with_type(_override_plan_type(field.type, target[index].type)) + ) + return pa.struct(fields) + return target + + +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.Date32Scalar, + pa.Date64Scalar, + pa.Time64Scalar, + pa.TimestampScalar, + pa.DurationScalar, + ), + ): + 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): + children = value.values + assert children is not None + if isinstance(value, pa.MapScalar): + return [ + (_override_builder_value(entry[0]), _override_builder_value(entry[1])) + for entry in children + ] + return [_override_builder_value(child) for child in children] + if isinstance(value, (pa.DictionaryScalar, pa.ExtensionScalar, pa.UnionScalar)): + return _override_builder_value(value.value) + return value.as_py() + + def _get_python_to_arrow_map() -> dict: """Return the Python→Arrow type map, building it on first call.""" global _PYTHON_TO_ARROW_MAP @@ -274,6 +361,21 @@ 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] = {} + 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, + tuple[_CheckedSetColumn, ...], + ] + | None + ) = None # Cache for type mappings self._python_to_arrow_types: dict[DataType, pa.DataType] = {} @@ -1066,6 +1168,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 @@ -1286,7 +1392,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 = {} @@ -1296,9 +1409,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( @@ -1387,7 +1498,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, ( @@ -1395,12 +1505,302 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_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: + 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, + projected_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 + ) + + 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 + ) struct_dicts = self.python_dicts_to_struct_dicts( python_dicts, python_schema=python_schema ) + return pa.Table.from_pylist(struct_dicts, schema=schema) - # TODO: add more helpful message here - return pa.Table.from_pylist(struct_dicts, schema=arrow_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]], + python_schema: SchemaLike, + arrow_schema: pa.Schema, + checked_columns: tuple[_CheckedSetColumn, ...], + ) -> pa.Table: + """Batch logical set columns and convert the remaining cells as usual.""" + 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 + ) + 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 + } + 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 _prepare_inferred_table_schema( + self, fields: tuple[tuple[str, DataType], ...] + ) -> tuple[pa.Schema, tuple[_CheckedSetColumn, ...]]: + """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_explicit_table_schema + 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) + if checked_columns: + self._last_explicit_table_schema = (fields, arrow_schema, checked_columns) + return checked_columns + + def _set_storage_plan( + self, annotation: DataType, storage_type: pa.DataType + ) -> _StoragePlan: + """Resolve and cache the converters for a logical-set column.""" + 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 + ) + 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 + + 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 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_set_output + + names = {column.field.name for column in checked} + remaining = { + name: annotation + for name, annotation in python_schema.items() + if name not in names + } + + def validate(rows: list[dict[str, Any]], _schema: SchemaLike) -> None: + row = rows[0] + for column in checked: + name = column.field.name + try: + 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: + self.python_dicts_to_arrow_table(rows, python_schema=remaining) + + return validate + + def _checked_set_columns( + self, + python_schema: SchemaLike, + arrow_schema: pa.Schema, + ) -> tuple[_CheckedSetColumn, ...]: + """Resolve the eligible columns and their converters once per schema.""" + if self._logical_type_registry is None: + return () + + columns: list[_CheckedSetColumn] = [] + for index, field in enumerate(arrow_schema): + annotation = python_schema.get(field.name) + if annotation is None: + continue + declared = self._checked_storage_for_annotation(annotation) + if declared is None: + continue + field_type = field.type + target = ( + field_type.storage_type + if isinstance(field_type, pa.ExtensionType) + else field_type + ) + storage_type = _override_plan_type(declared, target) + columns.append( + _CheckedSetColumn( + index, + field, + storage_type, + self._set_storage_plan(annotation, storage_type), + _is_optional_type(annotation), + None if storage_type.equals(target) else target, + ) + ) + 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]], + 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, 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. + 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: + storage = plan.encode_column(values, storage_type) + except CanonicalOrderError as exc: + raise type(exc)(f"Column {name!r}: {exc}") from exc + except UnsupportedValueError as exc: + raise UnsupportedValueError(f"Column {name!r}: {exc}") from exc + field_type = field.type + if override_type is not None: + try: + projected = storage.cast(override_type) + projected.validate() + except pa.ArrowException: + # 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) + else storage + ) + return encoded_columns def arrow_table_to_python_dicts( self, arrow_table: pa.Table @@ -2163,6 +2563,11 @@ 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() + 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/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c69d5ccdb..3a8c7d12f 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -37,6 +37,74 @@ 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, + *, + 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. 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(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[", "list[") + ): + 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..ec82c6d23 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -32,18 +32,27 @@ from typing import Any, Literal, NamedTuple, cast import numpy as np +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 @@ -1245,3 +1254,233 @@ 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." + ) + + +@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()) + + +@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()) + + +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() + + +@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))) + ) + rows = list(stream.iter_data()) + assert len(rows) == 32 + assert sizes == [] + table = stream.as_table(columns={"source": True}) + assert sizes == [128, 64] + first = table["y"].to_pylist()[0][0]["entries"] + assert [entry["d"][0]["key"] for entry in first] == [2, 8] + assert table["_source_y"].type == pa.large_string() + assert table["_source_y"].to_pylist() == [ + data.source_info()["y"] for _, data in rows + ] + + +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()) + + +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 new file mode 100644 index 000000000..655c56b7c --- /dev/null +++ b/tests/test_logical_types/test_set_of_logical_elements.py @@ -0,0 +1,1435 @@ +"""The stored order of a ``set[T]`` whose element ``T`` is a logical type (ITL-922). + +Struct storage is compared by declared field order, recursively through lists and +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 + +import asyncio +import dataclasses +import json +import os +import subprocess +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 random import Random +from typing import Any, Never, cast + +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 +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.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 + +# ── 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() # pyright: ignore[reportCallIssue] # factory fixes the extension name and storage type + + 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() # pyright: ignore[reportCallIssue] # factory fixes the extension name and storage type + + 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) + + +@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") +"""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 + 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]: + """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 ────────────────────────────────────────────────── + + +@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_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": -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} + + +@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 + ) + 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() + 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] + + +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})}}]) + + +@pytest.mark.parametrize( + ("item_type", "low", "high"), + [ + (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 +) -> None: + """Rank variable-width nullable list keys without decoding Python values.""" + from orcapod.semantic_types import logical_set_storage + + def unexpected(_keys: object) -> Never: + pytest.fail("list keys entered Python ranking") + + 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 + rows = [ + {"items": [first, high], "value": 0}, + {"items": [None], "value": 0}, + {"items": None, "value": 0}, + {"items": [tied], "value": 2}, + {"items": [], "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)) + + +@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.precomputed_converters import SemanticSchemaConverter + + 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 + assert isinstance(converter, UniversalTypeConverter) + schema: dict[str, Any] = {"s": set[ExactPoint]} + 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) + 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": 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( + 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), + ] + + +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(32)] + + [set()] + } + ] + result = converter.python_dicts_to_arrow_table(data, python_schema=schema) + assert sizes == [64] + assert result["s"].to_pylist() == [ + [[{"a": i + 2, "b": "a"}, {"a": i + 10, "b": "z"}] for i in range(32)] + [[]] + ] + + +@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 logical_set_storage + + validate = logical_set_storage._validate_scalar_column + sizes: list[int] = [] + + def record_size(storage: pa.LargeListArray[Any]) -> pa.LargeListArray[Any]: + sizes.append(len(storage.values)) + return validate(storage) + + 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)) + 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] + + +@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": []}] + ] + + +@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 + + 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) + + +@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]}] 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..863b41531 --- /dev/null +++ b/tests/test_semantic_types/test_arrow_schema_overrides.py @@ -0,0 +1,576 @@ +"""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, get_default_context +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) + + +@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 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}] + + +@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.""" + + 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.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") + ), + (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) + + +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(Schema({"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.""" + + omitted: int + 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 + 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.""" + # 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, + "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 + )