diff --git a/.zed/rules b/.zed/rules index 454407896..2e83b96b2 100644 --- a/.zed/rules +++ b/.zed/rules @@ -477,6 +477,12 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 only conversion, and Orcapod never calls it. - A declared class stores its own instances and subclasses (`UserClassLogicalType.accepts_instance`); only the declared class fields enter storage. Unrelated look-alike classes are refused. +- For 0.4.0, build a refusing Python-to-Arrow converter for native `set[T]` storage + when the element is a struct-stored user class (developer decision D47, ITL-922). + Use the converter's normal resolution and caching, including deferred types. + A logical type selected for the whole set owns its storage. + The refusal surfaces on a Python value write. Declarations and Arrow reads use + their existing paths. Direct writers to `list[T]`. ITL-1691 tracks canonical ordering. - The identity record (`logical_types/user_class_identity.py`) is `{kind, name, fields}` with JSON type tokens. The Arrow extension name is `name@` and the record is part of the extension metadata; together they are the logical type identifier. A nested diff --git a/CLAUDE.md b/CLAUDE.md index 91ffef8d2..644bbad41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -488,6 +488,12 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 only conversion, and Orcapod never calls it. - A declared class stores its own instances and subclasses (`UserClassLogicalType.accepts_instance`); only the declared class fields enter storage. Unrelated look-alike classes are refused. +- For 0.4.0, build a refusing Python-to-Arrow converter for native `set[T]` storage + when the element is a struct-stored user class (developer decision D47, ITL-922). + Use the converter's normal resolution and caching, including deferred types. + A logical type selected for the whole set owns its storage. + The refusal surfaces on a Python value write. Declarations and Arrow reads use + their existing paths. Direct writers to `list[T]`. ITL-1691 tracks canonical ordering. - The identity record (`logical_types/user_class_identity.py`) is `{kind, name, fields}` with JSON type tokens. The Arrow extension name is `name@` and the record is part of the extension metadata; together they are the logical type identifier. A nested diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md new file mode 100644 index 000000000..ebf88f1fd --- /dev/null +++ b/changelog.d/ITL-922.md @@ -0,0 +1,7 @@ +### Breaking changes and migration + +- Converting Python sets of struct-stored user classes to Orcapod's native set storage now + raises an error, including for nested sets. Use `list[T]` and supply the elements in the + order you want stored. Registered logical types for whole sets keep their own storage. + Annotations and reads of existing Arrow data continue to work. ITL-1691 tracks canonical + ordering for these sets. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 943874132..4f9c32463 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -285,6 +285,11 @@ output (ITL-1150). The same types are faithful as a column, inside a list, and a dataclass, an `orcapod.dataclass` or a pydantic model: hold such a value in a dataclass field, or declare the plain type (`dict[str, list[int]]`). +A pod definition can declare a set of user classes stored as structs. When the first +returned value is converted to native set storage, Orcapod 0.4.0 reports an +`OutputTypeError` for that output. Use `list[T]` to return these values, including inside +other types. + Outputs are validated against the declared storage schema immediately, and accepted numeric exceptions are normalized so downstream pods, hashes and stored rows see the same value. Eager validation never replaces a compatible user-class object; stored reads keep their diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index 33601e880..0bd59cb4e 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -172,6 +172,12 @@ that the element is a plain Arrow type, which a reader takes from the storage (`large_list`). A stored column whose storage is not a list of the element its name names is refused with `LogicalTypeIdentifierError`. +Orcapod 0.4.0 refuses native set conversion when the logical type for a set's user-class +elements stores them as Arrow structs. Use `list[T]` for these classes. Sets of primitives +and scalar-stored logical types such as `Path` and `UUID` are supported. A registered +logical type for the entire set defines its own storage. Existing Arrow data and saved +schemas can still be read. + ```python from orcapod.sources import DictSource diff --git a/docs/concepts/your-own-data-types.md b/docs/concepts/your-own-data-types.md index 1685122e3..cb4265b02 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -45,6 +45,16 @@ 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. +Orcapod 0.4.0 accepts annotations such as `set[T]` for user classes stored as Arrow +structs. The error occurs when Orcapod first converts a Python set to native set storage. +This applies to ordinary dataclasses, `op.dataclass` classes and pydantic models, +including sets nested in another type. Use `list[T]` and supply the items in the order +you want stored. Existing Arrow data can still be read. ITL-1691 tracks canonical +ordering for these sets. A registered logical type for the entire set defines its own +storage. A custom source's `from_config` follows the same rule when it +builds a source from fresh Python rows. If that conversion fails during a saved-job load, +the job logs a warning and leaves the source unbound. + ## `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-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md new file mode 100644 index 000000000..f31c51066 --- /dev/null +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -0,0 +1,22 @@ +## `src/orcapod/logical_types/list_logical_type_factory.py` — set storage order + +### SU1 — A set of struct-stored user classes needs a canonical order +**Status:** resolved +**Severity:** high +**Issue:** ITL-922 + +The stored order of a set of struct-stored user classes can follow the set's iteration +order, so equal sets can have different stored representations and row hashes. + +**Fix:** The native set converter checks the resolved Arrow destination after the +original encoder validates the elements. The converter caches the refusal decision for +resolved plans. A registered whole-set encoder owns its storage. Empty declarations +and Arrow reads keep their original behavior. For a cold or wrapped annotation that +fails eager resolution, a matching native Arrow destination and actual instances identify +the write to refuse. The refusal directs writers to `list[T]`. ITL-1691 tracks the +canonical storage order. + +With a cold converter and a matching explicit native Arrow schema, a required +`set[PlainPoint]` containing `PlainPoint(1)` and `None` raises +`UserClassSetNotStorableError` in place of the eager schema-resolution `ValueError` +(ITL-1754). diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index acba19b4c..9ba71342d 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -23,6 +23,9 @@ preserve a nested extension. Use the corresponding Orcapod container or class ty to keep the logical type: it stores its children in Arrow storage form within one top-level logical column. +Orcapod 0.4.0 refuses to convert Python sets of struct-stored user classes to native set +storage. Use `list[T]` for those classes. + What a cell says: - **kept**: read back exactly: the Arrow type with the name, nullability and metadata of diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 49826b24c..83c264394 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1114,6 +1114,10 @@ of affected inputs, and changing storage order would move row hashes and what a `set[T]` of a logical type (`set[Path]`, `set[UUID]`) is ordered by `ListLogicalType`, not by this rule. +Orcapod 0.4.0 refuses to convert Python `set[T]` values to native set storage when `T` is a +user class stored as a struct. Use `list[T]` and choose the element order before handing +the list to Orcapod. ITL-1691 tracks canonical storage ordering for those sets. + **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 identifier (extension name and metadata) with its stored values. So `{1, 2, 3}` as diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 286c6a0ea..0f960e8a7 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -48,6 +48,7 @@ PythonFunctionReturnCheckProtocol, ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.semantic_types.nested_storage import UserClassSetNotStorableError from orcapod.semantic_types.output_conformance import ( check_conformance, normalize_output_numbers, @@ -1190,13 +1191,15 @@ def _convert_outputs( failure.reason, failure.hint, ) from None - except Exception: + except Exception as failure: raise OutputTypeError( self.canonical_function_name, key, output_schema[key], value, - type(exc).__name__, + str(failure).removesuffix(".") + if isinstance(failure, UserClassSetNotStorableError) + else type(exc).__name__, ) from None raise diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 37ee98ba6..9496ca503 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -24,6 +24,10 @@ class NestedTypeNotStorableError(ValueError): """A logical type is declared where storage cannot keep it (ITL-1150).""" +class UserClassSetNotStorableError(NestedTypeNotStorableError): + """A set of struct-stored user classes has no canonical storage order (ITL-922).""" + + def require_storable_in_struct_field(arrow_type: pa.DataType) -> None: """Refuse a logical type or native container as a dict key or value or a tuple field. diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 3e56bc801..0260b8031 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -13,7 +13,11 @@ import pyarrow as pa -from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.semantic_types.nested_storage import UserClassSetNotStorableError +from orcapod.semantic_types.universal_converter import ( + UniversalTypeConverter, + _converter_for_arrow_field, +) class SemanticSchemaConverter: @@ -47,7 +51,8 @@ def __init__( 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(): + # Snapshot the caller's field plan before building converters. + for field_name, python_type in tuple(self.python_schema.items()): self._python_to_arrow_converters[field_name] = ( self.universal_converter.get_python_to_arrow_converter(python_type) ) @@ -72,20 +77,30 @@ 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]]: 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: converted_record[field_name] = None else: # Convert using the pre-computed converter - converted_record[field_name] = converter(value) + try: + converted_record[field_name] = converter(value) + except UserClassSetNotStorableError as exc: + raise UserClassSetNotStorableError( + f"Column {field_name!r}: {exc}" + ) from exc converted_data.append(converted_record) return converted_data @@ -140,10 +155,15 @@ 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 arrow_schema: + converters = { + name: _converter_for_arrow_field(converter, arrow_schema, name) + for name, converter in self._python_to_arrow_converters.items() + } + rows = self._convert_rows(data, converters) + else: + rows = self.python_dicts_to_struct_dicts(data) + return pa.Table.from_pylist(rows, schema=arrow_schema or self.arrow_schema) def arrow_table_to_python_dicts(self, table: pa.Table) -> list[dict[str, Any]]: """ diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 10914f456..42c2fe969 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -17,12 +17,15 @@ import types import typing from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, replace from datetime import date, datetime, timezone +from functools import cache # Handle generic types from typing import TYPE_CHECKING, Any, TypedDict, cast, get_args, get_origin import pyarrow as pa +from typing_extensions import TypeAliasType from orcapod.contexts import DataContext, resolve_context from orcapod.errors import ( @@ -47,11 +50,13 @@ ) from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, + UserClassSetNotStorableError, require_storable_in_struct_field, ) from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data from orcapod.types import DataType, Schema, SchemaLike from orcapod.utils import arrow_utils +from orcapod.utils.deferred_types import qualified_name if TYPE_CHECKING: from orcapod.hashing.semantic_hashing.type_handler_registry import ( @@ -176,6 +181,89 @@ def _is_optional_type(python_type: DataType) -> bool: return False +def _unwrapped_set_element(annotation: DataType) -> type | None: + """Find the concrete class behind a set element's transparent wrappers.""" + if get_origin(annotation) is not set or len(args := get_args(annotation)) != 1: + return None + + element = args[0] + seen: set[int] = set() + while not isinstance(element, type): + if id(element) in seen: + return None + seen.add(id(element)) + origin = get_origin(element) + if origin is typing.Annotated: + element = get_args(element)[0] + elif isinstance(element, typing.NewType): + element = element.__supertype__ + elif isinstance( + element, (TypeAliasType, getattr(typing, "TypeAliasType", TypeAliasType)) + ): + try: + element = element.__value__ + except NameError: + return None + elif origin in (typing.Union, types.UnionType): + args = get_args(element) + if len(args) != 2 or type(None) not in args: + return None + element = args[1] if args[0] is type(None) else args[0] + else: + return None + return element + + +def _has_struct_list_storage(arrow_type: pa.DataType) -> bool: + storage = ( + arrow_type.storage_type + if isinstance(arrow_type, pa.ExtensionType) + else arrow_type + ) + return isinstance(storage, (pa.ListType, pa.LargeListType)) and pa.types.is_struct( + cast(pa.DataType, storage.value_type) + ) + + +def _is_native_struct_set(arrow_type: pa.DataType) -> bool: + return ( + isinstance(arrow_type, pa.ExtensionType) + and arrow_type.extension_name.startswith("set[") + and _has_struct_list_storage(arrow_type) + ) + + +@dataclass(frozen=True) +class _NativeSetWriter: + """Keep the original encoder for destinations that store a different type.""" + + encode: Callable[[Any], Any] + refusal: Callable[[], str | None] + + def __call__(self, value: Any) -> Any: + encoded = self.encode(value) + if ( + isinstance(value, set) + and value + and (message := self.refusal()) is not None + and any(item is not None for item in encoded) + ): + raise UserClassSetNotStorableError(message) from None + return encoded + + +def _converter_for_arrow_field( + converter: Callable[[Any], Any], schema: pa.Schema, name: str +) -> Callable[[Any], Any]: + """Select the native set guard using the destination, preserving the Python plan.""" + if isinstance(converter, _NativeSetWriter) and ( + schema.get_field_index(name) < 0 + or not _is_native_struct_set(schema.field(name).type) + ): + return converter.encode + return converter + + def storable_instant(value: object, timezone_policy: str) -> datetime: """Return ``value`` as a ``datetime`` column holds it, or refuse it (ITL-1268). @@ -1283,6 +1371,8 @@ def python_dicts_to_struct_dicts( self, python_dicts: list[dict[str, Any]], python_schema: SchemaLike | None = None, + *, + _explicit_arrow_schema: pa.Schema | None = None, ) -> list[dict[str, Any]]: """ Convert a list of Python dictionaries to Arrow compatible list of structural dicts. @@ -1293,10 +1383,50 @@ def python_dicts_to_struct_dicts( python_schema = infer_python_schema_from_pylist_data(python_dicts) # prepare a LUT of converters from Python to Arrow-compatible data type - converters = { - field_name: self.get_python_to_arrow_converter(python_type) - for field_name, python_type in python_schema.items() - } + converters = {} + for field_name, python_type in python_schema.items(): + try: + converter = self.get_python_to_arrow_converter(python_type) + except ValueError: + # A supplied schema can identify native set storage when normal + # resolution rejects an unregistered or wrapped annotation. + if ( + self._logical_type_registry is None + or _explicit_arrow_schema is None + or get_origin(python_type) is not set + ): + raise + if _explicit_arrow_schema.get_field_index( + field_name + ) < 0 or not _is_native_struct_set( + arrow_type := _explicit_arrow_schema.field(field_name).type + ): + raise + for record in python_dicts: + value = record.get(field_name) + if isinstance(value, set) and any( + item is not None for item in value + ): + element = _unwrapped_set_element(python_type) + if element is None or any( + item is not None and not isinstance(item, element) + for item in value + ): + break + writer = self._native_set_writer( + python_type, arrow_type, lambda item: item + ) + try: + _ = writer(value) + except UserClassSetNotStorableError as exc: + raise with_context(f"Column {field_name!r}", exc) from exc + break + raise + if _explicit_arrow_schema is not None: + converter = _converter_for_arrow_field( + converter, _explicit_arrow_schema, field_name + ) + converters[field_name] = converter converted_data = [] for record in python_dicts: @@ -1310,6 +1440,8 @@ def python_dicts_to_struct_dicts( raise CanonicalOrderError( f"Column {field_name!r}: {exc}" ) from exc + except UserClassSetNotStorableError as exc: + raise with_context(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( @@ -1381,7 +1513,9 @@ def python_dicts_to_arrow_table( Returns: A PyArrow ``Table`` containing the converted data. """ + explicit_arrow_schema = None if python_schema is not None and arrow_schema is not None: + explicit_arrow_schema = arrow_schema logger.warning( "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." ) @@ -1407,7 +1541,9 @@ def python_dicts_to_arrow_table( python_schema = self.arrow_schema_to_python_schema(arrow_schema) struct_dicts = self.python_dicts_to_struct_dicts( - python_dicts, python_schema=python_schema + python_dicts, + python_schema=python_schema, + _explicit_arrow_schema=explicit_arrow_schema, ) # TODO: add more helpful message here @@ -1857,6 +1993,42 @@ def _generate_unique_type_name(self, field_specs: Mapping[str, DataType]) -> str self._created_type_names.add(base_name) return base_name + @staticmethod + def _check_set_write(python_type: DataType, arrow_type: pa.DataType) -> str | None: + """Return the write refusal for a native set over a user struct.""" + from orcapod.logical_types.user_class_identity import class_kind, class_name + + element = _unwrapped_set_element(python_type) + if element is None or class_kind(element) is None: + return None + + if isinstance(arrow_type, pa.ExtensionType) and not ( + # An explicit schema is the evidence for storage when the Python + # annotation cannot be resolved. Require its native class-set identity. + arrow_type.extension_name.startswith(f"set[{class_name(element)}@") + ): + return None + return ( + f"a set of {qualified_name(element)} values cannot be stored in this " + f"version; use list[{element.__name__}]." + ) + + def _native_set_writer( + self, + python_type: DataType, + arrow_type: pa.DataType, + encode: Callable[[Any], Any], + ) -> Callable[[Any], Any]: + """Keep the original encoder and check class sets at write time.""" + if not _has_struct_list_storage(arrow_type): + return encode + + @cache + def refusal() -> str | None: + return self._check_set_write(python_type, arrow_type) + + return _NativeSetWriter(encode, refusal) + def _create_python_to_arrow_converter( self, python_type: DataType ) -> Callable[[Any], Any]: @@ -1879,11 +2051,21 @@ def convert_logical(value: Any) -> Any: raise _none_not_admitted(python_type) return _lt.python_to_storage(value, _self) + if get_origin(python_type) is set: + from orcapod.logical_types.list_logical_type_factory import ( + ListLogicalType, + ) + + if type(lt) is ListLogicalType: + return self._native_set_writer( + python_type, lt._storage_type, convert_logical + ) + return convert_logical # Get the Arrow type for this Python type # TODO: check if this step is necessary - _ = self.python_type_to_arrow_type(python_type) + arrow_type = self.python_type_to_arrow_type(python_type) # Create conversion function based on type @@ -1958,7 +2140,12 @@ def convert_set(value: Any) -> list[Any]: raise _none_not_admitted(python_type) return sort_set_elements([element_converter(item) for item in value]) - return convert_set + storage_type = ( + arrow_type.storage_type + if isinstance(arrow_type, pa.ExtensionType) + else arrow_type + ) + return self._native_set_writer(python_type, storage_type, convert_set) elif origin is tuple: if len(set(args)) == 1: @@ -1978,9 +2165,18 @@ def convert_set(value: Any) -> list[Any]: if len(non_none_types) == 1: # Optional[T] - use converter for T, pass through None inner_converter = self.get_python_to_arrow_converter(non_none_types[0]) - return lambda value: ( - inner_converter(value) if value is not None else None + encode = ( + inner_converter.encode + if isinstance(inner_converter, _NativeSetWriter) + else inner_converter ) + + def convert_optional(value: Any) -> Any: + return encode(value) if value is not None else None + + if isinstance(inner_converter, _NativeSetWriter): + return replace(inner_converter, encode=convert_optional) + return convert_optional else: raise ValueError( f"Complex unions with multiple non-None types are not supported: {python_type}. " diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py index 1529249ec..45256d66d 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -59,7 +59,7 @@ from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.operators import SelectDataColumns from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from orcapod.types import CacheMode, Cursor, PollingConfig +from orcapod.types import CacheMode, Cursor, PollingConfig, Schema from orcapod.utils.arrow_utils import normalize_extension_columns from tests.test_databases import fake_spiral_sdk @@ -370,11 +370,10 @@ class Measurements: ("annotation", "events"), [ (list[Measurement], _MEASUREMENTS), - (set[Measurement], set(_MEASUREMENTS)), (list[list[Measurement]], [_MEASUREMENTS]), (Measurements, Measurements(_MEASUREMENTS)), ], - ids=["list", "set", "nested", "field"], + ids=["list", "nested", "field"], ) def test_native_containers_keep_key_value_dataclasses( annotation: Any, events: Any @@ -388,6 +387,26 @@ def test_native_containers_keep_key_value_dataclasses( assert next(source.iter_data())[1].as_dict()["d"] == events +def test_existing_set_storage_keeps_key_value_dataclasses() -> None: + # ITL-922 refuses new Python writes of this set. Build its legacy Arrow + # storage directly so the duplicate-key check still exercises the read. + converter = get_default_context().type_converter + declared = Schema({"a": str, "d": set[Measurement]}) + converter.ensure_types_registered_for_schemas(declared) + schema = converter.python_schema_to_arrow_schema(declared) + table = pa.Table.from_pylist( + [ + { + "a": "batch", + "d": [{"key": m.key, "value": m.value} for m in _MEASUREMENTS], + } + ], + schema=schema, + ) + source = ArrowTableSource(table, tag_columns=["a"], tag_only_columns=True) + assert next(source.iter_data())[1].as_dict()["d"] == set(_MEASUREMENTS) + + @dataclass class OrderedSamples: entries: list[dict[str, Any]] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ef47aba82..93ed6ae66 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1070,6 +1070,9 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: to keep the logical type: it stores its children in Arrow storage form within one top-level logical column. +Orcapod 0.4.0 refuses to convert Python sets of struct-stored user classes to native set +storage. Use `list[T]` for those classes. + What a cell says: - **kept**: read back exactly: the Arrow type with the name, nullability and metadata of diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py new file mode 100644 index 000000000..64fbc8abc --- /dev/null +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -0,0 +1,1116 @@ +"""Test the Python-to-Arrow refusal and the existing read paths (ITL-922).""" + +from __future__ import annotations + +import json +import subprocess +import sys +import typing +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from importlib.resources import files +from pathlib import Path +from textwrap import dedent +from types import UnionType +from typing import Annotated, Any, NewType, Optional, cast +from re import escape + +import polars as pl +import pydantic +import pyarrow as pa +import pytest +from unittest.mock import patch + +from typing_extensions import TypeAliasType, override + +import orcapod as op +from orcapod.contexts import create_registry, get_default_context +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.datagrams import Data, Tag +from orcapod.core.datagrams.datagram import Datagram +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import OutputTypeError, RowFailuresWarning, UnsupportedValueError +from orcapod.logical_types.dataclass_logical_type_factory import ( + DataclassLogicalTypeFactory, +) +from orcapod.logical_types.identifier import version_metadata +from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.logical_types.registry import ( + LogicalTypeRegistry, + make_arrow_extension_type, + make_polars_extension_type, +) +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.pipeline.serialization import SOURCE_REGISTRY, resolve_source_from_config +from orcapod.semantic_types.nested_none import NestedNoneNotRestorableError +from orcapod.semantic_types.nested_storage import ( + NestedTypeNotStorableError, + UserClassSetNotStorableError, +) +from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.sources import DataFrameSource, DictSource, ListSource, PollingSource +from orcapod.types import DataValue, Schema +from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data + +_METADATA = "private-annotation-sentinel-itl922" + + +@op.dataclass(frozen=True) +class Point: + x: int + + +NamedPoint = NewType("NamedPoint", Point) +PointAlias = TypeAliasType("PointAlias", Point) +NativePointAlias = getattr(typing, "TypeAliasType", TypeAliasType)( + "NativePointAlias", Point +) +NamedPointAlias = TypeAliasType("NamedPointAlias", NamedPoint) + + +@dataclass +class PointSet: + points: set[Point] + + +@dataclass(frozen=True) +class PlainPoint: + x: int + + +@typing.final +class PackedPoints(BaseLogicalType): + """A registered encoding for the complete set of points.""" + + logical_type_name = "test.itl922.packed_points" + python_type = set[PlainPoint] + _storage = pa.large_list(pa.int64()) + _metadata = version_metadata(1, "stored") + _extension = make_arrow_extension_type(logical_type_name, _storage, _metadata) + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + return cast("Callable[[], pa.ExtensionType]", self._extension)() + + def get_polars_extension_type(self) -> pl.BaseExtension: + factory = cast( + "Callable[[], pl.BaseExtension]", + make_polars_extension_type( + self.logical_type_name, self._storage, self._metadata.decode() + ), + ) + return factory() + + def python_to_storage( + self, value: set[PlainPoint], converter: TypeConverterProtocol | None = None + ) -> list[int]: + return sorted(point.x for point in value) + + def storage_to_python( + self, storage_value: list[int], converter: TypeConverterProtocol | None = None + ) -> set[PlainPoint]: + return {PlainPoint(x) for x in storage_value} + + +def test_registered_whole_set_encoder_round_trips() -> None: + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(PackedPoints()) + arrow_schema = converter.python_schema_to_arrow_schema({"points": set[PlainPoint]}) + rows = [{"points": {PlainPoint(2), PlainPoint(1)}}] + + table = converter.python_dicts_to_arrow_table(rows, arrow_schema=arrow_schema) + database = InMemoryArrowDatabase() + database.add_record(("points",), b"row", table, flush=True) + records = database.get_all_records(("points",)) + assert records is not None + saved = records.select(["points"]) + + assert saved.to_pylist() == [{"points": [1, 2]}] + assert converter.arrow_table_to_python_dicts(saved) == rows + assert converter.get_logical_type(PlainPoint) is None + + +class LegacyPoll: + """Write an Arrow declaration and restore the equivalent legacy Python one.""" + + def __init__(self, arrow_schema: pa.Schema | None = None) -> None: + self.arrow_schema = arrow_schema + + def identity(self) -> str: + return "legacy poll" + + def schema(self) -> pa.Schema | Schema: + if self.arrow_schema is not None: + return self.arrow_schema + return Schema({"id": int, "points": set[Point]}) + + def to_config(self) -> None: + return None + + @classmethod + def from_config(cls, config: dict[str, Any]) -> LegacyPoll: + return cls() + + async def poll(self, cursor=None) -> bool: + return False + + async def fetch(self, cursor=None): + raise AssertionError("Restoring the declaration must not fetch data") + + async def close(self) -> None: + pass + + +@contextmanager +def guard_calls() -> Iterator[list[Any]]: + """Record the actual refusal predicate, including unsuccessful checks.""" + calls: list[Any] = [] + check = UniversalTypeConverter._check_set_write + + def record(annotation: Any, arrow_type: pa.DataType) -> str | None: + calls.append(annotation) + return check(annotation, arrow_type) + + with patch.object(UniversalTypeConverter, "_check_set_write", staticmethod(record)): + yield calls + + +@dataclass(frozen=True) +class Word: + text: str + + +class WordType(BaseLogicalType): + """A dataclass stored as a scalar by a registered factory.""" + + logical_type_name = "test.itl922.word" + python_type = Word + _extension = make_arrow_extension_type( + logical_type_name, pa.large_string(), version_metadata(1, "stored") + ) + + def get_arrow_extension_type(self) -> pa.ExtensionType: + return self._extension() # pyright: ignore[reportCallIssue] # generated without arguments + + def get_polars_extension_type(self) -> pl.BaseExtension: + factory = cast( + "Callable[[], pl.BaseExtension]", + make_polars_extension_type(self.logical_type_name, pa.large_string(), "{}"), + ) + return factory() + + def python_to_storage( + self, value: Word, converter: TypeConverterProtocol | None = None + ) -> str: + return value.text + + def storage_to_python( + self, storage_value: str, converter: TypeConverterProtocol | None = None + ) -> Word: + return Word(storage_value) + + +class WordFactory: + def supports_class(self, python_type: type) -> bool: + return python_type is Word + + def create_for_python_type( + self, python_type: type, converter: TypeConverterProtocol + ) -> WordType: + return WordType() + + def reconstruct_from_arrow( + self, + arrow_extension_name: str, + storage_type: pa.DataType, + metadata: dict[str, Any], + converter: TypeConverterProtocol, + ) -> WordType: + return WordType() + + +def test_a_lazily_registered_scalar_dataclass_is_accepted() -> None: + context = create_registry().get_context() + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + factory = WordFactory() + converter.register_logical_type_factory(factory, python_bases=[Word]) + assert converter.get_logical_type(Word) is None + rows = [cast("dict[str, DataValue]", {"words": {Word("a"), Word("z")}})] + with patch.object( + factory, "create_for_python_type", wraps=factory.create_for_python_type + ) as create: + source = DictSource( + rows, data_schema={"words": set[Word]}, data_context=context + ) + assert converter.arrow_table_to_python_dicts(source.as_table()) == rows + create.assert_called_once() + + +@typing.final +class LazyPointType(BaseLogicalType): + """A struct encoding supplied by a deferred registration.""" + + logical_type_name = "test.itl922.lazy_point" + python_type = PlainPoint + _storage = pa.struct([pa.field("x", pa.int64())]) + _metadata = version_metadata(1, "stored") + _extension = make_arrow_extension_type(logical_type_name, _storage, _metadata) + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + return cast("Callable[[], pa.ExtensionType]", self._extension)() + + def get_polars_extension_type(self) -> pl.BaseExtension: + factory = cast( + "Callable[[], pl.BaseExtension]", + make_polars_extension_type( + self.logical_type_name, self._storage, self._metadata.decode() + ), + ) + return factory() + + def python_to_storage( + self, value: PlainPoint, converter: TypeConverterProtocol | None = None + ) -> dict[str, int]: + return {"x": value.x} + + def storage_to_python( + self, + storage_value: dict[str, int], + converter: TypeConverterProtocol | None = None, + ) -> PlainPoint: + return PlainPoint(storage_value["x"]) + + +@pytest.mark.parametrize("registration", ["deferred", "context", "warm"]) +def test_struct_set_write_uses_resolved_deferred_type( + registration: str, tmp_path: Path +) -> None: + entry = { + "python_type": f"{PlainPoint.__module__}.{PlainPoint.__qualname__}", + "extension_name": LazyPointType.logical_type_name, + "logical_type": f"{LazyPointType.__module__}.{LazyPointType.__qualname__}", + "requires": "pyarrow", + } + if registration == "context": + config = json.loads( + files("orcapod.contexts").joinpath("logical_types.json").read_text() + ) + config["logical_type_registry"]["_config"]["deferred_logical_types"].append( + entry + ) + path = tmp_path / "logical_types.json" + _ = path.write_text(json.dumps(config)) + converter = ( + create_registry(logical_types_file=str(path)).get_context().type_converter + ) + else: + converter = UniversalTypeConverter( + logical_type_registry=LogicalTypeRegistry(deferred_logical_types=[entry]) + ) + assert isinstance(converter, UniversalTypeConverter) + + schema = Schema({"points": set[PlainPoint]}) + schema_converter = UniversalTypeConverter( + logical_type_registry=LogicalTypeRegistry(logical_types=[LazyPointType()]) + ) + schema_converter.ensure_types_registered_for_schemas(schema) + arrow_schema = schema_converter.python_schema_to_arrow_schema(schema) + + with patch.object( + LazyPointType, "__init__", autospec=True, return_value=None + ) as load: + if registration == "warm": + converter.ensure_types_registered_for_schemas(schema) + load.assert_called_once() + else: + load.assert_not_called() + with guard_calls() as calls: + for _ in range(2): + with pytest.raises( + UserClassSetNotStorableError, + match=r"Column 'points'.*use list\[PlainPoint\]", + ): + _ = converter.python_dicts_to_arrow_table( + [{"points": {PlainPoint(0)}}], schema, arrow_schema + ) + load.assert_called_once() + assert calls == [set[PlainPoint]] + + +def test_a_cold_struct_factory_registered_by_python_base_is_refused() -> None: + context = create_registry().get_context() + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + factory = DataclassLogicalTypeFactory() + converter.register_logical_type_factory(factory, python_bases=[PlainPoint]) + assert converter.get_logical_type(PlainPoint) is None + with patch.object( + factory, "create_for_python_type", wraps=factory.create_for_python_type + ) as create: + with pytest.raises( + UserClassSetNotStorableError, match=r"use list\[PlainPoint\]" + ): + _ = converter.python_dicts_to_arrow_table( + [{"points": {PlainPoint(0)}}], {"points": set[PlainPoint]} + ) + create.assert_called_once() + + +class ModelPoint(pydantic.BaseModel, frozen=True): + x: int + + +@op.function_pod(output_keys="points") +def points_sync(x: int) -> set[Point]: + return {Point(x)} + + +@op.function_pod(output_keys="points") +async def points_async(x: int) -> set[Point]: + return {Point(x)} + + +@pytest.mark.parametrize("value", [Point(1), PlainPoint(1), ModelPoint(x=1)]) +def test_dict_source_refuses_each_struct_stored_class_kind(value: Any) -> None: + with pytest.raises( + NestedTypeNotStorableError, + match=r"cannot be stored in this version; use list\[", + ): + DictSource([{"points": {value}}]) + + +@pytest.mark.parametrize( + ("element", "values"), + [ + (Point, {Point(1)}), + (Point | None, {Point(1), None}), + (Optional[Point], {Point(1)}), + (NamedPoint, {Point(1)}), + (Annotated[Point, _METADATA], {Point(1)}), + (PointAlias, {Point(1)}), + (NativePointAlias, {Point(1)}), + (Annotated[PointAlias | None, _METADATA], {Point(1), None}), + (Annotated[NamedPointAlias | None, _METADATA], {Point(1)}), + ], +) +@pytest.mark.parametrize( + ("nested", "warm"), [(False, False), (False, True), (True, True)] +) +def test_converter_refuses_wrapped_user_class_set_elements( + element: Any, values: Any, nested: bool, warm: bool +) -> None: + annotation = list[set[element]] if nested else set[element] + value = [values] if nested else values + # Provide the compatible Arrow schema so every wrapper reaches the builder, + # including annotations the Python schema registration does not accept. + plain = list[set[Point]] if nested else set[Point] + declared = Schema({"points": plain}) + schema_converter = create_registry().get_context().type_converter + schema_converter.ensure_types_registered_for_schemas(declared) + arrow_schema = schema_converter.python_schema_to_arrow_schema(declared) + converter = ( + schema_converter if warm else create_registry().get_context().type_converter + ) + origin = typing.get_origin(element) + with guard_calls() as calls: + if nested and element is not Point and origin not in (typing.Union, UnionType): + # The outer list derives its storage type before building the child + # converter, so this path still reports the existing schema error. + with pytest.raises(ValueError, match="Unsupported"): + converter.python_dicts_to_arrow_table( + [{"points": value}], {"points": annotation}, arrow_schema + ) + assert calls == [] + return + for _ in range(2): + with pytest.raises( + UserClassSetNotStorableError, + match=r"Column 'points'.*use list\[Point\]", + ) as error: + converter.python_dicts_to_arrow_table( + [{"points": value}], {"points": annotation}, arrow_schema + ) + assert str(error.value.__cause__) == ( + f"a set of {Point.__module__}.Point values cannot be stored in this " + "version; use list[Point]." + ) + assert _METADATA not in str(error.value) + # Valid plans cache their decision. Failed plans are retried without caching + # a fallback that could suppress validation on a later non-write request. + assert calls in ([set[element]], [set[element], set[element]]) + + +@pytest.mark.parametrize("element", [Point, int, Word]) +def test_wrapped_set_annotations_preserve_schema_errors_and_registry( + element: type, +) -> None: + context = create_registry().get_context() + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type_factory(WordFactory(), python_bases=[Word]) + annotation = set[Annotated[element, "metadata"]] + before = converter.registered_logical_type_names() + with ( + guard_calls() as calls, + pytest.raises(ValueError, match="Unsupported annotation"), + ): + DictSource([], data_schema={"points": annotation}, data_context=context) + assert calls == [] + assert converter.registered_logical_type_names() == before + + value: Any = ( + {Point(1)} if element is Point else {1} if element is int else {Word("a")} + ) + with ( + guard_calls() as calls, + pytest.raises(ValueError, match="Unsupported annotation"), + ): + DictSource( + [{"points": value}], + data_schema={"points": annotation}, + data_context=context, + ) + assert calls == [] + assert converter.registered_logical_type_names() == before + + +def test_other_python_sources_refuse_the_conversion() -> None: + values = cast("list[DataValue]", [{Point(1)}]) + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): + ListSource("points", values) + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): + DataFrameSource(pl.DataFrame({"points": pl.Series(values, dtype=pl.Object)})) + + +@pytest.mark.parametrize("row_type", [Data, Datagram]) +def test_python_rows_refuse_table_conversion_and_hashing(row_type: Any) -> None: + values = {"points": {Point(1)}} + with guard_calls() as calls: + row = row_type(values, python_schema={"points": set[Point]}) + assert row.as_dict() == values + assert calls == [] + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): + row.as_table() + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): + row.content_hash() + + +@pytest.mark.parametrize( + ("annotation", "value"), + [ + (list[set[Point]], [{Point(1)}]), + (list[set[Point | None]], [{Point(1), None}]), + (set[Point] | None, {Point(1)}), + (PointSet, PointSet({Point(1)})), + ], +) +def test_nested_sets_refused_at_the_same_conversion_boundary( + annotation: Any, value: Any +) -> None: + converter = create_registry().get_context().type_converter + with guard_calls() as calls: + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): + converter.python_dicts_to_arrow_table([{"v": value}], {"v": annotation}) + assert len(calls) == 1 + + +def test_dict_values_follow_the_existing_nested_storage_rule() -> None: + converter = get_default_context().type_converter + with pytest.raises(NestedTypeNotStorableError, match="ITL-1150"): + converter.python_dicts_to_arrow_table( + [{"v": {"a": {Point(1)}}}], {"v": dict[str, set[Point]]} + ) + + +def test_sync_function_pod_output_includes_the_migration_hint() -> None: + source = DictSource([{"x": 1}]) + with pytest.raises(OutputTypeError, match=r"output 'points'.*use list\[Point\]"): + list(points_sync.pod(source).iter_data()) + + +@pytest.mark.asyncio +async def test_async_function_pod_output_includes_the_migration_hint() -> None: + source = DictSource([{"x": 1}]) + with pytest.raises(OutputTypeError, match=r"output 'points'.*use list\[Point\]"): + _ = [row async for row in points_async.pod(source).async_iter_data()] + + +def test_a_failed_job_checks_the_set_once_and_writes_no_tables() -> None: + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.clear_cache() + database = InMemoryArrowDatabase() + job = op.PipelineJob(name="refused", database=database) + with job: + points_sync.pod(DictSource([{"x": x} for x in range(20)]), label="points") + with guard_calls() as calls, pytest.warns(RowFailuresWarning, match="20 rows"): + job.run() + assert calls == [set[Point]] + assert list(database.list_table_paths(())) == [] + + +def _legacy_table() -> pa.Table: + """Build the Arrow storage that older Orcapod versions wrote.""" + converter = get_default_context().type_converter + schema = converter.python_schema_to_arrow_schema(Schema({"points": set[Point]})) + return pa.Table.from_pylist([{"points": [{"x": 1}]}], schema=schema) + + +class CustomEmptySource(DictSource): + SOURCE_KIND = "test_itl922_empty" + + @classmethod + def from_config( + cls, config: dict[str, Any], db_registry: Any = None + ) -> CustomEmptySource: + return cls( + [], + data_schema={"points": set[Point]}, + source_id=config["source_name"], + ) + + +class CustomRebuiltSource(DictSource): + SOURCE_KIND = "test_itl922_rebuilt" + + @classmethod + def from_config( + cls, config: dict[str, Any], db_registry: Any = None + ) -> CustomRebuiltSource: + return cls( + [{"points": cast(DataValue, [{Point(1)}])}], + data_schema={"points": list[set[Point]]}, + source_id=config["source_name"], + ) + + +def test_precomputed_write_retains_schema_after_caller_mutation() -> None: + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema = {"x": int} + precomputed = SemanticSchemaConverter(converter, python_schema=schema) + schema.clear() + + assert precomputed.python_dicts_to_arrow_table([{"x": 1}]).to_pylist() == [{"x": 1}] + + +@typing.final +class ReverseIntSet(BaseLogicalType): + """An alternate encoder for the complete primitive set.""" + + logical_type_name = "test.itl922.reverse_int_set" + python_type = set[int] + _storage = pa.large_list(pa.int64()) + _metadata = version_metadata(1, "stored") + _extension = make_arrow_extension_type(logical_type_name, _storage, _metadata) + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + return cast("Callable[[], pa.ExtensionType]", self._extension)() + + def get_polars_extension_type(self) -> pl.BaseExtension: + factory = cast( + "Callable[[], pl.BaseExtension]", + make_polars_extension_type( + self.logical_type_name, self._storage, self._metadata.decode() + ), + ) + return factory() + + def python_to_storage( + self, value: set[int], converter: TypeConverterProtocol | None = None + ) -> list[int]: + return sorted(value, reverse=True) + + def storage_to_python( + self, storage_value: list[int], converter: TypeConverterProtocol | None = None + ) -> set[int]: + return set(storage_value) + + +def test_precomputed_set_keeps_the_encoder_after_public_registration() -> None: + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + precomputed = SemanticSchemaConverter(converter, python_schema={"x": set[int]}) + + converter.register_logical_type(ReverseIntSet()) + table = precomputed.python_dicts_to_arrow_table([{"x": {1, 2, 3}}]) + + assert table.schema.equals(precomputed.arrow_schema, check_metadata=True) + assert table.to_pylist() == [{"x": [1, 2, 3]}] + assert precomputed.arrow_table_to_python_dicts(table) == [{"x": {1, 2, 3}}] + + +def test_zero_width_lists_keep_the_original_converter_validation() -> None: + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + array = pa.array([[]], type=pa.list_(pa.int64(), 0)) + table = pa.Table.from_arrays([array], names=["x"]) + table.validate(full=True) + + with pytest.raises(ValueError, match="^Empty tuple type not supported$"): + SemanticSchemaConverter(converter, arrow_schema=table.schema) + with pytest.raises(ValueError, match="^Empty tuple type not supported$"): + converter.python_dicts_to_arrow_table([], arrow_schema=table.schema) + + +@pytest.mark.parametrize( + ("element", "message"), + [ + (PlainPoint, f"Unsupported Python type: {PlainPoint}."), + ( + Annotated[PlainPoint, _METADATA], + f"Unsupported generic type: {Annotated}", + ), + (PlainPoint | None, f"Unsupported Python type: {PlainPoint}."), + ], +) +def test_empty_table_with_both_schemas_retains_eager_validation( + element: Any, message: str +) -> None: + maker = create_registry().get_context().type_converter + declared = Schema({"points": set[PlainPoint]}) + maker.ensure_types_registered_for_schemas(declared) + arrow_schema = maker.python_schema_to_arrow_schema(declared) + + converter = create_registry().get_context().type_converter + with pytest.raises(ValueError, match=f"^{escape(message)}$"): + _ = converter.python_dicts_to_arrow_table( + [], {"points": set[element]}, arrow_schema + ) + + +_SET_WRITE_CASES = [ + pytest.param({PlainPoint(3)}, id="instances"), + pytest.param({1, 2}, id="wrong-class"), + pytest.param({None}, id="only-null"), + pytest.param(set(), id="empty"), + pytest.param(None, id="null"), +] +_NONE_DIAGNOSTIC = ( + ", which does not admit None (it would be stored as an empty container or a wrong " + "value). Give a value of that type, or declare the column's own type '| None' " + "if a missing value is meant." +) + + +@pytest.mark.parametrize("api", ["universal", "precomputed", "source"]) +@pytest.mark.parametrize("destination", ["set", "list", "plain", "omitted"]) +@pytest.mark.parametrize("optional", [False, True], ids=["required", "optional"]) +@pytest.mark.parametrize("value", _SET_WRITE_CASES) +def test_set_write_validates_elements_and_uses_the_actual_destination( + api: str, destination: str, optional: bool, value: Any +) -> None: + """Match main's storage and diagnostics except on a valid native class-set write.""" + context = create_registry().get_context() + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + python_schema: dict[str, Any] = { + "id": int, + "points": set[PlainPoint] | None if optional else set[PlainPoint], + } + converter.ensure_types_registered_for_schemas( + Schema(python_schema), Schema({"points": list[PlainPoint]}) + ) + schema = converter.python_schema_to_arrow_schema(python_schema) + field = schema.field("points") + if destination == "list": + field = field.with_type(converter.python_type_to_arrow_type(list[PlainPoint])) + elif destination == "plain": + field = field.with_type(pa.large_list(pa.struct([("x", pa.int64())]))) + arrow_schema = pa.schema( + [schema.field("id")] + ([field] if destination != "omitted" else []) + ) + rows: list[dict[str, Any]] = [{"id": 5, "points": value}] + + def write() -> tuple[pa.Table, list[dict[str, Any]]]: + if api == "universal": + table = converter.python_dicts_to_arrow_table( + rows, python_schema, arrow_schema + ) + elif api == "precomputed": + writer = SemanticSchemaConverter(converter, python_schema=python_schema) + table = writer.python_dicts_to_arrow_table(rows, arrow_schema) + else: + table = ( + DictSource( + rows, + data_schema=python_schema if destination == "set" else arrow_schema, + data_context=context, + source_id="review", + ) + .as_table() + .select(arrow_schema.names) + ) + table.validate(full=True) + return table, converter.arrow_table_to_python_dicts(table) + + error: type[Exception] | None = None + message = "" + if api == "source" and destination == "omitted": + pass + elif api == "source" and destination == "plain" and value == {None}: + error = NestedNoneNotRestorableError + message = ( + "Column 'points': a stored None inside a container, at a position of " + "Arrow type struct, cannot be read back faithfully yet (it would " + "read as an empty value or fail). Remove the None before the value is put " + "in a container (e.g. DropNulls on the column before GroupBy or Batch), " + "or hold the value in a dataclass. Follow-up: ITL-1144." + ) + elif ( + api == "source" + and destination == "plain" + and value in ({PlainPoint(3)}, {1, 2}) + ): + error = pa.ArrowTypeError + item = ( + "PlainPoint(x=3) with type PlainPoint" + if value == {PlainPoint(3)} + else "1 with type int" + ) + message = ( + f"Could not convert {item}: was not a dict, tuple, or recognized null " + "value for conversion to struct type" + ) + elif value == {1, 2}: + error = TypeError + message = ( + f"Cannot store a value of class builtins.int as {PlainPoint.__module__}.PlainPoint: " + "an ordinary dataclass or pydantic model is stored only from instances of " + "that class or a subclass. Build an instance of the class, or annotate " + "the value with its own class." + ) + elif value == {None}: + error = UnsupportedValueError + prefix = "" if api == "precomputed" else "Column 'points': " + message = ( + f"{prefix}a None is given where {PlainPoint} is declared{_NONE_DIAGNOSTIC}" + ) + elif value is None and not optional and api != "precomputed": + error = UnsupportedValueError + declared = f"set[{PlainPoint.__module__}.PlainPoint]" + if api == "source" and destination == "list": + declared = f"list[{PlainPoint.__module__}.PlainPoint]" + elif api == "source" and destination == "plain": + declared = "list[orcapod.semantic_types.universal_converter.Struct_x_int]" + message = f"Column 'points': a None is given where {declared} is declared{_NONE_DIAGNOSTIC}" + elif destination == "set" and value == {PlainPoint(3)}: + error = UserClassSetNotStorableError + message = ( + f"Column 'points': a set of {PlainPoint.__module__}.PlainPoint values cannot " + "be stored in this version; use list[PlainPoint]." + ) + + if error is not None: + with pytest.raises(error) as caught: + _ = write() + assert type(caught.value) is error + assert str(caught.value) == message + return + + table, decoded = write() + assert table.schema.equals(arrow_schema, check_metadata=True) + expected: dict[str, Any] = {"id": 5} + if destination != "omitted": + expected["points"] = None if value is None else [{"x": 3}] if value else [] + assert table.to_pylist() == [expected] + if destination == "set": + expected["points"] = value + elif destination == "list" and value is not None: + expected["points"] = list(value) + assert decoded == [expected] + + +def test_required_set_null_keeps_the_existing_error() -> None: + converter = create_registry().get_context().type_converter + with pytest.raises(UnsupportedValueError) as error: + _ = converter.python_dicts_to_arrow_table( + [{"points": None}], {"points": set[Point]} + ) + assert str(error.value) == ( + f"Column 'points': a None is given where set[{Point.__module__}.Point] is declared, " + "which does not admit None (it would be stored as an empty container or a wrong " + "value). Give a value of that type, or declare the column's own type '| None' " + "if a missing value is meant." + ) + + +@pytest.mark.parametrize("value", [{1, 2}, {None}, set()]) +@pytest.mark.parametrize("wrapped", [False, True]) +def test_unresolved_set_plan_keeps_its_error_without_valid_instances( + value: set[Any], wrapped: bool +) -> None: + maker = create_registry().get_context().type_converter + declared = Schema({"points": set[PlainPoint]}) + maker.ensure_types_registered_for_schemas(declared) + arrow_schema = maker.python_schema_to_arrow_schema(declared) + converter = create_registry().get_context().type_converter + element = Annotated[PlainPoint, _METADATA] if wrapped else PlainPoint + message = ( + f"Unsupported generic type: {Annotated}" + if wrapped + else f"Unsupported Python type: {PlainPoint}." + ) + + with guard_calls() as calls, pytest.raises(ValueError) as caught: + _ = converter.python_dicts_to_arrow_table( + [{"points": value}], {"points": set[element]}, arrow_schema + ) + assert type(caught.value) is ValueError + assert str(caught.value) == message + assert calls == [] + + +def test_empty_declaration_and_precomputed_read_skip_classification() -> None: + context = create_registry().get_context() + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + with guard_calls() as calls: + source = DictSource( + [], + data_schema={"points": set[Point]}, + source_id="empty", + data_context=context, + ) + assert source.source_id == "dict_v1:empty" + table = _legacy_table() + read_converter = create_registry().get_context().type_converter + assert isinstance(read_converter, UniversalTypeConverter) + read_converter.ensure_types_registered_for_schemas( + Schema({"points": set[Point]}) + ) + reader = SemanticSchemaConverter(read_converter, arrow_schema=table.schema) + assert reader.arrow_table_to_python_dicts(table) == [{"points": {Point(1)}}] + assert calls == [] + + +def test_precomputed_set_write_refusal_names_the_column() -> None: + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + schema = {"points": set[Point]} + converter.ensure_types_registered_for_schemas(Schema(schema)) + precomputed = SemanticSchemaConverter(converter, python_schema=schema) + + with pytest.raises( + UserClassSetNotStorableError, match=r"^Column 'points': .*use list\[Point\]\." + ): + precomputed.python_dicts_to_arrow_table([{"points": {Point(1)}}]) + + +def test_declarations_inference_and_arrow_reads_skip_the_check() -> None: + with guard_calls() as calls: + pod = op.function_pod(output_keys="points")(points_sync) + assert pod.pod.data_function.output_data_schema == Schema( + {"points": set[Point]} + ) + restored = PythonDataFunction.from_config(pod.pod.data_function.to_config()) + assert restored.output_data_schema == Schema({"points": set[Point]}) + converter = get_default_context().type_converter + converter.ensure_types_registered_for_schemas(Schema({"points": set[Point]})) + values: dict[str, Any] = {"points": {Point(1)}} + assert infer_python_schema_from_pylist_data([values])["points"] == set[Point] + + table = _legacy_table() + assert converter.arrow_table_to_python_dicts(table) == [values] + assert isinstance(converter, UniversalTypeConverter) + precomputed = SemanticSchemaConverter(converter, arrow_schema=table.schema) + assert precomputed.arrow_table_to_python_dicts(table) == [values] + for row in (Data(table), Tag(table)): + assert row.as_datagram().as_dict() == values + assert row.as_table().equals(table) + assert row.content_hash() == Datagram(table).content_hash() + assert calls == [] + + +def test_a_cold_ipc_read_can_import_a_module_defining_a_set_output( + tmp_path: Path, +) -> None: + converter = get_default_context().type_converter + declared = Schema({"points": set[PlainPoint]}) + converter.ensure_types_registered_for_schemas(declared) + schema = converter.python_schema_to_arrow_schema(declared) + table = pa.Table.from_pylist([{"points": [{"x": 1}]}], schema=schema) + path = tmp_path / "legacy.arrow" + with pa.ipc.new_file(str(path), schema) as writer: + writer.write_table(table) + + subprocess.run( + [ + sys.executable, + "-c", + dedent(""" + import sys + import pyarrow as pa + from orcapod.contexts import get_default_context + + path, fixture_module = sys.argv[1:] + assert fixture_module not in sys.modules + def profile(frame, event, arg): + if event == "call" and frame.f_code.co_name == "_check_set_write": + raise AssertionError("An Arrow read entered the write check") + sys.setprofile(profile) + converter = get_default_context().type_converter + with pa.ipc.open_file(path) as reader: + table = converter.load_logical_types(reader.read_all()) + row, = converter.arrow_table_to_python_dicts(table) + point, = row["points"] + assert point.x == 1 + assert type(point).__module__ == fixture_module + assert sys.modules[fixture_module].points_sync.pod is not None + """), + str(path), + PlainPoint.__module__, + ], + check=True, + ) + + +@pytest.mark.parametrize("kind", ["builtin", "custom"]) +def test_source_construction_config_and_saved_job_skip_the_check( + kind: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setitem(SOURCE_REGISTRY, PollingSource.SOURCE_KIND, PollingSource) + monkeypatch.setitem( + SOURCE_REGISTRY, CustomEmptySource.SOURCE_KIND, CustomEmptySource + ) + with guard_calls() as calls: + if kind == "builtin": + schema = pa.schema( + [pa.field("id", pa.int64(), nullable=False), *_legacy_table().schema] + ) + source = PollingSource( + LegacyPoll(schema), + tag_columns=[], + record_id_columns="id", + source_id="legacy", + ) + else: + source = CustomEmptySource( + [], data_schema={"points": set[Point]}, source_id="legacy" + ) + config = source.to_config() + restored = resolve_source_from_config(config) + assert restored.output_schema() == source.output_schema() + assert restored.source_id == source.source_id + + job = op.PipelineJob(name="legacy", database=InMemoryArrowDatabase()) + with job: + op.operators.MapData({"points": "renamed"})(source, label="mapped") + path = tmp_path / "job.json" + job.save(path) + loaded = op.PipelineJob.load(path, database=InMemoryArrowDatabase()) + assert isinstance(loaded.sources["legacy"], type(source)) + assert loaded.nodes["mapped"].output_schema()[1]["renamed"] == set[Point] + assert calls == [] + + +def test_primitive_set_writes_skip_the_refusal() -> None: + converter = create_registry().get_context().type_converter + rows = [{"values": {3, 1, 2}}] * 1000 + schema = {"values": set[int]} + with guard_calls() as calls: + first = converter.python_dicts_to_arrow_table(rows, schema) + second = converter.python_dicts_to_arrow_table(rows, schema) + assert calls == [] + assert first.equals(second) + + +def test_custom_restore_that_builds_python_rows_is_a_write( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setitem( + SOURCE_REGISTRY, CustomRebuiltSource.SOURCE_KIND, CustomRebuiltSource + ) + source = CustomRebuiltSource( + [], data_schema={"points": list[set[Point]]}, source_id="legacy" + ) + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.clear_cache() + with guard_calls() as calls: + with pytest.raises( + NestedTypeNotStorableError, match=r"Column 'points'.*use list\[Point\]" + ): + resolve_source_from_config(source.to_config()) + assert calls == [set[Point]] + + job = op.PipelineJob(name="legacy", database=InMemoryArrowDatabase()) + with job: + op.operators.MapData({"points": "renamed"})(source, label="mapped") + path = tmp_path / "job.json" + job.save(path) + + restored = op.PipelineJob.load(path, database=InMemoryArrowDatabase()) + assert restored.unbound_sources == ["legacy"] + assert not restored.sources + assert restored.nodes["mapped"].output_schema()[1]["renamed"] == list[set[Point]] + assert "Could not reconstruct source 'legacy'" in caplog.text + assert "UserClassSetNotStorableError" in caplog.text + assert "Column 'points'" not in caplog.text + assert "use list[Point]" not in caplog.text + + +class CustomAnnotatedSource(DictSource): + SOURCE_KIND = "test_itl922_annotated" + + def to_config(self, db_registry=None): + return {**super().to_config(db_registry), "annotation_metadata": _METADATA} + + @classmethod + def from_config( + cls, config: dict[str, Any], db_registry: Any = None + ) -> CustomAnnotatedSource: + annotation = set[Annotated[Point, config["annotation_metadata"]]] + converter = get_default_context().type_converter + # A custom factory can provide its own compatible Arrow schema. + arrow_schema = converter.python_schema_to_arrow_schema( + Schema({"points": set[Point]}) + ) + table = converter.python_dicts_to_arrow_table( + [{"points": {Point(1)}}], {"points": annotation}, arrow_schema + ) + return cls( + converter.arrow_table_to_python_dicts(table), + source_id=config["source_name"], + ) + + +def test_annotation_metadata_is_absent_from_refusals_and_load_logs( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setitem( + SOURCE_REGISTRY, CustomAnnotatedSource.SOURCE_KIND, CustomAnnotatedSource + ) + source = CustomAnnotatedSource( + [], data_schema={"points": set[Point]}, source_id="legacy" + ) + config = source.to_config() + assert config["annotation_metadata"] == _METADATA + + with pytest.raises( + UserClassSetNotStorableError, match=r"use list\[Point\]" + ) as error: + resolve_source_from_config(config) + assert _METADATA not in str(error.value) + assert _METADATA not in str(error.value.__cause__) + + job = op.PipelineJob(name="legacy", database=InMemoryArrowDatabase()) + with job: + op.operators.MapData({"points": "renamed"})(source, label="mapped") + path = tmp_path / "job.json" + job.save(path) + assert _METADATA in path.read_text() + + restored = op.PipelineJob.load(path, database=InMemoryArrowDatabase()) + assert restored.unbound_sources == ["legacy"] + assert "Could not reconstruct source 'legacy'" in caplog.text + assert "from its saved config: UserClassSetNotStorableError." in caplog.text + for record in caplog.records: + assert _METADATA not in record.getMessage() + assert _METADATA not in caplog.text diff --git a/tests/test_user_types/test_structural_dataclass.py b/tests/test_user_types/test_structural_dataclass.py index c67c4386e..5615da412 100644 --- a/tests/test_user_types/test_structural_dataclass.py +++ b/tests/test_user_types/test_structural_dataclass.py @@ -652,12 +652,12 @@ class Sample: note: str | None file: Path history: list[Point] - keys: set[Key] + keys: list[Key] @function_pod(output_keys="sample") def make(x: int) -> Sample: - return Sample(f"s{x}", Point(x, x / 2), ["a", "b"], None, Path("/tmp/f"), [Point(0, 0.0)], {Key(1), Key(2)}) + return Sample(f"s{x}", Point(x, x / 2), ["a", "b"], None, Path("/tmp/f"), [Point(0, 0.0)], [Key(2), Key(1)]) job = PipelineJob(name="w", database=DeltaTableDatabase(Path(os.environ["WS_DB"]))) @@ -696,8 +696,7 @@ def make(x: int) -> Sample: "note": value.note, "file_is_path": isinstance(value.file, Path), "history": [dataclasses.asdict(p) for p in value.history], - "keys_is_set": isinstance(value.keys, set), - "keys": sorted(key.n for key in value.keys), + "keys": [key.n for key in value.keys], }) report(out) """ @@ -725,8 +724,7 @@ def test_stored_values_are_read_without_the_class(tmp_path: Path) -> None: "note": None, "file_is_path": True, "history": [{"x": 0, "y": 0.0}], - "keys_is_set": True, - "keys": [1, 2], + "keys": [2, 1], } ]